Last active
August 23, 2023 03:35
-
-
Save gogones/3d74fc899d01f9b3b49b967886960d2c to your computer and use it in GitHub Desktop.
find floor from locker number given
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
function findLockerLevel(lockerNumber) { | |
if(lockerNumber <= 0) { | |
return 'Error, Masukkan locker lebih dari 0' | |
} | |
let regionPosition = 1; | |
let currentFloor = 1; | |
let isFound = false; | |
while(!isFound) { | |
const lockerEachRegion = [5, 6, 7]; | |
const startRegion = [1, 6, 12]; | |
const nRegion = [(currentFloor + 2) / 3, (currentFloor + 1) / 3, currentFloor / 3]; | |
const startLockerNumber = 18 * nRegion[regionPosition-1] + (startRegion[regionPosition-1] - 18); | |
const endLockerNumber = startLockerNumber + lockerEachRegion[regionPosition-1] - 1 | |
if(lockerNumber >= startLockerNumber && lockerNumber <= endLockerNumber) { | |
isFound = true; | |
} else { | |
currentFloor++; | |
if(regionPosition === 3) { | |
regionPosition = 1; | |
} else { | |
regionPosition++ | |
} | |
} | |
} | |
return currentFloor; | |
} |
Alternative without looping
function findLockerLevel(lockerNumber) {
if (lockerNumber <= 0) {
return 'Error, Masukkan locker lebih dari 0';
}
function findLevel(regionPosition, currentFloor) {
const lockerEachRegion = [5, 6, 7];
const startRegion = [1, 6, 12];
const nRegion = [(currentFloor + 2) / 3, (currentFloor + 1) / 3, currentFloor / 3];
const startLockerNumber = 18 * nRegion[regionPosition - 1] + (startRegion[regionPosition - 1] - 18);
const endLockerNumber = startLockerNumber + lockerEachRegion[regionPosition - 1] - 1;
if (lockerNumber >= startLockerNumber && lockerNumber <= endLockerNumber) {
return currentFloor;
} else {
if (regionPosition === 3) {
return findLevel(1, currentFloor + 1);
} else {
return findLevel(regionPosition + 1, currentFloor + 1);
}
}
}
return findLevel(1, 1);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// 1, 19, 37
// 6, 24, 42
// 12, 30, 48
// Un = 18n + (1 - 18)
// Un = 18n + (6 - 18)
// Un = 18n + (12 - 18)