Count times a value appears in an array

0

Given an array of n integers, count the number of times a value appears determined. Solve the problem with a recursive algorithm

  • int contar (int [] array, int valor, int posInici)
  • array : array with values.
  • valor : value search.
  • posInici : Initial position where we started to search.

I pass the code that I have done:

package tema2;

public class Problema3 {

    public static void main(String[] args) {
        int [] array={3,12,314,1234,3};
        int valor=3;
        int posInici=1;

        Problema3 programa = new Problema3();

        programa.comptar(array,valor,posInici);
        System.out.println(posInici);
    }

    public static int comptar(int [] array,int valor,int posInici) {
        int j=0;
        if(posInici == array.length) {  
             j++;
        }
        if(valor == array[posInici]) {
             return array valor posInici + 1;
        } 
     }  
 }
    
asked by Kim Rb 29.03.2017 в 18:01
source

2 answers

1

Good morning ..

We're going to take your problem apart, but I'm not going to write you the solution. If I give you tips to get to it.

The first thing you should think is that your recursive function should return something ... something that will serve the previous step .. what if you return if you found what you were looking for or not?

Apart from that, your recursive function must know when it reaches the end ... so it has to end at some point ...

Notice that with these two tips, you can rethink what you are writing and looking for.

Go one step at a time if you want. First, look for the function to end ... and then look how to tell ...

P.D: your return is wrong;)

    
answered by 29.03.2017 в 18:18
0
    public static int comptar(int [] array,intvalor,int posInici) {
            if(posInici<array.lentgh){
            if(valor==array[posInici])
            return 1+comptar(array,valor,posInici+1);
            else
            return 0+ comptar(array,valor, posInici+1);
   } 
    return 0;
    } 

With this method you can count how many times a value appears in the array. Your method is wrong for the following reasons:

  • Your counter is inside the method and at the beginning, so every time you enter the method your value becomes zero then that makes that does not count.
  • In your return you must call the method again, because in that consists of recursion.
answered by 29.03.2017 в 22:35