How to count steps for complete the linear Search - java

I have an array,I Search one element using linear Search.But I want to
count after how many steps I got the result. But I am not able to
count the steps ,I am able to only search the element from the
array,But not able to find the steps.
LinearSearhc.java
public class ArrayRotation {
public static int linearSearch(int []arr,int x){
int n = arr.length-1;
for (int i=0;i<=n;i++){
if (arr[i]== x)
return i;
}
return -1;
}
public static void main(String[] args) {
ArrayRotation arrRotation = new ArrayRotation();
int arr[]={4,56,44,152,54,845};
int x = 26;
int result = linearSearch(arr,x);
if (result == -1)
System.out.println("searching element not Present in this array");
else
System.out.println("Searching element present at the index position" +result);
}
}

Since we cannot return 2 values in a method in Java, we can instead return a Array with 2 values, one being if the linear search found the element and other being the amount of steps.
Change the linearSearch Method to
public static int[] linearSearch(int []arr,int x){
int steps = 0;
int[] result = {-1,0};
int n = arr.length-1;
for (int i=0;i<=n;i++){
steps++;
if (arr[i]== x) {
result[0] = i;
break;
}
}
result[1] = steps;
return result;
}
Then change the code in the Main Method to take in a array as result and the first index will be the Integer if found and the second will be the amount of steps.
Example
public static void main(String[] args) throws IOException {
int arr[]={4,56,44,152,54,845};
int[]result = linearSearch(arr,54);
if (result[0] == -1)
System.out.println("searching element not Present in this array");
else
System.out.println("Searching element present at the index position " +result[0]+" in "+result[1]+" steps");
}

Since is a linear search it will search all the elements to say -1 or stop when it finds it
you can count the steps adding a counter inside the for loop
class Playground {
public static void main(String[] args) {
ArrayRotation arrRotation = new ArrayRotation();
int arr[]={4,56,44,152,54,845};
int x = 26;
int result = arrRotation.linearSearch(arr,x);
if (result == -1)
System.out.println("searching element not Present in this array");
else
System.out.println("Searching element present at the index position " +result);
}
}
public class ArrayRotation {
public static int linearSearch(int []arr, int x){
int n = arr.length-1;
int counter = 0;
int position = -1;
for (int i=0; i <= n; i++) {
counter++;
if (arr[i] == x) {
position = i;
break;
}
}
System.out.println("searching element stop after counting " + counter);
return position;
}
}

Related

I get different value in recursion for knapsack problem

I wrote two pieces of code for knapsack problem. The first code gives me the correct answer (which is 16) and the second one doesn't. Is it something wrong with my recursive function?
First code (correct answer):
public class knapsackProblem {
static int[] weight = {1,2,4,2,5};
static int[] value = {5,3,5,3,2};
int result = 0;
// recursive function
public int sack(int i, int cap)
{
//base case
if(i<0 || cap == 0)
{
return 0;
} else if(weight[i] > cap)
{
return sack(i-1, cap);
} else
{
//get maximum value
return Math.max(sack(i-1, cap), value[i] + sack(i-1, cap - weight[i]));
}
}
public static void main(String[] args)
{
int capacity = 10;
int len = weight.length;
knapsackProblem kp = new knapsackProblem();
int total = kp.sack(len - 1, capacity);
System.out.println("sacked array is " + total);
}
}
Second code (incorrect answer):
public class knapsackProblem {
static int[] weight = {1,2,4,2,5};
static int[] value = {5,3,5,3,2};
int result = 0;
int tempNO = 0;
int tempYES = 0;
// recursive function
public int sack(int i, int cap)
{
//base case
if(i<0 || cap == 0)
{
return 0;
} else if(weight[i] > cap)
{
return sack(i-1, cap);
} else
{
//no case, move on to next value
tempNO = sack(i-1, cap);
//yes case, add the current value and move on to next value with decreased capacity
tempYES = value[i] + sack(i-1, cap - weight[i]);
//get maximum value
return Math.max(tempNO, tempYES);
}
}
public static void main(String[] args)
{
int capacity = 10;
int len = weight.length;
knapsackProblem kp = new knapsackProblem();
int total = kp.sack(len - 1, capacity);
System.out.println("sacked array is " + total);
}
}
The only difference is that in second code I put the results from recursion into variables before comparing for maximum value.
Thanks
Your variables are attributes of the class. The recursive calls are modifying those attributes every time, because you're using one single instance of the class to make the calls to the function. Declare the variables inside the method and remove them from the class to make it work. :)

Reading data from Csv File

How to find sequence of missing number from a CSV file using java Program?
I was using Arraylist taking some numbers into consideration.
I want to read entire CSV file Data And find the missing sequences on numbers.I have near about 1,00,000 records in the file.
Program:-
public class MissingNumber {
public static long count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args) {
long a[] = {1054023,1054024,1054025,1054026,1054027,1054028,1054029,1054030,1054031,1054032,1054748,1054749,1054750,1054751,
1054752,1054753,1054754,1054755,1054756,1054757,1054758,1055297,1055298,1055299,1055300,1055301,1055302,1055303,1055304,
1055305,1055306,1055307,1055308,1055309,1056868,1057170,1057461,1057563,1057627,1057628,1057629,1057630,1057631,1057632,
1057633,1057634,1057635,1057636,1057637,1057652,1057653,1057654,1057656,1057657,1057661,1057662,1057663,1057664,1057665,
1057672,1057673,1057674,1057675,1057678,1057682,1057683,1057685,1057686,1057687,1057690,1057691,1057692,1057695,1057696,
1057697,1057698,1057699,1057701,1057702,1057705,1057706,1057707,1057708,1057710,1057712,1057718,1057722,1057729,1057730,
1057731,1057732,1057733,1057734,1057735,1057736,1057738,1057739,1057740,1057741,1057742,1057743,1057744,1057745,1057746,
1057747,1057748,1057749,1057750,1057751,1057752,1057753,1057754,1057755,1057756,1057757,1057758,1057759,1057762,1057763,
1057764,1057765,1057766,1057767,1057768,1057769,1057773,1057774,1057778,1057779,1057780,1057781,1057782,1057783,1057784,
1057785,1057786,1057787,1057788,1057789,1057790,1057791,1057792,1057793,1057794,1057795,1057796,1057797,1057798,1057799,
1057800,1057801,1057802,1057803,1057804,1057805,1057806,1057807,1057808,1057809,1057810,1057811,1057825,1057826,1057827,
1057829,1057838,1057843,1057857,1057858,1057859,1057860,1057861,1057862,1057863,1057864,1057865,1057866,1057867,1057868,
1057869,1057870,1057871,1057872,1057873,1057874,1057875,1057876,1057884,1057885,1057886,1057887,1057888,1057889,1057890,
1057891,1057892,1057893,1057894,1057895,1057896,1057897,1057898,1057899,1057900,1057901,1057902,1057903,1057905,1057906,
1057907,1057908,1057909,1057910,1057911,1057912,1057913,1057914,1057915,1057916,1057917,1057918,1057919,1057920,1057921};
findMissingNumbers(a, position);
}
private static void findMissingNumbers(long a[], int position) {
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++) {
if ((a[position] - count) != position)
{
System.out.println("position"+position);
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
}
}
if (flag) {
flag = false;
findMissingNumbers(a, position);
}
}
}
I assume your array is already sorted. If so itreate through and find the missing nrs like you were doing it manually; compare two neighbors and if the difference is more than one print the numbers missing. something like this:
public class MissingNumber {
public static void main(String[] args) {
long a[] = {1,2,3,5,9,11,23,24,25,26,27,28,39}; //try first on small arrays
findMissingNumbers(a);
}
private static void findMissingNumbers(long a[]) {
for(int i = 0; i<a.length-1; i++){
if(a[i+1]- a[i] > 1){
System.out.println("missing nr at index: " + (i+1));
System.out.println("missing nrs");
for (int j = 1;j<a[i+1]-a[i];j++){ // for ex. if a[i] = 13 and a[i+1]= 17 difference is 4 and there are 3 missing nrs.
System.out.println(a[i]+j);
}
}
}
}
}
And to easily read from csv file i recomend opencsv

IndexOutOfBoundsException error adding long numbers

I am trying to wrtie java application that adds up to 5 long numbers using LinkedLists. At the end of the run I get this:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:
0, Size: 0
at java.util.LinkedList.checkElementIndex(LinkedList.java:555) at java.util.LinkedList.remove(LinkedList.java:525) at
Assignment1.LongNumbers.remove(LongNumbers.java:33) at
Assignment1.LongNumbers.main(LongNumbers.java:92)
Here is the code:
import java.util.*;
/**
*
* #author .....
*/
public class LongNumbers
{
private List<Integer> [] theLists;
public LongNumbers() {
this.theLists = new LinkedList[6];
for (int i=0; i<6; i++)
this.theLists[i]= new LinkedList<>();
}
public void add(int location, int digit) {
//add digit at head of LinkedList given by location
theLists[location].add(digit);
}
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
public boolean isEmpty(int location) {
//check for an empty LinkedList given by location
return theLists[location].isEmpty();
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
//Local Variables
int digit;
int carry = 0;
int numberAt = 0;
int largestNumLength = 0;
char[] digits;
String number;
boolean userWantstoQuit = false;
LongNumbers Lists = new LongNumbers();
System.out.println("The program will enter up to 5 numbers and add them up.");
System.out.println();
while(!userWantstoQuit && numberAt != 5){
System.out.print("Enter a number, enter -1 to quit entry phase: ");
number = stdIn.nextLine();
if((number.compareTo("-1")) == 0)
userWantstoQuit = true;
else{
digits = new char[number.length()];
for(int i=0;i<number.length();i++)
digits[i] = number.charAt(i);
for(int i=0;i<number.length();i++){
int tempValue = digits[i] - 48;
try{
Lists.add(numberAt, tempValue);
}
catch(NumberFormatException nfe){
System.out.println("Invalid Input. Please try again.");
break;
}
if(i == (number.length() - 1))
numberAt++;
if(number.length() > largestNumLength)
largestNumLength = number.length();
}
}
}
for(int j=0;j<largestNumLength;j++){
int tempDigit = 0;
int index = 0;
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
digit = carry + tempDigit;
if(j < numberAt){
carry = digit/10;
digit = digit%10;
}
Lists.add(5, digit);
}
System.out.print("The sum of the numbers is: ");
for(int i=0;i<Lists.theLists[5].size();i++){
System.out.print(Lists.theLists[5].get(i));
}
System.out.println();
System.out.println();
System.out.println();
}//end main
}//end class
For starters, I don't think you can have an array of List<E> objects...
You should also make sure your list is initialized and has an item at the given location.
So your method might look something like this:
public int remove(int location)
{
if(theLists != null)
if(theLists.size() > location)
return theLists.remove(location);
return 0;
}
If you need 2 dimensions of lists, you could try using List<List<E>>
Treat all E as Integer.
Look at the code here:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
You are checking whether the first element of the index'th list is not null. If that is true, you are adding it and call the remove method. However, what if you already processed the first list and index'th value is 1? In that case theLists[1].get(0) != null is true, but Lists.remove(0) passes 0 as location. Take a look at this code:
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
In the scenario I have described, location is 0. But your 0'th list is already empty...
EDIT: Rewrite the remove method, like this:
public int remove(int location, int index) {
//remove a digit from LinkedList given by location
return theLists[index].remove(location); //LongNumbers.java:33
}
And whenever you call this method, pass the index of the list to work with. Example:
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0, index); //LongNumbers.java:99
}
index++;
}
Finally: In the future, please, structure your code, it was a real pain to read it in this, unstructured state, read about how to code.

How to print the maximum valued path in a 2D array in Java?

I guess you all know the "strawberry" problem that some give you in job interviews, where you need to calculate the path between 2 corners of a 2D array that you can only move up or to the right and you have the calculate the maximum valued path.
I have a perfectly working code that does it in Recursion, but it's complexity is to high.
i also solved the problem in the "for loop" solution that does it in O(n^2) complexity.
but in this solution i just couldn't figure out a way to print the route like i did in the recursion solution.
This is my code (it is quite long to read here so i guess you should copy,compile and run).
look at the results of the recursion solution, BTW - The path needs to be from the left bottom corner to the right upper corner
I want to print the route the same way in the better solution:
public class Alg
{
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[][] route2 = new String[array.length][array[0].length];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
//SHOULD PRINT HERE THE ROUTE
}
public static int loopAlg(int [][] arr,int x, int y, String[][] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j];}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j];}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; }
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];}
else { count[i][j]= count[i+1][j]+arr[i][j];}
}
}
}
return count[0][arr[0].length-1];
}
public static int recursionAlg(int [][] arr, int x, int y,String[] route)
{
return recursionAlg(arr,0,x,y,arr[0].length-1,route,0);
}
public static int recursionAlg(int[][]arr,int count,int x, int y, int max_y, String[] route, int i)
{
if (x == 0 && y == max_y) {return count;}
else if (x == 0) {
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
else if (y==max_y){
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else if (recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1)>recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1))
{
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else
{
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
}
public static void printRouteArray(String[] arr)
{
int i=0;
while (i<arr.length && (arr[i]=="Up" || arr[i]=="Right"))
{
System.out.print(arr[i]+"-->");
i++;
}
System.out.println("End");
}
}
Hope you can help, thanks!
You need another 2-dimensional array inside loopAlg that memorizes which step to take to come to this next entry for every entry in your initial 2-dim array. See the following code and https://ideone.com/kM8BAZ for a demo:
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[] route2 = new String[100];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
printRouteArray(route2);
}
public enum Dirs {START, FROM_LEFT, FROM_DOWN};
public static int loopAlg(int [][] arr,int x, int y, String[] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
Dirs[][] directions = new Dirs[arr.length][arr[0].length];
List<String> path = new ArrayList<String>();
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j]; directions[i][j] = Dirs.START;}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j]; directions[i][j] = Dirs.FROM_LEFT;}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; directions[i][j] = Dirs.FROM_DOWN;}
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];directions[i][j] = Dirs.FROM_LEFT;}
else { count[i][j]= count[i+1][j]+arr[i][j];directions[i][j] = Dirs.FROM_DOWN;}
}
}
}
int i=0, j=arr[0].length-1;
while(directions[i][j]!= Dirs.START) {
if(directions[i][j] == Dirs.FROM_LEFT) {
path.add("Right");
j--;
}
else {
path.add("Up");
i++;
}
}
Collections.reverse(path);
i=0;
for(String part:path) {
route[i] = part;
i++;
}
return count[0][arr[0].length-1];
}

Given a target sum, find if there is a pair of element in the given array which sums up to it

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;
}
}
}
}

Categories

Resources