본문 바로가기
프로그래밍/Java

[JAVA / 자바 / 자바 기초] 정수 배열 사이 값 구하기 + 카운트 -문제

by Mr.noobiest 2023. 12. 13.

java 문제

 

문제

1. 정수로 이루어진 배열이 있다.

2. 순서가 없이 무작위로 입력되어있음

3. 제일 작은값(min)과 제일 큰값(max)사이에 빈값이 몇개인지 카운트하는 클래스를 생성하라

 


 

 

바로 코드 짜기

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CheckBlankCount {

    private static List<Integer> countBlankValues(int[] ints) {
    	
        //정수로 이루어진 List를 입력하면 빈칸인 값이 몇개인지 count하는 함수
        //누락값 확인용    
        List<Integer> arrList = new ArrayList<>();

        int a_len = ints.length;
        
        //int[]인 ints를 오름차순 정렬
        Arrays.sort(ints);


	//1. 주어진 배열 ints 의 길이만큼의 배열 result 생성
        int[] result = new int[ints[a_len - 1] + 1];


	//2. ints의 각 자릿수를 지정 
        //ex) ints=[1,3,4,5]라면 -> result[1]=1,result[3]=1,result[4]=1,result[5]=1
        //3. 자릿수가 없을경우 생성 초기값 = 0
        for (int i = 0; i < a_len; i++) {
            result[ints[i]] = 1;
        }

	//4. 위에서 설정한 값을 토대로 1~N까지의 값중 없는값(0)을 인덱스 값으로 구한다. 
        for (int i = ints[0]; i <= ints[a_len - 1]; i++) {
            if (result[i] == 0) {
                arrList.add(i);
            }
        }
        return arrList;
    }

    public static void main(String[] args) {
        System.out.println(countBlankValues(new int[]{1, 5, 3, 2}));
        System.out.println(countBlankValues(new int[]{1, 7}));
        System.out.println(countBlankValues(new int[]{1, 2}));
        System.out.println(countBlankValues(new int[]{1, 7, 2, 2, 2}));
    }
}
 
 

 

실행 결과

입력 배열 결과
int[] {1,5,3,2} [4]
int[] {1, 7} [2, 3, 4, 5, 6]
int[] {1, 2} []
int[] {1, 7, 2, 2, 2} [3, 4, 5, 6]


 


 

추가 코드(이렇게 구한 결과 arrList의 갯수 구하는 코드)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CheckBlankCount {

    private static int countBlankValues(int[] ints) {

  
        List<Integer> arrList = new ArrayList<>();

        int a_len = ints.length;

        Arrays.sort(ints);

        int[] result = new int[ints[a_len - 1] + 1];

        for(int i = 0; i < a_len; i++){    
            result[ints[i]] = 1;
        }

        for(int i = ints[0]; i <= ints[a_len - 1]; i++){
            if (result[i] == 0){
                Integer j = Integer.valueOf(i);
                arrList.add(j);
            }
        }
        return arrList.size();
    }

    public static void main(String[] args) {
        System.out.println(countBlankValues(new int[]{1, 5, 3, 2}) == 1);  //[4]
        System.out.println(countBlankValues(new int[]{1, 7}) == 5);  //[2,3,4,5,6]
        System.out.println(countBlankValues(new int[]{1, 2}) == 0);  //[]
        System.out.println(countBlankValues(new int[]{1, 7}) == 2);  //[2,3,4,5,6]
    }
}

 


 

실행 결과

입력 배열 출력
new int[]{1, 5, 3, 2}) == 1 true
new int[]{1, 7}) == 5 true
new int[]{1, 2}) == 0 true
new int[]{1, 7}) == 2 false

 

 

끝.

728x90
반응형