0

ユーザーが同じ座標を2回入力したかどうかを確認するコードを書くのを手伝ってくれる人はいますか?

コードの一部:

rc = input('Enter your next move [row space column]: ');
              row = rc(1); %users coordinates 
              col = rc(2);
                           if row<0 || col<0
                           disp('Please enter positive coordinates');
                           rc = input('Enter your next move [row space column]: ');
                           row = rc(1); 
                           col = rc(2);
                           end
                           if row>size || col>size
                           disp('Please enter cordinates with in the game board');
                           rc = input('Enter your next move [row space column]: ');
                           row = rc(1);
                           col = rc(2);
                           end

正の値と大きすぎる値を既に確認しましたが、ユーザーが同じ座標を 2 回入力していないことを確認し、エラー メッセージが表示されているかどうかを確認したいと思います。どんな助けでも大歓迎ですありがとう

4

1 に答える 1

0

コメント セクションで既に述べたように、ユーザーが同じ座標を 2 回入力しないようにするには、有効な座標のすべてのペアを配列に格納して、次にユーザーが新しい座標のペアを入力したときに、次のことができるようにする必要があります。それらがすでに存在するかどうかを確認します。

座標用と座標用rowvの2 つの配列を作成しました。rowcolvcol

次に、論理演算子andを関係演算子と組み合わせてwhile使用​​して、次の条件を実装しました。 any&==

% Check that the point is not repeated.
while any((rowv == row) & (colv == col))

そのため、ユーザーが座標を繰り返し入力している限り、有効なペアが入力されるまで再試行するよう求められます。

次のコードは完全に機能する例なので、すぐにテストできます。

% Game board size.
size = 4;

% Ask for number of points.
n = input('Number of points: ');

% Preallocate arrays with -1.
rowv = -ones(1,n);
colv = -ones(1,n);

% Iterate as many times as points.
for p = 1:n
    % Ask for point coordinates.
    rc = input('Enter your next move [row space column]: ');
    row = rc(1);
    col = rc(2);

    % Check that coordinates are positive.
    while row<0 || col<0
        disp('Please enter positive coordinates');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end

    % Check that coordinates are within the game board.
    while row>size || col>size
        disp('Please enter cordinates within the game board');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end

    % Check that the point is not repeated.
    while any((rowv == row) & (colv == col))
        disp('Coordinates already exist. Please enter a new pair of cordinates');
        rc = input('Enter your next move [row space column]: ');
        row = rc(1);
        col = rc(2);
    end

    % The point is valid.
    % Store coordinates in arrays.
    rowv(p) = rc(1);
    colv(p) = rc(2);
end
于 2016-04-23T23:53:17.790 に答える