Skip to content

Instantly share code, notes, and snippets.

@thmain
Created October 18, 2017 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/f3ffe7921394a70c95d6e074d24db9de to your computer and use it in GitHub Desktop.
Save thmain/f3ffe7921394a70c95d6e074d24db9de to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.HashMap;
public class NutsAndBoltsHashMap {
public static void match(char[] nuts, char[] bolts) {
//Create a HashMap for nuts, nut as key and its position as value
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < nuts.length; i++) {
map.put(nuts[i], i);
}
//for each bolt , check for the nut in map
for (int i = 0; i < bolts.length; i++) {
char bolt = bolts[i];
if (map.containsKey(bolt)) {
nuts[i] = bolts[i];
} else {
System.out.println("for bolt " + bolt + " no nut is present.");
return;
}
}
System.out.println("(Hash Map) Matched nuts and bolts are: ");
System.out.println(Arrays.toString(nuts));
System.out.println(Arrays.toString(bolts));
}
public static void main(String[] args) {
char[] nuts = {'$', '%', '&', 'x', '@'};
char[] bolts = {'%', '@', 'x', '$', '&'};
match(nuts, bolts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment