Puzzles

From raju

The crazy Sword game

Q. 100 people standing in a circle in an order 1 to 100. No.1 has a sword. He kills the next person (i.e.no. 2) and gives the sword to the next (i.e no.3). All people do the same until only 1 survives. Which number survives at the last?
A. 73

Here is an octave code that solves it

#! /usr/bin/octave -qf
1;

function [survivors, new_sword_index] = kill_round(people, sword_index)
    n_people = length(people);
    survivors = people(sword_index:2:end);
    n_survivors = length(survivors);
    if (mod(length(people)-sword_index+1,2) == 1)
        new_sword_index = 2;
    else
        new_sword_index = 1;
    endif
endfunction

function [winner] = sword_game(N)
    a = [1:N];
    sword_index = 1;
    while (length(a) > 1)
        [a, sword_index] = kill_round(a, sword_index);
    endwhile
    winner = a;
endfunction

Run it as follows

rajulocal@hogwarts:~/work/puzzles$ octave -qf
octave:1> crazy_sword
octave:2> winner = sword_game(100)
winner =  73

Tested using octave 3.8.2 on a machine running a combination of Debian Lenny (stable) and Jessie (testing).