Arrays.Stream으로 이차원 배열 출력하는 방법 정도는 기억해두면 좋을 것 같다.

package org.example;

import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();

        int [][] matrix1 = new int[N][M];
        int [][] matrix2 = new int[N][M];
        int [][] result = new int[N][M];

        for(int i = 0; i < N; i++){
            for(int j = 0; j < M; j++){
                matrix1[i][j] = sc.nextInt();
            }
        }

        for(int i = 0; i < N; i++){
            for(int j = 0; j < M; j++){
                matrix2[i][j] = sc.nextInt();
            }
        }

        for(int i = 0; i < N; i++){
            for(int j = 0; j < M; j++){
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        Arrays.stream(result).forEach(row -> {
            Arrays.stream(row).forEach(value -> {
                System.out.print(value + " ");
            });
            System.out.println();
        });
    }
}

 

전공평점 = (학점 * 과목평점) / 학점의 총합

학점 , 등급 변환

 

과목, 학점, 등급을 입력받은 후

등급이 P 가 아닐 때만, 전공 학점 (학점 * 과목평점) / 학점을 누적시키면된다.

 

누적된 학점의 총합 (P 등급이 제외된) 과 전공 학점을 구할 수 있다.

package org.example;

import java.util.*;

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

        double totalScore = 0;
        double sumOfGradeAndSubjectAveragePoint = 0;

        for (int i = 0; i < 20; i++) {
            String subject = "";
            double score = 0;
            String grade = "";

            subject = sc.next();
            score = sc.nextDouble();
            grade = sc.next();

            if(!grade.equals("P")){
                sumOfGradeAndSubjectAveragePoint += majorScore(score, grade);
                totalScore+= score;
            }
        }
        double rst = result(totalScore, sumOfGradeAndSubjectAveragePoint);
        System.out.println(rst);
    }

    public static double majorScore(double score, String grade){
        // 등급 , 점수
        Map<String, Double> convertTo = new HashMap<>();
        convertTo.put("A+", 4.5);
        convertTo.put("A0", 4.0);
        convertTo.put("B+", 3.5);
        convertTo.put("B0", 3.0);
        convertTo.put("C+", 2.5);
        convertTo.put("C0", 2.0);
        convertTo.put("D+", 1.5);
        convertTo.put("D0", 1.0);
        convertTo.put("F", 0.0);

        return score * convertTo.get(grade);
    }

    public static double result (double sum, double sumOfEachScore){
        return sumOfEachScore / sum;
    }
}

시스템 입력을 String 으로 받고, 스트림으로 일단 변환했다.

 

스트림 API 메서드 사용하는 감을 아직 못잡겠다.

 

로직 자체는 떠올렸는데, 표현을 어떻게 하는지 모르겠다.

 

로직

필터링할 문자를 저장을 하고, 하나씩 꺼내서 입력받은 문자열요소와 순환하면서 비교후, 치환을 통해서 croatia 가 포함하지 않는 요소, 즉 a 와 같은 한글자의 문자열로 바꾼 후, String 의 길이를 출력하면 된다.

 

foreach 문을 통해서, List 를 순환하면서 요소를 하나씩 꺼내온다.

꺼낸 요소를 wordStream.map() 을 통해서 문자열을 치환한다.

map() 내부의 w 는 String word 의 문자열 전체를 의미하며, "helloc=" 이런 문자열을 가지고 있다면

 

w(helloc=).replace(list 요소, 치환 문자 a)

 

wordStream 은 "helloc=" 에서 -> "helloa" 로 바뀐다.

 

이걸 다시 wordStream 에 저장하여 모든 요소와 비교하여 치환하게 한다.

 

System.out::println 이런 표현도 어색해서 잘 모르겠다. 

뭔가 많이 보다보니, 한번씩 시도해보게 되는데 매커니즘을 좀 더 공부해봐야겠다.

 

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

        List<String> croatia = new ArrayList<>();
        croatia.add("c=");
        croatia.add("c-");
        croatia.add("dz=");
        croatia.add("d-");
        croatia.add("lj");
        croatia.add("nj");
        croatia.add("s=");
        croatia.add("z=");

        Stream<String> wordStream = Stream.of(word);

        for(String croatiaElements : croatia){
            wordStream = wordStream.map(w -> w.replace(croatiaElements, "a"));
        }
//        wordStream.forEach(System.out::println);
        wordStream.forEach(w -> System.out.println(w.length()));
    }
}

이 문제도 풀면서 GPT 에게 물어보았다.

Stream 예제를 눈으로 많이 익히기 위해서, 먼저 시도를 해보고 물어봤는데.

 

처음에는 Stream.of 로 arrays 를 string 으로 바꾸려고 했는데.. new String() 이라는 쉬운 방법이 있다니 충격.

 

처음부터 Map 자료형을 떠올리긴 했었는데, 중복제거나 이런 부분이 머리가 아파오기 시작하면서 for 문으로 시도하였으나, 

 

이중for 문에 if 가 들어가고, 케이스가 많아지면서 복잡해져서 포기했다.

 

new String(arrays) : char[] 를 String 으로 변환

chars() : String 에서 요소를 intStream 으로 변환

mapToObj(c -> (char) c ) : c 는 intStream 으로 변환된 ascii 코드의 문자 정수이며, (char) c 로 문자로 변환

filter : (Charater::isLetterOrDigit) : Charater 중에 영어문자 도는 숫자만 필터링

collect() : 스트림의 요소를 수집하여, 반환하며 어떻게 처리하고 반환할지 정의

Collectors.groupingBy() : 스트림 요소를 그룹화

 

Collections / Collectors 이런거 자주 사용되는데 따로 찾아봐야겠다.

package org.example;

import java.util.*;
import java.util.stream.Collectors;

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

        // 단어 입력 받는다.
        String word = sc.nextLine().toUpperCase();

        char[] arrays = word.toCharArray();

        Map<Character, Long> charFrequency = new String(arrays)
                .chars()
                .mapToObj(c -> (char) c)
                .filter(Character::isLetterOrDigit)
                .collect(Collectors.groupingBy(
                        Character::toUpperCase,
                        Collectors.counting()
                ));

        long maxFrequency = charFrequency.values().stream()
                .max(Long::compare)
                .orElse(0L);

        String mostFrequentChars = charFrequency.entrySet().stream()
                .filter(entry -> entry.getValue() == maxFrequency)
                .map(entry -> entry.getKey().toString())
                .collect(Collectors.joining());

        if (mostFrequentChars.isEmpty() || mostFrequentChars.length() > 1) {
            System.out.println("?");
        } else {
            System.out.println(mostFrequentChars);
        }
    }
}

역시나, 스트림 사용하는 것이 익숙하지 않고 많이 부족한 것 같다.

 

처음 작성한 코드는 아래와 같았다.

List<Integer> origin = spellings.boxed().collect(Collectors.toList());

List<Integer> reverse = origin;

Collections.reverse(reverse);

 

origin 과 reverse 를 비교해봐도, 둘의 결과가 계속 같았다.

 

GPT 에게 물어보았다. -> reverse = origin; 은 동일한 객체를 참조 하고 있는걸 뒤집기 때문에 문제다! 라고 했다.

원래 코드에서는 Collections.reverse(reverse);를 사용하여 reverse 리스트를 뒤집는 것이 아니라, reverse 리스트가 origin 리스트와 동일한 객체를 참조하게 됩니다. 이것은 실제로 두 리스트가 같은 데이터를 가리키기 때문에 reverse 또한 변경되면 origin도 변경됩니다.

따라서, Collections.reverse(reverse); 사용 대신에 reverse 리스트를 복제하여 origin의 역순을 만들어야 합니다. 아래는 수정된 코드에서 이것을 어떻게 수행하는지 보여줍니다:

 

// Create a reversed copy of the origin list
List<Integer> reverse = new ArrayList<>(origin); // Create a new list with the same elements

// Then reverse the 'reverse' list
Collections.reverse(reverse);

한번, 직접 검증해보고 싶어서 테스트를 해보기로 했다.

 

기존코드는 서로 같은 객체를 참조한다고 리턴했다.

 

이 때, 서로 같은 객체는 내부의 값이 같음을 비교하는 것이 아니라

 

두 변수가 참조하는 객체가 동일한 주소에 있다는 것을 말한다.

 

이 때, == 로 비교해야하며, equals 로 비교하면 내용 비교이므로 조심해야한다.

생각을 해보았는데, 진짜 헷갈린다. 여태껏 별 생각없이 써왔으니까.

침착하게 잘생각해보면, 인스턴스를 새로 생성한것이 아니기 때문에 같은 객체를 참조하는 것이 맞다.

한동안은 체화가 되게 의식하면서 쓰도록 노력해야겠다.

 

풀고나서 다른 풀이를 보면, 과연 스트림을 사용하는 것이 직관적이고 편한 것은 맞는데.

복잡한 사고를 피하는 건 아닌가 싶기도하다.

 

package org.example;

import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

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

        //단어
        String voca = sc.nextLine();

        IntStream spellings= voca.chars();

        List<Integer> origin = spellings.boxed().collect(Collectors.toList());

        List<Integer> reverse = origin.stream()
                .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
                    Collections.reverse(list);
                    return list;
                }));

        if(origin.equals(reverse)){
            System.out.println("1");
        }else{
            System.out.println("0");
        }
    }
}

 

문제를 보면, 결국 정수의 덧셈 뺄셈 문제이다.

 

피스의 알맞은 갯수를 담은 배열을 1 1 2 2 2 8 이렇게 생성한다.

 

그 다음, 입력한 값을 각각 인덱스에서 뺀다.

 

package org.example;

import java.util.Scanner;

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

        // 알맞은 세트
        int[] chess_set = {1, 1, 2, 2, 2, 8};

        // 체크할 세트 피스 입력
        int[] chess_piece_input = new int[6];

        // 결과 세트
        int[] result_set = new int[6];

        // 피스 갯수 입력
        for(int i = 0 ; i < chess_set.length; i++){
            chess_piece_input[i] = sc.nextInt();
        }

        // 연산 : set - piece
        for(int i = 0; i < chess_set.length; i++){
            result_set[i] = chess_set[i] - chess_piece_input[i];
        }

        // 결과 출력
        for (int x : result_set
             ) {
            System.out.print(x + " ");
        }
    }
}

솔직히 이런문제 너무 별론거같다.

 

 

public class Main {
    public static void main(String[] args) {
            System.out.println("         ,r'\"7");
            System.out.println("r`-_   ,'  ,/");
            System.out.println(" \\. \". L_r'");
            System.out.println("   `~\\/");
            System.out.println("      |");
            System.out.println("      |");
    }
}

String.substring();

package org.example;

import java.util.Scanner;

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

        // 단어 입력
        String voca = sc.nextLine();

        // 단어의 N 번째 스펠링
        int seletedOfSpell = sc.nextInt();

        String selected = voca.substring(seletedOfSpell-1, seletedOfSpell);

        System.out.println(selected);
    }
}

String.charAt();

package org.example;

import java.util.Scanner;

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

        // 단어 입력
        String voca = sc.nextLine();

        // 단어의 N 번째 스펠링
        int seletedOfSpell = sc.nextInt();

        char vocaArray = voca.charAt(seletedOfSpell-1);

        System.out.println(vocaArray);
    }
}

String.toCharArray();

package org.example;

import java.util.Scanner;

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

        // 단어 입력
        String voca = sc.nextLine();

        // 단어의 N 번째 스펠링
        int seletedOfSpell = sc.nextInt();

        char[] result = voca.toCharArray();

        System.out.println(result[seletedOfSpell-1]);
    }
}

조금 어려웠다.

버블정렬을 잘 쓸일이 없다보니, 할 때마다 복잡하게 느껴지고 불편했다.

그래서, 다른 방법이 없을까 고민했다.

 

1. 문제에서 필요한 스킬은 원하는 크기의 배열 생성

2. 배열에 값을 할당

3. 할당된 값을 특정 부분만 리버스 정렬하여

* 크기를 비교를 하는지, 단순히 자리만 바꾸는지는 문제에 따라서 다르겠지만 넋놓고 풀면 틀릴것 같다.

 

1. int array 로 값을 저장한다음, 스트림을 통해서 리스트로 변환해준다.

(변환한 이유는 Collections.reverse() 를 사용하기 위해서 래퍼타입으로 변환해줬다.

그리고, subList() 를 사용하여, reverse 할 범위를 지정할 수 있기 때문에 해볼만한 방법이라 생각했다.)

 

2. 원본을 복사하여 카피본을 저장한다

3. subList를 통해서 범위를 지정해서 자른다.

4. Collections.reverse(subList) 로 역정렬한다.

5. subList(시작, 끝) 을 사용했기 때문에 정확한 인덱스를 알고 있다

6. 원본인덱스에 맞게 덮어쓴다.

 

 

 

package org.example;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

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

        Scanner sc = new Scanner(System.in);

        int basketCount = sc.nextInt();
        int countOfReverse = sc.nextInt();

        int[] basket = new int[basketCount];
        // 바구니를 생성
        for(int i = 0 ; i < basketCount; i ++){
            basket[i] = i + 1;
        }

//        System.out.println(Arrays.stream(basket));

        // Reverse
        List<Integer> result = new ArrayList<>();
        for (int i = 0 ; i < countOfReverse; i++) {
            int indexOfFrom = sc.nextInt() - 1;
            int indexOfTo = sc.nextInt() - 1;

//            System.out.println("from : " + (indexOfFrom+ 1) + " to : " + (indexOfTo + 1) );

            List<Integer> list = Arrays
                    .stream(basket)
                    .boxed()
                    .collect(Collectors.toList());

            List<Integer> copy = list;
//            System.out.println("start : " + indexOfFrom + " end : " + indexOfTo);
            copy = copy.subList(indexOfFrom, indexOfTo + 1);
            Collections.reverse(copy);

//            System.out.println("copy reverse : " + copy);

            int count = 0;
            for(int j = indexOfFrom ; j < indexOfTo + 1; j ++){
                basket[j] = copy.get(count);
                count ++;
            }
        }
        for(int out : basket){
            System.out.print(out + " ");
        }
    }
}

 

주의할 부분은 인덱스 실수 하지 않기.

package org.example;

import java.util.*;
import java.util.stream.Collectors;

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

        Scanner sc = new Scanner(System.in);

        // 바구니 갯수
        int basketSize = sc.nextInt();
        int[] basket = new int[basketSize];

        // 공 바꿀 횟수
        int swapCount = sc.nextInt();

        int temp, source, target;

        // 바구니 초기화 (공 셋팅)
        for (int i = 1; i <= basketSize; i++){
            basket[i-1] = i;
        }

        // 스왑정보를 받을 인풋 호출 횟수
        for(int i = 0; i < swapCount; i++){
            // 바꿀공이 들어있는 바구니 번호 입력
            source = sc.nextInt() - 1;
            target = sc.nextInt() - 1;

            // 입력받은 바구니 번호를 토대로 스왑정렬로 교환
            temp = basket[source ];
            basket[source ] = basket[target];
            basket[target] = temp;
        }
        for (int out : basket
             ) {
            System.out.print(out + " ");
        }
    }
}

문제를 읽어보면, 차집합을 구하는 문제이다.

전체 U, 과제를 낸 집단을 A 라 했을 때,

U - A 를 구하는 문제.

 

Stream 을 잘 다룰줄 몰라서, 챗 GPT 에게 물어보았다.

  1. 스트림 API와의 호환성: 스트림 API는 기본 자료형(primitive types)에 대한 연산을 수행할 수 있도록 여러 메소드를 제공합니다. 그러나 배열을 스트림으로 변환할 때 기본 자료형 배열은 직접적으로 스트림으로 변환할 수 없습니다. 따라서 boxed()를 사용하여 기본 자료형을 래퍼 클래스로 변환하면 스트림 API를 활용할 수 있습니다.

 

package org.example;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

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

        Scanner sc = new Scanner(System.in);

        int[] submitted = new int[28];
        int[] all = new int[30];

        for (int counter = 0; counter < 28; counter++) {
            submitted[counter] = sc.nextInt();
        }

        for (int counter = 0; counter < 30; counter++) {
            all[counter] = counter + 1;
        }

        List<Integer> allList = Arrays.stream(all)
                .boxed()
                .collect(Collectors.toList());

        List<Integer> difference = new ArrayList<>(allList);
        difference.removeAll(Arrays.stream(submitted)
                .boxed()
                .collect(Collectors.toList()));

        for (int print : difference) {
            System.out.println("x: " + print);
        }
    }
}

List<Integer> allList = ...

Arrays.stream(all) 은 int[] 타입의 all 을 스트림으로 변환한다.

컬렉션API 를 사용하려면, Primitive 타입은 다룰수가 없기에 Wrapper Class 로 변환해준다. 

이것을 박싱이라고 표현한다.

그 것을 처리해주는 메서드가 boxed()이다. 

 

List<Integer> difference = ...

Arrays.stream(submitted) 는 int[] 타입 submitted 를 스트림으로 변환한다.

그다음 래퍼클래스로 박싱해준다. 

마지막으로 difference (all) 에서 removeAll() 을 사용하여, 괄호안의 요소를 제거할 수 있다.

 

문제를 이해하는데서 헷갈리는 부분이 많았다.

본능적으로 반복문 횟수를 정하는 요소를 찾아야 한다는 생각은 있었는데, 

잘보이지 않았다. 바구니 갯수를 반복해야할까? M번 공을 넣으려고 한다는 말을 아예 뺏으면 안헷갈렸을 것 같다.

 

M번이 횟수인지, 번호인지 혼동이 왔다.

뒷부분만 읽어보면 M 의 번호를 가진 공인걸 알 수 있다.

 

또 혼동된 부분은 가장 처음 바구니에는 공이 들어있지 않으며 라는 말?

모든 바구니가 비어있다는 말과는 다르기 때문에 이 부분을 어떻게 봐야하나 싶다.

그럼 결과 값은 0 으로 항상 시작해야하는 것 아닌가?

 

사실 이부분은 아무리 봐도 모르겠다... 

arrayOfBasket[i - 1] 은 솔직히 0 1 2 1 1 이렇게 나와서 한칸 밀어버린건데 

문해력이 부족한건지원.. 

 

 

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

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

        Scanner sc = new Scanner(System.in);

        // baskets
        int numberOfBaskets = sc.nextInt();
        int[] arrayOfBaskets = new int[numberOfBaskets];

        // ball
        int numberOfBalls = sc.nextInt();

        int i, j ,k;

        // 공을 N 번 넣을 예정이니까 공번호 시작 1 번 ~
        for (int startAt = 0;  startAt < numberOfBalls; startAt++) {
            // 바구니 선택 범위와 공번호를 지정
            i = sc.nextInt();
            j = sc.nextInt();
            k = sc.nextInt();

            // 바구니에 공을 넣어 보기
            while(i <= j){
                arrayOfBaskets[i - 1] = k;
                i++;
            }
        }
        for (int print : arrayOfBaskets
             ) {
            System.out.println(print);
        }
    }
}

Int 형 Array 를 Stream 으로 변환하여, 필터를 통해서 입력한 숫자와 같은 숫자를 필터링 한다.

후에 카운팅을 하고, Long 을 반환하기 때문에,  int 형으로 캐스팅 해주었다.

package org.example;

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

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

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();

        int[] inputArray = new int[N];

        for(int i = 0; i <= N - 1; i++){
            inputArray[i] = sc.nextInt();
        }

        int searchNum = sc.nextInt();

        int count = (int) Arrays.stream(inputArray).filter(value -> value == searchNum).count();

        System.out.println(count);
    }
}

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();

        int counter = (N / 4);

        String longStr = "long";

        String intStr = "int";

        String result = "";

        // N / 4 의 몫 만큼 long 출력 + int
        while (counter  > 0) {
            result += longStr + " ";
            counter--;
        }
        result = result + intStr;

        System.out.println(result);
    }
}
import java.util.Scanner;

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

       Scanner sc = new Scanner(System.in);

       //합계 금액
       int X = sc.nextInt();

       //물건 갯수
       int N = sc.nextInt();

       //물건 가격
       int price = 0;
       int quantity = 0;

       int total = 0;

       //물건 갯수 만큼 반복
       while(N>0){
           price = sc.nextInt();
           quantity = sc.nextInt();
           total += price * quantity;
           N--;
       }
       if(X == total){
           System.out.println("Yes");
       }else{
           System.out.println("No");
       }
    }
}
import java.util.Scanner;

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

        //주사위 1 ~ 6
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        int compare1 = 0;
        int compare2 = 0;

        int result = 0;
        int point = 0;

        // 주사위 3개를 굴린다

        // 그 중 눈이 같은게 있는지 확인

            // 같은 눈 3개
            if(a == b && b == c){
                result = 10000 + (a * 1000);
                System.out.println(result);
            }
            // 같은 눈 2개 셋중 하나만 다른 경우
            // 셋다 같은 경우 제외, 모두 다른눈 제외
            if(!((a == b) && (b == c)) && !(!(a == b) && !(b == c) && !(a == c))){
                if((a == b)){
                    point = a;
                }
                if((b == c)){
                    point = b;
                }

                if ((c == a)){
                    point = c;
                }
                result = 1000 + (point * 100);
                System.out.println(result);
            }

            // 모두다른눈
            if( (!(a == b) && !(b == c) && !(a == c)) ){
                compare1 = (a > b)? a : b;

                compare2 = c > compare1? c : compare1;

                result = (compare2 * 100);
                System.out.println(result);
            }


    }
}

처음에 int a = sc.nextInt(); 로 했을 때, 통과를 못했다.

아래 조건의 범위가 10^12 여서 int 범위가 커버를 못해서 그런것 같다.

int 형은 10^9 의 제한된 범위까지만 커버한다.

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);

        Long a = sc.nextLong();
        Long b = sc.nextLong();
        Long c = sc.nextLong();

        System.out.println(a+b+c);
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 25304 - 영수증  (0) 2023.10.23
[백준] - 2480 주사위 세개  (0) 2023.10.23
[백준] - 2869 - 달팽이  (0) 2021.09.23
[백준] - 2164 - 카드2  (0) 2021.09.07
[백준] - 10773 - 제로  (0) 2021.09.07

시간 초과 남

import java.util.Scanner;

public class Main {

    static int up = 0;
    static int down = 0;
    static int now = 0;
    static int vertical = 0;
    static int days = 0;

    public static int moveUp(int now, int up){
        now += up;
        return now;
    }

    public static int movedown(int now, int down){
        now -= down;
        return now;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        now = 0;
        up = sc.nextInt();
        down = sc.nextInt();
        vertical = sc.nextInt();

        // 1. 낮 -> 체크
        // 2. 체크 > v return 종료
        // 2. 체크 < v -> 밤 -> 1

        while(true){
            //System.out.println("before [ " + " now : " + now + " up : " + up + " down : " + down + " vertical : " + vertical + " ]");
            now = moveUp(now, up);

            //올라간 후 목표높이보다 더올라가면 종료
            if(now >= vertical){
                days++;
                break;
            }
            //올라간 후 목표높이보다 낮으면 밤
            else{
                now = movedown(now, down);
            }
            //한사이클 돌았으니 날짜 +1
            days ++;
            //System.out.println("after [ " + " now : " + now + " up : " + up + " down : " + down + " vertical : " + vertical + " ]");
        }
        System.out.println(days);
    }
}

 

시간제한이 0.25초 라서 공식을 만들어 풀이를 해야 통과가 가능하다고함

 

첫째날 : 높이(0) + An < h(높이)

둘째날 : 높이(0) + (An - Bn) + An < h(높이)

...n 째  : 높이(0) + (n - 1)(An - Bn) + An < h

 

일절 반복문 사용은 불가능함

-> 주의 : double 형으로 나누어서 소수점 자리를 잃어버리지 않아야함

import java.util.Scanner;

public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int An = sc.nextInt();
            int Bn = sc.nextInt();
            int V = sc.nextInt();
            System.out.println( (int)Math.ceil((double) (V-An) / (An - Bn)) + 1 );
        }
}

 

메모리 초과...

 

배열 객체를 생성하고, 꺼내고 집어넣고를 반복해서 그런것 같다.

좀 더 간단한 방법을 찾아봐야겠다.

import java.util.Scanner;

public class Main {

    public static int[] makeDeck(int num){
        int[] deck = new int[num];
        for(int i = 0; i < deck.length; i++){
            deck[i] = i+1;
        }
        return deck;
    }

    public static void status(int[] Card){
        //덱확인
        for(int i = 0; i < Card.length; i++){
            System.out.println(Card[i]);
        }
    }

    public static void arrange(int[] Card) {
        int size = Card.length;

        int save = 0;
        int[] renew = new int[size - 1];

        for(int i = 0; i < renew.length; i++){
            renew[i] = Card[i+1];
        }
        //status(renew);
        save = renew[0];
        for (int i = 0; i < renew.length - 1; i++) {
            renew[i] = renew[i+1];
        }
        renew[renew.length - 1] = save;
        if(renew.length != 1){
            arrange(renew);
        }
        if(renew.length == 1){
            System.out.println(renew[0]);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //카드덱 생성
        int[] Card = makeDeck(sc.nextInt());

        //로직 구현
        arrange(Card);
    }
}