Skip to content

Instantly share code, notes, and snippets.

@heyrutvik
Last active August 29, 2015 14:06
Show Gist options
  • Save heyrutvik/dfad6df4a60ab99d3953 to your computer and use it in GitHub Desktop.
Save heyrutvik/dfad6df4a60ab99d3953 to your computer and use it in GitHub Desktop.
100 people standing in a circle in the order 1 to 100. No.1 has a sword. He kills the next person (i.e. no. 2 ) and gives sword to next to next (i.e no.3). All persons do the same until only 1 survives. Which number survives at the end?
#include <stdio.h>
int main()
{
int n;
printf("Enter a number (must be <= 100): ");
scanf("%d", &n);
if (n <= 1) {
printf("There must be at least two people, my friend!\n");
return 1;
}
/*
* static 100 because
* "variable-sized object may not be initialized".
* change array size as per your input range...
*/
char people[100] = {0};
char count = n;
int p = 0;
int answer;
while (count != 1) {
/* do while to validate value of p before compare in condition */
do {
if (p >= n)
p %= n;
} while (people[p++] != 0);
/*
* because range of people is between 1 to N,
* not from 0 to N - 1, we assign 'p' to 'answer'.
* no need to add 1 to 'p'.
* it is already incremented.
*/
answer = p;
do {
if (p >= n)
p %= n;
} while (people[p++] != 0);
/* decrement count if new index is encounter */
/* p - 1 because we move one step ahead in last loop 'p++' ;) */
if (people[p - 1] == 0) {
count--;
people[p - 1] = 1;
}
}
printf("ANSWER IS %d\n", answer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment