백준

백준 - 음계 (2920번) JAVA

MoveForward 2022. 12. 28. 15:24

2920번 음계 (JAVA)

 

import java.util.Scanner;

public class Main{

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);

        int[] a = new int[8];
        for (int i=0; i<8; i++){
            a[i] = sc.nextInt();
        }
        
        int[] check = new int[7];
        for(int i=0; i<7; i++){
            check[i] = 0;
        } // [0, 0, 0, 0, 0, 0, 0]

        for (int i=0; i<7; i++){
            if (a[i] - a[i+1] == -1){ // ascending
                check[i] = 1;
            }
            else if (a[i] - a[i+1] == 1){ // descending
                check[i] = 2;
            }
            else {check[i] = 3;} // mixed
        }

        int sum = 0;
        for(int i=0; i<7; i++){
            sum += check[i];
        }
        if (sum == 7){System.out.println("ascending");}
        else if (sum == 14){System.out.println("descending");}
        else {System.out.println("mixed");}
    }
}

 

1 ~ 8까지의 자연수 나열에서 오름차순과 내림차순의 특징은 i번째 수와 8-i번째 수의 합이 동일하다는 것이다.

이 특징을 이용한 방법은 다음과 같다.

import java.util.Scanner;

public class Main{

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);

        int[] a = new int[8];
        for (int i=0; i<8; i++){
            a[i] = sc.nextInt();
        }
        int check = 0;
        for (int i=0; i<4; i++){
            if (a[i] + a[7-i] == 9 && a[i+1] - a[i] == 1){
                check ++;
            } else if(a[i] + a[7-i] == 9 && a[i+1] - a[i] == -1){
                check --;
            }
        }
        if(check == 4)
            System.out.println("ascending");
        else if(check == -4)
            System.out.println("descending");
        else
            System.out.println("mixed");
    }
}