matlab code pls help
Archiviert a year ago
I
Disabled Account
Verified
function [score1, score2] = factor_game(n)
numbers = 1:n; % Initialize the list of numbers
score1 = 0; % Player 1's score
score2 = 0; % Player 2's score
currentPlayer = 1; % Start with Player 1
while ~isempty(numbers) % Continue while there are numbers remaining
disp('The remaining numbers are: ')
disp(numbers)
% Prompt the current player for input
if currentPlayer == 1
chosenNumber = input('Player 1, please choose a number from this list: ');
else
chosenNumber = input('Player 2, please choose a number from this list: ');
end
% Validate input: check if the chosen number is in the list
if ismember(chosenNumber, numbers)
% Remove the chosen number from the list
numbers(numbers == chosenNumber) = [];
% Identify factors of the chosen number in the remaining numbers
factors = chosenNumber; % Include the chosen number itself
for i = 1:length(numbers)
if mod(numbers(i), chosenNumber) == 0 % Check divisibility
factors = [factors, numbers(i)];
end
end
% Remove the factors from the list of remaining numbers
numbers = setdiff(numbers, factors);
% Calculate points for the player
points = sum(factors);
% Update scores and switch player
if currentPlayer == 1
score1 = score1 + points;
fprintf('Player 1 gains %d points, giving them a total of %d.\n', points, score1)
currentPlayer = 2; % Switch to Player 2
else
score2 = score2 + points;
fprintf('Player 2 gains %d points, giving them a total of %d.\n', points, score2)
currentPlayer = 1; % Switch to Player 1
end
else
disp('Invalid choice. Please choose a valid number from the list.')
end
end
% Display the final scores
fprintf('Final scores: Player 1 = %d, Player 2 = %d\n', score1, score2)
if score1 > score2
disp('Congratulations Player 1!')
elseif score2 > score1
disp('Congratulations Player 2!')
else
disp('It''s a tie!')
end
end
