I am building a score keeper for a card game that a group of friends and I play. The program that I have developed has a separate variable for each players score. p1Score, p2Score,etc. At the end of the game I am trying to figure out how to compare up to 10 variables and then sort them from lowest to highest (lowest score wins the game).
int p1Score=100;
int p1rank=0;
int p2Score=150;
int p2rank=0;
int p3Score=155;
int p3rank=0;
int p4Score=75;
int p4rank=0;
int p5Score=80;
int p5rank=0;
int p6Score=100;
int p6rank=0;
so the idea is that the program compares all the scores and then changes the "rank" variables to reflect the lowest to highest ranking. There will also sometimes be ties. I don't know how to phrase the question or accomplish this other than a stampeding herd of "if" statements to get the ranks. Is there a way to do this that I cant see. I saw a way to do it with "sorting a string" but this isnt really a string soooo... Help please.
One solution is to use what is called a structure in C. A structure is simply a convenient way to group data. The following program illustrates one way to use a structure:
#define NUMBEROFSCORES 10
struct Score { // The structure
int score;
int rank;
} myScores[NUMBEROFSCORES];
void setup() {
int i;
int val;
randomSeed(analogRead(0)); // Seed random number generator
Serial.begin(9600);
for (i = 0; i < NUMBEROFSCORES; i++) {
myScores[i].score = random(200); // Generate random values up to 200
Serial.print("Score for #");
Serial.print(i);
Serial.print(" is: ");
Serial.println(myScores[i].score);
}
Sort(); // Sort the scores
Serial.println("After sort: ");
for (i = 0; i < NUMBEROFSCORES; i++) {
Serial.print("Score for #");
Serial.print(i);
Serial.print(" is: ");
Serial.println(myScores[i].score);
}
}
void Sort()
{
int i, j, k, temp;
for (i = 1; i < NUMBEROFSCORES; i++) {
for (j = 0; j < NUMBEROFSCORES - 1; j++) {
if (myScores[j].score > myScores[j + 1].score) { // Read and swap if necessary
temp = myScores[j].score;
myScores[j].score = myScores[j + 1].score;
myScores[j + 1].score = temp;
}
}
}
}
void loop() {
// put your main code here, to run repeatedly:
}
There's a bazillion ways to sort data and this is one of the simplest. I'll let you add the code to figure out the rank for each score.
Not sure I understand what you are saying but I got the structures as a way of grouping data then examining it/sorting it. Ill have to do some reading to grasp it more. Thanks for the direction tip.
In C++ you can use qsort http://www.cplusplus.com/reference/cstdlib/qsort/
Can sort a regular array of ints.
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
if ( int_a == int_b ) return 0;
else if ( int_a < int_b ) return -1;
else return 1;
}
qsort( a, 6, sizeof(int), compare )
PS before you get into structures - learn how to use simple arrays first.