2

I'm trying to write a program in Java that checks if at least one digit of one of the numbers, matches one digit of the other number. For example, if the two numbers are 238 and 345 it should return a certain string.
So far this is what I have, but it only works properly for the right most digit:

if ((computerGuess/10) == (userGuess/10) || (computerGuess%10) == (userGuess%10) || (computerGuess%10) == (userGuess/10) || (userGuess%10) == (computerGuess/10)) {
                System.out.println("You have won S1000");
                break;
            }
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • Does this answer your question? [Best way to check if a number contains another number](https://stackoverflow.com/questions/31703110/best-way-to-check-if-a-number-contains-another-number). Not the same language, but you can easily adapt it to java – jhamon Jul 28 '20 at 12:39
  • 1
    @jhamon OP doen't ask about JS. – Matt Jul 28 '20 at 12:40

4 Answers4

2

One clean solution would be to convert each number into a set of digits, and then check for overlap:

public Set<Integer> getDigits (int input) {
    Set<Integer> digits = new HashSet<>();
    while (input > 0) {
        digits.add(input % 10);
        input /= 10;
    }

    return digits;
}

int computerGuess = 238;
int userGuess = 345;
Set<Integer> computerDigits = getDigits(computerGuess);
Set<Integer> userDigits = getDigits(userGuess);
computerDigits.retainAll(userDigits);

if (computerDigits.size() > 0) {
    System.out.println("There is an overlap: " + computerDigits.toString());
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

The reason is always you are using "10", either '/10' or '%10'.

The best solution would convert them into string, and check for sub-string.

String computerGuessStr = new String (computerGuess);
String userGuess = new String (userGuess);

for (int i=0;i<computerGuessStr.length();i++){

char computerChar = computerGuessStr.getCharAt(i);

if(userGuess.contains(computerChar)){
//do something
} else {
//do something
}
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
0

Something like this?

int computerNumber = 543;
int guess = 238;
List<Integer> numbers = Stream.of(10, 100, 1000).map(n -> guess % n).collect(Collectors.toList());

Stream.of(10,100,1000).map(n -> computerNumber % n).anyMatch(num -> numbers.contains(num));
godzsa
  • 2,105
  • 4
  • 34
  • 56
0

Another option is the plain old loop. This will work with any length number.

boolean digitMatch(int num1, int num2)
{
    for ( ; num1 > 0; num1 /= 10) {
        // Get a digit from num1
        int digit1 = num1 % 10;
        for (int n2 = num2; n2 > 0; n2 /= 10) {
            // Get a digit from num2
            int digit2 = n2 % 10;
            // compare
            if (digit1 == digit2) return true;
        }
    }
    return false;
}

Note: you need to add a little extra code for negative numbers.

001
  • 13,291
  • 5
  • 35
  • 66