Organizing Structures of name and score by score
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (1)
ag
el 17 de Sept. de 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');
for i = 1:length(scoreData)
fprintf('%s: %d\n', scoreData(i).name, scoreData(i).score);
end
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!
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!