简体   繁体   中英

Checking two integer array elements and positions in java

I have two integer array that keeps number of digits entered by user. User enters two number. I want to print out the similarity of two number is the count of the digits that occur in both numbers in different positions, and the count of digits that occur in the same positions.

First of all your method is not complete. You are iterating 10 times in both the loops for checking equal numbers which is wrong, you only have to iterate j times for the secret number and i times for the guess number. You can rather use vectors.

This solves the correct numbers and for wrong position you have to maintain an array int occurrences[10] for your secret number and occurence[digit] = 1 indicates that digit is present in secretNumberDigitsArray . First make this array and while checking equals condition, check if the digit is present in occurences .

If you don't want repeated occurrences that are equal, first get the equal ones and make occurrences[equal] = 0 and then iterate over guessNumberDigitsArray .

You can also use a hash table that stores the number and the frequency of its occurrence instead of a plain array. It can give you more control for solving wrong places

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM