Last active
March 16, 2023 11:16
-
-
Save edrdesigner/42168237cdd967d2051730207b7d16df to your computer and use it in GitHub Desktop.
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
/** | |
In a game, there is a string, direction, of length n that consists of characters | |
L and R. | |
L denotes left. R denotes right, and there is a line segment of | |
length 2" that extends from [0, 2"], a player takes n turns. | |
In the th turn, | |
• The player places the number i at the center of the current line segment. | |
• If direction[i] = L; the player proceeds in the left direction, eliminating the right half of the current line segment, | |
and vice versa for direction[i] = 'R'. | |
Following this rule, find the final order of numbers on the line segment, | |
starting from the left. | |
Example direction = "LRRLLL". | |
There are n = 6 characters in the initial length of the line segment. | |
The segment length is 2" = 2" = 64 in the range [0, 64]. | |
*/ | |
function findNumberSequence(direction) { | |
const n = direction.length; | |
const result = []; | |
let lower = 0; | |
let higher = 2 ** n; // Math.pow(2, n); | |
for (let i = 0; i < n; i += 1) { | |
const center = Math.floor((lower + higher) / 2); | |
result[center] = i + 1; | |
if (direction[i] === 'L') { | |
higher = center - 1; | |
} else { | |
lower = center + 1; | |
} | |
} | |
return result.filter(num => num !== undefined); | |
} | |
const direction = 'LRRLLL'; | |
const result = findNumberSequence(direction); | |
console.log(result); // output: [2, 4, 5, 6, 3, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple hacker rank solution for a problem.