so my challenge is to make a MxM zeros matrix but with about 15% of those values as 1s.The 'sum' of all those 1s needs to be as close to 15% as it can, while also making it into a global variable for another function, but for some reason it gets stuck in an infinite loop sometimes. Does anyone know why this is happening?
function [ board ] = randomking1( a,b )
clc
global sum
sum = 0; %initalizes sum to zero
kings = ceil(0.15*a*b); %finds number of kings needed for board size
board = randi([0,1],a,b); %creates game board of random zeros and ones.
% ones being the kings on the board.
for I = 1:a
for J = 1:b
if board(I,J) == 1
sum = sum + 1; %this set of for loops counts the
%number of kings on the board
end
end
end
while sum > kings || sum < kings-1 %if number of kings on the board is greater than
%number needed, the number of ones is reduced.
for I = 1:a
for J = 1:b
if sum
if board(I,J) == 1 %if a board value =1
board(I,J) = randi([0,1],1) %randomize 0 or 1
if board(I,J) == 0 %if the value becomes zero, subtract from the sum
sum = sum - 1
end
end
end
end
end
disp(sum)
end