2011-04-12 99 views
3

在外星人的世界里,这些生物的遗传密码是在基-4系统(四元)中。对“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); 
+0

尝试REGEXP功能。 – yuk 2011-04-12 14:34:36

+1

“222”算作多少种疾病? – 2011-04-12 14:51:41

+0

它算作2种疾病 – 2011-04-12 14:53:26

回答

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

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); 
+0

这是比我更优雅的解决方案 – MikeKusold 2011-04-12 16:12:57