在一个陌生的世界里,生物的遗传密码是以四进制为基数的。配对"13“和"22”被认为是遗传疾病。有了长度为n的遗传密码,如果有至少n/4的紊乱,这个生物就会变成僵尸!!例如,在n=5中,遗传密码为01321的生物有这种疾病,但不是僵尸,而遗传密码为22132的生物是僵尸(因为他有两种疾病,大于n/4)。
现在,我需要编写一个MATLAB程序,并从用户那里获得一个值n,这很容易,并显示生物的数量以及它们中有多少是僵尸
这是我到目前为止所写的,我不知道如何确定具有僵尸遗传密码的生物。我真的很感谢你的想法和help.Thank你
n=input('Enter the length of the genetic sequence: ');
while (n<4) || (mod(n,1))~=0
disp('Invalid input!')
n=input('Enter the length of the genetic sequence: ');
end
nOfCreatures=4^n;
count=0;
for i=0:nOfCreatures
k=dec2base(i,4);
end
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);
发布于 2011-04-13 00:10:11
我在我的评论中推荐你尝试REGEXP功能。但实际上,如果你想计算重叠,那么STRFIND会更适合,比如将'222‘算作2种紊乱。
所以你需要这样的东西:
k=dec2base(i,4,n); %# use n to include trailing 0s, just for other possible types of disorders
m = [strfind(k,'13') strfind(k,'22')];
if numel(m) > n/4
count = count+1;
end
此外,您可以将n=0
作为第一行,而不是重复输入行。并将for-loop更正为以nOfCreatures-1
结尾。
编辑
对于额外的好处,一个矢量化的解决方案:
nOfCreatures=4^n;
k=cellstr(dec2base(0:nOfCreatures-1,4,n));
m = cellfun(@numel,strfind(k,'13')) + cellfun(@numel,strfind(k,'22'));
count = sum(m > n/4);
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);
发布于 2011-04-12 23:32:54
error = 0
for i<n.len:
if n[i] == 1:
if n[i+1] == 3:
error = error + 1
if n[i] == 2:
if n[i+1] == 2:
error = error + 1
if error >= n/4
zombie = true
这是psuedo代码中的一般思想。
这里有一个链接可以帮助您将其转换为真正的代码:String Handling
https://stackoverflow.com/questions/5636540
复制相似问题