3

Let's say I have an array in the length of n, and the only values that can appear in it are 0-9. I want to create a recursive function that returns the number of different values in the array.

For example, for the following array: int[] arr = {0,1,1,2,1,0,1} --> the function will return 3 because the only values appearing in this array are 0, 1 and 2.

The function receives an int array and returns int something like this:

int numOfValues(int[] arr)
4
  • 1
    And what did you try? Commented Oct 9, 2015 at 10:55
  • 3
    Put the Array inside of a Set, and then check the size of the Set Commented Oct 9, 2015 at 10:55
  • This particular task is a very bad candidate for recursion. You cannot deduce the number of distinct items in a slice from the numbers of distinct items in halves of that slice. Commented Oct 9, 2015 at 11:03
  • Unfortunately I didn't have anything except for drafts that didn't work. The recursion is not clear to me, I was just wondering whether this problem could be solved using recursion. The basic cases are if the array is null you return 0, and if the array.length is 1 you return 1. Now I am trying to figure out the loop of the third case and how you sum it all up. Commented Oct 9, 2015 at 11:14

6 Answers 6

5

If you are using Java 8, you can do this with a simple one-liner:

private static int numOfValues(int[] arr) {
    return (int) Arrays.stream(arr).distinct().count();
}

Arrays.stream(array) returns an IntStream consisting of the elements of the array. Then, distinct() returns an IntStream containing only the distinct elements of this stream. Finally, count() returns the number of elements in this stream.

Note that count() returns a long so we need to cast it to an int in your case.


If you really want a recursive solution, you may consider the following algorithm:

  • If the input array is of length 1 then the element is distinct so the answer is 1.
  • Otherwise, let's drop the first element and calculate the number of distinct elements on this new array (by a recursive call). Then, if the first element is contained in this new array, we do not count it again, otherwise we do and we add 1.

This should give you enough insight to implement this in code.

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

4 Comments

Isn't he asking for recursive function?
@Ata Yes and I added an algorithm for a recursive solution. I didn't provide the code but the idea. Is this worth down-voting?
Not now, but I didn't see the recursive implementation.
@Ata I initially posted the code but finally removed it (you can see it in the revision history if you want) but I figured the OP would learn more by implementing this himself. The algorithm written in English is pretty self explanatory. Would you consider removing your down-vote?
1

Try like this:

public int myFunc(int[] array) {

     Set<Integer> set = new HashSet<Integer>(array.length);
     for (int i : array) {
        set.add(i);
     }
     return set.size();
 }

i.e, add the elements of array inside Set and then you can return the size of Set.

Comments

0
public int f(int[] array) {
   int[] counts = new int[10];
   int distinct = 0;
   for(int i = 0; i< array.length; i++) counts[array[i]]++;
   for(int i = 0; i< counts.length; i++) if(counts[array[i]]!=0) distinct++;
   return distinct;

 }

You can even change the code to get the occurrences of each value.

Comments

0

You can try following code snippet,

Integer[] arr = {0,1,1,2,1,0,1};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));

Output: [0, 1, 2]

Comments

0

As you asked for a recursive implementation, this is one bad way to do that. I say bad because recursion is not the best way to solve this problem. There are other easier way. You usually use recursion when you want to evaluate the next item based on the previously generated items from that function. Like Fibonacci series.

Ofcourse you will have to clone the array before you use this function otherwise your original array would be changed (call it using countDistinct(arr.clone(), 0);)

public static int countDistinct(int[] arr, final int index) {
    boolean contains = false;

    if (arr == null || index == arr.length) {
        return 0;
    } else if (arr.length == 1) {
        return 1;
    } else if (arr[index] != -1) {
        contains = true;
        for (int i = index + 1; i < arr.length; i++) {
            if (arr[index] == arr[i]) {
                arr[i] = -1;
            }
        }
    }

    return countDistinct(arr, index + 1) + (contains ? 1 : 0);
}

Comments

0
int numOfValues(int[]  arr)  {
    boolean[]  c = new boolean[10];
    int count = 0;
    for(int i =0; i < arr.length; i++) {
        if(!c[arr[i]]) {
            c[arr[i]] = true;
            count++;
        } 
    } 
    return count;
} 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.