MATLAB:如何使用FOR循环将项目分组

时间:2013-07-25 02:14:01

标签: matlab

我需要一些帮助来解决我在课堂上分配的问题。这是我们对for loops的介绍。这是问题所在:

考虑下面的谜语。

飞机失事后,3人被困在荒岛上。他们花了 第一天聚集一堆香蕉。他们决定把他们算在内 第二天早上,在每个人之间平等分配。

在半夜,每个人都决定不信任他们 同船们。因此,每个人依次起床并将桩分成3个 平等的部分和隐藏他们的份额。但是,将它分开时 剩下的是一根香蕉,他们给了附近的一只熊。什么时候 早上来,小组将剩余的桩分成3个相等的桩 并留下一个香蕉,然后将它们交给附近的熊。

什么是解决谜语的最小堆?

写一组for循环,可以解决任何数字的这个谜题 人和任何数量的熊。

我真的不确定如何解决这个问题。我认为它应该涉及两个for loops(一个在另一个中?)。

到目前为止,这就是我的全部内容:

function pile = IslandBananas(numpeople, numbears)
for pilesize=1:10000000
ultimatepile=(1/3)*((2/3)*(pile-1)-1) = 1;
end
for pile>1
ultimatepile=pile-1
end

我不确定这是多么正确,所以我非常感谢你的意见。

1 个答案:

答案 0 :(得分:0)

我现在无法访问MATLAB,但我认为您只需要这样:

p = input('Enter the number of people: ');
while(ceil(p) ~= floor(p))    %    `p` has to be an integer value.
    p = input('Nice try. Enter the number of people: ');
end
b = input('Enter the number of bears: ');
while(ceil(p) ~= floor(p))    &    `b` has to be an integer value.
    p = input('Nice try. Enter the number of bears: ');
end

for min_share = 1:Inf
    S = min_share*p + b;    %    `S` will hold the size of the pile.

    for ii = 1:p
        if(ceil(S) ~= floor(S))    %    The pile must have an integer size at the end of every itereation.
            break;
        end
        S = (S/2)*p + b;
    end

    if(ceil(S) == floor(S))    %    If the size of the current pile is an integer, we have found our answer.
        break;
    end
end