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.
Related
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 new to programming and I am trying to teach myself some basic coding skills.
I have started experimenting with arrays and would like to solve the following task:
Create a method which returns all matching values from two arrays and display those matching values in the console.
So far I’ve only got as far as creating two arrays, list1 and list2. I believe I need to use a for or a while loop to find the matching values in each array but I am unsure of how to do this and then what I need to do next.
Can someone give me some advice please?
So far this is what I’ve written:
package project1;
public class Array {
public static void main(String[] args) {
int list1 [] = {1,2,55,8,7,9,60,4};
int list2 [] = {3,12,1,71,4,6,1,10};
}
}
Try this.
public static void main(String[] args) {
int list1 [] = {1,2,55,8,7,9,60,4};
int list2 [] = {3,12,1,71,4,6,1,10};
for(int x : list1){
if(Arrays.asList(list2).contains(x)){
System.out.println( x + " : present in second array.");
}
}
}
You are right, you have to create a loop to read an array.
public static void main(String[] args) {
int list1 [] = {1,2,55,8,7,9,60,4};
int list2 [] = {3,12,1,71,4,6,1,10};
for (int i=0;i<list1.length;i++){
System.out.println(list[i]);
//If you want to print any specific position put the position of the array that you want to print (taking into account that arrays start in 0 position):
System.out.println(list[0]);
}
for (int j=0;i<list2.length;j++){
System.out.println(list[j]);
}
}
Those simply two loops creates an integer called i and j which initially has value 0. In every loop, you will print every position of your arrays until i and j reaches the length of the array (list1.length and list2.length). When the loop prints the first position, those integers increments their value in one (i++ and j++) and prints the next position.
Ok, I think I get it now. You want to print out the values that exist both in list1 and list2. Try this:
public static void main(String[] args)
{
int list1 [] = {1,2,55,8,7,9,60,4};
int list2 [] = {3,12,1,71,4,6,1,10};
getMatchingValues(list1,list2);
}
public static void getMatchingValues(int[] list1, int[] list2)
{
for(int value1 : list1)
{
for(int value2 : list2)
{
if(value1==value2)
{
System.out.println("Both lists contain "+value1);
break;
}
}
}
}
Please go through the following code and try to understand it. Refer the java documentation or if you're using an IDE like eclipse, hover your mouse on functions to get a description about the functionality.
public static void getMatchingElements(int[] array1, int[] array2) {
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if(array1[i] == array2[j]){
System.out.println(array1[i]);
break;
}
}
}
}
The above algorithm is a very simple one. Hope you can improve on it.
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
Aim is to get an array and arrange it accending, and print
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int i, count=0, m;
System.out.println("Enter the integers, with 0 to end the array" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
Zero breaks the array here
if(num[i]==0)
break;
count++;
Calling the function here\
}
Sorting(num, count);
The function sorting is here
}
public static void Sorting(int[] sort, int con){
if(con<0)
return;
int j, max=0, coun=0, temp;
for(j=0; j<con; j++){
if(sort[j]>max)
max=sort[j];
coun=j;
}
here am swaping the last value in the array for any index thats the highest
temp=sort[con];
sort[con]=sort[coun];
sort[coun]=temp;
Calling the function again here(recursive)
Sorting(sort, con-1);
Here am printing, why is it not printing
for(j=0; j<con; j++){
System.out.println(sort[j]);
}
}
}
Is there a reason not to use Arrays.sort() ?
All you have to do is call
Arrays.sort(num);
Be careful since this will modify your array and will not create a sorted coyp of it!
i have one array with the following values [1,2,3,4,5]
i want to print a message when my array hold the values 1,2,3. How do I do this? :)
int[] myarray = new int[] {1,2,3,4,5};
if ( ... ) {
System.out.println("This array is on fire!");
I suppose you could do like this:
if (myarray[0]==1 && myarray[1]==2 && myarray[2]==3) {
.....
}
but if it's possible, i will avoid this. I wish to avoid the position in the array being a factor.
Unluckily Arrays.asList(myarray) doesnt work for int, as noted in the comments, i forgot...
So use Integer as Array-Type or convert first in an Integer-List:
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < myarray.length; index++)
{
intList.add(myarray[index]);
}
as pointed out here, then follow the old solution with this list:
if (intList.contains(1) && intList.contains(2) && intList.contains(3)) {
...
}
You could write a utility method as follows (assumes the array is sorted before hand please see the update if it's not the case):
public static boolean checkIfOnFire(int[] arr, int... nums) {
for(int n : nums) {
if(Arrays.binarySearch(arr, n) < 0) {
return false;
}
}
return true;
}
Test with:
int[] myarray = new int[] {1,2,3,4,5};
System.out.println(checkIfOnFire(myarray, 1, 2, 3));
System.out.println(checkIfOnFire(myarray, 1, 2, 7));
Prints:
true
false
Update:
Since I am using the Arrays.binarySearch. The input array to the checkIfOnFire method has to be sorted as it is in your example.
But if your array might not be sorted then checkIfOnFire has to be modified as follows:
public static boolean checkIfOnFire(int[] arr, int... nums) {
//make a copy of the original array
int[] copyArr = new int[arr.length];
System.arraycopy(arr, 0, copyArr, 0, arr.length);
//sort the copy
Arrays.sort(copyArr);
for(int n : nums) {
if(Arrays.binarySearch(copyArr, n) < 0) {
return false;
}
}
return true;
}
It ain't pretty, but if you wrote something like this:
public static boolean containsAll(int[] arrayToTest, int... values) {
return asList(arrayToTest).containsAll(asList(values));
}
public static List<Integer> asList(int[] values) {
List<Integer> asList = new ArrayList<Integer>(values.length);
for (int intVal : values) {
asList.add(intVal);
}
return asList;
}
You can then call it like this:
int[] myarray = new int[] {1,2,3,4,5};
boolean result = containsAll(myarray, 1, 2, 3);
If your wanted ints are non-negative, small, and dense; and you don't care about the order they appear in ints, then:
BitSet wanted = new BitSet();
wanted.set(1);
wanted.set(2);
wanted.set(3);
for (int i : ints) {
wanted.clear(i);
}
boolean hasAll = wanted.cardinality() == 0;
If you do care about order, then you probably want to test whether one array is a sub-sequence of another: Get the list of index in subsequence matching
To find the elements in any order in the array, first add the elements you're interested to a hash map. Then see if they are in the array.
Runtime: O(m) to add to map, to iterate over array O(n), m < n. Total O(n).
In the code below, call main() to run the sample I wrote.
Map<Integer,Boolean> lookFor = new HashMap<Integer,Boolean>();
void main(){
int[] array = new int[] {1,2,3,4,5};
addMeaningfulValues();
System.out.println( arrayHasValues(lookFor, array) );
}
void addMeaningfulValues(){
lookFor.put(1,false);
lookFor.put(2,false);
lookFor.put(3,false);
}
boolean arrayHasValues(Map<Integer,Boolean> values, int [] array){
//mark entries found in array
for (int i=0; i<array.length; i++){
if (values.containsKey(array[i])){
values.put(array[i], true);
}
}
//go over map entries and see if they have all been found in the array
for (Boolean crtValue: values.values()){
if (!crtValue){
return false;
}
}
return true;
}
Put it in a Collection or List and do a contains for each item you are looking for.
Integer[] myarray = {1,2,3,4,5};
List<Integer> intList = Arrays.asList(myArray);
if (intList.contains(1) && intList.contains(2) && intList.contains(3))
// print your message
Longer solution, but requires only one pass. Can be easily customized to check for any number of items.
public boolean onFire(int array[])
{
boolean found1 = false;
boolean found2 = false;
boolean found3 = false;
for (int i : array) {
if(i==1)
{
found1= true;
continue;
}
if(i==2)
{
found2= true;
continue;
}
if(i==3)
{
found3= true;
continue;
}
if(found1&&found2&&found3)
return true;
}
if(found1&&found2&&found3)
return true;
return false;
}
Make use of the containsAll method in the Collection interface.
Collection<Integer> coll = new ArrayList<Integer>();
Collection<Integer> test = new ArrayList<Integer>();
for( int i=1; i<=5; i++)
coll.add(i);
test.add(1);
test.add(2);
test.add(3);
System.out.println(coll.containsAll(test));
Due to wide use of collections java considered as collection is a framework and each collections consisting of a method contains(Object o) to check whether an element is existing or not in a collection.
so first we can convert the int[] array to a List
List<Integer> list=new ArrayList<Integer>();
int[] myarray = new int[] {1,2,3,4,5};
for(int i=0;i<myarray.length;i++)
{
list.add(myarray[i]);
}
please use list.contains(Object o) to check whether its existing or not
for(Integer i:list)
{
if(list.contains(1)&&list.contains(2)&&list.contains(3))
{
flag=true;
break;
}
}
and check the complete code below
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
boolean flag=false;
List<Integer> list=new ArrayList<Integer>();
int[] myarray = new int[] {1,2,3,4,5};
for(int i=0;i<myarray.length;i++)
{
list.add(myarray[i]);
}
for(Integer i:list)
{
if(list.contains(1)&&list.contains(2)&&list.contains(3))
{
flag=true;
break;
}
}
if(flag)
{
System.out.println("yes contain");
}
else
System.out.println("NO");
}
}