다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다.
1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다.
연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오.
첫째 줄에 8개 숫자가 주어진다. 이 숫자는 문제 설명에서 설명한 음이며, 1부터 8까지 숫자가 한 번씩 등장한다.
첫째 줄에 ascending, descending, mixed 중 하나를 출력한다.
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
8 1 7 2 6 3 5 4
ascending
descending
mixed
숫자들을 배열 arr에 담은 후,
오름차순인 경우 arr[0] - arr[1] = -1이 되고, 내림차순인 경우에는 1이 되므로 arr[0] - arr[1] 값을 기준으로 삼음.
→ mixed인 경우를 제외하고는 그 이후에도 arr[i] - arr[i+1]의 값이 1 또는 -1로 유지되기 때문!
중간에 정렬이 끊기는 경우 mixed로 판단하고 그 외에는 처음 기준대로 판단함.
#include <iostream>
using namespace std;
int main(void)
{
int arr[8];
for (int i = 0; i < 8; i++)
cin >> arr[i];
// 1이면 내림차순, -1이면 오름차순을 기준으로 판단
int check = arr[0] - arr[1];
for (int i = 1; i < 7; i++)
{
if (arr[i] - arr[j+1] != check) // 정렬이 끊기면?
{
cout << "mixed" << "\n" // mixed로 판단
return 0;
}
}
if (check == 1)
cout << "descending\n";
else if (check == -1)
cout << "ascending\n";
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
int[] arr = new int[8];
for (int i = 0; i < 8; i++) {
arr[i] = Integer.parseInt(s[i]);
}
// 1이면 내림차순, -1이면 오름차순을 기준으로 판단
int check = arr[0] - arr[1];
for (int i = 1; i < 7; i++)
{
if (arr[i] - arr[i+1] != check) // 정렬이 끊기면?
{
System.out.println("mixed"); // mixed로 판단
return;
}
}
if (check == 1)
System.out.println("descending");
else if (check == -1)
System.out.println("ascending");
}
}