Java Program to check for similar digits
The way you are computing the lower digit is correct, but the way you compute the upper one is wrong: you need to integer-divide the number by ten before obtaining the remainder:
int f = (a/10) % 10;
Since the output that you give is always the same, you would be better off combining the four conditions into one with OR
operator, like this:
if ((l==j) || (f==d) || ... )
How to find duplicate values based upon first 10 digits?
A straight-forward loop solution would be
List<String> a1 = Arrays.asList("1070045028000", "1070045028001",
"1070045052000", "1070045086000", "1070045052001", "1070045089000");
Set<String> unique = new HashSet<>();
Map<String,String> map = new HashMap<>();
for(String s: a1) {
String firstTen = s.substring(0, 10);
if(!unique.add(firstTen)) map.put(firstTen, s);
}
for(String s1: a1) {
String firstTen = s1.substring(0, 10);
map.computeIfPresent(firstTen, (k, s2) -> s1.compareTo(s2) < 0? s1: s2);
}
List<String> minDup = new ArrayList<>(map.values());
First, we add all duplicates to a Map
, then we iterate over the list again and select the minimum for all values present in the map.
Alternatively, we may add all elements to a map, collecting them into lists, then select the minimum out of those, which have a size bigger than one:
List<String> minDup = new ArrayList<>();
Map<String,List<String>> map = new HashMap<>();
for(String s: a1) {
map.computeIfAbsent(s.substring(0, 10), x -> new ArrayList<>()).add(s);
}
for(List<String> list: map.values()) {
if(list.size() > 1) minDup.add(Collections.min(list));
}
This logic is directly expressible with the Stream API:
List<String> minDup = a1.stream()
.collect(Collectors.groupingBy(s -> s.substring(0, 10)))
.values().stream()
.filter(list -> list.size() > 1)
.map(Collections::min)
.collect(Collectors.toList());
Since you said that there will be only 2 duplicates per key, the overhead of collecting a List
before selecting the minimum is negligible.
The solutions above assume that you only want to keep values having duplicates. Otherwise, you can use
List<String> minDup = a1.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(s -> s.substring(0, 10), Function.identity(),
BinaryOperator.minBy(Comparator.<String>naturalOrder())),
m -> new ArrayList<>(m.values())));
which is equivalent to
Map<String,String> map = new HashMap<>();
for(String s: a1) {
map.merge(s.substring(0, 10), s, BinaryOperator.minBy(Comparator.naturalOrder()));
}
List<String> minDup = new ArrayList<>(map.values());
Common to those solutions is that you don’t have to identify duplicates first, as when you want to keep unique values too, the task reduces to selecting the minimum when encountering a minimum.
Finding Whether Two Numbers Share a Digit
You should reset testSecondNumber before the next testFirstNummber loop.
In your code, the inner loop is called only once, because testSecondNumber goes to 0 and is not reset.
The right solution is:
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
if ((firstNumber < 10 || firstNumber > 99) || (secondNumber < 10 || secondNumber > 99)) {
return false;
}
int testFirstNumber = firstNumber;
while (testFirstNumber != 0) {
int testSecondNumber = secondNumber;
while (testSecondNumber != 0) {
if ((testFirstNumber % 10) == (testSecondNumber % 10)) {
return true;
}
testSecondNumber /= 10;
}
testFirstNumber /= 10;
}
return false;
}
How to check duplicate numbers and print out the read input numbers in the same order that they were read (excluding all duplicates.)
Use a HashMap to keep track of numbers already seen. Only add to your output string if it is a new number. You can modify your code with the following:
int[] array = new int[1000];
Scanner input = new Scanner(System.in);
int index = 0;
while(input.hasNext()) {
array[index] = input.nextInt();
index++;
}
HashMap<Integer, Boolean> seenNumbers = new HashMap<Integer, Boolean>();
String result = "";
for (int i = 0; i < index; i++) {
int value = array[i];
if (!seenNumbers.containsKey(value)) {
result += " " + value;
seenNumbers.put(value, true);
}
}
System.out.println(result);
How to compare different positions of digits of two integers?
I suggest doing it without storing the digits individually as a list. First convert both to String. Then, run a loop to iterate over each character. If the characters at the current index of both strings are the same, display "A". Else, check - if the character at all exists in targetNumber
; if it does, display "S", else display "I".
public static void function(int targetNumber, int userGuess){
String a = Integer.toString(targetNumber),
b = Integer.toString(userGuess);
for(int i=0 ; i<4; i++){
if(a.charAt(i) == b.charAt(i))
System.out.print("A");
else{
if(a.indexOf(b.charAt(i)) == -1)
System.out.print("I");
else
System.out.print("S");
}
}
}
In your case, since your targetNumber is 1743 and userGuess is 1564, you should call
function(1743, 1564);
which will display the output as
AIIS
Related Topics
Several Ports (8005, 8080, 8009) Required by Tomcat Server At Localhost Are Already in Use
Optimizing Multiple If-Else Condition in Java
How to Restart a Java Program Here
Regular Expression to Match a Backslash Followed by a Quote
How to Link Feature and Step Definition in Cucumber
Changing Scene When a Button Is Pressed Fxml
Default Value in Lombok. How to Init Default With Both Constructor and Builder
How to Return a List of Specific Type Instead of List<Object[]> in Hibernate
How to Do Post Request With Raw Data Via Spring Rest Template
How to Count the Rows in Hibernate Query Language
Passing Empty List as Parameter to JPA Query Throws Error
How to Apply Spring Boot Filter Based on Url Pattern
Status Expected:<200> But Was:<404> in Spring Test
How to Retrieve Mapping Table Name for an Entity in JPA At Runtime
How to Get Amount of Tens in a Int
Launching Spring Application Address Already in Use
Beanutils Copyproperties API to Ignore Null and Specific Propertie
Find Maximum Score or the Maximum Average Score of Candidate Scores Given in Two Dim Array