2016-03-29 22 views
0

再帰を使用して配列の最初の整数よりも少ない数のカウントを取得する必要があります。再帰を使用して配列からカウントを取得

public static int countGreaterThanFirst(int[] 
numbers, int startIndex, int endIndex, int firstNumber){} 

私はループやグローバル/静的変数を使用することは想定されていません。上記の2つの条件を満たすために、以下の実装をどのように変換できますか。私は最近、another同様の質問をしましたが、これはカウント変数を追跡する必要があるために少し異なります。誰かが助けることができれば、私は本当に感謝します。 以下は私のループでの実装です。

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) { 
    int greater_than_first = 0; 
    for (int count = startIndex; count <= endIndex; count++) { 
     if (numbers[count] > firstNumber) { 
      greater_than_first++; 
     } 
    } 
    return greater_than_first; 
} 
+0

これはうまくいくはずですが、それは期待される実装ではありません。 –

答えて

3

おそらくあなたはそのくらいのパラメータは必要ありません:あなたが見つけることを意図した場合

countGreaterThanFirst(someArray, 1); 

public static int countGreaterThanFirst(int[] numbers, int currentIndex) { 
    if (currentIndex == numbers.length) return 0; 
    else { 
     if (numbers[currentIndex] > numbers[0]) { 
      return 1 + countGreaterThanFirst(numbers, currentIndex + 1); 
     } else { 
      return countGreaterThanFirst(numbers, currentIndex + 1); 
     } 
    } 
} 

、あなたは(例えば)でそれを呼び出す必要がfirstNumberより大きいnumbers[startIndex]numbers[endIndex]の間のすべての数値は、上記のものとかなり似ているはずです:

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) { 
    if (startIndex > endIndex) return 0; 
    else { 
     if (numbers[startIndex] > firstNumber) { 
      return 1 + countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber); 
     } else { 
      return countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber); 
     } 
    } 
} 
+0

パラメータは条件です。 –

+0

はい、私は与えられた定義に従って関数を実装しなければなりません –

+0

@mungaihpk、checkout私の更新。 –

関連する問題