Jumping Jack

March 22, 2013

We have a fun little programming puzzle today; I found it here, but don’t know the original source of the puzzle:

Jack starts at 0 on the number line and jumps one unit in either direction. Each successive jump he makes is longer than the previous by 1 unit, and can be made in either direction. Write a program that takes a number and returns the minimum number of jumps Jack makes to reach that number.

For example, it takes seven jumps to reach 12, first a jump left to -1, then a jump right to 1, a jump right to 4, a jump right to 8, a jump right to 13, a jump right to 19, and a jump left to 12. To go to -12, simply reverse the direction of each jump.

Your task is to write programs that compute the minimum number of steps Jack must take to reach his target and that compute the actual steps. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Assume the destiny number is k, the step is n
we are looking for a minimal value of n that n(n+1) = 2k + 4x where x is the sum of a sub set of [1…n] so x can be any positive integer(no larger than n(n+1)/2)

# The algorithm works in two steps:
# – In the first step, we create the shortest array of the form [1, 2, 3, 4, 5, …] so that
# the sum s of the contained numbers satisfies ‘s – number % 2 == 0’. If ‘s – number == 0’
# we are done. In any case, the resulting array has exactly the length we are looking for.
# – In the second step, we adjust the signs of the numbers from the first array so that their
# sum equals the given number.
#
def JumpingJack.jump_to_positive_number(number)
n = 0
sum = 0
ret = []
loop do
diff = sum – number
return ret if diff == 0
break if diff > 0 && diff % 2 == 0