2
votes

I need some help in this Turbo Pascal problem:

Two integers are said to be brothers if each digit of N1 appears at least once in N2 and vice versa. Examples: if N1 = 1164 and N2 = 614 the program will display N1 and N2 are brothers, if N1 = 504 and N2 = 455 the program will display N1 and N2 are not brothers

My question is: How to check whether the 2 integers are brothers or not? This is my work:

function brother(n1, n2: integer): boolean;
var 
  test: boolean; 
  ch1, ch2: string; 

begin 
  chr(n1, ch1);
  chr(n2, ch2);
  i := 0;
  repeat 
    j := 0;
    i := i + 1;
    test := false;
    repeat
      j := j + 1;
      if ch1[i] = ch2[j] then 
        test := true;
    until (test = true) or (j = length(ch2));
  until (test = false) or (i = length(ch1)); 
  brother := test;
end;

when I run this, it always print ("integers are brothers") even when I put 504 and 455, I want to know where the mistake is.

2
Here's some lubbely pseudo code for you!... I think part of your problem stems from your function being a bit confused... try this: make a loop (loops through each char of str1) that uses a function which itself is passed one char at a time (1 char at a time of str1), and sees if the char exists in a given string (str2), increment a 'yes' counter or if it's a 'no' at any point then stop all testing. Once you have reached the end of the given string (str2) and have a number of yes = the length of the given string = string is brother.Paul Zahra
Your code looks wrong. chr is a pseudo-function that converts an integer to a single char. I assume that in your real code, you have something like str(n1, ch1);. You also had (n1,n2:integers) as your parameter list (I corrected that), and that is not compilable code either.Rudy Velthuis

2 Answers

1
votes

Try something like this instead:

function contains(s: string; ch: char): boolean;
var
  i: integer;
begin
  contains := false;
  for i := 1 to length(s) do
    if s[i] = ch then
      contains := true;
end;

function brother(n1, n2: integer): boolean;
var
  test: boolean;
  ch1, ch2: string;
  i: integer;
begin
  str(n1, ch1);
  str(n2, ch2);
  test := true; { assume "brotherhood" }

  for i := 1 to length(ch1) do
    if not contains(ch2, ch1[i]) then
      test := false; { obviously no brothers after all }

  { must test both ways, so (n1=455, n2=504) fails too } 
  for i := 1 to length(ch2) do
    if not contains(ch1, ch2[i]) then
      test := false;

  brother := test;
end;

Instead of for, you can use repeat until too.

-1
votes

You need pascal's else/if variant and there you have to check it's equality.