Last active
April 10, 2019 10:13
-
-
Save d-lobanov/60318f2e170cea720302135db5d327ec to your computer and use it in GitHub Desktop.
Gin in rooms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * This code sloves the problem with gin in rooms. | |
| */ | |
| const GIN_IN_ROOM = true; | |
| const GIN_NOT_IN_ROOM = false; | |
| function generateRooms(length, fillWith) { | |
| return Array.apply(null, Array(length)).map(_ => fillWith); | |
| } | |
| function moveGin(rooms) { | |
| let resultRooms = generateRooms(rooms.length, GIN_NOT_IN_ROOM); | |
| for (let i = 0, total = rooms.length - 1; i <= total; i++) { | |
| if (rooms[i] === GIN_IN_ROOM) { | |
| if (i > 0) resultRooms[i - 1] = GIN_IN_ROOM; | |
| if (i < total) resultRooms[i + 1] = GIN_IN_ROOM; | |
| } | |
| } | |
| return resultRooms; | |
| } | |
| function openRoom(rooms, roomIndex) { | |
| rooms[roomIndex] = GIN_NOT_IN_ROOM; | |
| return moveGin(rooms); | |
| } | |
| function isGinGone(rooms) { | |
| return rooms.every(room => room === GIN_NOT_IN_ROOM); | |
| } | |
| function main(numberOfRooms) { | |
| let rooms = generateRooms(numberOfRooms, GIN_IN_ROOM); | |
| let totalSteps = 0; | |
| for (let i = 1; i < numberOfRooms - 1; i++) { | |
| rooms = openRoom(rooms, i); | |
| totalSteps++; | |
| } | |
| for (let i = numberOfRooms - 2; i >= 1; i--) { | |
| rooms = openRoom(rooms, i); | |
| totalSteps++; | |
| } | |
| console.log(isGinGone(rooms) ? 'done' : 'error'); | |
| console.log('Total: ' + totalSteps); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment