- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
The Zombie Apocalypse case study - JavaScript
A nasty zombie virus is spreading out in the digital cities. We work at the digital CDC and our job is to look over the city maps and tell which areas are contaminated by the zombie virus so the digital army would know where to drop the bombs.
They are the new kind of digital zombies which can travel only in vertical and horizontal directions and infect only numbers same as them.
We'll be given a two-dimensional array with numbers in it.
For some mysterious reason patient zero is always found in north west area of the city (element [0][0] of the matrix) and the plague spreads from there to other cells by moving left, right, up or down.
We must create a function that returns a map (2-dimensional array) with all the contaminated areas marked as 1 and virus-free marked as 0.
In other words, we have to find all the matrix elements with the same value as [0][0] that we can go to by moving only down, up, right or left from [0][0] - without going into a field storing any other value.
Example
Following is the code −
const arr = [ [9, 1, 2, 3, 4, 1, 2, 9], [9, 9, 9, 2, 1, 5, 9, 9], [9, 2, 9, 3, 7, 9, 1, 9], [6, 9, 9, 9, 0, 9, 2, 9], [5, 4, 3, 9, 9, 9, 4, 9], [9, 3, 9, 5, 8, 9, 9, 9], [9, 9, 9, 9, 9, 9, 7, 9], [9, 9, 1, 2, 3, 9, 8, 9] ]; const findZombies = arr => { let i, j, result = [], zombie = arr[0][0], tree = {}; const chance = ([i, j]) => { if (!tree[i] || !tree[i][j]) return; result[i][j] = 1; var temp = tree[i][j]; tree[i][j] = undefined; temp.forEach(chance); } for (i = 0; i < arr.length; i++) { result.push([]); for (j = 0; j < arr[i].length; j++) { result[i].push(0); if (arr[i][j] !== zombie) continue; if (!tree[i]) tree[i] = {}; tree[i][j] = [[i, j - 1], [i, j + 1], [i - 1, j], [i + 1, j]].filter(([x, y]) => arr[x] && arr[x][y] === zombie); }; }; chance([0, 0]); return result; }; console.log(findZombies(arr));
This will produce the following output on console −
[ [ 1, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 1, 1, 0, 0, 0, 1, 1 ], [ 1, 0, 1, 0, 0, 1, 0, 1 ], [ 0, 1, 1, 1, 0, 1, 0, 1 ], [ 0, 0, 0, 1, 1, 1, 0, 1 ], [ 1, 0, 1, 0, 0, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 0, 0, 0, 1, 0, 1 ] ]