OFFSET
1,2
COMMENTS
The king moves to the square with the fewest steps to reach 1 using the 3x+1 function. The function works as follows: start with the number, and if it is even, divide it by 2. Otherwise, multiply it by 3 and add 1, and repeat the process until you reach 1. If there are two squares with the same number of steps, the king picks the square with the smaller number.
The sequence contains 511 terms; the king gets stuck because all the adjacent squares are already taken.
The last square visited is numbered a(511) = 6619.
The highest-numbered square reached is a(327) = 12853.
EXAMPLE
The spiral board:
17--16--15--14--13 .
| | .
18 5---4---3 12 29
| | | | |
19 6 1---2 11 28
| | | |
20 7---8---9--10 27
| |
21--22--23--24--25--26
a(1) = 1, the initial square.
a(2) = 2 because 2 has the fewest steps to reach 1 applying the function {n/2 if n is even, 3n + 1 if n is odd} repeatedly.
PROG
(Python)
class Spiral:
def __init__(self):
self.spiral = [[1]]
def increment(self, increment_size):
if increment_size == 0: # Recursion stop condition
return
size = len(self.spiral)
count = size ** 2 + 1
if size % 2 != 0:
self.spiral.insert(0, [])
for i in reversed(range(0, size + 1)):
self.spiral[i].append(count)
count += 1
for _ in range(size):
self.spiral[0].insert(0, count)
count += 1
else:
self.spiral.append([])
for i in range(0, size + 1):
self.spiral[i].insert(0, count)
count += 1
for _ in range(size):
self.spiral[-1].append(count)
count += 1
self.increment(increment_size - 1)
def find_position(self, target):
for i, row in enumerate(self.spiral):
for j, element in enumerate(row):
if element == target:
return (i, j)
def find_king_neighbours(self, target):
i, j = self.find_position(target)
neighbours_position = (
(i - 1, j - 1), (i - 1, j), (i - 1, j + 1),
(i, j - 1), (i, j + 1),
(i + 1, j - 1), (i + 1, j), (i + 1, j + 1)
)
return [self.spiral[i][j] for i, j in neighbours_position]
def steps(x):
count = 0
while x != 1:
if x % 2 == 0:
x //= 2
else:
x = 3 * x + 1
count += 1
return count
def min_steps(lst):
"""Find the value with the minimal amount of steps with the 3x+1 function (the smallest in case of tie)"""
if len(lst) == 0:
raise ValueError("Empty list")
min_steps_seen, min_seed = float("inf"), float("inf")
for n in lst:
step = steps(n)
if step < min_steps_seen or step == min_steps_seen and n < min_seed:
min_steps_seen = step
min_seed = n
return min_seed
spiral = Spiral()
sequence = [1]
count = 1
print(count, 1)
while True:
count += 1
spiral.increment(2)
neighbours = spiral.find_king_neighbours(sequence[-1])
neighbours = [n for n in neighbours if n not in sequence]
try:
next_square = min_steps(neighbours)
except ValueError:
print("End of the sequence.")
break
sequence.append(next_square)
print(count, sequence[-1])
CROSSREFS
KEYWORD
nonn,walk,fini
AUTHOR
Wagner Martins, Jul 15 2023
STATUS
approved