SHARE
TWEET

Untitled

a guest Apr 20th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * This code sloves the problem with gin in rooms.
  3.  */
  4. const GIN_IN_ROOM = true;
  5. const GIN_NOT_IN_ROOM = false;
  6.  
  7. function generateRooms(length, fillWith) {
  8.   return Array.apply(null, Array(length)).map(_ => fillWith);
  9. }
  10.  
  11. function moveGin(rooms) {
  12.   let resultRooms = generateRooms(rooms.length, GIN_NOT_IN_ROOM);
  13.  
  14.   for (let i = 0, total = rooms.length - 1; i <= total; i++) {
  15.     if (rooms[i] === GIN_IN_ROOM) {
  16.       if (i > 0) resultRooms[i - 1] = GIN_IN_ROOM;
  17.       if (i < total) resultRooms[i + 1] = GIN_IN_ROOM;
  18.     }
  19.   }
  20.  
  21.   return resultRooms;
  22. }
  23.  
  24. function openRoom(rooms, roomIndex) {
  25.   rooms[roomIndex] = GIN_NOT_IN_ROOM;
  26.  
  27.   return moveGin(rooms);
  28. }
  29.  
  30. function isGinGone(rooms) {
  31.   return rooms.every(room => room === GIN_NOT_IN_ROOM);
  32. }
  33.  
  34. function main(numberOfRooms) {
  35.   let rooms = generateRooms(numberOfRooms, GIN_IN_ROOM);
  36.   let totalSteps = 0;
  37.  
  38.   for (let i = 1; i < numberOfRooms - 1; i++) {
  39.     rooms = openRoom(rooms, i);
  40.     totalSteps++;
  41.   }
  42.  
  43.   for (let i = numberOfRooms - 2; i >= 1; i--) {
  44.     rooms = openRoom(rooms, i);
  45.     totalSteps++;
  46.   }
  47.  
  48.   console.log(isGinGone(rooms) ? 'done' : 'error');
  49.   console.log('Total: ' + totalSteps);
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top