Замена нерекурсивного метода на рекурсивный - PullRequest
0 голосов
/ 28 апреля 2020

У меня есть два нерекурсивных метода, один из них читает все символы "e" внутри строки, другой проверяет, является ли ArrayList алфавитным или нет.

public static int counter( String str ) {
      int k = 0;
      for( int i = 0; i < str.length(); i++) {
         if( str.charAt(i) == 'e' || str.charAt(i) == 'E' ) {
            k++;
         }
      }
      return k;
   }
public static boolean isAlpha( ArrayList<String> words ) {
      int n = 0;
      if ( words.isEmpty() ) {
         return false;
      } else if ( words.size() == 1 ) {
         return true;
      }
      while( n < (words.size() - 1) ){
         int j = words.get(n).compareTo( words.get(n + 1));
         if ( j > 0 ) {
            return false;
         }
         n++;
      }
      return true;
   }

Определение рекурсивного метода состоит в том, что метод вызывает сам себя. Я верю, что понимаю эту концепцию, однако ее трудно реализовать или преобразовать в рекурсивный метод. Как я могу превратить этот метод в рекурсивный и при этом делать, как я должен думать? Кроме того, вот мой другой метод, который печатает числа только с указанным размером di git.

public static void printN( int n, int step ) {
      if ( step > Math.pow( 10, n - 1 ) - 1 ) {
         if ( step < Math.pow( 10, n ) - 1 ) {
            if ( step % 2 == 0 ) {
               if ( condition( step )) {
                  System.out.print( step + " " );
               }
            }
         }
      }
      if ( step >= Math.pow( 10, n ) ) {
         return;
      }
      printN( n, step + 1 );
   }

метод условия проверяет, больше ли первое di git - справа - числа, больше второго, и снова проверяет, больше ли второго числа третье. Этот процесс проверки продолжается до тех пор, пока не достигнет последней ди git. Можно ли написать printN "method" только со значением параметра "int n"? Плюс метод "счетчик" рекурсивным способом только с одним значением параметра?

1 Ответ

1 голос
/ 28 апреля 2020

Самое важное, что нужно учитывать при написании рекурсивной функции / метода, - это когда возвращаться из метода.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(counter("He She They", 0));

        System.out.println(isSortedAlphabatically(List.of("Hello", "World")));
        System.out.println(isSortedAlphabatically(List.of("Good", "Hello", "World")));
        System.out.println(isSortedAlphabatically(List.of("Morning", "Good", "World")));
        System.out.println(isSortedAlphabatically(List.of("Good", "Bad", "Morning", "Evening", "Poor", "Rich")));
        System.out.println(isSortedAlphabatically(List.of("Bad", "Evening", "Good", "Morning", "Poor", "Rich")));
        System.out.println(isSortedAlphabatically(null));
        System.out.println(isSortedAlphabatically(List.of()));
    }

    public static int counter(String str, int count) {
        if (str.isEmpty()) {
            return count;
        }
        if (str.charAt(0) == 'e' || str.charAt(0) == 'E') {
            // Call the function recursively with the substring starting from index 1 and
            // count + 1
            return counter(str.substring(1), count + 1);
        }
        // Call the function recursively with the substring starting from index 1
        return counter(str.substring(1), count);
    }

    public static boolean isSortedAlphabatically(List<String> words) {
        if (words == null || words.isEmpty()) {
            return false;
        }
        if (words.size() == 1) {
            return true;
        }
        return words.get(0).compareTo(words.get(1)) > 0 ? false
                : isSortedAlphabatically(words.subList(1, words.size()));
    }
}

Вывод:

3
true
true
false
false
true
false
false
...