【问题标题】:While loop infinite loopWhile循环无限循环
【发布时间】:2015-06-25 23:04:35
【问题描述】:

所以我的挑战是制作一个 MxM 零矩阵,但其中大约 15% 的值是 1。所有这些 1 的“总和”需要尽可能接近 15%,同时还要使其成为另一个函数的全局变量,但由于某种原因,它有时会陷入无限循环。有谁知道为什么会这样?

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

【问题讨论】:

  • “有时”?究竟是哪个循环?对于哪些输入参数会卡住?
  • 嗯,有时它可以工作并给我我正在寻找的答案,但每隔一段时间,它只是在垂直 0 后 0 后无限输出 0。我认为问题可能出在while循环中。如果我输入 randomking1(4,4),它会输出 3 或 4。如果我输入 randomking1(5,5),它会输出 4 或 5。但是对于所有这些输入,随机它会卡在循环中,有时是第一次进入,有时是第五次运行。
  • 我输入的矩阵数量越多,它似乎就越容易卡住。

标签: matlab if-statement while-loop infinite-loop


【解决方案1】:

我建议不要尝试使用蛮力方法找到解决方案,而是将 15% 的 K 放在公共牌上并然后随机化。

function [ board ] = randomking1( a,b )

board_size = a*b;
% finds number of kings needed for board size
kings = ceil(0.15*board_size); 

% creates game board (as a linear vector) of ones and zeros
% ones being the kings on the board.
board = [ones(1,kings), zeros(1, board_size-kings)];

% shuffle the board
board = board(randperm(board_size));

% create the a x b matrix out of the linear vector
board = reshape(board,[a,b]);
end

示例运行:randomking1(3,3):

board_size =

     9


kings =

     2


board =

     1     1     0     0     0     0     0     0     0


board =

     0     1     0     0     0     1     0     0     0


board =

     0     0     0
     1     0     0
     0     1     0

【讨论】:

  • 甜蜜!非常感谢你,这对我的项目很有帮助!
猜你喜欢
  • 2014-03-29
  • 2012-12-24
  • 2021-02-20
  • 2013-02-22
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多