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()));
}
}
Related
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;
How do I remove duplicate numbers on ArrayList and replace them with new ones?
I want to print the numbers without them duplicating.
This is my code:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
int opt = Integer.parseInt(JOptionPane.showInputDialog("How many numbers?");
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Set<Integer> s = new HashSet<>();
for (Integer d : al){
if (s.add(d) == false)
JOptionPane.showMessageDialog(null,"The number " + d + " was duplicated in position " + al.lastIndexOf(d));
JOptionPane.showMessageDialog(null,"Replace new number"); //This is where I would like to replace the numbers if possible
}
JOptionPane.showMessageDialog("Your numbers without duplicates: "); //This is where it would print
}
}
}
Prevent from entering duplicate numbers when the user enters them, instead of checking and replacing them later.Do it in this place:
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Chceck if a number already exists, if yes then ask for another not duplicated, if yes then add it and ask for next number :
for (int i=0 ; i < opc ; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while( true ){
if( ! al.contains( myNumber ))
al.add( myNumber );
break;
}
myNumber = Integer.parseInt(JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
}
======== EDIT ==================
I've corrected the example. There is missing { after if in the above (previous) one:
public class MmuClass {
public static void main(String... wwwx) {
List<Integer> lst = Arrays.asList(4, 2, 6, -6, 9);
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while (true) {
if (!al.contains(myNumber)) {
al.add(myNumber);
break;
}
myNumber = Integer.parseInt(
JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
al.stream().forEach(System.out::println);
}
}
}
I want to find the duplicate numbers in the array.
For this am comparing in the following way, but I am not able to get the desired output
The new array should contain numbers without duplicacy.
I have tried the following
public static void main(String[] args) {
int[] a={1,2,3,6,3,5,7,3,9,7};
int[] k=new int[a.length];
for(int i=0;i<a.length;i++){
for(int j=1;j<a.length;j++){
if(a[i]==a[j]){
k[i]=a[j];
}
}
}
for(int n=0;n<k.length;n++){
System.out.print(k[n]);
}
}
If you are not interested in finding the duplicates but only interested in removing them. the following approach would work.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Test
{
public static void main(String args[])
{
Integer[] a = new Integer[] {1,2,3,6,3,5,7,3,9,7};
Set<Integer> numberset = new HashSet<Integer>(Arrays.asList(a));
Integer[] output = numberset.toArray(new Integer[0]);
for (Integer i : output)
{
System.out.println(i);
}
}
}
Nice one.
public static void main(String[] args) {
int[] a={1,2,3,6,3,5,7,3,9,7};
int[] k=new int[a.length];
Set<Integer> dups = new HashSet<Integer>();
int index = 0;
for(int i=0;i<a.length;i++){
boolean found = false;
for(int j=1;j<index && !found;j++){
if(a[i]==k[j]){
// found duplicate.
found = true;
dups.add(a[i]);
}
}
if (!found)
{
k[index++]=a[i];
}
}
System.out.print("Unique entries: ");
for(int n=0;n<index;n++){
System.out.print(k[n]+" ");
}
System.out.println("\nDups:" + dups);
Output
Unique entries:1 2 3 6 5 7 9
Dups:[3, 7]
You should iterate your inner loop from i+1 to length, change it to following.
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]==a[j]){
k[i]=a[j];
}
}
}
The problem with your code is, It will check all the values at a[i] from 1 to n and will compare the values. It will be true for all i such that 1 <= i < n.
I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two
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!