gimyeondong 2020. 2. 12. 09:52
  • 프로그래머스, 백준알고리즘 -> 알고리즘레벨
  • 자신의 삶에서 나오는 아이디어

  • 배열 : 개념자체는 범용성 문법
    • but, java에서는 문법이 약간 다르다
  • 배열이란?
    • 동일한 타입을 가지는 변수들의 집합
  • 배열의 쓰임
    • 여러 개의 변수를 한번에 선언 가능.
    • 같은 형의 변수들을 연속적으로 쓸 수 있다.
    • 배열을 대체 할 수 있는 대안들이 많이 나온 상황(컬렉션) -> 그래도 여전히 쓰인다.
  • 배열 참조 변수 생성
    • DataType[] 배열이름;
    • 일반 선언문과 동일하며 배열이름 뒤 배열의 요소 크기를 정한다.
    • 배열 선언시 []괄호가 1개 일 때 1차원 배열 2개 일 때 2차원 배열이라 한다.
    • 사용할 수 잇는 배열의 요소의 첨자는 0부터 시작한다.
    • 배열의 이름은 배열의 첫 번째 주소를 가지는 참조 변수이다.
    • 가변적이고 큰 데이터 -> 힙메모리에 저장 (예전 c언어에서는 씀)
    • 그 주소값을 스택메모리에 (참조 변수)

import java.util.Scanner;

public class Exam_01 {

	public static void main(String[] args) {
		
		int a = 10;
//		int[] arr;//배열의 주소를 저장할 참조 변수 만들기(스택)->배열은 아님 가변적인 배열 본체는 힙에
		
//		new int[5];//new 힙에다 만들어짐.//주소값을 저장하거나 출력하지 않으면 오류 나타남
		//ex. 주소값1000번지->int형,String형 변수에 못넣음,주소도 자료형
		//system.in.read -> 값이 정해지지 않은 int형
		//sc.nextLine -> 값이 정해지지 않은 String형
		
		//(참조변수)=(인트형 변수 5개를 담을 배열을 만들었다)
		//cf. c언어에서는 참조변수에 자료크기를 넣지만 자바에서는 다르다.
		
//		int[] arr = new int[5]
//		arr[0] = 10;//0번째 칸에다가 10을 넣는다.
//		arr[1] = 20;
//		arr[2] = 30;
//		arr[3] = 40;
//		arr[4] = 50;

		int[] arr = new int[]{10, 20, 30, 40, 50};
		//선언하는 부분에서만 {}로 값 넣을 수 있음,{}안 개수를 세서 크기를 정하므로 배열[]은 비워둠
//		int i = 0;
//		while(i<5){			
//			System.out.println(arr[i]);
//			i++;
//		}
		for(int i = 0; i < arr.length; i++){
			System.out.println(arr[i]);
		}
		
//		arr[5] = 60;
		//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
		//배열의 첨자값(index)이 범위를 벗어남
		
		//첨자값은 offset의 의미를 가진다. '기준점에서부터 얼만큼 떨어졌는가?' offset 5 : 기준점에서 5만큼 떨어짐
		//기준점은 arr, arr[0] 1000번지 , arr[1] 1001번지, ... arr[4] 1004번지
		
//		System.out.println(arr[0]);
//		int index = 0;
//		System.out.println(arr[index]); // []안에 변수나 연산식이 들어가도 된다.
//		System.out.println(arr[5-3]);
//		System.out.println(arr[(int)(Math.random()*3)]); //결과적으로 int값이 나오면 된다.
//		
//		Scanner sc = new Scanner(System.in);
//		System.out.println(arr[Integer.parseInt(sc.nextLine())]);
		
	}
}

public class Quiz_01 {
	public static void main(String[] args) {
		// int형 배열 100칸짜리를 생성하고,
		// 각각의 칸에 1~100까지 저장하시오.		
		int[] arr = new int[100];
		for(int i = 0; i< arr.length; i++) {
			arr[i] = i+1;
		}				
		//정답확인 방법
		System.out.println(arr[0]);; //1
		System.out.println(arr[99]);; //100
	}
}
public class Quiz_02 {

	public static void main(String[] args) {
		// int형 배열 100칸짜리를 생성하고,
		// 각각의 칸에 100~1까지 저장하시오.
		int[] arr = new int[100];
		for(int i = 0; i< arr.length; i++) {
			arr[i] = arr.length-i;
		}				
		//정답확인 방법
		System.out.println(arr[0]); //100
		System.out.println(arr[99]); //1
		
	}

}

 

public class Quiz_03 {
	public static void main(String[] args) {
		//char 형 배열 26칸 짜리를 생성하고
		//배열의 각 요소에 Z~A까지 저장하세요.
		
		char[] arr = new char[26];
		for(int i = 0; i< arr.length; i++) {
			arr[i] = (char)('Z'-i) ; // 'A' =65
		}				
		
		//정답 확인 방법
		System.out.println(arr[0]); // Z
		System.out.println(arr[25]); // A
		
	}
}

 

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

			String[] str =new String[] {
					"To be conscious that you are ignorant is a great step to knowledge. -Benjamin Disraeli-",
					"Paradise is where I am. -Voltaire-",
					"You may be disappointed if you fail, but you are doomed if you don't try. -Beverly Sills-"
			};
			System.out.println("오늘의 명언!");
			//배열의 3개 명언 중 하나가 무작위로 출력되게 만드세요.
			System.out.println(str[(int)(Math.random()*3)]);
	}
}

배열의 선언

 


import java.util.Scanner;

public class Exam_02 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
//		System.out.print("1 번째 수 : ");
//		int num1 = Integer.parseInt(sc.nextLine());
//		
//		System.out.print("2 번째 수 : ");
//		int num2 = Integer.parseInt(sc.nextLine());
//		
//		System.out.print("3 번째 수 : ");
//		int num3 = Integer.parseInt(sc.nextLine());
//
//		System.out.println("num1 : "+num1);
//		System.out.println("num2 : "+num2);
//		System.out.println("num3 : "+num3);
		//배열을 쓰는 이유 : 반복을 줄일 수 있다.
		
		int[] nums = new int[3];
		for(int i = 0; i< nums.length; i++) {
			System.out.print((i+1)+" 번째 수 : ");
			nums[i] = Integer.parseInt(sc.nextLine());
			//변수 이름은 i값과 조합 불가능하지만 index값은 가능(numi X, nums[i] O),반복문에 유리
		}
		for(int i = 0; i< nums.length; i++) {
			System.out.println("nums"+(i+1)+" : "+nums[i]);
		}//for문 2번 반복?
	}
}

import java.util.Scanner;

public class Quiz_05 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		System.out.print("나이를 입력할 학생의 수는 입력해주세요. : ");
		int count = Integer.parseInt(sc.nextLine());

		String[] name = new String[count];

		int[] age = new int[count];

		for(int i = 0; i< name.length; i++) {
			System.out.print((i+1)+" 번째 학생의 이름 : ");
			name[i] = sc.nextLine();

			System.out.print((i+1)+" 번째 학생의 나이 : ");
			age[i] = Integer.parseInt(sc.nextLine());				
		}
		System.out.println("======= 결 과 =======");
		for(int i = 0; i< name.length; i++) {
			System.out.println(name[i]+" 학생은 "+age[i]+"세 입니다.");
		}	
	}
}

[ 2 ] count

 

[ tom ][ jack ] names

[ 0 ]    [ 1 ]

[ 15 ][ 20 ] ages

[ 0 ]  [ 1 ]

 

 


import java.util.Scanner;

public class Quiz_06 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int count = 3;
		String[] names = new String[count];
		int[] kor = new int[count];
		int[] eng = new int[count];

		for(int i =0;i<names.length;i++) {
			System.out.print((i+1)+"번째 학생 이름 : ");
			names[i] = sc.nextLine();
			System.out.print(names[i]+" 학생 국어 : ");
			kor[i] = Integer.parseInt(sc.nextLine());
			System.out.print(names[i]+" 학생 영어 : ");
			eng[i] = Integer.parseInt(sc.nextLine());		
		}
		System.out.println("이름	국어	영어	합계	평균");
		for(int i =0;i<names.length;i++) {
			System.out.println(names[i]+"	"+kor[i]+"	"+eng[i]+"	"+(kor[i]+eng[i])+"	"+(kor[i]+eng[i])/2.0);
		}



	}
}

public class Exam_03 {
	public static void main(String[] args) {
		//스왑기법
		//		int[] num = new int[] {1,2,3,4,5}; 		
		//		int a = num[2];
		//		num[2] = num[4];
		//		num[4] = a;
//		char[] A = new char[2];
//		char tmp;
//		
//		A[0] = 'A';
//		A[1] = 'B';
//		System.out.println(""+A[0]+A[1]);
//		
//		tmp = A[0];
//		A[0] =A[1];
//		A[1] = tmp;
//		System.out.println(""+A[0]+A[1]);
		int[] arr = new int[] {1,2,3,4,5};
		int tmp = arr[0];
		arr[0]=arr[1];
		arr[1] = tmp;

	    tmp = arr[1];
		arr[1]=arr[2];
		arr[2] = tmp;		

		tmp = arr[2];
		arr[2]=arr[3];
		arr[3] = tmp;
		
		for(int i=0;i<arr.length;i++) {
			System.out.print(arr[i]+"	");
		}
	}
}

//손코딩 테스트 대비! 한번쯤은 만들어 볼것
public class Quiz_07 {
	public static void main(String[] args) {
		//Bubble Sort
		int[] arr = new int[]{24, 99, 86, 34};
		//왼쪽이 오른쪽보다 크다면 스왑
		for(int i=0;i<arr.length;i++) {
			System.out.print(arr[i]+" ");			
		}
		System.out.println("");
		//n-1의 반복문을 n-1번 반복
		for(int i =0; i<arr.length-1;i++) {
			for(int j=0; j<arr.length-1;j++) {
				if(arr[j]>arr[j+1]) {
					int tmp = arr[j];
					arr[j]=arr[j+1];
					arr[j+1] = tmp;	
				}
			}
		}
		for(int i=0;i<arr.length;i++) {
			System.out.print(arr[i]+" ");
		}
	}
}

//중복방지
//1)검증로직(이중for문,상황에 따라 ++뿐 아니라 --도)루프를 통해 뽑은 수를 변수에 저장,그 다음 난수를 뽑아놓은 변수와 같으면 다시 뽑기
//2)카드 섞기 기법
public class Exam_04 {
	public static void main(String[] args) {
		
//		System.out.println((int)(Math.random()*5+1));
//		System.out.println((int)(Math.random()*5+1));
//		System.out.println((int)(Math.random()*5+1));
//		System.out.println((int)(Math.random()*5+1));
//		System.out.println((int)(Math.random()*5+1));
		
		int[] numbers = new int[] {1,2,3,4,5};
		
//		numbers[0];
//		numbers[1];
//		numbers[2];
		
		for(int i =0; i<100; i++) {
		int x = (int)(Math.random()*5);
		int y = (int)(Math.random()*5);
		
		int tmp = numbers[x];
		numbers[x] = numbers[y];
		numbers[y] = tmp;
		}
		System.out.println
		(numbers[0]+" : "+numbers[1]+" : "+numbers[2]+" : "+numbers[3]+" : "+numbers[4]);
	}
}

//로또 1~45중 중복 제외 6개 숫자
public class Quiz_08 {
	public static void main(String[] args) {
		
		int[] lotto = new int[45];
		
		for(int i=0; i<lotto.length; i++) {
			lotto[i]=i+1;
		}
		
		for(int i =0; i< 500; i++) {

			int x = (int)(Math.random()*45);
			int y = (int)(Math.random()*45);			
			int tmp = lotto[x];
			lotto[x] = lotto[y];
			lotto[y] = tmp;
		}
		
		System.out.println
		(lotto[0]+" "+lotto[1]+" "+lotto[2]+" "+lotto[3]+" "+lotto[4]+" "+lotto[5]);
		
	}
}

//로또 시뮬
//1등, 당첨횟수, 당첨확률, 몇회만에 당첨
//로또 구매 금액
//2등 5자리가 동일 + 보너스 번호가 맞을 경우, 3등5000원
public class Quiz_09 {
	public static void main(String[] args) {
		//당첨 배열 생성
		int[] lotto = new int[45];		
		for(int i=0; i<lotto.length; i++) {
			lotto[i]=i+1;
		}		
		for(int i =0; i< 500; i++) {
			int x = (int)(Math.random()*45);
			int y = (int)(Math.random()*45);			
			int tmp = lotto[x];
			lotto[x] = lotto[y];
			lotto[y] = tmp;
		}

		//2등 세기
		int count2 = 0;
		//3등 세기
		int count3 = 0;
		//4등 세기
		int count4 = 0;
		//5등 세기
		int count5 = 0;

		//반복 시도할 배열 생성
		buylotto:for(int count =0;;count++) {
			int[] trylotto = new int[45];
			for(int i=0; i<trylotto.length; i++) {
				trylotto[i]=i+1;
			}		
			for(int i =0; i< 500; i++) {
				int x = (int)(Math.random()*45);
				int y = (int)(Math.random()*45);			
				int tmp = trylotto[x];
				trylotto[x] = trylotto[y];
				trylotto[y] = tmp;
			}
			System.out.println();
			System.out.print(count+"회 구입한 번호 :	("+trylotto[0]+")	("+trylotto[1]+")	("+trylotto[2]+")	("+trylotto[3]+")	("+trylotto[4]+")	("+trylotto[5]+")");

			int match = 0;

			// 당첨배열과 try배열의 중복값 개수 세기
			for(int i = 0; i<6; i++) {
				for(int j =0; j<6; j++) {
					if(lotto[i]==trylotto[j]) {
						match += 1;
					}
				}
			}

			if(match == 6) {
				System.out.println("1등! 인생역전!!!");				
				System.out.println("***금주의 당첨 번호***");
				System.out.println
				("("+lotto[0]+")	("+lotto[1]+")	("+lotto[2]+")	("+lotto[3]+")	("+lotto[4]+")	("+lotto[5]+")");
				System.out.println("보너스 번호 : "+lotto[6]);
				System.out.println("총 "+ count+"회 시도하여 구입비로"+(count*0.5)+"만원을 사용하였습니다.");
				System.out.println("그 동안 2등은 "+count2+"번 당첨되었습니다.");
				System.out.println("그 동안 3등은 "+count3+"번 당첨되었습니다.");
				System.out.println("그 동안 4등은 "+count4+"번 당첨되었습니다.");
				System.out.println("그 동안 5등은 "+count5+"번 당첨되었습니다.");		
				break;

			}else if(match == 5) {
				//보너스 숫자lotto[6]와 일치하면 2등
				for(int i =0; i<6; i++) {
					if(trylotto[i]==lotto[6]) {
						System.out.print("	2등! 보너스번호"+lotto[6]);
						count2 += 1;
						continue buylotto;
					}
				}
				//보너스 숫자와 일치하지 않으면 3등
				System.out.print("	3등");
				count3 += 1;
				continue buylotto;
			}else if(match == 4) {
				//4등
				System.out.print("	4등");
				count4 += 1;
				continue buylotto;
			}else if(match == 3) {
				System.out.print("	5등");
				count5 += 1;
				continue buylotto;
			}
		}
	}
}