본문 바로가기

프로그래밍/통계

난수의 개수 세기

class exercise
{
public static void main(String[] args){

int[] num = new int[10];
int[] count = new int[10];

for(int i = 0; i<num.length; i++){
num[i] = (int)(Math.random()*10);
System.out.print(num[i] + ", ");
}

for(int i = 0; i<num.length; i++){
count[num[i]]++;
}

System.out.println();
for(int i = 0; i<count.length; i++){
System.out.println( i + "의 개수 : " + graph('#', count[i]) + " " + count[i]);
}
}

public static String graph(char shape, int value){

char[] bar = new char[value];

for(int i = 0 ; i<bar.length; i++){
bar[i] = shape;
}

return new String(bar);

}
}


음... 이걸로 뭘 만들어볼 수는 없을까?


약간 개념은 다르지만, 줄기-잎 그래프를 만들어볼 수 있을 것 같다.


코드를 좀 변형해서, 시험점수라고 생각하고 해당 점수대에 몇 명이 있는지 만들어보았다.

대신 기호 '#'을 활용해서 그래프적인 측면을 강조했다.


문제가 하나 발생했는데, 시험점수 100점은 '미만'이라고 써주는 의미가 없다.

따라서 이를 적절하게 수정해야 하는데 아직 방법을 못찾았다.



class exercise
{
public static void main(String[] args){

int[] num = new int[10];
int[] count = new int[10];

Random random = new Random();

for(int i = 0; i<num.length; i++){
num[i] = (int)(random.nextInt(100)+1);
System.out.print(num[i] + ", ");
}

for(int i = 0; i<num.length; i++){
if(num[i]==100){
count[count.length-1]++;
} else{
count[num[i]/10]++;
}

}

System.out.println();
for(int i = 0; i<count.length; i++){
System.out.println( i*10 + "점 이상 ~ " + (i+1)*10 + "점 미만 : "                                              + graph('#', count[i]) + " " + count[i] + "명");
}
}

public static String graph(char shape, int value){

char[] bar = new char[value];

for(int i = 0 ; i<bar.length; i++){
bar[i] = shape;
}

return new String(bar);

}


}

이번에는 Random 클래스를 활용해서 0부터 100까지 난수를 생성했다.


1. 여기서 주의해야할 점은 nextInt (100) 을 하면, 100은 포함되지 않으므로 +1을 해주어야 한다.


2. count 배열의 개수는 10자리이므로 ( 점수 ) / 10을 해야 제 자리를 찾아갈 것이다.


count [ 0 ] = 0~10점

count [ 1 ] = 10점~20점

...

count [ 9 ] = 90점~100점 이렇게 말이다.


3. 최고점, 최저점을 출력할 수도 있다.



class exercise
{
public static void main(String[] args){

int[] num = new int[10];
int[] count = new int[10];


Random random = new Random();

for(int i = 0; i<num.length; i++){
num[i] = (int)(random.nextInt(100)+1);
System.out.print(num[i] + ", ");
}

int max = num[0];
int min = num[0];

for(int i = 1; i<num.length; i++){
if(max<num[i])
max = num[i];
}

for(int i = 1; i<num.length; i++){
if(min>num[i])
min = num[i];
}


for(int i = 0; i<num.length; i++){
if(num[i]==100){
count[count.length-1]++;
} else{
count[num[i]/10]++;
}

}
System.out.println();
for(int i = 0; i<count.length; i++){
System.out.println( i*10 + "점 이상 ~ " + (i+1)*10 + "점 미만 : "
+ graph('#', count[i]) + " " + count[i] + "명");
}

System.out.println("최고점 : " + max + "점");
System.out.println("최저점 : " + min + "점");
}

public static String graph(char shape, int value){

char[] bar = new char[value];

for(int i = 0 ; i<bar.length; i++){
bar[i] = shape;
}

return new String(bar);

}


}