2011-04-12 115 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