알고리즘/기초

입력된 데이터를 읽고 각 숫자의 개수를 출력하는 프로그램

leegeonwoo 2023. 8. 7. 16:52

임의의 배열로 입력된 데이터를 읽어 각 데이터의 개수를 세어 *로 출력해주는 프로그램이다

 

임의의 데이터를 입력해준다.

int[] answer = {1,4,4,3,1,4,4,2,1,3,2};

 

answer데이터의 범위가 1,2,3,4 총 4개이므로 데이터 개수를 세어줄 배열의 길이를 4로 선언하여 생성해준다.

int[] counter = new int[4];

 

데이터의 범위는 4이지만 index는 0부터시작하기때문에 answer[i] - 1을 해주고,

데이터와 일치하는 index의 값을 증감(++)해준다.

for(int i=0; i<answer.length; i++) {

counter[answer[i]-1]++;

}

 

*이해를 돕기위한 counter배열

Index(실제데이터속성) 0(1) 1(2) 2(3) 3(4)
counter[i]++된 값 3 2 2 4

 

전체코드

public class Main {

public static void main(String[] args) {

int[] answer = {1,4,4,3,1,4,4,2,1,3,2};

int[] counter = new int[4];

 

for(int i=0; i<answer.length; i++) {

counter[answer[i]-1]++;

}

 

for(int i=0; i<counter.length; i++) {

System.out.printf("[%d]의 개수: ", i+1);

 

for(int j=0; j<counter[i]; j++) {

System.out.print("*");

}System.out.println();

}

}

}

 

출력결과

[1]의 개수: ***

[2]의 개수: **

[3]의 개수: **

[4]의 개수: ****

 

728x90