Created
October 18, 2017 02:15
-
-
Save thmain/f3ffe7921394a70c95d6e074d24db9de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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