Skip to content

Instantly share code, notes, and snippets.

@gogones
Last active August 23, 2023 03:35
Show Gist options
  • Save gogones/3d74fc899d01f9b3b49b967886960d2c to your computer and use it in GitHub Desktop.
Save gogones/3d74fc899d01f9b3b49b967886960d2c to your computer and use it in GitHub Desktop.
find floor from locker number given
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;
}
@gogones
Copy link
Author

gogones commented Oct 25, 2022

// 1, 19, 37
// 6, 24, 42
// 12, 30, 48
// Un = 18n + (1 - 18)
// Un = 18n + (6 - 18)
// Un = 18n + (12 - 18)

@gogones
Copy link
Author

gogones commented Aug 23, 2023

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