# Attempting to completely fill out an array(6,7) with 1's and 2's for connect4

2 views (last 30 days)
Preston Waddell on 27 Sep 2019
Edited: Adam Danz on 28 Sep 2019
clc,clf
col = 1;
row = 1;
board = zeros(6,7); %Creates a board of zeros
maxturns = 0;
while maxturns <= 42
maxturns = maxturns + 1; %increments maxturns by 1 each time pcOne puts a 1 on the board
pcOne = randi(7); % pcOne generates a number 1-7
col = pcOne; %pcOne sends the number to col to place 1 in the correct column
while (board(row,col)~=0)%loops the input of row and col to ensure it isnt replacing a number that is already in place
pcOne = randi(7);
col = randi(7);
end
row = 6; %starts the row at the bottom of the array
played = 0;
while (played == 0)
if board(row,col) == 0
board(row,col) = 1; % if board space = 0 then it is replaced with a 1
played = 1; %when the loop is true played will equal 1 and exit the loop
end
row = row - 1; %will reduce the row to 5 if 6 is full in the respected column
end
maxturns = maxturns + 1; %adds to the max turns
pcTwo = randi(7);
col = pcTwo;
while (board(row,col)~=0)%iniates when a board has a number in the row,col spot
pcTwo = randi(7); %generates a column value for the array
col = pcTwo;
end
row = 6;
played = 0;
while (played == 0)%ends after the board finds a 0
if board(row,col) == 0
board(row,col) = 2;%replaces a 0 in the array with a 2
played = 1;
end
row = row - 1;%if bottom row in the selected column it will move up a row
end
disp(board); %should display a board full of 1' and 2's
end% loop ends after 42 moves are made
RESULTS:
0 0 0 0 0 0 0
0 0 0 2 0 0 0
2 1 0 2 0 0 0
2 2 0 1 1 2 1
1 2 1 1 2 1 2
2 1 2 1 1 2 1
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in ConnectFour (line 27)
while (board(row,col)~=0)

James Tursa on 27 Sep 2019
Maybe you could explain what your code is supposed to be doing. Commenting the code would be great. But if you just want a board with all 1's, then
board = ones(6,7);

David Hill on 27 Sep 2019
If you want an array of ones (6x7)
ones(6,7);
Otherwise, I don't understand your question.

### Categories

Find more on STMicroelectronics Discovery Boards in Help Center and File Exchange

R2019a

### Community Treasure Hunt

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

Start Hunting!