简体   繁体   中英

Count different values in array in Java

I'm writing a code where I have an int[a] and the method should return the number of unique values. Example: {1} = 0 different values, {3,3,3} = 0 different values, {1,2} = 2 different values, {1,2,3,4} = 4 different values etc. I am not allowed to sort the array .

The thing is that my method doesn't work probably. There is something wrong with my for statement and I can't figure it out.

public class Program
{

    public static void main(String[] args)
    {
        int[] a = {1, 2, 3, 1};

        System.out.println(differentValuesUnsorted(a));
        //run: 4 //should be 3
    }

public static int differentValuesUnsorted(int[] a)
{
    int values;      //values of different numbers

    if (a.length < 2)
    {
        return values = 0;
    }else if (a[0] == a[1])
    {
        return values = 0;
    }else
    {
        values = 2;
    } 

    int numberValue = a[0];
    for (int i = a[1]; i < a.length; i++)
    {
        if (a[i] != numberValue)
        {
             numberValue++;
             values++;
        }
    }
        return values;
    }
}

Can anybody help?

This is actually much simpler than most people have made it out to be, this method works perfectly fine:

public static int diffValues(int[] numArray){
    int numOfDifferentVals = 0;

    ArrayList<Integer> diffNum = new ArrayList<>();

    for(int i=0; i<numArray.length; i++){
        if(!diffNum.contains(numArray[i])){
            diffNum.add(numArray[i]);
        }
    }

    if(diffNum.size()==1){
            numOfDifferentVals = 0;
    }
    else{
          numOfDifferentVals = diffNum.size();
        } 

   return numOfDifferentVals;
}

Let me walk you through it:

1) Provide an int array as a parameter.

2) Create an ArrayList which will hold integers:

  • If that arrayList DOES NOT contain the integer with in the array provided as a parameter, then add that element in the array parameter to the array list
  • If that arrayList DOES contain that element from the int array parameter, then do nothing. (DO NOT ADD THAT VALUE TO THE ARRAY LIST)

NB: This means that the ArrayList contains all the numbers in the int[], and removes the repeated numbers.

3) The size of the ArrayList (which is analogous to the length property of an array) will be the number of different values in the array provided.


Trial

Input :

  int[] numbers = {3,1,2,2,2,5,2,1,9,7};

Output : 6

First create distinct value array, It can simply create using HashSet .

Then alreadyPresent.size() will provide number of different values. But for the case such as - {3,3,3} = 0 (array contains same elements); output of alreadyPresent.size() is 1. For that use this simple filter

if(alreadyPresent.size() == 1)){
    return 0;
}

Following code will give the count of different values.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Demo {

  public static void main(String[] args)
  {
       int array[] = {9,9,5,2,3};
       System.out.println(differentValuesUnsorted(array));
  }

  public static int differentValuesUnsorted(int[] array)
  {

     Set<Integer> alreadyPresent = new HashSet<Integer>();

     for (int nextElem : array) {
         alreadyPresent.add(nextElem);
     }

     if(alreadyPresent.size() == 1){
         return 0;
     }

     return alreadyPresent.size();

  }
}

You can use a HashSet , which can only contain unique elements. The HashSet will remove the duplicated items and you can then get the size of the set.

public static int differentValuesUnsorted(int[] a) {
    Set<Integer> unique = new HashSet<Integer>();
    for (int val : a) {
        unique.add(val); // will only be added if a is not in unique
    }
    if (unique.size() < 2) { // if there are no different values
        return 0;
    }
    return unique.size();
}

For small arrays, this is a fast concise method that does not require the allocation of any additional temporary objects:

public static int uniqueValues(int[] ids) {
    int uniques = 0;

    top:
    for (int i = 0; i < ids.length; i++) {
        final int id = ids[i];
        for (int j = i + 1; j < ids.length; j++) {
            if (id == ids[j]) continue top;
        }
        uniques++;
    }
    return uniques;
}

Try this:

import java.util.ArrayList;
public class DifferentValues {

 public static void main(String[] args)
  {
    int[] a ={1, 2, 3, 1};
    System.out.println(differentValuesUnsorted(a));
  }

 public static int differentValuesUnsorted(int[] a)
 {
   ArrayList<Integer> ArrUnique = new ArrayList<Integer>();
   int values=0;      //values of different numbers
   for (int num : a) {
       if (!ArrUnique.contains(num)) ArrUnique.add(num);
   }
   values = ArrUnique.size();
   if (values == 1) values = 0;       
   return values;
 }
}

input: {1,1,1,1,1} - output: 0
input: {1,2,3,1} - output: 3

Try this... its pretty simple using ArrayList . You don't even need two loop. Go on

import java.util.*;
public class distinctNumbers{

 public static void main(String []args){
    int [] numbers = {2, 7, 3, 2, 3, 7, 7};
    ArrayList<Integer> list=new ArrayList<Integer>();
    for(int i=0;i<numbers.length;i++)
    {

        if(!list.contains(numbers[i]))  //checking if the number is present in the list
        {
            list.add(numbers[i]); //if not present then add the number to the list i.e adding the distinct number
        }

    }
    System.out.println(list.size());
}
}

Try this simple code snippet.

public static int differentValuesUnsorted(int[] a)
{
    ArrayList<Integer> list=new ArrayList<Integer>();   //import java.util.*;
    for(int i:numbers)                                  //Iterate through all the elements
      if(!list.contains(i))                             //checking for duplicate element
        list.add(i);                                    //Add to list if unique
    return list.size();
}

What about this?

private <T> int arrayDistinctCount(T[] array) {
    return Arrays.stream(array).collect(Collectors.toSet()).size();
}

Use a set to remove duplicates

 public static int differentValuesUnsorted(int[] a) {
     if (a.length < 2) {
         return 0;
     }

     Set<Integer> uniques = new HashSet<>(a);
     return singleUnique.size();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM