29
3
The challenge
Write a function that takes two positive integers n and k as arguments and returns the number of the last person remaining out of n after counting out each k-th person.
This is a code-golf challenge, so the shortest code wins.
The problem
n people (numbered from 1 to n) are standing in a circle and each k-th is counted out until a single person is remaining (see the corresponding wikipedia article). Determine the number of this last person.
E.g. for k=3 two people will be skipped and the third will be counted out. I.e. for n=7 the numbers will be counted out in the order 3 6 2 7 5 1 (in detail 1 2 3 4 5 6 7 1 2 4 5 7 1 4 5 1 4 1 4) and thus the answer is 4.
Examples
J(7,1) = 7 // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7 // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4 // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21
Can you add an explanation, please? – Sherlock9 – 2015-11-26T18:49:26.667
@Sherlock9, I managed to figure out what I was doing despite almost 3.5 years having passed. Who says that GolfScript is read-only? ;) – Peter Taylor – 2015-11-26T21:45:01.427
Ahem. s/read/write/ – Peter Taylor – 2015-11-26T22:40:22.937
Sorry. I've only started learning Golfscript two or three days ago and I every time I read your code, I kept thinking I'd missed something. ... Ok, I'm still missing something, how does folding
{k block}
over[0..n-1]
get youg(0,k) 0 k
to start with? Sorry, if I'm posting these questions in the wrong place. – Sherlock9 – 2015-11-27T05:30:03.713@Sherlock9, fold works pairwise, so the first thing it does is evaluate
0 1 block
. Very conveniently, that happens to beg(1, k) (2-1) block
. So it's starting atg(1,k) 1
rather thang(0,k) 0
. Then after executing the block, it pushes the next item from the array (2
) and executes the block again, etc. – Peter Taylor – 2015-11-27T06:47:21.553OH! Ok that makes sense. Thanks @Peter Taylor – Sherlock9 – 2015-11-27T07:06:01.417