프로그래밍/Java 공부

배열, 이차원 배열

개발계발게발 2021. 5. 26. 17:30
반응형
import java.util.Arrays;
import java.util.Scanner;


public class Array04 {
	public static void main(String[] args) {
		
		int[] arr01 = null; //객체 기본 타입
		arr01 =new int [5];
		
		arr01[0] = 112;
		arr01[arr01.length-1] = 150;
		
		System.out.println(Arrays.toString(arr01));
		//String java.util.Arrays.toString(int[] a)
		//		 	경로    클래스명  메소드명(파라미터)
		
		String str = Arrays.toString(arr01);
		System.out.println(str);
		
		int[] arr02 = new int[] {112, 113, 114, 115, 116};
		System.out.println(arr02.length);
		
		int[] arr03 = {122, 123, 124, 125, 126};
		
		//	arr02의 값을 arr01에 복사
		for(int i = 0; i<arr01.length; i++) {
			arr01[i] = arr02[i];
		}
		
		
		for(int i = 0; i < arr01.length; i++) {
			System.out.println(arr01[i]);			
		}
		for (int i : arr01) {
			System.out.println(i);
		}
		
		//String name = new String("홍길동");	
		String name = "홍길동";	//문자열, R, 객체
		System.out.println(name.length());	//3
		
		String addr = "서울시 관악구 신림 1222";		
		System.out.println(addr.length());	//15
		
		System.out.println(name.charAt(0));	//홍
		//char java.lang.String.charAt(int index)
		
		char name01 = name.charAt(0);
		System.out.println(name01);	//홍
		
		System.out.println(addr.charAt(4));	//관
		
		String apple ="apple";
		System.out.println(apple.charAt(3));	//l
		System.out.println(Character.toUpperCase(apple.charAt(3)));	//대문자 L
		
		char[] appleArray = new char[apple.length()];

		appleArray[0] = apple.charAt(0);
		
		for(int i = 0; i < appleArray.length; i++) {
			appleArray[i] = apple.charAt(i);	//appleArray 배열에 apple 배열 복사
		}
		
		appleArray = apple.toCharArray();	//appleArray 배열에 appple 배열 복사
		
		System.out.println(Arrays.toString(appleArray));
		
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		char[] cArray = new char[N];

	}
}

 


 

import java.util.Arrays;
import java.util.Scanner;

public class Array05 {
	public static void main(String[] args) {
		// 사용자 입력

		// 문자열 대문자로 -> 캐릭터 배열로 만들기

		// 배열을 돌면서 정해진 숫자만큼 밀기 - > 출력

		Scanner sc = new Scanner(System.in);
		System.out.println("암호화 할 문자를 입력하세요.");
		String input = sc.next();

		System.out.println("이동할 숫자를 입력하세요.");
		int num = sc.nextInt();
		num %=26;
		char[] inputArray = input.toCharArray();
		for (int i = 0; i < input.length(); i++) {
			inputArray[i] = Character.toUpperCase(input.charAt(i));
		}
		for (int i = 0; i < input.length(); i++) {
			inputArray[i] += num;
			if(inputArray[i]>'Z') {
				inputArray[i]=(char) (inputArray[i]-26);
			}
		}			
		System.out.println("배열을 문자열로 변환");
		String conv = String.valueOf(inputArray);	//char array to String;
		String conv2 = String.copyValueOf(inputArray);	//동일
		System.out.println(inputArray);	//CBGAYD
		System.out.println(Arrays.toString(inputArray));	//[C, B, G, A, Y, D]
		System.out.println(conv);	//CBGAYD
		System.out.println(conv2);	//CBGAYD
		String.valueOf(123);	// ->"123"
		
		sc.close();
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class Array06 {
	public static void main(String[] args) {
		//int java, jsp, spring, total;
		String[] str = {"java", "jsp", "spring","Total"};
		int[] subject = new int[4];//
		double avg = 0;
		char grade;
		Scanner sc = new Scanner(System.in);
		
		for (int i = 0; i <str.length-1; i++) {
			do {
				System.out.println(str[i] + "점수를 입력하세요.");
				subject[i] = sc.nextInt();				
			}while (subject[i]<0 || subject[i]>100);
		}
		

		
		for(int i = 0; i<subject.length-1; i++) {
			subject[subject.length-1]+=subject[i];
		}
		avg = (double) subject[subject.length-1]/(subject.length-1);
		
		switch((int)avg/10){
		case 10:
		case 9:
			grade = 'A';
			break;
		case 8:
			grade = 'B';
			break;
		case 7:
			grade = 'C';
			break;
		case 6:
			grade = 'D';
			break;
		default:
			grade = 'F';
			break;		
		}
		for(int i = 0; i<str.length; i++) {
			System.out.println(str[i]+" 점수 : "+subject[i]);
		}
		
		System.out.println("JAVA 점수는 : "+subject[0]);
		System.out.println("JSP 점수는 : "+subject[1]);
		System.out.println("SPRING 점수는 : "+subject[2]);
		System.out.println("합계 : "+subject[3]);
		System.out.printf("평균 : %.2f\n",avg);	
		System.out.println("성적 : "+grade);
		System.out.println(Arrays.toString(subject));
	}
}

  1차원 점들이 주어졌을때
  그 중 가장 거리가 짧은 것의 쌍을 출력하는 함수를 작성
  (단, 점들의 배열은 모두 정렬되어있다고 가정)
  EX) S={1, 3, 4, 8, 13, 17, 20}
  결과값 = (3, 4) 

public class Daum {
	public static void main(String[] args) {
		int[] dot = { -5, -3, -2, 0, 4, 6, 8, 13, 17, 19, 21, 22};
		int temp = dot[1]-dot[0];
		
		for (int i = 0; i < dot.length-1; i++) {
			if (temp > dot[i + 1] - dot[i]) {
				temp = dot[i + 1] - dot[i];			
			}
		}		
		for (int i = 0; i < dot.length-1; i++) {//중복값 모두 출력
			if (temp == dot[i + 1] - dot[i]) {
				temp = dot[i + 1] - dot[i];			
				System.out.println("(" + dot[i] + " , " + dot[i + 1] + ")");
			}
		}	
	}
}

public class Daum {
    public static void main(String[] args) {
        int[] s={1, 3, 4, 8, 9, 13, 17, 20};
        System.out.println(findMinDist(s));
    }
    private static String findMinDist(int[] input) {
        int mVal = 0;
        String result = null;
        for(int i=0;i<input.length-1;i++){
            int tempVal = input[i+1] - input[i]; 
            if(result != null){
                if(tempVal < mVal){
                    mVal = tempVal; 
                    result = "(" + input[i] + "," + input[i+1] +")";
                }
            }else{
                mVal = tempVal; 
                result = "(" + input[i] + "," + input[i+1] +")";
            }
        }
        return result;
    }
}

 

로또 번호 추출

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Lotto {
	public static void main(String[] args) {
		int[] lotto = new int[6];

		for (int i = 0; i < lotto.length; i++) {
			int ran = (int) (Math.random() * 45 + 1);
			lotto[i] = ran;
			for (int j = 0; j < i; j++) {
				if (lotto[i] == lotto[j]) {
					System.out.println(lotto[i] + "," + lotto[j] + "번호중복 재추출");
					i--;// 번호 중복되면 다시 한번 돌기
					break;
				}
//				if (lotto[i] < lotto[j]) { // 오름 차순 정렬
//					int temp = lotto[j];
//					lotto[j] = lotto[i];
//					lotto[i] = temp;
//				}
			}
		}
		Arrays.sort(lotto);
		System.out.println(Arrays.toString(lotto));
		
		//컬랙션 SET;
		
		Set<Integer> lotto2 = new HashSet<Integer>();
		//중복을 제거 Set
		
		while(lotto2.size() < 6) {
			lotto2.add((int)(Math.random() * 45 +1));
		}
		System.out.println(lotto2);
		
	}
}

 

타노스는 프로그램의 균형을 위해서는 리스트의 원소 절반을 무작위로 삭제해야 한다고 믿고 있다.

타노스가 손가락을 튕겼을 때(프로그램을 실행했을 때) 입력된 리스트에서 절반의 원소를 무작위로 삭제하여 리턴하는 인피니티 건틀렛 프로그램을 작성하시오.

(무작위 삭제이므로 입력값이 같아도 출력값이 매번 달라야 합니다)

입력 예시

[2, 3, 1, 6, 5, 7]

출력 예시 1

[2, 5, 7]

출력 예시 2

[3, 6, 5]

참고: 리스트의 원소가 홀수개일 경우 절반의 확률로 절반보다 많은 원소가 삭제되거나 절반보다 적은 원소가 삭제되어야 합니다.

(만약 리스트의 원소가 7개라면 절반의 확률로 3개 또는 4개의 원소가 삭제됨)

 

import java.util.Arrays;

public class Tanos {
	public static void main(String[] args) {
		int[] people = {2, 3, 1, 6, 5, 7, 8};
		int ran = people.length/2;
		if(people.length%2==1) {	//원소가 홀수라면
			ran = (int) (Math.random()*2 + 1);// 1,2 절반 확률
			
			if(ran%2==1) {
				ran = (people.length/2)+1;	// 1일때 배열초기화 값 저장
				System.out.println("1일때");
			}
			else {
				ran = (people.length/2);	// 2일때 배열초기화 값 저장
				System.out.println("2일때");
			}			
		}
		int[] half = new int[ran];	//half 배열 초기화
		
		for(int i = 0; i < half.length; i++) {
			int r = (int) (Math.random()*people.length);
			if(people[r] !=0) {	// 0이 아니라면
				half[i] = people[r];	//half[i]에 people[i]값 저장
				people[r] = 0;	//저장된 people[r] 값 0으로 
			}else {
				i--;	//배열값이 0이면 다시 반복
			}			
		}
		System.out.println(Arrays.toString(people));
		System.out.println(Arrays.toString(half));
	}
}

 

이차원 배열

 

import java.util.Arrays;


public class MultiArray01 {
	public static void main(String[] args) {
		
		int[] arr01 = {10, 20, 30, 40};	//길이 4, index 0~3;
		int[][] multiArr01 = new int[4][5];	
		
		//대입
		multiArr01[1][2] = 500;
		multiArr01[3][1] = 100;
		int cnt=0;
		for (int i = 0; i < multiArr01.length; i++) {
			for (int j = 0; j < multiArr01[i].length; j++) {
				multiArr01[i][j]=cnt++;
			}
			
		}
		for (int i = 0; i < multiArr01.length; i++) {
			for (int j = 0; j < multiArr01[i].length; j++) {
				System.out.println(i + ","+j+"="+multiArr01[i][j]+" ");
			}	
		}
		//Arrays
		for (int i = 0; i < multiArr01.length; i++) {
			System.out.println(Arrays.toString(multiArr01[i]));
		}
		
		//foreach
		for(int[] is : multiArr01) {
			for(int i : is) {
				System.out.println(i);
			}
		}
	}
}

 

 

 

반응형