vamsu
8/18/2018 - 7:52 PM

Practice recursion.. count target

Practice recursion.. count target

import java.io.*;
import java.util.*;



class Solution {
  public static void main(String[] args) {
   Solution solution = new Solution();
    int[][] input = {
      {1,1,1,1},
      {0,0,0,1},
      {0,0,0}
    };
    
    int[] target = {1,0,9};
    
    for(int i=0; i< input.length; i++){
       System.out.println("Input :" + Arrays.toString(input[i]) + ", Result:" + solution.targetCount(input[i], target[i], input[i].length));
      System.out.println("Input :" + Arrays.toString(input[i]) + ", Result:" + solution.targetCountR(input[i], target[i], input[i].length));
      System.out.println("Input :" + Arrays.toString(input[i]) + ", Result:" + solution.targetCountRT(input[i], target[i], input[i].length));
    }
  }
  
  public int targetCountR(int[] input, int target, int size){
    if(size == 0){
     return  0; 
    }
    int count = targetCount(input, target, size-1);
    if(input[size-1] == target){
     count++; 
    }
    return count;
  }
  
  public int targetCountRT(int[] input, int target, int size){
    if(size==0){
      return 0;
    }
    if(input[size-1] == target){
      return 1 + targetCountRT(input, target, size-1);
    }
    return targetCountRT(input, target, size-1);
  }
  
  public int targetCount(int[] input, int target, int size){
    int count = 0;
    for(int i=0;i<size;i++){
      if(input[i] == target) {
        count++;
      }
    }
    return count;
  }
}