문제)
1. 아래 조건을 만족하는 Java 프로그램을 작성합니다.
- 일정 범위(1~max변수의 값)의 난수를 발생시키는 과정에서 중복된 숫자가 나오지 않도록 하는 메소드 구현.
- 난수 발생 메소드 구현용 클래스(Math)와 콘솔 인터페이스 구현 클래스(Main)를 별도로 작성.
- 난수 발생의 결과는 정수형 배열(int[])로 반환하도록 한다.
- 난수 발생 메소드는 아래 형식으로 작성한다. 난수는 1부터 max 범위까지 발생시키고, 배열의 크기는 size로 지정한다.
- public static int[] randomFromAtoB(int max, int size)
- 결과 출력시 배열 요소를 정렬 시켜서 출력한다.
실행예)
배열 크기(2~n)?10
난수 범위(2~n)?50
발생 난수 : 4 6 9 10 18 25 33 34 43 47
- 1) 1~max 까지 저장할 수 있는 배열 준비 및 1~max를 초기값으로 저장
- 2) 배열 요소 전체를 랜덤하게 뒤섞는다. 처음 요소부터 마지막 요소까지 난수로 발생한 위치의 요소와 바꾸면 된다.
- 3) 배열 요소 중에서 특정 갯수(size개) 만큼만 새로운 배열에 저장
- 4) 새로운 배열 반환
==============================================
답)
--------------------
//Math.java
package com.test;
public class Math {
//메소드 추가 -> static 멤버
public static int[] randomFromAtoB(int max, int size) {
int[] result = new int[size]; //난수가 저장될 결과 배열
int[] array = new int[max]; //1~max까지의 수 저장용 임시 배열
for (int i=0; i<array.length; ++i) {
array[i] = i+1;
}
for (int i=0; i<array.length; ++i) {
int pos = (int)(java.lang.Math.random()*max);
int temp = array[pos];
array[pos] = array[i];
array[i] = temp;
}
for (int i=0; i<size; ++i) {
result[i] = array[i];
}
return result;
}
}
--------------------
//Main.java
package com.test;
import java.util.*;
public class Main {
public static void main(String[] args) {
//입력 -> 외부 입력 -> Scanner
Scanner sc = new Scanner(System.in);
System.out.print("배열범위?");
int size = sc.nextInt();
System.out.print("난수범위?");
int max = sc.nextInt();
sc.close();
//처리 -> 추가 액션 -> 메소드 호출
int[] result = Math.randomFromAtoB(max, size);
//출력
System.out.print("발생 난수(정렬전) : ");
for (int i=0; i<result.length; ++i) {
System.out.printf("%d ", result[i]);
}
System.out.println();
Arrays.sort(result);
System.out.print("발생 난수(정렬후) : ");
for (int i=0; i<result.length; ++i) {
System.out.printf("%d ", result[i]);
}
}
}
'Test' 카테고리의 다른 글
JSP Test - 문제 (0) | 2015.06.22 |
---|---|
JDBC TEST - 답 (0) | 2015.06.21 |
JDBC TEST - 문제 (0) | 2015.06.21 |
JavaSE - Test 2 (답) (0) | 2015.06.21 |
JavaSE - Test 2 (문제) (0) | 2015.06.21 |