Organizing Structures of name and score by score

1 次查看(过去 30 天)
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.

回答(1 个)

ag
ag 2024-9-17
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!

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by