Taken from DailyCodingProblem
Starting from 0
on a number line, you would like to make a series of jumps that lead to the integer N
.
On the i
th jump, you may move exactly i
places to the left or right.
Find a path with the fewest number of jumps required to get from 0
to N
.
This is the answer I came up with using JavaScript:
And also implemented using Ruby:
Solution tested in JavaScript REPL:
https://www.typescriptlang.org/play/?filetype=js#code/PTAEBcAsFNQGwIYGdymnaBbaA7VBLJCGUfPaAc2gCdQA5AGlGugAcWldxoATUAIwCeoBDhHVqCYQHsAZvFwUo9AFAZU3MQF5QAbQCMDAEwMAzAwAsDAKwMAbAwDsDABwMAnA30AGALoqQUAB3WABjUREAN2l8PgBXJDIKEXh8bkk4UFlpWjhpHCpaBAkpJDVoVHRoSNxQHQBBEsEACn19AEpyjSDpOtBGyRajTvVQfNgdA39R8BC8QQB5HAn+puajDq6snPBBAGVq2oa1i0dOgIAqC5VQC9AAAVZihExQAG8cOMx+Gl1fAF9xNQbnd7ixwHFqDgiB8vj9qP8QcAVCpZHEcKFwPh8qAAFZfVhIZrFajtd43UCUwL4zCsLLUaSvbwQXr6CmU-DyYkSAB0GAKyi0QtAHXezAqkLE+lAiPZoGpBPpjNAzPAvTowBMIhwfCgtTVqkpHK5JL5imUAFJQEY6sLvGS3nKjeKIVDrXLAehOOTnc6FbSlUyWSKmKJdTAxAaNVqw8R9eqnUbwZLQKYPSpZaF8khpBg+dIKM05TTCc1NO0mIEjMWCUSqjUcBX5WBTM6a7SibNpE2q5T26Xxj2wNKjf3O3NdktoEPU2PmtlqLsDg2yYE050gA
Solution tested in Ruby REPL:
https://try.ruby-lang.org/playground/#code=ten+%3D+Array.new(10)%0Aeleven+%3D+Array.new(11)%0Atwo+%3D+Array.new(2)%0Aone+%3D+Array.new(1)%0Atwenty_one+%3D+Array.new(21)%0Aforty_seven+%3D+Array.new(47)%0A%0Adef+jumps(array)%0A++if+array.length+%3D%3D%3D+1%0A++++return+1%0A++end%0A++%0A++if+array.length+%25+2+%3D%3D%3D+0%0A++++return+2%0A++else%0A++++return+3%0A++end%0Aend%0A%0Aputs+jumps(ten)+%23+2%0Aputs+jumps(eleven)+%23+3%0Aputs+jumps(two)+%23+2%0Aputs+jumps(one)+%23+1%0Aputs+jumps(twenty_one)+%23+3%0Aputs+jumps(forty_seven)+%23+3%0A&engine=cruby-3.2.0