CLooker

hackerRank cut the sticks

Jan 28th, 2018
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://www.hackerrank.com/challenges/cut-the-sticks/problem
  2.  
  3. // declarative, recursive, immutable
  4. const handleSticks = ({
  5.   mutableSticksArr,
  6.   sticksLeftPerTurn,
  7.   shortestStick
  8. }) => {
  9.   const shortestStickReturned = shortestStick(mutableSticksArr);
  10.   return mutableSticksArr.length > 0
  11.     ?   handleSticks({
  12.             mutableSticksArr: mutableSticksArr
  13.                 .map(stick => stick - shortestStickReturned)
  14.                 .filter(stick => stick > 0),
  15.             sticksLeftPerTurn: [
  16.                 ...sticksLeftPerTurn, mutableSticksArr.length
  17.             ],
  18.             shortestStick
  19.         })
  20.     :   sticksLeftPerTurn
  21. }
  22.  
  23. const cutTheSticks = arr => (  
  24.     handleSticks({
  25.         mutableSticksArr: [...arr],
  26.         sticksLeftPerTurn: [],
  27.         shortestStick: (stickArr) => (
  28.           stickArr.slice(0).sort((a, b) => a - b)[0]
  29.         )
  30.     })
  31. )
  32.  
  33. // imperative/immutable
  34. const cutTheSticks = arr =>  {
  35.     let mutableSticksArr = [...arr];
  36.     let sticksLeftPerTurn = [];    
  37.     const shortestStick = (stickArr) => (
  38.       stickArr.slice(0).sort((a, b) => a - b)[0]
  39.     );
  40.    
  41.     do {
  42.         sticksLeftPerTurn = [
  43.           ...sticksLeftPerTurn,
  44.           mutableSticksArr.length
  45.         ];
  46.         shortestStickReturned = shortestStick(mutableSticksArr);
  47.         mutableSticksArr = mutableSticksArr
  48.             .map(stick => stick - shortestStickReturned)
  49.             .filter(stick => stick > 0)
  50.     }
  51.     while(mutableSticksArr.length > 0)
  52.    
  53.     return sticksLeftPerTurn;
  54. }
Add Comment
Please, Sign In to add comment