在外星世界中,生物的遗传密码属于基础4系统(四分之一)。对“13”和“22”被认为是遗传性疾病。使用长度为n的遗传密码,如果至少有n / 4种疾病,该生物就变成了僵尸!例如,当n = 5时,具有遗传密码01321的生物具有疾病,但不具有僵尸,而具有遗传密码22132的生物是僵尸(因为他具有两种> n / 4的疾病)。
现在我需要编写一个MATLAB程序并从用户那里获得一个值n,这很简单,并显示生物的数量以及它们中有多少是僵尸
这是我到目前为止所写的内容,我无法弄清楚如何确定具有僵尸遗传密码的生物。我真的很感激你的想法和帮助。谢谢你
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);
答案 0 :(得分:2)
我在评论中建议您尝试使用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循环更正为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);
答案 1 :(得分:0)
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
这是伪代码中的一般概念。
以下链接可帮助您将其转换为实际代码:String Handling