Recently bumped into a hackerrank challenge, got to find pair of int in a given array.
Using ArrayList as an approach.
Can anyone rectify the errors in this code.
Error :Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 9
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at Solution.main(Solution.java:32)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c[] = new int[n];
for(int c_i=0; c_i < n; c_i++){
c[c_i] = in.nextInt();
}
int count=0;
Arrays.sort(c);
ArrayList<Integer> ch = new ArrayList<>();
for(int c_i=0; c_i < n; c_i++){
ch.add(c[c_i]);
}
for(int i=0;i<ch.size();i++){
int a = ch.get(i);
int b=ch.indexOf(a);
if(b<0)
continue;
else{
ch.remove(a);
ch.remove(b);
count++;
for (int j=0;j<ch.size()-2;j++){
ch.add(j,ch.get(j+2));
}
}
System.out.println(count);
}
}
Edited the above approach and while finding that b will give the index of a removing only one element always, so now tried the approach that the first element is removed no matter what and then searching for the matching pair element until the arrayList is empty.
while(ch.size()!=0){
int a = ch.get(0);
ch.remove(0);
int b = ch.indexOf(a);
if(b<0){
for (int j=0;j<ch.size()-1;j++)
ch.add(j,ch.get(j+1));
continue;
}
else{
ch.remove(b);
count++;
for (int j=0;j<ch.size()-2;j++)
ch.add(j,ch.get(j+2));
}
}
Error: Terminated due to timeout
int a = ch.get(i);
This will retrieve the value at location i
ch.remove(a);
This will remove the value stored at index a. The value a could be possibly greater than the ArrayList size.
This is where you are going wrong. Try commenting that out, maybe it will work
//if some one needs a different approach to find total number of pairs in a arraylist.
int pair=0;
List<Integer> list = new ArrayList<Integer>();//your input
Set<Integer> uniqueSet = new HashSet<Integer>(list);
for (Integer temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));
if(Collections.frequency(list, temp)==2|| Collections.frequency(list, temp)>2)
{
int t=Collections.frequency(list, temp)/2;
pair=pair+t;
}
}
return pair;
Related
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList < Integer > list = new ArrayList < Integer > ();
System.out.println(" Enter the length of array :");
int n = sc.nextInt();
int array[] = new int[n];
System.out.println("Enter List : ");
for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
if (itr.next() != null) {
while (itr.hasNext()) {
Integer thisInt = itr.next();
if (thisInt % 2 == 0) {
list.add(thisInt);
}
System.out.println(" Even Index Position Sum : ");
}
}
}
}
}
Your code has several problems according to the context you have asked.
You haven't added anything to the list yet using scanner. So, how can you get the values to be calculated?
Using two loops for iterating through the list and checking again, this does not seem correct.
Printing your final output inside the loop will print it several times.
So, here is the complete code:
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the length of array :");
int n = sc.nextInt();
System.out.println("Enter List : ");
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
Iterator<Integer> itr = list.iterator();
int sum = 0;
int count = 0;
while (itr.hasNext()) {
int val = itr.next();
if (count % 2 == 0) {
sum += val;
}
count++;
}
System.out.println("Even Index Position Sum : " + sum);
}
}
You haven't added anything to the ArrayList, so your for loop doesn't do anything. You have to add something to it first using list.add(element) where element is an int.
I have a method which accepts two parameters. 1st is an integer array and 2nd is an integer.
The method should print the index pairs where sum of the values present in those indexes equal to the 2nd input parameter.
The brute force approach is to have two loops which will take O(n^2) time. But I need to solve this in O(n) time.
The array can have repetitions and can have negative numbers also.
If it prints one pair then the reverse pair is not allowed. For example in the below sample if it should not print (4,0), (3,2), (5,3)
int[] arr = {3,4,-1,6,2,-1};
int sum = 5;
The method signature is :findPairs(int[] arr, int sum);
The output of this method will be : (0,4), (2,3), (3,5)
Explanation:
Element present at index 0 + Element present at index 4 = 3+2 = 5
Element present at index 2 + Element present at index 3 = -1+6 = 5
Element present at index 3 + Element present at index 5 = 6+-1 = 5
To clarify some confusions, I have tried using HashMap<Integer, List<Integer>>. Here, key is the elements of array and value is their respective indices. As repetition is allowed, so for a given element there can be multiple index locations. So value in the map is a list.
Your approach is absolutely correct.
Using Map does solve this problem in O(n).
We will capitalise the benefits provided to us by JAVA by making use of TreeMap in this case. (Not necessary to be used).
Also, the problem of repeated pairs of indices in the final answer can be solved using a visited map. This map checks if I have visited the particular index before. If yes, then I will not include it in my answer.
Have a look the implementation below:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
private static SortedMap<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
private static final Scanner scanner = new Scanner(System.in);
String findPairs(int[] arr, int sum){
for(int i=0;i<arr.length;i++){
List<Integer> indexList = map.get(arr[i]);
if(indexList == null){
List<Integer> newIndexList = new ArrayList<Integer>();
newIndexList.add(i);
map.put(arr[i], newIndexList);
}else{
indexList.add(i);
}
}
Set s = map.entrySet();
HashMap<Integer, Boolean> visited = new HashMap<Integer, Boolean>();
// Using iterator in SortedMap
Iterator it = s.iterator();
String finalOutput = "";
while (it.hasNext())
{
Map.Entry m = (Map.Entry)it.next();
int key = (Integer)m.getKey();
List<Integer> indexList1 = (List<Integer>)m.getValue();
if(map.containsKey(sum-key)){
List<Integer> indexList2 = (List<Integer>)map.get(sum-key);
for(int i=0;i<indexList1.size();i++){
if(!visited.containsKey(indexList1.get(i))){
for(int j=0;j<indexList2.size();j++){
if(!(finalOutput.equals("") || finalOutput==null)){
finalOutput += ", ";
}
finalOutput += "(" + indexList1.get(i) + "," + indexList2.get(j) + ")";
visited.put(indexList2.get(j), true);
}
visited.put(indexList1.get(i), true);
}
}
}
}
return finalOutput;
}
public static void main(String[] args) throws IOException {
int[] arr = {3,4,-1,6,2,-1};
int sum = 5;
Solution obj = new Solution();
System.out.println(obj.findPairs(arr, sum));
}
}
Kindly feel free to ask doubts.
public HashMap<Integer, ArrayList<List<Integer>>> getPairs(int[] input, int targetSum) {
HashMap<Integer, ArrayList<List<Integer>>> hashMapList = new HashMap<Integer, ArrayList<List<Integer>>>();
for(int i=0;i< input.length;i++) {
//int j=i+1;
for(int j=1;j< input.length;j++) {
//if(j < input.length && input[i] + input[j] == targetSum ) {
if(i != j && input[i] + input[j] == targetSum ) {
ArrayList<List<Integer>> indexPairList = new ArrayList<List<Integer>>();
List<Integer> listPairs = new ArrayList<Integer>();
if( null != hashMapList.get(targetSum)) {
indexPairList = hashMapList.get(targetSum);
for(List<Integer> listPair : indexPairList) {
listPairs.addAll(listPair);
}
}
//System.out.println("listPairs - "+listPairs);
if(!listPairs.contains(i)
|| (!listPairs.contains(j))) {
List<Integer> pair = new ArrayList<Integer>();
pair.add(i);
pair.add(j);
indexPairList.add(pair);
hashMapList.put(targetSum, indexPairList);
}
}
}
}
return hashMapList;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a code which will find the duplicate value in an array. So, far I have written below code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
}
}
But I am not getting the expected output, for example:
If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.
But if I provide 2 set of duplicate value in an array, still it is finding the first duplicate.
e.g. 1,2,1,2,1,3. It is giving output only 1.
I found the reason of incorrect result which is condition of count i.e. count is set to greater than 1 and it is not matching to first if condition.
So, I have tried to reset the counter to 0 after one loop iteration, now it is giving all duplicate values but duplicate values printing twice.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
**count = 0;**
}
}
e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2
Please suggest how to get the correct result.
I do not like to use Streams or smth hight-level for solving algorythmic problem; only plain java. So this is my solution:
public static Set<Integer> findDuplicateInArray(int... arr) {
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicate = new HashSet<>();
for (int val : arr)
if (!unique.add(val))
duplicate.add(val);
return duplicate;
}
In case you are able to modify incomming arr, then with some small modification, you can refuce from Set<Integer> unique.
Maybe it's easier to convert the array to list and make all the logic with the Java 8 streams api in one sentence:
Integer[] numbers = new Integer[] { 1, 2, 1, 2, 1, 3 };
List<Integer> listInteger = Arrays.asList(numbers);
listInteger.stream().filter(i -> Collections.frequency(listInteger, i) >1).collect(Collectors.toSet()).forEach(System.out::println);
Output
1
2
You are in the right way, I have just updated your method, I hope that you will understand what was your mistake:
public void findDupicateInArray(int[] a) {
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k]) {
count++;
}
}
if(count==1)
System.out.println(a[j]);
count = 0;
}
}
Nevertheless, this will make your code running correctly, and that does not mean you have written the optimal code.
Please have a look in below code it will help you.
We have to count the no of repeatation of each element and then at the last find the count, which will tell the duplicate nos.
package com.java;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public class FindDuplicateInArray {
public static void main(String[] args) {
int[] intArr = new int[] { 1, 2, 1, 2, 1, 3, 4, 6, 2, 8 };
Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < intArr.length; i++) {
// take first element and then matched complete array
int temp = intArr[i];
int count = 0;
for (int j = 0; j < intArr.length; j++) {
if (temp == intArr[j]) {
// element matched -- break
count++;
}
}
map.put(temp, count);
}
Set<Integer> duplicate = new LinkedHashSet<Integer>();
Set<Integer> noDuplicate = new LinkedHashSet<Integer>();
for (int i = 0; i < intArr.length; i++) {
if (map.containsKey(intArr[i])) {
System.out.println("Key :" + intArr[i] + " Value : " + map.get(intArr[i]));
if (map.get(intArr[i]) > 1) {
// means repeated character
duplicate.add(intArr[i]);
} else {
// non repeated character
noDuplicate.add(intArr[i]);
}
}
}
System.out.println("Duplicate Chars : " + Arrays.toString(duplicate.toArray()));
System.out.println("No Duplicate Chars : " + Arrays.toString(noDuplicate.toArray()));
}
}
I'm pretty new to java, and I'm trying to create a simple method that sorts inputted numbers, either ascending or descending. However, there's a problem that I can't put in repeated values. Is there a way to get the key of a certain item of an array??
My code:
import java.io.Console;
public class TestSort {
public static void main(String args[]) {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
System.out.println("TESTSORT.java");
System.out.println("-------------");
System.out.println("Type in a set of numbers here:");
String in = c.readLine();
System.out.println("(A)scending or (D)escending");
String ad = c.readLine();
boolean d = false;
if(ad.equals("a")) d = false;
else if(ad.equals("d")) d = true;
else {
System.out.println("Invalid Input.");
System.exit(1);
}
String[] in2 = in.split(" ");
int[] x = new int[in2.length];
int count1 = 0;
for(String val : in2)
x[count1++] = Integer.parseInt(val);
int[] a = new int[x.length];
int count = 0;
for(int y : x) {
for(int z : x) {
// if index of y equals index of z continue
if(z < y) count++;
}
a[count] = y;
count = 0;
}
if(d) {
int[] arr3 = new int[a.length];
int length = a.length;
for(int b : a) arr3[--length] = b;
for(int b : arr3) System.out.println(b);
} else
for(int b : a)
System.out.println(b);
}
}
This program just counts up the number of other numbers smaller than itself, but not including itself. However, it doesn't differentiate itself from other numbers with the same value.
Help would be appreciated.
Thanks.
To get the index of a certain value for an array you will have to loop through the array. However if there is multiple entries with the same value this approach wouldn't work (without modification)
int indexVal = -1;
int inputValue; // This is your input vlaue you are trying to find
for(int i = 0; i < array.length ; i++)
{
if (array[i] == inputValue)
{
indexVal = i;
break;
}
}
You may also want to look at Array.sort for built in array sorrting
If you want an index you should not be using for each loops. You will have to use a regular for loop to get at an index in the array.
A SortedSet is perfect for this. As a set, it does not allow duplicate values, and it is sorted automatically for you!
Just add your elements to the set, e.g:
SortedSet<Integer> set = new SortedSet<Integer>();
for(String value : in2.split(" ")){
set.add(Integer.parseInt(value));
}
To reverse the order of the set do something like this:
SortedSet<Integer> descending = set.descendingSet();
You can iterate through sets just like arrays too:
for(Integer i : set){
//Do something
}
Good luck!
Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}