[자바 알고리즘] 50. 로또 만들기

김건우's avatar
Feb 12, 2025
[자바 알고리즘] 50. 로또 만들기

1. 뼈대 만들기

package Test01; import java.util.Arrays; public class Lotto { public static void main(String[] args) { // 로또 번호를 담을 6공간의 배열 생성 int[] arr = new int[6]; // math.random 을 이용하여 45까지의 난수 생성 코드 int rand = (int) (Math.random() * 45)+1; arr[0] = rand; // 배열을 출력하는 코드 // Arrays.toString(배열이름)으로 출력이 가능 System.out.println(Arrays.toString(arr)); } }
 
랜덤 값이 0번지에 나옴
랜덤 값이 0번지에 나옴

2. 노가다 코드 작성하기

public class Lotto { public static void main(String[] args) { int[] arr = new int[6]; int rand = (int) (Math.random() * 45) + 1; arr[0] = rand; rand = (int) (Math.random() * 45) + 1; // 두번째 열에 대입하기 전 첫번째 배열이랑 중복되지 않는지 체크 if (arr[0] != rand) { } arr[1] = rand; rand = (int) (Math.random() * 45) + 1; if (arr[0] != rand) { } if (arr[1] != rand) { } arr[2] = rand; rand = (int) (Math.random() * 45) + 1; if (arr[0] != rand) { } if (arr[1] != rand) { } if (arr[2] != rand) { } arr[3] = rand; rand = (int) (Math.random() * 45) + 1; if (arr[0] != rand) { } if (arr[1] != rand) { } if (arr[2] != rand) { } if (arr[3] != rand) { } arr[4] = rand; System.out.println(Arrays.toString(arr)); } }
notion image

3. 함수화

import java.util.Arrays; import java.util.Random; public class Lotto { public static void main(String[] args) { int[] arr = new int[6]; int rand = (int) ((Math.random() * 45) + 1); arr[0] = rand; // 각 배열 자리에 랜덤 값을 넣는 코드 for (int i = 1; i < 6; i++) { rand = (int) ((Math.random() * 45) + 1); // 난수를 먼저 업데이트 하고 비교하고, 같은 값이면 재회전 하도록 하기 arr[i] = rand; // 비교하는 동안에는 배정된 난수가 변하면 안됨. for (int j = 0; j < i; j++) { if (arr[j] == rand) { // 새로운 난수로 재회전하기 위해서 난수 위에 for 구문을 회전시켜줌. i--; break; } } } System.out.println(Arrays.toString(arr)); } }
notion image
Share article

gunwoo