I need to compare the roman letters and get the correct integer out of it.
If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key.
The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now.
I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms.
package com.company;
import java.util.*;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
romanToArabic("MMXX");
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
for (int i = 0; i < romanLetters.size(); i++) {
System.out.println(romanLetters.get(i));
}
// retrive keys and values
for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) {
String key = (String) romanNumbersKey.getKey();
Object value = romanNumbersKey.getValue();
System.out.println(key + " " + value);
}
return 2020;
}
}
You could just Map.get each array element.
package com.company;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
System.out.println(romanToArabic("MMXX"));
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
int sum = 0;
for (int i = 0; i < romanLetters.size(); i++) {
String key = String.valueOf(romanLetters.get(i));
if (romanNumbers.containsKey(key)) {
sum += romanNumbers.get(key);
}
}
return sum;
}
}
As stated in the comments, this just answers your question of how to get values from an hashmap where keys are the array elements. It is not a solution to calculate the numeric value out of a roman number. For that, you will have to look at the next letter, and join if it is larger, before consulting the map for the final value to sum.
I'd like to suggest a completly different approach using an enum.
public enum RomanNumber {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int arabic;
RomanNumber(int arabic) {
this.arabic = arabic;
}
public int getArabicNumber() {
return arabic;
}
// This is obviously broken. IV wouldn't work for example.
public static int toArabic(String romanLetters) {
romanLetters = romanLetters.toUpperCase();
int arabicResult = 0;
for (int i = 0; i < romanLetters.length(); i++) {
char romanNumber = romanLetters.charAt(i);
// valueOf(String) returns the enum based on its name. So a String of "I" returns the RomanNumber I enum.
int arabicNumber = valueOf(String.valueOf(romanNumber)).getArabicNumber();
arabicResult = arabicResult + arabicNumber;
}
return arabicResult;
}
}
Can be used like this:
String romanNumber = "MMXX";
System.out.println(RomanNumber.toArabic(romanNumber));
Btw. every enum has an ordinal() method which returns the declaration position inside the enum. (I.ordinal() == 1 or V.ordinal() == 2) I think this could help you with the IV problem aswell. :)
Related
I am new to Java and I am trying to build up a set of tuples like this:
Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc.
Then, to define other arrays like:
int u [Slegs][G];
for instance :
u[<1,2,500>][1] = 80
u[<2,5,400>][1] = 80
u[<1,2,500>][2] = 65
u[<2,5,400>][2] = 130
and etc.
For this, I have coded as follows:
public class Model {
public static int Y = 7;
public static int K = 42;
public static int G = 3;
class Sleg {
public int i;
public int j;
public double l;
List<Sleg> Slegs = new ArrayList<Sleg>();
Map <Integer, Sleg> slTup = new HAshMap<Integer, Sleg>();
int[][] u = new int [key][G]; /* I want to define and use a key here*/
}
My problem is that I don't know how to add those tuples into the slTup a for loop, and how to assign a key to them so that I can use the key to define the u[key][G]; As well, how to assert / define that i and j are in Y and i !=j in each tuple <i,j,l>;
I would really appreciate if you could instantiate and printout u[key][g], using the given theoretical data above.
I have some code with these following as a requirement. Not sure what this application is all about, but here is my attempt to answer the questions posed:
Problem:
how to add those tuples into the slTup in a for loop
how to assign a key to them so that I can use the key to define the u[key][G];
could instantiate and printout u[key][g]
want to have a map of integers and Slegs like <1,<1,2,500>> and <2,<2,5,400>>, where the integer is the key and I can then use it in: u[Key][G]
how to assert / define that i and j are in Y and i !=j in each tuple .
Note that its not clear about what it means by "assert i and j are in Y". But, i != j can be asserted by throwing a run time exception (see Sleg class code constructor).
The program with possible answers:
import java.util.*;
public class SlegProgram {
private static int key;
public static void main(String [] args) {
// Create some Slegs
List<Sleg> slegs = Arrays.asList(new Sleg(1,2,500), new Sleg(2,5,400), new Sleg(1,2,500), new Sleg(2,5,400));
System.out.println(slegs);
// Create a Sleg Map with keys
Map <Integer, Sleg> slegMap = new HashMap<>();
for (Sleg sleg : slegs) {
slegMap.put(++key, sleg);
}
System.out.println(slegMap);
// Instantiate and printout u [key][G]
for (Map.Entry<Integer, Sleg> entry : slegMap.entrySet()) {
int [][] u = new int [entry.getKey()][Model.G];
System.out.println(Arrays.deepToString(u)); // prints array with initial values: 0
assignValuesToU(u);
}
// Assert i != j in each Sleg
Sleg illegal = new Sleg(1, 1, 90); // This will throw an exception as i and j are equal
}
private static void assignValuesToU(int [][] u) {
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < u[i].length; j++) {
u [i][j] = 80; // 80 or whatever it needs to be
}
}
System.out.println(Arrays.deepToString(u)); // prints array with assigned values
}
}
class Sleg {
private int i;
private int j;
private int k;
public Sleg(int i, int j, int k) {
if (i == j) {
throw new IllegalArgumentException("Invalid sleg parameters: " + Integer.toString(i));
}
this.i = i;
this.j = j;
this.k = k;
}
public String toString() {
return Integer.toString(i) + "-" + Integer.toString(j) + "-" + Integer.toString(k);
}
}
class Model {
public static final int Y = 7;
public static final int K = 42;
public static final int G = 3;
}
Catching the exception:
try {
Sleg illegal = new Sleg(1, 1, 90);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // This prints something like: Invalid sleg parameters: 1
}
I didn't understand your problem completely, but as per my understanding to implements Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc. like List Slegs = new ArrayList(); create separate class like below:
class slegs{
int i, j, k;
slegs(int i, int j, int k){
this.i = i;
this.j = j;
this.k = k;
}
}
You can also add your logic in the class like for assert / define or while creating an instance you can add checks.
Then you can create instance of these class and add them to list (slegs) using slegs.add(s1). To insert it in map just use the instance map.put(key, s1).
First, to use Sleg as a key of the HasMap or HasSet you have to corerctly define hashCode() and equals(). E.g. like this one:
class Sleg {
private final UUID id;
private final int i;
private final int j;
private final double l;
public Sleg(int i, int j, double l) {
id = UUID.randomUUID();
this.i = i;
this.j = j;
this.l = l;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Sleg))
return false;
Sleg sleg = (Sleg)obj;
return i == sleg.i && j == sleg.j && Double.compare(sleg.l, l) == 0;
}
#Override
public int hashCode() {
return Objects.hash(i, j, l);
}
}
Note: this class Sleg is ready to be a key of the HashMap.
Second, you want to assign an unique integer key with each Sleg instance. I could reccomend you to add this id directly into Skeg instance and increment it each time when you create new object:
class Sleg {
private final int id;
private static final AtomicInteger nextId = new AtomicInteger();
public Sleg(int i, int j, double l) {
id = nextId.incrementAndGet();
}
}
I'm taking a binary String like this:
010010010000110100001010
as a String, converting it to Integer Array like this:
int[] DD = new DD[binString.length()];
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
and I'm tying to save these Integer values in to HashMap(I have to store into a HashMap as per instructions given to me) like this:
Map<String, Integer> toMemory = new HashMap<String, Integer>();
for(int i=0;i<binString.length();i++) {
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
if((DD[i] & (DD[i]-1) ) == 0) {
toMemory.put(new String("ON"), new Integer(DD[i]));
} else {
toMemory.put(new String("ON"), new Integer(DD[i]));
}
}
for(String s: toMemory.keySet()) {
if(s.startsWith("ON")) {
System.out.println(toMemory.get(s));
}
}
The issue I'm facing here is that, only one entry is being stored in the HashMap, say {"ON",0}. And no other values are being stored. My expected output is this:
{"ON" , 1 , "OFF" , 0, "ON" , 1 .........}
Is there any better way to store the values to get my expected output? Any help will be much appreciated.
P.S: Please ignore the recurring code, and I'm relatively new to programming.
Your usage of a Map is flawed. Maps take a unique key and return a value.
You are trying to use duplicate keys. Instead, look at using a List with a wrapper class:
class ClassName {
public String status;
public int value;
public ClassName(String status, int value){
this.status = status;
this.value = value;
}
}
List<ClassName> list = new ArrayList();
To add to the list, create a new instance of your class and call List#add:
list.add(new ClassName("ON", 1));
as Infuzed Guy said, you are using the Map the wrong way. It's a unique "key to value mapping".
As long as you are using several times the same key and want to store all the dada, you need to use a List.
Here is what I could come up with the little you gave us: test it here
import java.util.LinkedList;
import java.util.List;
class Main {
public static void main(String[] args) {
class Tuple<X, Y> { //The wrapper object
public final X x;
public final Y y;
public Tuple(X x, Y y) { //Object constructor
this.x = x;
this.y = y;
}
public String toString() //Here for printing purpose
{
return "\"" + this.x + "\", " + this.y;
}
}
//Note here te use of List
List<Tuple> toMemory = new LinkedList<>();
String binString = "10100100101100101011";
int[] DD = new int[binString.length()];
for(int i=0; i < binString.length(); ++i)
{
//Here I use the char value
//to get the by subtraction
DD[i] = binString.charAt(i) - '0';
if(DD[i] == 1) //Simple check with the int value
{
toMemory.add(new Tuple<>("ON", DD[i]));
}
else
{
toMemory.add(new Tuple<>("OFF", DD[i]));
}
}
//Print the List
System.out.print("{ ");
for(Tuple s: toMemory) {
System.out.print(s +", ");
}
System.out.println("}");
}
}
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].
I started to learn java yesterday and I wrote the followind program which should print pairs of equal numbers, but when I run it I get
Exception in thread "main" java.lang.NullPointerException
at _aaaa.main(_aaaa.java:26)
Here is my program:
import java.util.*;
class pair {
int first, second;
pair() {
first = second = 0;
}
public void make_pair(int a, int b)
{
first = a;
second = b;
}
}
public class aaaa {
public static void main(String[] idontneedthis)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt(), i, lg = 0;
int[] A = new int[5010];
pair[] B = new pair[5010];
for (N <<= 1, i = 1; i <= N; ++i)
{
int var = input.nextInt();
if (A[var] > 0)
{
B[++lg].make_pair(A[var], var);
A[var] = 0;
}
else
{
A[var] = i;
}
}
if (lg == 0) System.out.print("-1");
for (i = 1; i <= lg; ++i)
{
System.out.print(B[i].first + " " + B[i].second + "\n");
}
}
}
Please tell me what is wrong or why do I get this error. I mention that if I cut the line 26 ( B[++lg].make_pair(A[var], var); ) it will write -1.
Thank you!
You need to initialise the pairs in your array:
if (A[var] > 0) {
B[++lg] = new pair(); //here
B[lg].make_pair(A[var], var);
A[var] = 0;
}
This line:
pair[] B = new pair[5010];
creates an array of 5010 pairs but until you initialise them, they are all null.
Also note that since 5010 and N are not related, you could get an ArrayIndexOutOfBoundException depending on N.
This is how I would write it. The less said the better ;)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Pair {
final int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
#Override
public String toString() {
return first + " " + second;
}
}
public class Main {
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
int numOfPairs = input.nextInt();
List<Pair> pairs = new ArrayList<Pair>();
for(int i = 0; i < numOfPairs;i++) {
int first = input.nextInt();
int second = input.nextInt();
pairs.add(new Pair(first, second));
}
for (Pair pair : pairs)
System.out.println(pair);
}
}
pair[] B = new pair[5010];
Only allocates the space for 5010 B elements. You need to instantiate each element in that array.
for(int i = 0; i <B.length;i++)
{
B[i] = new pair();
}
Style things:
Class names start with upper case letters: AAAA not aaaa.
also star imports are bad:
import java.util.*;
replace with:
import java.util.Scanner;
import java.util.HashMap;
public class target
{
public static void hash(int []a,int sum)
{
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int i;
for (i = 0; i < a.length; ++i)
map.put(a[i], sum-a[i]);
for (i = 0; i < a.length; ++i)
if(map.containsValue(a[i]) && map.get(a[i])!=null)
{
System.out.println("("+a[i]+","+map.get(a[i])+")");
map.remove(a[i]);
}
}
public static void main(String[] args)
{
int []a={1, 2, 13, 34, 9, 3, 23, 45, 8, 7, 8, 3, 2};
hash(a,11);
}
}
I want to know if there is a better and more efficient solution that the above one. Complexity of this is n. Can I do better?
Your implementation misses duplicated pairs.
You could
sort the array
iterate from the start and for each element
calculate the required complement (sum - element)
do a reverse binary search (from the end of the sorted array) looking for that precise value
if found, remove both
It boils down to the observation that, with elements sorted:
n1 < n2 < n3 < n4 < n5 < n6
the most likely pairs are coming symmetrically from both ends to the middle. Now, the worst case is still bad, but at least you don't have the hashtable overhead
As I commented, your sollution is not O(N), because the containsValue make a search of all values stored at the HashMap. To solve it, I made a different approach using your solution:
public static void newVersion(int[] a, int sum){
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
for (int i= 0; i< a.length; i++) {
map.put(sum - a[i], true);
}
for (int i = 0; i < a.length; i++) {
if (map.containsKey(a[i]) && map.get(a[i])) {
System.out.println("("+(sum-a[i])+","+a[i]+")");
map.put(a[i], false);
map.put(sum-a[i], false);
}
}
}
At the first step, it stores the "complement value" of each integer and at the second step it checks if the complement exists. If it exists, mark both pair as used.
This complexity is:
* O(N) for the first looping
* O(N) * (O(1) + O(1)) for the second loop and the containsValue and get.
* Finally: O(N) + O(N) .:. O(N) solution,
I have the following solution for this problem. The time complexity should be O(N) because the HashMap operations put, get and keySet are O(1).
import java.util.HashMap;
import java.util.Map;
/**
* Find a pair of numbers in an array given a target sum
*
*
*/
public class FindNums {
public static void findSumsForTarget(int[] input, int target)
{
// just print it instead of returning
Map<Integer, String> myMap = populateMap(input);
// iterate over key set
for (Integer currKey : myMap.keySet()) {
// find the diff
Integer diff = target - currKey;
// check if diff exists in the map
String diffMapValue = myMap.get(diff);
if(diffMapValue!=null)
{
// sum exists
String output = "Sum of parts for target " + target + " are " + currKey + " and " + diff;
System.out.println(output);
return; // exit; we're done - unless we wanted all the possible pairs and permutations
}
// else
// keep looking
}
System.out.println("No matches found!");
}
private static Map<Integer, String> populateMap(int[] input)
{
Map<Integer,String> myMap = new HashMap<Integer,String>();
for (int i = 0; i < input.length; i++) {
String currInputVal = myMap.get(input[i]);
if(currInputVal!=null) // value already exists
{
// append current index location to value
currInputVal = currInputVal + ", " + i;
// do a put with the updated value
myMap.put(input[i], currInputVal);
}
else
{
myMap.put(input[i], Integer.toString(i)); // first argument is autoboxed to Integer class
}
}
return myMap;
}
// test it out!
public static void main(String[] args)
{
int[] input1 = {2,3,8,12,1,4,7,3,8,22};
int[] input2 = {1,2,3,4,5,6,7,8,9,10};
int[] input3 = {2,-3,8,12,1,4,7,3,8,22};
int target1 = 19;
int target2 = 16;
// test
FindNums.findSumsForTarget(input1, target1);
FindNums.findSumsForTarget(input1, -1);
FindNums.findSumsForTarget(input2, target2);
FindNums.findSumsForTarget(input3, target1);
}
}
import java.util.*;
import java.io.*;
class hashsum
{
public static void main(String arg[])throws IOException
{
HashMap h1=new HashMap();
h1.put("1st",new Integer(10));
h1.put("2nd",new Integer(24));
h1.put("3rd",new Integer(12));
h1.put("4th",new Integer(9));
h1.put("5th",new Integer(43));
h1.put("6th",new Integer(13));
h1.put("7th",new Integer(5));
h1.put("8th",new Integer(32));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.");
int no=Integer.parseInt(br.readLine());
Iterator i=h1.entrySet().iterator();
boolean flag=false;
while(i.hasNext())
{
Map.Entry e1=(Map.Entry)i.next();
Integer n1=(Integer)e1.getValue();
Iterator j=h1.entrySet().iterator();
while(j.hasNext())
{
Map.Entry e2=(Map.Entry)j.next();
Integer n2=(Integer)e2.getValue();
if(no==(n1+n2))
{
System.out.println("Pair of elements:"+n1 +" "+n2);
flag=true;
}
}
}
if(flag==false)
System.out.println("No pairs");
}
}
public static void hash1(int[] a, int num) {
Arrays.sort(a);
// printArray(a);
int top = 0;
int bott = a.length - 1;
while (top < bott) {
while (a[bott] > num)
bott--;
int sum = a[top] + a[bott];
if (sum == num) {
System.out.println("Pair " + a[top] + " " + a[bott]);
top++;
bott--;
}
if (sum < num)
top++;
if (sum > num)
bott--;
}
}
Solution: O(n) time and O(log(n)) space.
public static boolean array_find(Integer[] a, int X)
{
boolean[] b = new boolean[X];
int i;
for (i=0;i<a.length;i++){
int temp = X-a[i];
if(temp >= 0 && temp < X) //make sure you are in the bound or b
b[temp]=true;
}
for (i=0;i<a.length;i++)
if(a[i]<X && b[a[i]]) return true;
return false;
}
Recursively to find the subset whose sum is the targeted sum from given array.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static Set<List<Integer>> set = new HashSet<>();
public static void main(String[] args) {
int[] biggerArray = {1, 2, 1, 1};
int targetedSum = 3;
findSubset(biggerArray, targetedSum);
}
public static void findSubset(int[] biggerArray, int targetedSum) {
for (int i = 0; i < biggerArray.length; i++) {
List<Integer> subset = new ArrayList<>();
if (biggerArray[i] > targetedSum)
continue;
else
subset.add(biggerArray[i]);
if (i + 1 < biggerArray.length)
find(subset, i, biggerArray, targetedSum, i);
}
System.out.println(set);
}
public static List<Integer> find(List<Integer> subset, int startIndex, final int[] biggerArray, final int targetedSum, final int skipIndex) {
if (skipIndex == startIndex) {
find(subset, startIndex + 1, biggerArray, targetedSum, skipIndex);
return null;
}
int subsetSum = findSumOfList(subset);
int remainedSum = targetedSum - subsetSum;
int i = startIndex;
if (remainedSum == 0) {
set.add(subset);
return null;
}
if ((startIndex < biggerArray.length) && (biggerArray[startIndex] == remainedSum)) {
List<Integer> temp = new ArrayList<Integer>(subset);
temp.add(biggerArray[i]);
set.add(temp);
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] < remainedSum)) {
while (i + 1 <= biggerArray.length) {
List<Integer> temp = new ArrayList<Integer>(subset);
if (i != skipIndex) {
temp.add(biggerArray[i]);
find(temp, ++i, biggerArray, targetedSum, skipIndex);
}
else {
i = i + 1;
}
}
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] > remainedSum)) {
find(subset, ++i, biggerArray, targetedSum, skipIndex);
}
return null;
}
public static int findSumOfList(List<Integer> list) {
int i = 0;
for (int j : list) {
i = i + j;
}
return i;
}
}
We need not have two for loops. The match can be detected in the same loop while populating the map it self.
public static void matchingTargetSumPair(int[] input, int target){
Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>();
for(int i=0; i<input.length; i++){
targetMap.put(input[i],target - input[i]);
if(targetMap.containsKey(target - input[i])){
System.out.println("Mathcing Pair: "+(target - input[i])+" , "+input[i]);
}
}
}
public static void main(String[] args) {
int[] targetInput = {1,2,4,5,8,12};
int target = 9;
matchingTargetSumPair(targetInput, target);
}
We can easily find if any pair exists while populating the array itself. Use a hashmap and for every input element, check if sum-input difference element exists in the hashmap or not.
import java.util.*;
class findElementPairSum{
public static void main(String[] args){
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sum key: ");
int sum=sc.nextInt();
for(int i=0; i<10; i++){
int x = sc.nextInt();
if(!hm.containsKey(sum-x)){
hm.put(x, 1);
} else {
System.out.println("Array contains two elements with sum equals to: "+sum);
break;
}
}
}
}