java 2차원배열 및 알고리즘

메타플랫폼대표
|2024. 5. 14. 17:33
반응형
package mymain;

import util.MyArray2;

public class _07_Example07_배열 {

	// 배열 : 동일한 자료형이 연속할당되는 자료구조(인접리스트)
	public static void main(String[] args) {
		// 고정길이배열
		//											  행   열
		int [][] mm = new int[3][4];
		MyArray2.display(mm);
		
		// 가변길이배열(행마다 열의 갯수가 틀린배열)
		int [][] mm2 = new int[3][];
		mm2[0] = new int[2];
		mm2[1] = new int[3];
		mm2[2] = new int[4];
		
		System.out.println("---[가변길이배열]---");
		MyArray2.display(mm2);
		
		// 2차원배열 초기화
		int [][] mm3 = new int[][] {
			{1,2},{3,4,5},{6,7,8,9}
			// 0            1                2
		};
		MyArray2.display(mm3);

		
		System.out.println("---[가변길이배열2]---");
		// 테트리스
		int [][] box = {
				{1,1,1},
				{1,1,1},
				{1,1,1},
		};
		int [][] block_l = {
				{1,0,0},
				{1,0,0},
				{1,1,1},
		};
		int [][] block_t = {
				 {1,1,1},
				{0,1,0},
				{0,1,0},
		};
		MyArray2.display_block(box);
		MyArray2.display_block(block_l);
		MyArray2.display_block(block_t);
		
		
		
		
	}// main-end
}
package util;

public class MyArray2 {

	public static void display(int[][]mm) {
		for(int i =0; i < mm.length; i++) {	// 행첨자
			for(int k = 0; k < mm[i].length; k++) {	// 열첨자
				System.out.printf("[%4d]", mm[i][k]);
			}
			System.out.println();
		}
	}// display-end
	
	public static void display_block(int[][]mm) {
		for(int i =0; i < mm.length; i++) {	// 행첨자
			for(int k = 0; k < mm[i].length; k++) {	// 열첨자
				if(mm[i][k] == 1) {
					System.out.print("■");
				} else {
					System.out.print("□");
				}
			
			}
			System.out.println();
		}
	}// display-end
}

 

★★★★마방진구하기 온라인 Season.4★★★★

package util;

public class MaBangJin {

	int chasu;
	int [][] ma_array;
	// main 마방진에 있는 차수를 가져오기 위해서 사용한다.
	public void setChasu(int chasu) {
		this.chasu = chasu;
		// 마방진 생성
		make_mabangjin();
	}

	private void make_mabangjin() {
		// 마방진을 채울 배열 생성
		ma_array = new int [chasu][chasu];
		
		int row = 0; // 행첨자
		int col = chasu/2; // 열첨자
		int su = 1; // 채워질 값
		
		// 1. 첫 번째 칸 값 채우기
		ma_array[row][col] = su++;
		// 2. 채우는 식
		for(int i = 0; i < chasu*chasu-1; i++) {
			// 1. 대각으로 이동
			row--; col++;
			// 2. 위/우측으로 나갔냐? (지금 현재 전부 0으로 값이 저장되어 있다)
			if (row<0 && col == chasu) {
				// 아래로 2칸
				row += 2;
				// 앞으로 1칸
				col --;
			}
			// 3. 위로 나갔냐 -> 맨 아래로 이동시켜라
			else if (row<0) {
				row =  chasu-1;
			}
			// 4. 우측으로 나갔냐
			else if(col == chasu) {
				col = 0;

			}
			// 5. 값이 이미 채워져 있냐?
			if (ma_array[row][col] != 0) {
				row = row + 2;
				col--;
			}
			// 값넣기
			ma_array[row][col] = su++;
		} // for-end
		
	}// make_mabangjin-end
	
	// 만든 마방진 출력하기
	public void display() {
		for(int i = 0; i < chasu; i++) {
			for (int k = 0; k < chasu; k++) {
				System.out.printf("%4d", ma_array[i][k]);
			}
			System.out.println();
		}
	}// display-end
}
package mymain;

import java.util.Scanner;

import util.MaBangJin;

public class _08_Exam08_마방진 {

	public static void main(String[] args) throws InterruptedException {

		
		Scanner scanner = new Scanner(System.in);
		int chasu; // 칸수
		String yn = "y"; // 계속 진행할지 유무
		
		MaBangJin mabangjin = new MaBangJin();
		
		while(true) {
			System.out.println("Season 서버(3, 5, 7, 9, 11):");
			chasu = scanner.nextInt();
			if(chasu%2==0) {
				System.out.println("홀수만 입력해주시길 바랍니다.");
				continue;
			}
			// 마방진 객체에 차수를 넣는다 => 마방진 구성
			mabangjin.setChasu(chasu);
			// 마방진 출력
			mabangjin.display();
			
			// 계속유무
			System.out.println("게임 매칭하기(y/n)");
			yn = scanner.next();
			if(!yn.equalsIgnoreCase("y")) break;
		}// while-end
		
		System.out.println("---[End]---");
	}// main-end
}

 

 

- 달팽이 알고리즘

package mymain;

import java.util.Scanner;

import util.MaBangJin;
import util.Snail;

public class _09_Exam09_달팽이 {

	public static void main(String[] args) throws InterruptedException {

		
		Scanner scanner = new Scanner(System.in);
		int chasu; // 칸수
		String yn = "y"; // 계속 진행할지 유무
		
		Snail snail = new Snail();
		
		while(true) {
			System.out.println("차수를 입력");
			chasu = scanner.nextInt();
			// 마방진 객체에 차수를 넣는다 => 마방진 구성
			snail.setChasu(chasu);
			// 마방진 출력
			snail.display();
			// 계속유무
			System.out.println("게임 매칭하기(y/n)");
			yn = scanner.next();
			if(!yn.equalsIgnoreCase("y")) break;
		}// while-end
		
		System.out.println("---[End]---");
	}// main-end
}
package util;

public class Snail {
	
	// 방향상수
	public static final int LEFT = 1;
	public static final int RIGHT = 2;
	public static final int UP = 3;
	public static final int DOWN = 4;
	
	int chasu;
	int [][] snail_array;
	int direction; // 이동방향
	
	public void setChasu(int chasu) {
		this.chasu = chasu;
		make_snail();
	} // setChasu-end

	private void make_snail() {
		snail_array = new int[chasu][chasu];
		// 방향 : 오른쪽
		direction = RIGHT;
		int row = 0;
		int col = -1;
		int su = 1;
		
		for(int i =0; i < chasu*chasu; i++) {
			if(direction == RIGHT) {
				col++;
				if(col == chasu || snail_array[row][col] != 0) {
					col--; row++;
					direction = DOWN;
				}
				
			}else if (direction == DOWN) {
				row++;
				if(row == chasu || snail_array[row][col] != 0) {
					row--; col--;
					direction = LEFT;
				}
				
			}else if (direction == LEFT) {
				col--;
				if(col == -1 || snail_array[row][col] != 0) {
					row--; col++;
					direction = UP;
				}
				
			}else if (direction == UP) {
				row--;
				if(snail_array[row][col] != 0 || snail_array[row][col] != 0) {
					row++; col++;
					direction = RIGHT;
				}
			}
			// 값넣기
			snail_array[row][col] = su++;
		}
	} // make_snail-end
	
	public void display() {
		for(int i = 0; i < chasu; i++) {
			for (int k = 0; k < chasu; k++) {
				System.out.printf("%4d", snail_array[i][k]);
			}
			System.out.println();
		}
	}// display-end

}

 

 

- 달팽이 알고리즘을 위는 직관적인 방법이고 새로운 로직를 찾아서 만드는 방법

col 열과 row 열에서 +만 되는 구간이 있고, -만 되는 구간이 따로 존재한다.

void make_snail2() {
    snail_array = new int[chasu][chasu];
    int n = chasu;
    int row = 0;
    int col = -1;
    int su = 1;
    int sign = 1;
    while(n>0) {
        for (int i = 0; i < n*2-1; i++) {
            // 차수를 5를 넣을시 0,1,2,3,4번 수행
            if(i<n) col = col + sign;
            // 차수를 5를 넣을시 5, 6, 7, 8번 수행
            else row = row + sign;
            snail_array[row][col] = su++;
        }// for-end
        sign = -sign; // toggle 방식
        n--;
    }

 

 

 

 

달력 만들기 알고리즘

 

생각해야 할 것


2024년 5월 1일은 무슨 요일인가?
2024년 1월 1일부터의 기간부터 5월 1일까지의 기간 % 7 == 0 (월요일)
각 month 별로 며칠까지 존재하는지, 1차항배열로 만들기
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
2월은 4년마다 29일로 따진다. (4의 배수이면서, 100의 배수가 아니여야 한다. 400년은 예외)

package mymain;

import java.util.Scanner;

import util.MyCalendar;

public class _10_Exam10_달력 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int year;
		int month;
		String yn = "y";
		
		MyCalendar mc = new MyCalendar();
		
		while(true) {
		
			System.out.println("년/월 :");
			// nextInt는 spacebar를 입력구분자로 판단한다.
			year = scanner.nextInt();
			month = scanner.nextInt();
			
			// 입력값을 MyCalendar에게 전달
			mc.setDate(year, month);
			
			// 달력 출력
			mc.display();
			System.out.println("계속(y/n) :");
			yn = scanner.next();
			if(!yn.equalsIgnoreCase("y")){
				break;
			}
		}// while-end
			System.out.println("---[End]---");
			scanner.close(); // 이런 형태의 프로그램은 무한히 실행되기에 scanner를 종료시킨다.
		
		
		
	}// main-end
}
package util;

import java.util.Calendar;

public class MyCalendar {

	// 각달의 마지막 날을 저장 [인덱스로 받았으므로, month-1을 해서 받을 수 있다]
	int [] month_array = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	
	private int year;
	private int month;
	int [][] cal_array;
	
	public void setDate(int year, int month) {
		this.year = year;
		this.month = month;
		makeCalendar();
	}// setDate-end
	
	// 윤년여부(4년에 1번 : 지구가 완전히 정확하게 365일을 도는것이 아니라, 
	// 윤년으로 하루를 29일로 하루를 더 채워야 정확히 맞는다.)
	boolean isYoon() {
		// 1. 최우선 윤년 조건(400년마다) : 400의 배수
		if(year % 400 == 0) return true;
		// 2. 4의 배수이면서, 100의 배수가 아닌 해
		if(year%4 == 0 && year%100 !=0) return true;
		return false;
	}
	
	void makeCalendar() {
		cal_array = new int[6][7];
		int yoil;
		int week = 0;
		// 윤년여부체크
		if(isYoon())
			month_array[1] = 29;
		else
			month_array[1] = 28;
		// month_array를 [인덱스로 받았으므로, month-1을 해서 받을 수 있다]
		int last_day = month_array[month-1];
		
		// 요일구하기
		Calendar c = Calendar.getInstance();
		
		// 날짜수정(내가 입력받은 날짜) month는 인덱스 기준이라 구하고 싶은 월 -1
		c.set(year, month-1, 1);
		
		// Calendar에서 요일은 => 1:일   2:월   3:화   4: 수   5: 목   6: 금   7: 토
		// 배열의 첨자를 관리해야 하기에 1을 빼준다.
		yoil = c.get(Calendar.DAY_OF_WEEK) -1;
		
		// 달력 채우기(이전달) - 1월의 전달은 12월이기에 유의 / 1일이 처음인경우 이전달은 없다
//		if (yoil > 0) {
//			int prev_yoil = yoil -1;
//			int prev_month;
//			if(month==1)
//				prev_month = 12;
//			else {
//				prev_month = month-1;
//				int prev_last_day = month_array[prev_month-1];
		int prev_last_day = month_array[month == 1 ? 11 : (month-2)];
		// 마지막 날부터 거꾸로 채우기
		for(int i = yoil -1;0 <= i ;i--) {
			cal_array[0][i] = prev_last_day--;
		}
				
		// 달력 채우기(현재달)
		for(int i = 1; i <= last_day; i++) {
			// i의 범위 : i~last_day
			cal_array[week][yoil] = i;
			yoil++;
			if(yoil > 6) {
				week++; // 다음줄로 내려가라
				yoil = 0;
			}
		}
		
		// 달력 채우기(다음달)
		for(int i = 1; i <= 14; i++) {
			// i의 범위 : i~last_day
			cal_array[week][yoil] = i;
			yoil++;
			if(yoil > 6) {
				week++; // 다음줄로 내려가라
				yoil = 0;
				if(week == 6) break;
			}
		}
		
	}// makeCalendar-end
	public void display() {
		// 제목
		System.out.printf("%d년 %02d월\n", year, month);
		for(int i  = 0; i < 6; i++) {	// 주차(row)
			for(int k = 0; k < 7; k++) {	// 요일(col)
				System.out.printf("%4d", cal_array[i][k]);
			}
			System.out.println();
		}
	}// display-end
	
}

 

 

 

- 로또 번호 추첨기 알고리즘

package util;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;

public class Lotto {

	int [] lottoArray;	// 내가 작성한 로또 번호
	int [] lottoResultArray = new int[7]; // 추첨번호 6자리 + 보너스번호 1자리

	// 로또 구매 수동
	public void setLottoArray(int [] lottoArray) {
		this.lottoArray = lottoArray;
		Arrays.sort(lottoArray);
	}

	Random random = new Random();
	String rank; // 등수
	int count = 0; //맞은갯수
	int bounsCount = 0; // 보너스번호 카운팅

	public void makeWinNo() {
		int n = 7;
		int i = 0;
		// 방법1
		//		while (n>0) {
		//			int su = random.nextInt(45)+1; // 1~45
		//			// 현재 발생된 수가 이전에 있냐
		//			boolean bSame = false;
		//			for(int k = 0; k < i; k++) {
		//				if(lottoResultArray[k] == su)
		//					bSame = true;
		//					break;
		//			}
		//			//  같은수가 있으면
		//			if(bSame) continue;
		//			lottoResultArray[i] = su;
		//			i++;
		//			n--;
		//		}// while-end
		// 방법 2
		OUT_WHILE : while (n>0) {
			int su = random.nextInt(45)+1; // 1~45
			for(int k = 0; k < i; k++) {
				if(lottoResultArray[k] == su)
					continue OUT_WHILE;
			}
			lottoResultArray[i] = su;
			i++;
			n--;
		}// while-end

		// 마지막 7번째를 제외한 앞번호 6자리 오름차순 정렬
		Arrays.sort(lottoResultArray, 0, 6);; // 인덱스 0부터 6-1까지


	}// makeWinNo-end

	// 올바른 번호넣었는지 확인(중복 x 1~45)
	public boolean isValidation() {
		for(int i = 0; i < lottoArray.length; i++) {
			if (0 < lottoArray[i] && lottoArray[i] < 46) {
				return false;
			}
			for(int k = 0; k < lottoArray.length; k++) {
				if(lottoArray[i] == lottoArray[k])
					return true;
			}
		}
		return false;
	}// isValidation-end


	public void checkRank() {
		count = 0; rank = ""; bounsCount = 0;
		for(int i = 0; i < lottoResultArray.length; i++) {
			// 가상의 변수에 배열의 인덱스 값 저장 (보너스점수는 동일한 숫자가 5개가 있어야한다)
			for(int k = 0; k < 6; k++) {
				if(lottoResultArray[i] == lottoArray[k]) {
					count++;
				} else if (count == 5 && lottoResultArray[6] == lottoArray[k]) {
					count--; bounsCount++;
				}
			}
		}//for-end

		// 카운트와 보너스 카운트에 따른 번호 매기기
		if (count == 6) {
			rank = "1등";
		}else if(count == 5 && bounsCount == 1) {
			rank = "2등";
		}else if (count == 5) {
			rank = "3등";
		} else if(count == 4) {
			rank ="4등";
		} else if(count == 3) {
			rank = "5등";
		} else {
			rank = "꽝";
		}
	}// checkRank-end

	public void display() {
		System.out.println("추첨번호는 : ");
		for(int i = 0; i<7; i++) {
			if(i<6) {
				System.out.printf("%3d", lottoResultArray[i]);
			} else {
				System.out.printf(" (%d)", lottoResultArray[i]);
			}
		}
		System.out.println();
		// 선택(유저)번호 출력
		for(int i = 0; i<6 ; i++) {
			System.out.printf("%3d", lottoArray[i]);
		}
		System.out.printf("맞은 갯수 : %d(개)\n", count);
		System.out.printf("내 등수 : %s입니다.\n", rank);

	}// display-end


}
package mymain;

import java.util.Scanner;

import util.Lotto;

public class _11_Exam11_로또 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int [] lottoArray = new int[6];
		String yn = "y";
		
		Lotto lotto = new Lotto();
		// 추첨번호 생성
		lotto.makeWinNo();
		
		while(true) {
			System.out.print("로또 번호 6자리를 입력해주세요.");
//			for(int i = 0; i < lottoArray.length; i++) {
//				lottoArray[i] = scanner.nextInt();
//				System.out.println(lottoArray[i]);
			lottoArray[0] = scanner.nextInt();
			lottoArray[1] = scanner.nextInt();
			lottoArray[2] = scanner.nextInt();
			lottoArray[3] = scanner.nextInt();
			lottoArray[4] = scanner.nextInt();
			lottoArray[5] = scanner.nextInt();
			
			// 1. 로또처리 객체에게 넘긴다.
			lotto.setLottoArray(lottoArray);
			// 2. 검증요청
			if(lotto.isValidation()) {
				System.out.println("입력번호가 유효하지 않습니다.");
				continue;
			}
			// 3. 등수체크한 결과
			lotto.checkRank();
			// 4. 결과출력
			lotto.display();
			
			System.out.println("계속(y/n) : ");
			yn = scanner.next();
			if(!yn.equalsIgnoreCase("y")) break;
		}// while-end
		System.out.println("로또 추첨이 종료되었습니다.");
		scanner.close();
	}// main-end
}

 

 

-made in teacher

package util;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;

public class Lotto2 {

	int [] lottoArray;	// 내가 작성한 로또 번호
	int [] lottoResultArray = new int[7]; // 추첨번호 6자리 + 보너스번호 1자리

	// 로또 구매 수동
	public void setLottoArray(int [] lottoArray) {
		this.lottoArray = lottoArray;
		Arrays.sort(lottoArray);
	}

	Random random = new Random();
	String rank; // 등수
	int count = 0; //맞은갯수
	int bounsCount = 0; // 보너스번호 카운팅

	public void makeWinNo() {
		int n = 7;
		int i = 0;
		OUT_WHILE : while (n>0) {
			int su = random.nextInt(45)+1; // 1~45
			for(int k = 0; k < i; k++) {
				if(lottoResultArray[k] == su)
					continue OUT_WHILE;
			}
			lottoResultArray[i] = su;
			i++;
			n--;
		}// while-end

		// 마지막 7번째를 제외한 앞번호 6자리 오름차순 정렬
		Arrays.sort(lottoResultArray, 0, 6);; // 인덱스 0부터 6-1까지


	}// makeWinNo-end

	// 올바른 번호넣었는지 확인(중복 x 1~45)
	public boolean isValidation() {
		// 1. 유효범위(1~45)
		for(int no : lottoArray) {
			// 1~45 사이 값이 아니면
			if(no<1 || no < 45)return true;
		}
		for(int i = 0; i < lottoArray.length-1; i++) {
			if(lottoArray[i] == lottoArray[i+1]) return false;
		}
		return true;
	}// isValidation-end


	public void checkRank() {
		count = 0; rank = ""; bounsCount = 0;
		for(int i = 0; i < 6; i++) {
			for(int k = 0; k < 6; k++) {
				if(lottoArray[i] == lottoResultArray[k]) {
					count++;
					break;
				}
			}
		}

		// 카운트와 보너스 카운트에 따른 번호 매기기
		if (count == 6) {
			rank = "1등";
		}else if (count == 5) {
			rank = "3등";
		} else if(count == 4) {
			rank ="4등";
		} else if(count == 3) {
			rank = "5등";
		} else {
			rank = "꽝";
		}

		if(count == 5) {
			for(int i = 0; i < 6; i++) {
				if(lottoResultArray[6] == lottoArray[i]) {
					rank = "2등";
					break;
				}
			}
		}
	}// checkRank-end

	public void display() {
		System.out.println("추첨번호는 : ");
		for(int i = 0; i<7; i++) {
			if(i<6) {
				System.out.printf("%3d", lottoResultArray[i]);
			} else {
				System.out.printf(" (%d)", lottoResultArray[i]);
			}
		}
		System.out.println();
		// 선택(유저)번호 출력
		for(int i = 0; i<6 ; i++) {
			System.out.printf("%3d", lottoArray[i]);
		}
		System.out.println();
		System.out.printf("맞은 갯수 : %d(개)\n", count);
		System.out.printf("내 등수 : %s입니다.\n", rank);

	}// display-end


}
반응형

'java(2)↗' 카테고리의 다른 글

java 알고리즘 보물창고  (0) 2024.05.29
java Stream  (0) 2024.05.29
java 요약노트(2)  (0) 2024.05.13
VO와 DTO와 DAO  (0) 2024.05.12
java 네트워크  (0) 2024.05.10