4

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?

6
  • 3
    This code is poorly formatted and not even runnable. Please make sure your program doesn't have any compile errors, and that it is properly formatted before posting. Commented Sep 7, 2015 at 18:20
  • those if else-if else statements at the top of differentValuesUnsorted, are they just for an array that has a length less than 2, or should they be going through arrays that have more than one int stored in them? Commented Sep 7, 2015 at 18:45
  • Your for-loop is also bad. what happens if a[1] has a value larger than the length of the array? AIOOB error happens Commented Sep 7, 2015 at 18:49
  • Maybe I have misunderstood the task, but it says (in translated english): If the array is empty (has length 0), the method should return 0 because there is 0 different values in an empty array. I have been thinking that it means that if the array got, for instance, one value like int[] a = {2} there is no different values. So with the if/else-if/else statements I been trying to make it so that the results become: int[] a = {2} => 0 different values, int[] a = {2,2} => 0 different values, but int[] a = {1,2} => 2 different values. Commented Sep 7, 2015 at 18:51
  • be careful though, if the array, of a length 2 or greater, for our purpose lets say greater than 2, so 3, hits the else if(a[0] == a[1]) line, and the first 2 ints are the same, it will return 0, when it should be 2, and your for-loop still has an issue Commented Sep 7, 2015 at 19:08

9 Answers 9

8

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)

N.B: 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

Sign up to request clarification or add additional context in comments.

Comments

3

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();

  }
}

3 Comments

"I am not allowed to sort the array"
Besides the sort issue pointed out by @RamanSB posting a block of code and "Try this" is an unacceptable answer. SO is about helping people understand code and any mistakes they may have made. You need to explain the function of your code, no matter how straightforward it may seem to you.
try reading my comment. your answer is still not an acceptable one. if you dont believe what im saying about how your answer should be formatted, check out meta.
1

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

9 Comments

doesn't solve the problem since from my understanding {3,3,4,4} should be 0
@PKuhn Why should it be 0? {3,3,4,4} has two different elements: 3 and 4.
the code is looking for the number of different elemetns, so in 3,3,4,4 there are 0 unique elements, but the HashSet to my understanding would have a 3 and 4 remaining, and your code would return 2, not 0
@JohnnyCoder Is the op looking for the number of different elements (2 different elements: 3 and 4) or the number of unique elements (0 unique elements)? My understanding was that he was looking for different values. If this is wrong then I'll delete the answer
@JohnnyCoder: according to the op's code, he is indeed looking for the number of different values: {1,2,3,1} should return 3. If he were looking for unique values, the return value would be 2.
|
1

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

3 Comments

This solution has O(n^2) time complexity due to the nested loop and is much slower than other solutions for large arrays.
True, for large arrays you would want to find a method using some kind of hash indexing, but Java HashSet is a really bad way of storing integers and has big overheads. I did a benchmark and found that the cross-over point was about a 25 element array. Below this, the above method is faster (e.g, 3 times faster for a 10 element array). Above, the HashSet starts to gain and by 1000 elements it is 10 times faster.
I added the qualifier "for small arrays" to the answer.
0

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

Comments

0

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

Comments

0

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

1 Comment

Same as previous answer and doesn't compile.
0

What about this?

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

1 Comment

Yes? What about it? Do you have a problem with that code? Would you like proposals for improving it? Or is this supposed to be an answer to the question? In that case please add some explanation about how it works and why it helps.
-1

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

2 Comments

when running this method I get wrong answer. With int[] a = {0,2,3,5,4,3}; I get "run: 4". There should be 5.
I don't think that HashSet has a constructor that takes an array of ints.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.