Last active
March 16, 2017 16:19
-
-
Save devNoiseConsulting/f58348b31801ddb1c4dd3783272b679b to your computer and use it in GitHub Desktop.
Parking at Hanoi - PhillyDev Slack #daily_programmer - 20170306
This file contains 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
/* | |
There are N+1 parking spots, numbered from 0 to N. There are N cars numbered | |
from 1 to N parked in various parking spots with one left empty. Reorder the | |
cars so that car #1 is in spot #1, car #2 is in spot #2 and so on. Spot #0 will | |
remain empty. The only allowed operation is to take a car and move it to the | |
free spot. | |
*/ | |
function initParking(size) { | |
let parking = (new Array(size)).fill(null); | |
let i = 1; | |
while (i < parking.length) { | |
let spot = Math.floor(Math.random() * (size + 1)); | |
if (parking[spot] === null) { | |
parking[spot] = i++; | |
} | |
} | |
return parking; | |
} | |
function reorderParking(parking) { | |
console.log(0, parking); | |
for (let i = 1; i < parking.length; i++) { | |
if (parking[i] == i) { | |
continue; | |
} | |
let emptySpot = parking.indexOf(null); | |
if (emptySpot != i) { | |
parking = swapParkingSpots(parking, emptySpot, i); | |
console.log(i, parking); | |
} | |
let carSpot = parking.indexOf(i); | |
parking = swapParkingSpots(parking, carSpot, i); | |
console.log(i, parking); | |
} | |
return parking; | |
} | |
function swapParkingSpots(parking, i, j) { | |
let tmp = parking[i]; | |
parking[i] = parking[j]; | |
parking[j] = tmp; | |
return parking; | |
} | |
let size = Math.floor(Math.random() * (10 - 3)) + 3; | |
let result = reorderParking(initParking(size)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment