Coding Test/Solution

TIL_알고리즘 풀이 / 최댓값, 점의 위치 구하기

마이트너 2023. 6. 12. 14:23

작성 일자

20230612 : 최댓값, 점의 위치 구하기


목 차

오늘의 TIL 주제

오늘의 사설

오늘의 회고

 

알고리즘 풀이

✅ 참고한 자료모음

 


오늘의 TIL 주제

기술 스택 : Java

 

오늘의 알고리즘 풀이 목록

(1) 배열의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 return하는 solution 함수 만들기

(2) 좌표가 사분면의 어디에 속하는지 1,2,3,4를 return 하는 solution 메서드 만들기

 

오늘의 사설

오늘도 뚠뚠!

알고리즘 스터디 준비를 하네~! 뚠뚠!

 

오늘의 회고

다행히 크게 어려운 점은 없었지만

Math.random() 메서드 괄호 범위를 잘못 설정하여

x, y 좌표 값을 의미하는 randomDot[]의 원소값들이 난수가 아닌 -500으로 고정되는 이슈가 있었다.

다음부터 해당 메서드를 사용할 때 주의할 점 하나를 챙길 수 있는 시간이었다.

 

더불어 현재 알고리즘 풀이에 그치지 않고

나름대로 나중에 이러한 코드 로직을 프로젝트에서 구현할 것을 고려하여

최대한 다른 코드와 동화되기 쉽고 응용하기 좋은 구조로 짜도록 노력했다.

사실 큰 차이는 없지만 알고리즘 풀이가 결국 개발에서의 컴퓨팅 사고 등을 기르기 위함이라는 사실을

인지하고 작업했다는 것에 만족한다.

 

추가로

저번 프로젝트가 끝나고 자바의 다양한 메서드를 사용해보기로 마음 먹었는데,

난수 만들 때 너무 Math 클래스 메서드만 사용하는 것 같아서

다음에는 Math.random() 메서드 말고 다른 방법으로 난수를 만들기로 결심하면서 오늘의 TIL 기록 끄읕~♥


✅ 알고리즘 풀이

[깃허브] song-eojin/algorithm: 자바 알고리즘 스터디 (github.com)

 

(1) 배열의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 return하는 solution 함수 만들기

package array;

import com.sun.source.tree.NewArrayTree;

import java.util.*;

/*프로그래머스 최댓값 만들기(1)*/
//배열의 원소 중 두 개를 곱해 만들 수 있는 최댓값을 return 하는 solution 함수 만들기
public class Maximum {
    public static void main(String[] args) {
        System.out.println("위 배열의 원소 중 두 개를 곱해 만들 수 있는 최댓값은 " + solution(randomArray()) + " 입니다.");
    }

    public static int[] randomArray(){
        int[] randomArray = new int[(int)(Math.random()*8 +2)];
        for(int i=0; i<randomArray.length; i++){
            randomArray[i] = (int)(Math.random()*100);
        }
        System.out.println("int[] randomArray = " + Arrays.toString(randomArray));
        System.out.println("randomArray.length = " + randomArray.length);
        System.out.println();

        return randomArray;
    }

    public static int solution(int[] randomArray){
        List<Integer> multiplyList = new ArrayList();

        for(int i=0; i<randomArray.length; i++){
            for(int j=i; j<randomArray.length; j++) {
                if (i!=j) {
                    int multiValue = randomArray[i] * randomArray[j];
                    System.out.printf("randomArray[%s] * randomArray[%s] = %s\n", i, j, multiValue);

                    multiplyList.add(multiValue);
                }
            }
        }
        System.out.println();

        int answer=0;
        for (int multiValue : multiplyList){
            if(answer<multiValue){
                answer=multiValue;
            }
        }

        return answer;
    }
}

(2) 좌표가 사분면의 어디에 속하는지 1,2,3,4를 return 하는 solution 메서드 만들기

 

▶ problem : 풀이 과정에서 randomDot 배열의 원소 값들이 난수가 아닌 -500으로 값이 고정되는 issue가 있었다.

 

solution : Math.random() 코드 부분에서 괄호를 삽입했다.

 cause : 괄호가 없으면 연산자 우선순위에 의해 Math.random()이 int형으로 casting 된다. 이때 Math.random()은 0.0부터 1 미만 즉, 0.999999!의 범위를 갖으므로 int형으로 변환하면 0이 된다.

package array;

import java.util.Arrays;

/*프로그래머스 점의 위치 구하기*/
public class Coordinate {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(randomDot()) + "은 " + solution(randomDot()) + "사분면입니다.");
    }
    public static int[] randomDot(){
        int[] randomDot = new int[2];

        randomDot[0] = (int) (Math.random() * 1000) - 500; 
        randomDot[1] = (int) (Math.random() * 1000) - 500;


        return randomDot;
    }
    public static int solution(int[] dot){
        int x=dot[0];
        int y=dot[1];

        int answer=0;

        //x, y 모두 양수
        if(x>0 && y>0) {
            return answer=1;
        }
        //x 양수, y 음수
        else if (x>0 && y<0) {
            return answer=4;
        }
        //x 음수, y 양수
        else if (x<0 && y>0) {
            return answer=2;
        }
        //x 음수, y 음수
        else if (x<0 && y<0) {
            return answer=3;
        }
        else {
            solution(randomDot());
        }

        return answer;
    }
}

✅ 참고한 자료모음

[블로그] Java에서 난수 생성 (tistory.com)

[블로그] [Java] 난수(random)값 생성하는 방법(Math.random(), Random Class) (tistory.com)


728x90