I'm trying to implement a simple game where the array symbolizes people standing in a circle, drawing an integer at the beginning of the game. each iteration is the size of the integer and removes people from the game.
so if array[]={a,b,c,d} and integer=3; c is the first to be removed. Then b , then d. the winner is a. at the end I need to print the array with the results by order of removal. so the printed array should be: a, d, b, c. I'm trying to accomplish this only with use of pointers with no additional arrays.
Here's what i got, the problem is i'm trying to restart the for loop from the correct index and iterate through the remaining players who have not yet lost and cant get it right:
char *names[] = {"Tyrion Lannister","Daenerys Targaryen","Jon Snow","Arya Stark","Theon Greyjoy", "Joffrey Baratheon","Khal Drogo","Ted Mosby","Marshall Eriksen","Robin Scherbatsky","Barney Stinson", "Lily Aldrin", "Tracy McConnell", "Ted Mosby", "Leonard Hofstadter","Sheldon Cooper", "Penny", "Howard Wolowitz", "Raj Koothrappali", "Bernadette Rostenkowski-Wolowitz","Amy Farrah Fowler", "Gregory House", "Lisa Cuddy", "James Wilson","Eric Foreman", "Allison Cameron", "Robert Chase" ,"Lawrence Kutner", "Chris Taub","Remy 13 Hadley", "Amber Volakis"};
int Length = 31;
int number = 10;
char *tmp;
int i = 0, j;
int boom = number;
for (int i = number - 1; i < Length; i += boom - 1)
{
tmp = *(names + i);
for (int index = i; index < Length - 1; index++)
{
*(names + index) = *(names + index + 1);
}
*(names + Length - 1) = tmp;
Length--;
if (((number - 1) + i) >= Length)
{
int tempIndex = i;
i = tempIndex - Length;
printf("tmep index is %d, i is %d, Length is %d\n", tempIndex, i, Length);
}
}
for (i = 0; i < 31; i++)
printf("%s\n", names[i]);
I also tried another way with % operator, but couldn't quite get it done. Help would be much appreciated:
for (int i = number - 1; i < Length * (number - 1); i += boom - 1)
{
int t = i % Length;
printf("%d\n", t);
if (t < size)
{
counter++;
tmp = *(names + t);
// tmptwo = *(names + 31 - j);
for (int index = t; index < size - 1; index++)
{
*(names + index) = *(names + index + 1);
}
*(names + size - 1) = tmp;
size--;
printf("size %d\n", size);
}
}
aand indexi, the expression*(a + i)is exactly equal toa[i]. The latter is usually easier to understand, and a couple of characters less to write. That means that e.g.*(names+index)=*(names+index+1)is equal tonames[index] = names[index+1].a[i]) into pointer arithmetic (as in*(a + i)) not being allowed to use the array variant is kind of useless and a waste of good typing (IMO) :) Tell your teacher that!