20220514 TIL

Don Lee·2022년 5월 15일
0

EpiTIL

목록 보기
6/24
  • 20220514 조원들과 아침에 수다 떨면서 한 말. 마치 닥터 스트레인지가 된 거 같다. 새벽에 컴퓨터를 끄고 자고 일어나 다시 컴퓨터 앞에 앉아 있는 모습이, 끊임없는 시간 루프 속에 도르마무랑 싸운 스트렌지와 같다고. 영겁의 죽음을 당한 스트레인지이지만 결국 승리를 쟁취하는 그의 모습처럼, 우리도 코딩에서 매 번 패배할지라도 결국 취업이라는 승리를 얻길 바라며 오늘도 컴퓨터 앞에 앉아있다.
    • 코딩 연습

      행렬의 덧샘

      https://programmers.co.kr/learn/courses/30/lessons/12950
      import java.util.Arrays;
      
      public class Main {
          public static void main(String args[]) {
      //        Arrays.deepToString, toString, asList의 추가적으로 공부를 해야 할 필요가 있다.
              Solution sol = new Solution();
      //
              int[][] a = {{1, 2}, {2, 3}};
              int[][] b = {{3, 4}, {5, 6}};
      
      //        int[][] a = {{1}, {2}};
      //        int[][] b = {{3}, {4}};
      
              System.out.println(Arrays.deepToString(sol.solution(a, b)));
      //        System.out.println(Arrays.toString(sol.solution(new int[][]{{1, 2}, {2, 3}}, new int[][]{{3, 4}, {5, 6}})));
      //        System.out.println(Arrays.asList(sol.solution(new int[][]{{1, 2}, {2, 3}}, new int[][]{{3, 4}, {5, 6}})));
      
          }
      }
      
      class Solution {
          public int[][] solution(int[][] arr1, int[][] arr2) {
              int[][] answer = new int[arr1.length][arr1[0].length];
      //        int[][] answer = new int[arr1.length][arr2.length];
      //        이렇게 코드를 짤 경우 11, 12행의 코드를 실행시킬 때 [[4, 0], [6, 0]] 이란 결과가 나옴. arr2의 length가 2이기 때문. 아래 29행도 마찬가지 임.
      
              for (int i = 0; i < arr1.length; i++) {
                  for (int j = 0; j < arr1[0].length; j++) {
                      answer[i][j] = arr1[i][j] + arr2[i][j];
                  }
              }
              return answer;
          }
      }
      [JAVA] 배열 출력하기(toString, deepToString) https://seongsillvanas.tistory.com/9
      • 배열print하면 배열의 hashcode가 출력. 배열의 문자열을 출력하려면 toString, deepToString 메소드를 이용.
        - 1차원 배열 : toString

            ```java
            import java.util.Arrays;
            
            public class ArrayExec {
            	public static void main(String[] args) {
            
            		int[] arr = {5,2,1,6,7};
            
            		System.out.println(Arrays.toString(arr));
            	}
            }
            ```
            
            ```java
            출력 결과
            
             [5, 2, 1, 6, 7]
            ```
            
        - 다차원 배열 : deepToString
            
            ```java
            import java.util.Arrays;
            
            public class ArrayExe {
            	public static void main(String[] args) {
            
            		int[][] arr = {{1,2,3,4,5},{5,4,3,2,1}};
            
            		System.out.println(Arrays.deepToString(arr));
            	}
            }
            ```
            
            ```java
            출력 결과
            
            [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]
            ```
            

        x만큼 간격이 있는 n개의 숫자

        https://programmers.co.kr/learn/courses/30/lessons/12954

        import java.util.Arrays;
        
        public class Main {
            public static void main(String[] args) {
                Solution solution = new Solution();
                System.out.println(Arrays.toString(solution.solution(2, 5)));
            }
        }
        
        class Solution {
            public long[] solution(int x, int n) {
                long[] answer = new long[n];
        //      배열 변수를 미리 선언한 후 값 목록들이 나중에 결정되는 경우이다. 이럴 때는 new 연산자를 이용해야 한다. 혼공자 181p를 참고햐자.
        
        //      long[] answer = {n};
        //      해당 배열은 값을 하나, n만을 넣겠다는 뜻이다. 혼공자 180p를 참고하자.
        
                for (int i = 0; i < answer.length; i++) {
                    answer[i] = (i + 1) * x;
                }
                return answer;
            }
        }
        
        // 리스트에 n의 길이를 받는다.
        // n의 길이만큼 있는 리스트에 각 x를 넣는다.
        // 첫 번째는 x가 0이므로 (i+1)*x를 해줘야 할 것이다. 이 것을 반복.

        코드 실행할 때는 문제가 없었는데 제출할 때는 몇몇 테스트를 통과하지 못해 아래와 같이 수정함

        import java.util.Arrays;
        
        public class Main {
            public static void main(String[] args) {
                Solution solution = new Solution();
                System.out.println(Arrays.toString(solution.solution(2, 5)));
            }
        }
        
        class Solution {
            public static long[] solution(int x, int n) {
                long[] answer = new long[n];
                answer[0] = x;
        
                for (int i = 1; i < n; i++) {
                    answer[i] = answer[i - 1] + x;
                }
        
                return answer;
        
            }
        }

        배열 변수를 미리 선언하는 방법의 차이가 존재한다. 각주를 참고하자.

        부족한 금액 계산하기

        https://programmers.co.kr/learn/courses/30/lessons/82612

        class Solution {
            public long solution(int price, int money, int count) {
                long answer = 0;
                long totalPrice = 0;
        
                for (int i = 0; i < count; i++) {
                    totalPrice += price * (i +1);
                }
                answer = money - totalPrice;
                if (answer < 0){
                    answer = Math.abs(money - totalPrice);
                } else {
                    answer = 0;
                }
                return answer;
            }
        }
        
        // totalPrice를 선언한다.
        // price + price * 2 + price * 3 ~~ 카운트 숫자만큼 반복한다.
        // 그러면 price > money일 것이다.
        // 그걸 출력한다.
        // 난이도 중하라고 하는데 쉬웠음.
        💡 제출하려니 틀린 답. 왜그럴까? → `totalPrice`를 `long`으로 바꾸니 해결됨.
        class Solution {
            public long solution(long price, long money, long count) {
                return Math.max(price * (count * (count + 1) / 2) - money, 0);
            }
        }

        다른 사람이 작성한 진짜 멋진 답

        2016년

        https://programmers.co.kr/learn/courses/30/lessons/12901

        public class Main {
            public static void main(String[] args) {
                Solution solution = new Solution();
                System.out.println(solution.solution(5, 24));
            }
        }
        
        class Solution {
            public String solution(int a, int b) {
                String answer = "";
                int month_sum = 0;
                int[] month_list = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                String[] day = {"FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"};
        
        //      1월부터 5월 24일까지 31, 29, 31, 30, 24일을 더한다. 5월의 31일은 빼야함으로 a-1을 해준다.
                for (int i = 0; i < a - 1; i++) {
                    month_sum += month_list[i];
                }
        
        //      1월 1일부터 175일이 지난 것이므로 -1을 해준다. 그렇지 않으면 1월 1일+144일인데 그러면 1월 145일이 되기 때문이다.
                int what_date = month_sum + b - 1;
                answer = day[what_date % 7];
        
                return answer;
            }
        }
        
        // 2016년 윤년이다. 그러므로 2월이 29일까지 있다.
        // 1월 1일은 금요일. 다시말해 index 0은 금요일이란 뜻이다.
        // 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31이 각 월의 일이다.
        // 5월 24일은 31,29,31,30을 더하고 24를 더한 것이다.
        // 1월 1일이 금요일이니 day는 금요일부터 시작한다.
        // 그 결과 값을 리턴한다.

        5월 24일까지 세는 것, 마지막에 -1을 해야하는 것을 어려워했다. 5월 24일까지라면 4월까지 달과 24일을 더해야 하는 것과, 1월 0일이 아닌 1월 1일부터 시작음로 -1일을 하는 것을 기억하자.

        나누어 떨어지는 숫자 배열

        https://programmers.co.kr/learn/courses/30/lessons/12910

        import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.List;
        
        public class Main {
            public static void main(String[] args) {
                Solution solution = new Solution();
                int[] a = {5, 9, 7, 10};
        
                System.out.println(Arrays.toString(solution.solution(a, 5)));
            }
        }
        
        class Solution {
            public int[] solution(int[] arr, int divisor) {
                List<Integer> list = new ArrayList<Integer>();
        
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i] % divisor == 0) {
                        list.add(arr[i]);
                    }
                }
                if (list.isEmpty()) {
                    list.add(-1);
                }
        
        //      
                int[] answer = new int[list.size()];
        
                for (int i = 0; i < list.size(); i++) {
                    answer[i] = list.get(i);
                }
                Arrays.sort(answer);
                return answer;
            }
        }
        
        // arr배열에 있는 것을 하나 하나 꺼내서 divisor으로 나눈다.
        // 실수가 나오면 버린다. -> 어떻게 하는지 모르겠다. 살술 연산자와 divisor을 이용해 0이 나오면 더하는 걸로?
        // 전부 오름차순 한다
        // 배열 안에 아무것도 없으면 -1을 넣는다.
        💡 배열과 리스트 구분하기. 정확히 알기.

        배열과 리스트의 정리

        https://mong9data.tistory.com/132

        https://velog.io/@adam2/Array와-List그리고-Java-List

        https://velog.io/@humblechoi/자료구조-Array-vs-ArrayList

        Array(배열)ArrayList((배열) 리스트)
        사이즈초기화시 고정
        int[] arr = new int[3];초기화시 사이즈를 표시하지 않음. 사이즈가 동적이다.
        ArrayList arrList = new ArrayList<>();
        속도초기화 시 메모리에 할당되어 속도 빠름추가시 메모리를 재할당하여 속도가 느림
        변경사이즈 변경 불가추가,삭제 가능
        다차원가능불가능
        타입primitive type(int,byte, char etc), objectobject elemnet만 가능
        제네릭사용 불가능사용 가능(타입 안정성 보장)
        길이length 변수size() 메서드
        변수 추가assignment 연산자 사용add() 메소드 사용
profile
쾌락코딩

0개의 댓글