Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://www.hackerrank.com/challenges/cut-the-sticks/problem
- // declarative, recursive, immutable
- const handleSticks = ({
- mutableSticksArr,
- sticksLeftPerTurn,
- shortestStick
- }) => {
- const shortestStickReturned = shortestStick(mutableSticksArr);
- return mutableSticksArr.length > 0
- ? handleSticks({
- mutableSticksArr: mutableSticksArr
- .map(stick => stick - shortestStickReturned)
- .filter(stick => stick > 0),
- sticksLeftPerTurn: [
- ...sticksLeftPerTurn, mutableSticksArr.length
- ],
- shortestStick
- })
- : sticksLeftPerTurn
- }
- const cutTheSticks = arr => (
- handleSticks({
- mutableSticksArr: [...arr],
- sticksLeftPerTurn: [],
- shortestStick: (stickArr) => (
- stickArr.slice(0).sort((a, b) => a - b)[0]
- )
- })
- )
- // imperative/immutable
- const cutTheSticks = arr => {
- let mutableSticksArr = [...arr];
- let sticksLeftPerTurn = [];
- const shortestStick = (stickArr) => (
- stickArr.slice(0).sort((a, b) => a - b)[0]
- );
- do {
- sticksLeftPerTurn = [
- ...sticksLeftPerTurn,
- mutableSticksArr.length
- ];
- shortestStickReturned = shortestStick(mutableSticksArr);
- mutableSticksArr = mutableSticksArr
- .map(stick => stick - shortestStickReturned)
- .filter(stick => stick > 0)
- }
- while(mutableSticksArr.length > 0)
- return sticksLeftPerTurn;
- }
Add Comment
Please, Sign In to add comment