Hi I have an array of scores. I would like to sort this from smallest to largest. To each of the scores should be assigned to the player's name. How can I do it? Should I have two fields - names and scores? When the scores are sorted, the order is changed, then how to assign names to the correct position?
If you're working in C#, SortedList or SortedDictionary will be the easiest way to go Code (csharp): using System.Collections.Generic: SortedList<int, string> highscores; ... highscores.Add(2000, "Player A"); highscores.Add(3000, "Player B"); highscores.Add(1000, "Player C"); highscores.Add(999, "Player D"); However, this will only work if the scores are unique, which is pretty unlikely. Better approach is to create a Score class, like Code (csharp): public class Score : IComparable { public int score; public string playerName; public Score(int score, string playerName) { this.score = score; this.playerName = playerName; } public int CompareTo(object obj) { Score otherScore = obj as Score; if(otherScore!=null) { return this.score.CompareTo(otherScore.score); } else { throw new ArgumentException("Object is not a Score"); } } public override ToString() { return String.Format("{0}: {1}", this.playerName, this.score); } } List<Score> highscores = new List<Score>(); highscores.Add(new Score(2000,"Player A")); highscores.Add(new Score(3000, "Player B")); highscores.Add(new Score(1000, "Player C")); highscores.Add(new Score(999, "Player D")); highscores.Sort(); for(int i=0;i<highscores.Count; i++) { Debug.Log(highscores[i].ToString()); } By implementing IComperable you can define your own sorting criteria in the CompareTo(...) method. Since it should be sorted by score, you just use the Int classes CompareTo function and compare the score of both results. Also see the IComperable MSDN documentation.
Thanks. I have everything written in JS. I try to do this as a function in a separate file. It is possible to make similar solution in JS?
I get error The modifier `override' is not valid for this item on Code (csharp): public override ToString() { return String.Format("{0}: {1}", this.playerName, this.score); } What am I doing wrong ?
Another approach is to use this version of System.Array.Sort, which takes two arrays and sorts them in parallel, based on the order of keys in the first array:- Code (csharp): var scores: float[]; // The nth name corresponds with the nth score. var names: String[]; ... System.Array.Sort(scores, names);