finding if a digit repeats itself an equally at 2 different numbers

i got an assignment to see if the digit "d" repeats itself equally in "n1" and "n2" without using loops and using recursive function only. I've managed to find the difference between these numbers (the difference between the times 'd' appears in "n1" and in "n2"). now i have to return a logic "1" or "0". "1" if the difference is 0. "0" if the difference is not 0.

6 commentaires

function r=check_numbers(n1,n2,d)
if n1==0 && n2==0;
r=0;
else
x=(((mod(n1,10)==d)-(mod(n2,10)==d) + ...
(check_numbers(floor(n1/10),floor(n2/10),d))));
end;
What is your question then?
i can't return the logic true or false
What is actually allowed in your function? Because the following does not use any loop (or recursive function):
r = sum(num2str(n1)-'0' == d) == sum(num2str(n2)-'0' == d)
i must use recursive function. and not allowed "num2str".
Same without num2str. Still does not need recursion:
decompose = @(n) floor(mod(n, 10.^(1:ceil(log10(n)))) ./ 10.^(0:ceil(log10(n)-1)));
r = sum(decompose(n1) == d) == sum(decompose(n2) == d)

Réponses (2)

r = ~x
should do the trick if x is the difference that can be 0 or greater

6 commentaires

i have tried it already... the difference enters in the function "r".
Adam
Adam le 11 Mar 2015
Modifié(e) : Adam le 11 Mar 2015
Ah yes, I see, the recursion gets messed up by doing that. I forgot it was a recursive function.
Simplest option is probably to call this from inside another function. Are you only allowed to use the one recursive function and nothing else?
I guess you could put a recursion level counter in then and only convert to logical if you are at the top level of recursion. It's ugly, but then recursion is pretty ugly in general. I got lost in a recursive function yesterday and gave up in the end!
Guillaume
Guillaume le 11 Mar 2015
Modifié(e) : Guillaume le 11 Mar 2015
That's the only way you could do it using a single function that recurse on itself since you need to keep track of all digits at all level of recursion.
This is kind of against the spirit of recursion though.
Recursion is ill suited to this problem anyway.
David Shapiro
David Shapiro le 11 Mar 2015
Modifié(e) : Image Analyst le 11 Mar 2015
this is the solution... not close to mine... http://s1.postimg.org/604pdqxjj/hw5_q3.jpg

1 commentaire

Urgh, 3 explicit hasty returns and 5 elseif clauses...if I could use an emoticon it'd be throwing up!

Cette question est clôturée.

Tags

Clôturé :

le 20 Août 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by