Skip to content

Commit 5e426b2

Browse files
committed
Added NutsAndBolt Problem Using Hashmap Approach in java
1 parent ea7d776 commit 5e426b2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

NutBoltWithHashmap.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.Arrays;
2+
import java.util.HashMap;
3+
4+
public class NutBoltWithHashmap{
5+
6+
public static void domatch(char[] nuts, char[] bolts) {
7+
8+
//Create a HashMap for nuts, nut as key and its position as value
9+
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
10+
for (int j = 0; j < nuts.length; j++) {
11+
map.put(nuts[j], j);
12+
}
13+
14+
//for each bolt , check for the nut in map
15+
for (int j = 0; j < bolts.length; j++) {
16+
char bolt = bolts[j];
17+
if (map.containsKey(bolt)) {
18+
nuts[j] = bolts[j];
19+
} else {
20+
System.out.println("for bolt " + bolt + " no nut is present.");
21+
return;
22+
}
23+
}
24+
System.out.println(" Matched nuts and bolts are: ");
25+
System.out.println(Arrays.toString(nuts));
26+
System.out.println(Arrays.toString(bolts));
27+
}
28+
29+
public static void main(String[] args) {
30+
char[] nuts = {'$', '%', '&', 'x', '@'};
31+
char[] bolts = {'%', '@', 'x', '$', '&'};
32+
domatch(nuts, bolts);
33+
}
34+
}

0 commit comments

Comments
 (0)