Solving the Josephus Problem: Excel, M Code, and Python in Excel
Numerous Methods to accomplish a challenge:
Challenge:
A hundred people stand in a circle, numbered 1 to 100. Number 1 taps number 2 out. Number 3 taps number 4 out. Number 5 taps number 6 out, and so on round the circle.
The tapping keeps going, round and round, each person still standing tapping out the next person still standing, until one person is left.
Which number survives?
Excel:
=LET(n,100,L,n-2^INT(LOG(n,2)),2*L+1)
=LET(n,100,a,DEC2BIN(n),BIN2DEC(MID(a,2,10)&LEFT(a)))
=LET(l,LAMBDA(l,x,IF(ROWS(x)=2,@x,l(l,VSTACK(DROP(x,2),TAKE(x,1))))),l(l,SEQUENCE(100)))
Power Query:
let
fx = (L as list) as number => if List.Count(L) = 2 then L{0} else @fx(List.Skip(L,2) & List.FirstN(L,1)),
Result = fx({1..100})
in
Result
Python in Excel:
def fx(l):
return l[0] if len(l) == 2 else fx(l[2:] + [l[0]])
fx(list(range(1,101)))





Comments