Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

genetic code and zombies!

Tags:

matlab

In an alien world, the genetic codes of the creatures are in base-4 system(quartenary). The pairs "13" and "22" are considered as genetic disorders. With a genetic code of lenght n, if there are at least n/4 disorders, the creature becomes a zombie!! For example with n=5, the creature with genetic code 01321 has the disorder, but not a zombie while the creature with genetic code 22132 is a zombie( because he has two disorders which is >n/4).

Now I need to write a MATLAB program and get a value n from the user, which is easy, and display the number of creatures and how many of them are zombies

Here is what i've written so far, I can't figure out how to determine the creatures with has genetic codes of a zombie. I'd really appreciate your ideas and help.Thank you

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);
like image 836
matlab padawan Avatar asked Jul 30 '26 04:07

matlab padawan


1 Answers

I recommended you in my comment to try REGEXP function. But actually STRFIND would suite much better if you want to count overlaps, like count '222' as 2 disorders.

So you need something like this:

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

In addition, you can do n=0 as the first line instead of duplicating the input line. And correct for-loop to end at nOfCreatures-1.

EDIT

For the bonus a vectorized solution:

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);
like image 74
yuk Avatar answered Aug 02 '26 18:08

yuk