Multiply the same numbers in a given array
- We can multiply same/similar numbers in the given array by using for -loops and hashmap.
Examples:
Input: { 2, 3, 4, 2, 3, 4, 4 }
o/p: 4 9 64
Here, 2 repeated 2 times, 3 repeated 2 times and 4 repeated 3 times. So multiply the same numbers in the given array (2*2, 3*3, 4*4*4)
Input: { 2, 3, 4, 2, 3, 4, 9 }
o/p: 4 9 16 9
Program:
import java.util.HashMap;
import java.util.Set;
public class multiplySameNumbers {
public static void main(String[] args) {
int[] a = { 2, 3, 4, 2, 3, 4, 9 };
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int n : a) {
if (hm.containsKey(n)) {
hm.put(n, hm.get(n) + 1);
} else {
hm.put(n, 1);
}
}
System.out.println("Given values in array");
for (int n : a) {
System.out.print(n + " ");
}
// printing count of each value in array
System.out.println("\nHash Map key and values=" + hm);
Set<Integer> s = hm.keySet();
int value = 1;
System.out.println("Multiply same numbers in given array");
for (int sv : s) {
for (int i = 0; i < hm.get(sv); i++) {
value = value * sv; // based on count value,multiply number in array
}
System.out.print(value + " ");
value = 1;
}
}
}
Output:
Multiply same numbers in given array |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.