0

I am a cs student and i have an assignment that I'm not sure how to complete here is the prompt,

"Develop a Java console application for a simple game of guessing at a secret five-digit code (a random number from 10000 to 99999). When the user enters a guess at the code, the program outputs two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840 and the user guesses 83241, the digits 3 and 4 are in the correct positions. Thus, the program should respond with 2 (number of correct digits) and 7 (sum of the correct digits). Allow the user to guess until s/he gets it correct."

basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together. Here is my code so far.

Random rand = new Random();
    int secretNumber = rand.nextInt(99999 - 10000 + 1) + 10000;
    System.out.println(secretNumber);
    Scanner consoleScanner = new Scanner(System.in);
    int guess;
    do {
        System.out.print("Please enter a 5-digit code (your guess): ");
        guess = consoleScanner.nextInt();
        if (guess == secretNumber)
            System.out.println("****HOORAY!  You solved it.  You are so smart****");
        else if (guess > 99999 || guess < 10000)
            System.out.println("Guess must be a 5-digit code between 10000 and 99999.\n");
    } while (guess != secretNumber);

any help would be greatly appreciated.

chubupanda
  • 23
  • 4

6 Answers6

1

Integer.toString(int) returns the string representation of an integer. You can compare the strings returned from Integer.toString(secretNumber) and Integer.toString(guess) character-by-character to determine which digits differ.

thomasd
  • 2,593
  • 1
  • 22
  • 23
  • Not an answer to the question "basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together." – Simon Kraemer Mar 15 '16 at 19:18
  • 1
    @SimonKraemer Assuming that the asker knows how to compare strings, `Integer.toString(int)` is exactly an answer to the question. – thomasd Mar 15 '16 at 19:23
  • Just writing *"`Integer.toString(int)` returns the string representation of an integer."* without any context is not an answer to anything except to the question how to convert an int to a String. Also isn't converting the values to String and than back again to get the sum a bit of an overkill? – Simon Kraemer Mar 15 '16 at 19:28
  • 1
    Simon is going through and down voting everyone, and we are all saying the same thing, and we are all right. Go char by char through a string of the number and compare the integer values. It is the obvious answer and the one literally everyone said. I have no idea what Simon thinks is going on here. – Max von Hippel Mar 15 '16 at 19:28
  • 1
    Simon I think the convention here is that we try not to say more than we have to. Just saying what thomasd did is MORE than enough to figure out the rest. And yeah it's a bit overkill, but so what? He's lose like a byte of wasted memory. Plus, that's what the linkers and loaders are doing anyway - Strings resolve to char arrays. – Max von Hippel Mar 15 '16 at 19:30
  • @MaxvonHippel None of you were answering the question OP asked. Look at the edits that were made since I made my comments and downvoted. None of the answers was an answer. – Simon Kraemer Mar 15 '16 at 19:30
  • @MaxvonHippel That's a great approach to teach people to create good code. Just use the "easiest" solution that might somewhat work.... – Simon Kraemer Mar 15 '16 at 19:32
  • BTW: I removed my downvotes after the answer was corrected. I still don't think it's the "right" way to do it but so be it. – Simon Kraemer Mar 15 '16 at 19:33
  • 1
    Simon your answer employs a huge amount of division which is more computationally expensive than conversion to a char array anyway. – Max von Hippel Mar 15 '16 at 19:33
  • 1
    @MaxvonHippel: How exactly do you think `Integer.toString` works? Right: It does exactly the same divisons I do. But it also converts the result to their char representation.... – Simon Kraemer Mar 15 '16 at 19:45
  • 1
    Just researched a bit and you are correct (source: http://stackoverflow.com/questions/25505720/how-does-integer-tostring-works-internally). That said, it would not surprise me if letting the compiler do this under the hood turned out to be faster than doing it by hand. Do you know whether or not your hand written code beats the many efficiency tricks of the compiler? – Max von Hippel Mar 15 '16 at 19:49
  • 1
    @MaxvonHippel I am more active in `C++` and there the compilers can do amazing optimizations. I don't think that one should try to optimize too hard but rather keep the code readable. Even in this case the results are pretty close, yet the to char from char conversion doesn't get optimized as it seems... The String version has a slightly larger compilation output (617 bytes vs 811 bytes). So it really depends on the use case. But arithmetic operations can be pretty much optimized by most compilers AFAIK. – Simon Kraemer Mar 15 '16 at 19:55
  • 1
    @MaxvonHippel And please don't misunderstand me: Smaller code output doesn't always mean that the program runs faster - but it is at least an indicator on the efficiency, considering speed and used memory. – Simon Kraemer Mar 15 '16 at 19:57
1

You have a number. I'm going to call it blarg. Let's say blarg is a double. You also have a number called input.

    String blargString = Double.toString(blarg);
    String inputString = Double.toString(input);
    ArrayList<Integer[]> indexNumberList = new ArrayList<Integer[]>();
    int n = 0;
    for (char c : blargString.toCharArray()) {
        n++;
        if (c == inputString.toCharArray()[n]) {
            Integer[] entry = new Integer[2];
            entry[0] = n;
            entry[1] = Character.getNumericValue(c);
            indexNumberList.add(entry);
        }
   }

Now you have a list of Integer pairs. Do what you will with it. For each pair, entry[0] is the location in the number, the index, and entry[1] is the value.

Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
  • 1
    Now it does. And I think it did answer the question, the obvious (in my opinion) connotation of my original answer was to go char by char and figure it out. As I did in the code above. However, since you appear to think implicit aid is inappropriate, I made my answer explicit. – Max von Hippel Mar 15 '16 at 19:27
0

you could use integers, use modulus and divide to get the digit you want.

53840 % 100000 / 10000 = 5
53840 % 10000 / 1000 = 3

loop and compare

0

Here's how I'd go about solving that problem. My solution is quick but probably naive. Convert the number the user enters and your generated number to strings and then to two arrays of 5 bytes each. Scan through the arrays and compare two corresponding bytes at a time. Let the user know that the position of a digit was guessed correctly if two corresponding bytes are equal. Below, I show you how you can get the array of bytes you need.

byte[] a =  Integer.toString(guess).getBytes();
byte[] b =  Integer.toString(secretNumber).getBytes();
akinfermo
  • 166
  • 7
  • 1
    This definitely gets points for creativity! But I think it's totally unnecessary to convert to bytes, easier to keep as chars or even as an array of ints. The conversion to and from bytes is probably more expensive than char <-> int and almost definitely beyond what OP can easily do rn. – Max von Hippel Mar 15 '16 at 19:36
  • 1
    @MaxvonHippel I agree. I thought of that solution on the fly. Using the charAt() method of the String class is a better solution. Xoce shows how to do so in his answer. – akinfermo Mar 15 '16 at 19:53
0

So you have 2 5-digit numbers that you need to compare. I would recommend you to do this with a loop:

//Make copies so we can modify the value without changing
// the original ones.
int tempGuess = guess;
int tempSecret = secretNumber;

//Create variables for the output
int numCorrect = 0;
int sumCorrect = 0;
for(int i = 0; i < 5; i++) //for each of the digits
{
     //Get the last digit of each number and remove it from the number:
     int lastGuess = tempGuess%10;
     tempGuess/=10;
     int lastSecret = tempSecret%10;
     tempSecret/=10;

     //Compare both digits:
     if(lastGuess == lastSecret)
     {
         //Found a match: Increas number of found by one
         numCorrect++;
         //Add value of digit to sum
         sumCorrect += lastGuess;
     }
 }
 //numCorrect now contains the number of matching digits
 //sumCorrect now contains the sum of matchig digits
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
  • Simon I think this presumes the input and secret number are of equal length, as you are basically truncating off the last digit each time. Your solution would thus say I'm nowhere close if I guessed CAT and the word was CATS. – Max von Hippel Mar 15 '16 at 19:37
  • @MaxvonHippel That condition is already checked by OP `if (guess > 99999 || guess < 10000)`. So there is no reason to worry about that. – Simon Kraemer Mar 15 '16 at 19:40
0

The solution can be address like:

  • define an counter for the coincidences and an accumulator for the adition of those
  • make a loop through the guess and compare char by char if the input at any given char match the random number, if so:
  • increase counter by one and add to the accumulator the integer value of the char.

Example:

final String s1 = Integer.toString(secretNumber);
final String s2 = Integer.toString(guess);
for (int i = 0; i < s1.length(); i++) {
    if (s1.charAt(i) == s2.charAt(i)) {
        counter++;
        acumm = Character.getNumericValue(s1.charAt(i));
    }
}
System.out.println("There is/are " + counter + " coincidences");
System.out.println("The addition of those is: " + acumm);
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97