I have an array with the top 10 high scores. I know how to add to the array, and sort the array with Sort(); but how do you add a value to the array, lets say that is the 2nd highest score, so I want to add this new 2nd place high score, deleting the current 10th high score and moving the other scores down one place?
Cheers for any ideas
5 Answers
5
Use generic lists instead. With lists you can Add, Insert, RemoveAt, etc.
C#
using System.Collections.Generic
List<int> scores = new List<int>();
scores.Add(25);
scores.Add(50);
scores.Insert(0, 28);
scores.Sort();
scores.RemoveAt(0);
javascript
import System.Collections.Generic;
var scores : List.<int> = new List.<int>();
scores.Add(25);
scores.Add(50);
scores.Insert(0, 28);
scores.Sort();
scores.RemoveAt(0);
This is a very basic programming exercise.
C#
int [] highScore = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int InsertScore( int score ) {
int i = 0;
//Look for the index to insert score
while( i < highScore.length ) {
if( highScore *<= score ) {*
break;
}
i++;
}
//Score doesn’t make it to top 10
if( i >= highScore.length ) {
return -1;
}
//Push all the scores not higher than score backward
for( int j = highScore.length - 1; j <= i; --j ) {
highScore[j] = highScore[j-1];
}
//Set score
highScore = score;
return i;
}
Correction for Chronos-L Answer. [JS version , but I guess its correct in C# too].
function recordHighScore(score) {
var i = 0;
while(i < highScores.length) {
if(highScores *<= score)*
break;
i++;
}
if(i >= highScores.length)
return;
for(var j = highScores.length - 1; j > i; --j) {
console.log(highScores[j - 1]);
highScores[j] = highScores[j - 1];
}
highScores = score;
}
Correction for Chronos-L Answer. [JS version , but I guess its correct in C# too].
function recordHighScore(score) {
var i = 0;
while(i < highScores.length) {
if(highScores *<= score)*
break;
i++;
}
if(i >= highScores.length)
return;
for(var j = highScores.length - 1; j > i; --j) {
console.log(highScores[j - 1]);
highScores[j] = highScores[j - 1];
}
highScores = score;
}
function recordHighScore(score) {
var i = 0;
while(i < highScores.length) {
if(highScores <= score)
break;
i++;
}
if(i >= highScores.length)
return;
for(var j = highScores.length - 1; j > i; --j) {
console.log(highScores[j - 1]);
highScores[j] = highScores[j - 1];
}
highScores = score;
}
Well, i would just put them in the array in any order, and then sort the list by the highest value. Infact i would use a generic list.
– EliteMossyArrays differ in unity greatly between c# and js, which are you using?
– HunterKrechSorry for those who posted a c# answer, I am using js
– kiwi_koder