2023.04.08 - First TIL

Jay Ji·2023년 4월 8일
0
post-thumbnail

Problem

4월 1일부터 코딩공부를 시작했고 지난 1주일간 Java 공부 및 Java 알고리즘을 풀고 있다.

class Solution {
    public static void main(String[] args) {
        int [] array = {149, 180, 192, 170};
        int height = 167;
        Solution solution = new Solution();
        int result = solution.solution(array, height);
        System.out.println(result);
    }
    public int solution(int[] array, int height) {
        int answer = 0;
        for(int i = 0; i <= array.length; i++){
            if(array[i] > height){
                answer += 1;

            }
        }
        return answer;
    }
}

해당 문제가 원하는 것은 main 메소드에 있는 int[] arry 에 있는 숫자들 중, int height 보다 큰 숫자가 몇개가 있지 푸는 것이였다.

위에 작성한 코드가 1차 시도로 작성한 코드였지만, 아래와 같이 에러가 떴다.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Easy_mHeight.Solution.solution(mHeight.java:15)
at Easy_mHeight.Solution.main(mHeight.java:8)

Process finished with exit code 1

What I tried

public int solution(int[] array, int height) {
        int answer = 0;
        for(int i = 0; i <= array.length; i++){
            if(array[i] > height){
                answer += 1;

ArrayIndexOutOfBoundsException을 보고 for문에서 문제가 있는 것을 느끼고, 해당 부분에서 이것저것 수정해 봤다. if문에서의 array[i] 를 array.length[i]로도 수정해보고, 이것저것 바꿔봤지만 계속 원하는 답은 나오지 않았다.

What was Wrong?

찾다보니 for문에서 i <= array.length; 해당 부분을 i < array.length;로 수정해보았다.
원하는 답이 나왔다.
도대체 왜??

What I learned

먼저 답을 찾아서 좋았지만, 이유는 여전히 알 수 없었다.
그래서 구글링으로 array.length에 대해서 조금 더 공부해보았다.
내가 생각했던 for(int i = 0; i <= array.length; i++){} 에서 array.length 만큼 돌려야한다고 생각했지만 완전 틀리게 생각하고 있던 것이였다.

나의 생각: [1, 2, 3, 4] = index 안에 4개의 수가 있으니 그 길이 만큼 4번 돌려야 한다 =

for(int i = [4]; i <= array.length; i++){}

하지만 index는 0부터 시작한다. for(int i = 0 ; ...) 심지어 여기에도 명시를 해놓는데 그동안은 왜 저렇게 쓰는지도 모르고 썼나보다.. 그렇기 때문에 i = 0, 1, 2, 3 의 index를 돌려야 하고, 그렇기 때문에 아래 두가지 방법으로 사용 할 수 있다.

1. for(int i = [4]; i < array.length; i++){} // i = 4가 될 수 없음
2. for(int i = [4]; i <= array.length-1; i++){} // array.length에서 1을 빼주기

정말 간단한거였지만, 제대로 이해를 하지 못한 상황에서 .length를 사용하여 일어난 불상사였고,
이제라도 for문과 index 관련하여 정확하게 알게 된것 같아 다행이라고 생각한다.

마지막으로...
오늘 ChatGPT가 알려준 알고리즘 푸는 방법:

  1. Understand the problem statement: Before starting to write any code, it is important to make sure that you understand the problem statement and its requirements. Try to identify the input and output format, any constraints on the input values, and any rules or conditions that need to be satisfied.

  2. Break down the problem: Once you understand the problem statement, break it down into smaller sub-problems. This will help you to identify the different components of the problem and the steps required to solve it.

  3. Choose the right data structures and algorithms: Depending on the problem requirements and constraints, choose the appropriate data structures and algorithms to implement the solution. For example, if the problem involves searching or sorting, you might want to use a binary search or a sorting algorithm like quicksort or merge sort.

  4. Write modular and readable code: When writing code, make sure to break it down into smaller functions or modules. This will make the code more readable, easier to debug, and more reusable.

  5. Test and debug: Once you have implemented the solution, test it thoroughly using different input values and edge cases. This will help you to identify any errors or bugs in the code, which you can then debug and fix.

profile
Think out of the Box

0개의 댓글