Organizing Structures of name and score by score

1 view (last 30 days)
Austin
Austin on 17 Mar 2014
Answered: ag on 17 Sep 2024
I need a script which will store the top five scores from a game script. I have a file with a structure containing 5 dummy names and scores. That file will need to check those 5 verses the score that was just obtained, arrange the 6 with lowest score first, then save the new top 5 and display those back into the game script.

Answers (1)

ag
ag on 17 Sep 2024
Hi Austin,
To implement the specifed functionality you can create a MATLAB script that reads the existing scores from a file, compares them with a new score, updates the top five scores, and then saves and displays the updated list.
Below code snippet illustrates how to achieve this:
% Initializing with dummy data
scoreData = struct('name', {'Alice', 'Bob', 'Charlie', 'David', 'Eve'}, ...
'score', {100, 90, 80, 70, 60});
% New score can be obtained via user input
newName = 'Charles';
newScore = 85;
% Add new score to the existing structure
scoreData(end+1) = struct('name', newName, 'score', newScore);
% Sort the scores in descending order
[~, sortedIndices] = sort([scoreData.score], 'descend');
scoreData = scoreData(sortedIndices);
% Keep only the top 5 scores
scoreData = scoreData(1:min(5, end));
% % Display the top 5 scores
fprintf('Top 5 Scores:\n');
Top 5 Scores:
for i = 1:length(scoreData)
fprintf('%s: %d\n', scoreData(i).name, scoreData(i).score);
end
Alice: 100 Bob: 90 Charles: 85 Charlie: 80 David: 70
Please modify the above logic for reading and saving a file as per the requirement.
For more details, please refer to the following MathWorks documentation page: Sort Array Elements- https://www.mathworks.com/help/matlab/ref/double.sort.html;jsessionid=211ce60c46654a1ec59e441b9ae6
Hope this helps!

Categories

Find more on Just for fun in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!