티스토리 뷰

728x90
반응형

지난 번 글에서 재귀함수의 정의와 구현방법에 대해 알아보았다.

 

https://gnidinger-coding.tistory.com/37

 

[Java]재귀 함수(Recursive Functions)

출처: https://www.geeksforgeeks.org/recursive-functions/ Recursive Functions - GeeksforGeeks A Computer Science portal for geeks. It contains well written, well thought and well explained computer..

gnidinger-coding.tistory.com

이 글을 바탕으로 이번 글에선 여러가지 적용 예를 들어본다.

 

 

sayHello

 

이름 그대로 문자열 "Hello"를 n번 출력하는 함수이다.

public static void sayHello(int n) {

    if(n == 0)  return;

    int tail = n - 1;

    System.out.println("Hello");
    sayHello(tail);

	}

 

gugudan

 

단수를 입력받아 구구단을 출력하는 함수이다.

public static void Gugudan(int level, int count) {

    if(level > 9 || count > 9) return;
    
        System.out.printf("%d x %d = %d\n", level, count, level * count);
        Gugudan(level, count + 1);
    
	}

 

sumTo

 

n부터 1까지의 합을 리턴하는 함수이다.

public static int sumTo(int n){

    if(n == 0) return 0;
    
    int head = n;
    int tail = n - 1;

    return head + sumTo(tail);


    }

 

isOdd

 

주어진 값에서 2를 계속해서 빼는 방식으로 홀수인지 여부를 판별하는 함수이다.

public static boolean isOdd(int n) {

    if(n == 0) return false;
    if(n == 1) return true;

    if(n < 0) return isOdd(-n);

    int tail = n - 2;

    return isOdd(tail);
    
    }

 

fibonacci

 

피보나치 수열의 n번째 항을 리턴하는 함수이다.

public static int fibonacci(int n){

    if(n <= 1) return n;

    return fibonacci(n - 2) + fibonacci(n - 1);

    }

 

arrSum

 

수열 arr을 입력받아 모든 요소의 합을 리턴하는 함수이다.

 

첫 번째 요소가 제거된 배열을 얻기 위해 Arrays.copyOfRange() 메서드가 사용되었다.

public static int arrSum(int[] arr){

    if(arr.length == 0) return 0;

    int head = arr[0];
    int[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return head + arrSum(tail);

    }

 

arrPruduct

 

수열 arr을 입력받아 모든 요소의 곱을 리턴하는 함수이다.

 

arrSum과 유사하게 구현한다.

public static int arrProduct(int[] arr){

    if(arr.length == 0) return 1;

    int head = arr[0];
    int[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return head * arrProduct(tail);
        
    }

 

arrLength

 

수열 arr을 입력받아 길이를 리턴하는 함수이다.

public static int arrLength(int[] arr){

    if(arr.length == 0) return 0;

    int head = 1;
    int[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return head + arrLength(tail);
    
    }

 

drop

 

숫자 n과 배열 arr을 입력받아 앞에서부터 n개의 요소가 제거된 배열을 리턴하는 함수이다.

public static int[] drop(int n, int[] arr){

    if(n >= arr.length) return new int[]{};
    if(n == 0) return arr;

    int[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return drop(n - 1, tail);

    }

 

take

 

숫자 n과 배열 arr을 입력받아 앞에서부터 n개의 요소만 포함된 배열을 리턴하는 함수이다.

 

새로운 배열을 생성해 원소를 추가하는 방식이다.

public static int[] take(int n, int[] arr){

    if(n >= arr.length) return arr;
    if(n == 0) return new int[]{};

    int[] head = Arrays.copyOfRange(arr, 0, 1);
    int[] tail = take(n - 1, Arrays.copyOfRange(arr, 1, arr.length));

    int[] dest = new int[head.length + tail.length];

    System.arraycopy(head, 0, dest, 0, head.length);
    System.arraycopy(tail, 0, dest, head.length, tail.length);

    return dest;

    }

 

and

 

배열 arr을 입력받아 모든 요소의 논리곱을 리턴하는 함수이다.

public static boolean and(boolean[] arr){

    if(arr.length == 0) return true;

    boolean head = arr[0];
    boolean[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return (head && and(tail));
        
    }

 

or

 

배열 arr을 입력받아 모든 요소의 논리합을 리턴하는 함수이다.

public static boolean or(boolean[] arr){

    if(arr.length == 0) return false;

    boolean head = arr[0];
    boolean[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return (head || or(tail));

    }

 

reverseArr

 

배열 arr을 입력받아 순서가 뒤집힌 배열을 리턴하는 함수이다.

 

스트림을 적용해서 구현하는 방식이다.

public static int[] reverseArr(int[] arr){

    if(arr.length == 0) return arr;

    int[] head = Arrays.copyOfRange(arr, 0, 1);

    int[] tail = Arrays.copyOfRange(arr, 1, arr.length);

    return IntStream.concat(IntStream.of(reverseArr(tail)), IntStream.of(head)).toArray();

    }
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함