<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>2-dean.log</title>
        <link>https://velog.io/</link>
        <description>냅다 써보는 공부의 흔적😇</description>
        <lastBuildDate>Fri, 08 Sep 2023 07:18:49 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <copyright>Copyright (C) 2019. 2-dean.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/2-dean" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[프로그래머스] 문자열 정렬하기 (1)]]></title>
            <link>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%A0%95%EB%A0%AC%ED%95%98%EA%B8%B0-1-nib49qst</link>
            <guid>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%A0%95%EB%A0%AC%ED%95%98%EA%B8%B0-1-nib49qst</guid>
            <pubDate>Fri, 08 Sep 2023 07:18:49 GMT</pubDate>
            <description><![CDATA[<h3 id="❤️-문제">❤️ 문제</h3>
<p>문자열 my_string이 매개변수로 주어질 때, my_string 안에 있는 숫자만 골라 오름차순 정렬한 리스트를 return 하도록 solution 함수를 작성해보세요.</p>
<hr>
<h3 id="🧡-제한사항">🧡 제한사항</h3>
<ul>
<li>1 ≤ my_string의 길이 ≤ 100</li>
<li>my_string에는 숫자가 한 개 이상 포함되어 있습니다.</li>
<li>my_string은 영어 소문자 또는 0부터 9까지의 숫자로 이루어져 있습니다.</li>
</ul>
<hr>
<h3 id="💛-입출력예">💛 입출력예</h3>
<table>
<thead>
<tr>
<th>my_string</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>hi12392</td>
<td>[1, 2, 2, 3, 9]</td>
</tr>
<tr>
<td>p2o4i8gj2</td>
<td>[2, 2, 4, 8]</td>
</tr>
<tr>
<td>abcde0</td>
<td>[0]</td>
</tr>
</tbody></table>
<hr>
<h3 id="😇-문제풀이">😇 문제풀이</h3>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


class Solution {
    public int[] solution(String my_string) {

        List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();

        for (char str : my_string.toCharArray()) {
            // 숫자, 문자 확인
            if(Character.isDigit(str)) {
                int number = Character.getNumericValue(str);
                // 숫자만 담기
                numbers.add(number);
            }
        }
        // 오름차순으로 정렬하기
        Collections.sort(numbers);

        int[] answer = new int[numbers.size()];
        for (int i=0; i&lt;numbers.size(); i++) {
            answer[i] = numbers.get(i);
        }

        return answer;
    }
}</code></pre><hr>
<h3 id=""></h3>
<p>Character.isDigit(char) : 명시된 char 값이 숫자인지 여부를 판단 하여 true/false return
Character.getNumericValue(char): 숫자형태의 char 형을 int형으로 변환</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[프로그래머스] 외계행성의 나이]]></title>
            <link>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%99%B8%EA%B3%84%ED%96%89%EC%84%B1%EC%9D%98-%EB%82%98%EC%9D%B4</link>
            <guid>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%99%B8%EA%B3%84%ED%96%89%EC%84%B1%EC%9D%98-%EB%82%98%EC%9D%B4</guid>
            <pubDate>Wed, 23 Aug 2023 07:05:00 GMT</pubDate>
            <description><![CDATA[<h3 id="❤️-문제">❤️ 문제</h3>
<p>우주여행을 하던 머쓱이는 엔진 고장으로 PROGRAMMERS-962 행성에 불시착하게 됐습니다. 
입국심사에서 나이를 말해야 하는데, PROGRAMMERS-962 행성에서는 나이를 알파벳으로 말하고 있습니다. a는 0, b는 1, c는 2, ..., j는 9입니다. 
예를 들어 23살은 cd, 51살은 fb로 표현합니다. 나이 age가 매개변수로 주어질 때 PROGRAMMER-962식 나이를 return하도록 solution 함수를 완성해주세요.</p>
<hr>
<h3 id="🧡-제한사항">🧡 제한사항</h3>
<ul>
<li>age는 자연수입니다.</li>
<li>age ≤ 1,000</li>
<li>PROGRAMMERS-962 행성은 알파벳 소문자만 사용합니다.</li>
</ul>
<hr>
<h3 id="💛-입출력예">💛 입출력예</h3>
<table>
<thead>
<tr>
<th>age</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>23</td>
<td>&quot;cd&quot;</td>
</tr>
<tr>
<td>51</td>
<td>&quot;fa&quot;</td>
</tr>
<tr>
<td>100</td>
<td>&quot;baa&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="😇-문제풀이">😇 문제풀이</h3>
<p>내가 하면 노가다 + 아는거없이 끝남 일 것 같아서 찾아봤다.</p>
<pre><code>
class Solution {
    public String solution(int age) {
    StringBuilder answer = new StringBuilder();

    while (age &gt; 0) {
        int remainder = age % 10;
        char ageChar = (char) (&#39;a&#39; + remainder);
        answer.insert(0, ageChar);
        age /= 10;
    }

    return answer.toString();
        }
}</code></pre><h3 id="아하">아하</h3>
<ul>
<li>age%10 으로 일,십,백,천의 자리 숫자를 차례대로 찾기</li>
<li>&#39;a&#39; + 숫자 로 해당하는 숫자의 문자를 찾기</li>
<li>StringBuilder insert(int offset, char c)
  -&gt; stringBuilder 클래스의 인스턴스에 문자열을 지정된 위치에 삽입할 때 사용됩니다. 
  -&gt; offset : 삽입할 위치, c : 삽입할 문자</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[프로그래머스] 배열 자르기]]></title>
            <link>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%B0%B0%EC%97%B4-%EC%9E%90%EB%A5%B4%EA%B8%B0</link>
            <guid>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%B0%B0%EC%97%B4-%EC%9E%90%EB%A5%B4%EA%B8%B0</guid>
            <pubDate>Wed, 23 Aug 2023 06:37:16 GMT</pubDate>
            <description><![CDATA[<h3 id="❤️-문제">❤️ 문제</h3>
<p>정수 배열 numbers와 정수 num1, num2가 매개변수로 주어질 때, numbers의 num1번 째 인덱스부터 num2번째 인덱스까지 자른 정수 배열을 return 하도록 solution 함수를 완성해보세요.</p>
<hr>
<h3 id="🧡-제한사항">🧡 제한사항</h3>
<ul>
<li>2 ≤ numbers의 길이 ≤ 30</li>
<li>0 ≤ numbers의 원소 ≤ 1,000</li>
<li>0 ≤num1 &lt; num2 &lt; numbers의 길이</li>
</ul>
<hr>
<h3 id="💛-입출력예">💛 입출력예</h3>
<table>
<thead>
<tr>
<th>numbers</th>
<th>num1</th>
<th>num2</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[1, 2, 3, 4, 5]</td>
<td>1</td>
<td>3</td>
<td>[2, 3, 4]</td>
</tr>
<tr>
<td>[1, 3, 5]</td>
<td>1</td>
<td>2</td>
<td>[3, 5]</td>
</tr>
</tbody></table>
<hr>
<h3 id="😇-문제풀이">😇 문제풀이</h3>
<pre><code>
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] solution(int[] numbers, int num1, int num2) {
       List&lt;Integer&gt; list = new ArrayList&lt;&gt;();
        for (int i=num1; i&lt;= num2; i++) {
           list.add(numbers[i]);
        }

        int[] answer = new int[list.size()];
        for(int i=0; i&lt; answer.length; i++) {
            answer[i] = list.get(i);
        }
        return answer;
    }
}</code></pre><p>계속 이런문제 나오는데 귀찮아.ㅅ..</p>
<h3 id="개선된-풀이방법">개선된 풀이방법;;</h3>
<pre><code>import java.util.Arrays;

class Solution {
    public int[] solution(int[] numbers, int num1, int num2) {
        return Arrays.copyOfRange(numbers, num1, num2 + 1);
    }
}</code></pre><p>ㄷ ㄷ ㄷ 한줄로 끝내버리기.</p>
<ul>
<li>Arrays.copyOfRange(int[] original, int from, int to)
from, to 에는 인덱스 번호를 적어준다 기억하잣</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[프로그래머스] 특정 문자 제거하기]]></title>
            <link>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%8A%B9%EC%A0%95-%EB%AC%B8%EC%9E%90-%EC%A0%9C%EA%B1%B0%ED%95%98%EA%B8%B0</link>
            <guid>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%8A%B9%EC%A0%95-%EB%AC%B8%EC%9E%90-%EC%A0%9C%EA%B1%B0%ED%95%98%EA%B8%B0</guid>
            <pubDate>Wed, 23 Aug 2023 05:47:41 GMT</pubDate>
            <description><![CDATA[<h3 id="❤️-문제">❤️ 문제</h3>
<p>문자열 my_string과 문자 letter이 매개변수로 주어집니다. my_string에서 letter를 제거한 문자열을 return하도록 solution 함수를 완성해주세요..</p>
<hr>
<h3 id="🧡-제한사항">🧡 제한사항</h3>
<ul>
<li>1 ≤ my_string의 길이 ≤ 100</li>
<li>letter은 길이가 1인 영문자입니다.</li>
<li>my_string과 letter은 알파벳 대소문자로 이루어져 있습니다.</li>
<li>대문자와 소문자를 구분합니다.</li>
</ul>
<hr>
<h3 id="💛-입출력예">💛 입출력예</h3>
<table>
<thead>
<tr>
<th>my_string</th>
<th>letter</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;abcdef&quot;</td>
<td>&quot;f&quot;</td>
<td>&quot;abcde&quot;</td>
</tr>
<tr>
<td>&quot;BCBdbe&quot;</td>
<td>&quot;B&quot;</td>
<td>&quot;Cdbe&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="😇-문제풀이">😇 문제풀이</h3>
<pre><code>class Solution {
    public String solution(String my_string, String letter) {
        String answer = &quot;&quot;;


        for (char str : my_string.toCharArray()) {
            if (str != letter.charAt(0)) {
                answer+= str;
            } 
        }

        return answer;
    }
}</code></pre><ul>
<li>char 타입과 String 타입의 비교
  -&gt; letter는 항상 1글자 이므로 charAt() 메소드를 이용해서 해결</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[websocket 채팅 - 진행중]]></title>
            <link>https://velog.io/@2-dean/websocket-%EC%B1%84%ED%8C%85</link>
            <guid>https://velog.io/@2-dean/websocket-%EC%B1%84%ED%8C%85</guid>
            <pubDate>Wed, 23 Aug 2023 05:13:05 GMT</pubDate>
            <description><![CDATA[<h1 id="websocket-">WebSocket ?</h1>
<p>WebSocket은 서버와 클라이언트 간에 양방향 통신을 가능하게 하는 프로토콜이다.</p>
<p>HTTP 프로토콜에서는 클라이언트에서 요청을 보내면 서버에서 응답을 하고 연결이 끊어졌지만, WebSocket을 사용하면 클라이언트와 서버 간에 계속해서 연결을 유지하면서 양방향으로 데이터를 주고받을 수 있다.</p>
<p>클라이언트에서는 <strong>WebSocket 객체를 만들고 서버와의 연결을 설정한 다음 데이터를 전송할</strong> 수 있다.</p>
<p>서버에서는 <strong>클라이언트와의 연결을 수신하고 연결을 유지하면서 데이터를 전송할</strong> 수 있다.</p>
<h2 id="요구사항">요구사항</h2>
<ul>
<li>웹소켓을 활용해 채팅방</li>
<li>ID를 입력받아서 채팅방입장</li>
<li>방은 1개</li>
<li>입,퇴장 안내</li>
<li>사진 전송</li>
<li>현재 접속자 명단 보임</li>
<li>DB에 데이터 저장 안 함</li>
</ul>
<h2 id="구조">구조</h2>
<h3 id="라이브러리-추가">라이브러리 추가</h3>
<ul>
<li>Spring web</li>
<li>Thymeleaf</li>
<li>Websocket</li>
<li>Lombok</li>
<li>json-simple</li>
</ul>
<h3 id="java">java</h3>
<pre><code>java
└─ WEBSOCKET
    │  WebsocketApplication.java
    │
    ├─config
    │      WebSocketConfig.java
    │
    ├─controller
    │      ChatController.java
    │
    └─handler
            ChatHandler.java</code></pre><h3 id="resources">resources</h3>
<pre><code>resources
    └─ static
    │    ├─ css
    │    │    └─ styles.css
    │    └─ js
    │         └─ main.js
    └─ templates
            ├─ websocket_index.html
               └─ websocket_chatroom.html
</code></pre><h3 id="websocket-통신-흐름">websocket 통신 흐름</h3>
<ul>
<li>인풋 태그에 메시지를 입력하고 send 버튼을 누름</li>
<li>send() 에서 타입, 메시지, 사용자 이름으로 구성된 객체를 서버로 보냄</li>
<li>서버의 websocketHandler에서 해당 객체를 받음</li>
<li>서버에서 클라이언트로 보낼 객체를 만듦 - 타입, 메시지, 사용자 수 등 필요한 데이터를 담은 후</li>
<li>현재 연결된 session들에 해당 객체를 보내줌</li>
<li>클라이언트에서는 서버에서 받은 객체의 타입에 따라 처리해줌</li>
</ul>
<hr>
<h1 id="구현하기">구현하기</h1>
<h2 id="서버">서버</h2>
<h3 id="웹소켓-핸들러-만들기---chathandlerjava">웹소켓 핸들러 만들기 - ChatHandler.java</h3>
<p>웹소켓 프로토콜은 기본적으로 Text, Binary 타입을 지원하기 때문에 필요에 따라 * TextWebSocketHandler, BinaryWebSocketHandler 를 상속하여 구현해주면 된다.</p>
<pre><code>import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class ChatHandler extends TextWebSocketHandler {
    Map&lt;String, WebSocketSession&gt; sessionMap = new HashMap&lt;&gt;(); //웹소켓 세션을 담아둘 맵
    Map&lt;String, String&gt; userMap = new HashMap&lt;&gt;();    //사용자

    /* 클라이언트가 소켓 연결시 동작 */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info(&quot;SESSION &gt; {} 연결되었습니다.&quot;, session.getId());
        log.info(&quot;SESSION.toString() &gt; {}&quot;,session.toString());

        super.afterConnectionEstablished(session);
        sessionMap.put(session.getId(), session);

        JSONObject obj = new JSONObject();
        obj.put(&quot;type&quot;, &quot;getId&quot;);
        obj.put(&quot;sessionId&quot;, session.getId());

        //클라이언트에게 메세지 전달
        session.sendMessage(new TextMessage(obj.toJSONString()));
    }


    /* 클라이언트로부터 메시지 수신시 동작 */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        String msg = message.getPayload();
        log.info(&quot;===============Message=================&quot;);
        log.info(&quot;{}&quot;, msg);
        log.info(&quot;===============Message=================&quot;);
        JSONObject obj = jsonToObjectParser(msg);


        for(String key : sessionMap.keySet()) {
            // 세션을 찾아서
            WebSocketSession wss = sessionMap.get(key);

            if(userMap.get(wss.getId()) == null) {
                userMap.put(wss.getId(), (String)obj.get(&quot;userName&quot;)); // 세션 ID - userName 저장
            }

            JSONArray usersArray = new JSONArray();
            usersArray.addAll(userMap.values());
            obj.put(&quot;users&quot;, usersArray);
            obj.put(&quot;userCount&quot;, usersArray.size());

            //클라이언트(모든접속자) 에게 메시지 전달
            wss.sendMessage(new TextMessage(obj.toJSONString()));
        }

        log.info(&quot;클라이언트로 보낼 obj : {}&quot; , obj);
    }


    /* 바이너리 메시지 발송 */
    @Override
    public void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        //ByteBuffer 객체는 메시지의 실제 데이터를 담고 있음
        ByteBuffer byteBuffer = message.getPayload();

        // 데이터 확인
        log.info(&quot;===============handleBinaryMessage=================&quot;);
        log.info(&quot;SESSION {}&quot;, session);
        log.info(&quot;BYTE BUFFER {}&quot;, byteBuffer);

        //1. 클라이언트에 이미지만 전달 할 경우
        /*
        for (String key : sessionMap.keySet()) {
              WebSocketSession wss = sessionMap.get(key);
              try {
                  wss.sendMessage(new BinaryMessage(byteBuffer)); //버퍼 발송
              } catch (IOException e) {
                  e.printStackTrace();
              }
          } 
          */

        // 2. 클라이언트에 이미지와 그 외의 정보를 함께 넘겨줄 경우
        JSONObject obj = new JSONObject();
        obj.put(&quot;type&quot;, &quot;file&quot;);

        obj.put(&quot;userCount&quot;, sessionMap.size()); // 사용자 수
        obj.put(&quot;userName&quot;, userMap.get(session.getId())); // 사용자 정보
        obj.put(&quot;sessionId&quot;, session.getId()); // 세션 ID 등의 추가 정보 추가
        obj.put(&quot;imageData&quot;, Base64.getEncoder().encodeToString(byteBuffer.array())); // 이미지 데이터를 Base64로 인코딩하여 추가

        for (String key : sessionMap.keySet()) {
            WebSocketSession wss = sessionMap.get(key);
            try {
                wss.sendMessage(new TextMessage(obj.toString())); // JSON 객체를 문자열로 변환하여 메시지 전송
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        log.info(&quot;클라이언트로 보낼 obj : {}&quot; , obj);
    }


    /* 클라이언트가 소켓 종료시 동작 */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info(&quot;{} 연결이 종료되었습니다.&quot;, session.getId());
        super.afterConnectionClosed(session, status);
        sessionMap.remove(session.getId());

        String userName = userMap.get(session.getId());
        for(String key : sessionMap.keySet()) {
            WebSocketSession wss = sessionMap.get(key);

            if(wss == session) continue;

            JSONObject obj = new JSONObject();
            obj.put(&quot;type&quot;, &quot;close&quot;);
            obj.put(&quot;userName&quot;, userName);
            obj.put(&quot;userCount&quot;, sessionMap.size());

            wss.sendMessage(new TextMessage(obj.toJSONString()));
        }
        userMap.remove(session.getId());
    }


    /**
     * JSON 형태의 문자열을 JSONObejct로 파싱
     */

    private static JSONObject jsonToObjectParser(String jsonStr) throws Exception{
        JSONParser parser = new JSONParser();
        JSONObject obj = null;
        obj = (JSONObject) parser.parse(jsonStr);
        return obj;
    }



}</code></pre><h3 id="handlebinarymessage">handleBinaryMessage()</h3>
<p>원래 이미지만 전달 하려면 아래와 같이하면 되는데
이미지 </p>
<pre><code>@Override
    public void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        //바이너리 메시지 발송
        ByteBuffer byteBuffer = message.getPayload();

        //이미지를 발송한다.
        for (String key : sessionMap.keySet()) {
            WebSocketSession wss = sessionMap.get(key);
            try {
                wss.sendMessage(new BinaryMessage(byteBuffer)); //버퍼 발송
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    } // method</code></pre><h3 id="핸들러-등록---websocketconfigjava">핸들러 등록 - WebSocketConfig.java</h3>
<ul>
<li>핸들러 등록하는 class</li>
<li>클라이언트에서 ws://localhost:8080<strong>/chat</strong>으로 요청이 들어오면 websocket 통신을 진행</li>
</ul>
<pre><code>@Slf4j
@Configuration
@EnableWebSocket // 웹소켓 활성화
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer { 
    //WebSocket 요청 처리를 구성하는 콜백 메서드를 정의

    private final ChatHandler chatHandler; // 

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // WebSocketHandler 추가
        registry.addHandler(chatHandler, &quot;/chat&quot;)
                            .setAllowedOriginPatterns(&quot;*&quot;); //도메인이 다른 서버에서도 접속 가능하도록 CORS : setAllowedOprigins(&quot; * &quot;);를 추가해줍니다.
    }
}
</code></pre><h2 id="클라이언트">클라이언트</h2>
<h3 id="웹소켓-연결">웹소켓 연결</h3>
<ul>
<li>WebSocketConfig 에서 설정한 것 처럼 ws://localhost:8080/chat 으로 요청하면
웹소켓이 연결된다.</li>
</ul>
<pre><code>const socket = new WebSocket(&#39;ws://localhost:8080/chat&#39;);

// 웹 소켓 연결 이벤트
socket.onopen = function (event) {
    console.log(&quot;웹소켓 서버와 연결에 성공했습니다.&quot;);
};</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[[프로그래머스] 피자 나눠 먹기 (2)]]></title>
            <link>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%94%BC%EC%9E%90-%EB%82%98%EB%88%A0-%EB%A8%B9%EA%B8%B0-2</link>
            <guid>https://velog.io/@2-dean/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%94%BC%EC%9E%90-%EB%82%98%EB%88%A0-%EB%A8%B9%EA%B8%B0-2</guid>
            <pubDate>Sat, 19 Aug 2023 13:48:30 GMT</pubDate>
            <description><![CDATA[<h3 id="❤️-문제">❤️ 문제</h3>
<p>머쓱이네 피자가게는 피자를 여섯 조각으로 잘라 줍니다. 피자를 나눠먹을 사람의 수 n이 매개변수로 주어질 때, n명이 주문한 피자를 남기지 않고 모두 같은 수의 피자 조각을 먹어야 한다면 최소 몇 판을 시켜야 하는지를 return 하도록 solution 함수를 완성해보세요.</p>
<hr>
<h3 id="🧡-제한사항">🧡 제한사항</h3>
<pre><code>    1 ≤ n ≤ 100</code></pre><hr>
<h3 id="💛-입출력예">💛 입출력예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>6</td>
<td>1</td>
</tr>
<tr>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
</tr>
</tbody></table>
<hr>
<h3 id="😇-문제풀이">😇 문제풀이</h3>
<pre><code>    public static int solution(int n) {
        int pizzaBox = 6;
        // 
        while (pizzaBox % n != 0) {
            pizzaBox += 6;
        }
        // 박스 수 반환
        return pizzaBox / 6;
    }</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[bash script & cron]]></title>
            <link>https://velog.io/@2-dean/bash-script</link>
            <guid>https://velog.io/@2-dean/bash-script</guid>
            <pubDate>Wed, 26 Jul 2023 09:48:26 GMT</pubDate>
            <description><![CDATA[<p>#!/bin/bash</p>
<p>shebang</p>
<pre><code>dduui-MacBookPro:Linux ddu$ nano hi
dduui-MacBookPro:Linux ddu$ ls
Cleanup            Todos            msg
Exercise        bigboys.txt        myGG
Greatgatsby.txt        blue            percent.txt
MealDiary        colors.txt        pho.txt
Permissions        colorsNwords.txt    photo.txt
Planner            count.txt        prices
Redirection        countries.txt        programs.txt
SongOfMyself.txt    greeting.txt        words.txt
Styles            hi            yellow
TimeStuff        letters.txt
dduui-MacBookPro:Linux ddu$ hi
-bash: hi: command not found
dduui-MacBookPro:Linux ddu$ bash hi
Hello there  ddu
Today is 2023년 7월 25일 화요일 22시 23분 19초 KST
dduui-MacBookPro:Linux ddu$ ls
Cleanup            Todos            letters.txt
Exercise        bigboys.txt        msg
Greatgatsby.txt        blue            myGG
MealDiary        colors.txt        percent.txt
Permissions        colorsNwords.txt    pho.txt
Planner            count.txt        photo.txt
Redirection        countries.txt        prices
SongOfMyself.txt    greeting.txt        programs.txt
Styles            hi            words.txt
TimeStuff        hi.log            yellow
dduui-MacBookPro:Linux ddu$ bash hi
Hello there  ddu
Today is 2023년 7월 25일 화요일 22시 23분 49초 KST
dduui-MacBookPro:Linux ddu$ bash hi
Hello there  ddu
Today is 2023년 7월 25일 화요일 22시 23분 51초 KST
dduui-MacBookPro:Linux ddu$ cat hi.log
last ran hi at 2023년 7월 25일 화요일 22시 23분 19초 KST
last ran hi at 2023년 7월 25일 화요일 22시 23분 49초 KST
last ran hi at 2023년 7월 25일 화요일 22시 23분 51초 KST
dduui-MacBookPro:Linux ddu$</code></pre><p>PATH</p>
<p><a href="https://jinnynote.com/learn/how-to-add-paths-on-mac/">https://jinnynote.com/learn/how-to-add-paths-on-mac/</a></p>
<hr>
<p>모든사용자는 자신의 자신의 작업을 예약하고 자신의 cronjob을 설정할 수 있음 </p>
<h2 id="cron-syntax">Cron Syntax</h2>
<p><a href="https://crontab.guru/">https://crontab.guru/</a>
-&gt; 참고</p>
<table>
<thead>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>e</th>
<th>command</th>
</tr>
</thead>
<tbody><tr>
<td>Minuete(0-59)</td>
<td>hour(0-23)</td>
<td>day(1-31)</td>
<td>month(1-12)</td>
<td>day(of week) (0-6)</td>
<td></td>
</tr>
<tr>
<td>- 0: 일요일</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>6: 토요일</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>- &#39;*&#39; any value</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>---</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h3 id="예시">예시</h3>
<ul>
<li>매시간, 매일, 매월, 모든 요일마다 시계 분침이 30 분을 가리킬때마다 뒤에있는 커맨드 실행 (30분 마다 실행 X)<pre><code>30 * * * * command</code></pre></li>
</ul>
<hr>
<ul>
<li>매일, 매월, 매요일 마다 시간이 0시 0분 마다 실행 (자정)<pre><code>0 0 * * * command</code></pre></li>
</ul>
<hr>
<ul>
<li>매일, 매월, 매요일 마다 시간이 6이고 분은 30 마다 실행 (오전 6:30)<pre><code>30 6 * * *command</code></pre></li>
</ul>
<hr>
<ul>
<li>월요일 6:30 마다 실행<pre><code>30 6 * * 1 command</code></pre></li>
</ul>
<hr>
<ul>
<li>4월의 월요일 6:30 마다 실행<pre><code>30 6 * 4 1 command</code></pre></li>
</ul>
<hr>
<ul>
<li>매월 1일 0:00 자정에 실행<pre><code>0 0 1 * * command</code></pre></li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[리스트(배열)]]></title>
            <link>https://velog.io/@2-dean/%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%B0%B0%EC%97%B4</link>
            <guid>https://velog.io/@2-dean/%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%B0%B0%EC%97%B4</guid>
            <pubDate>Thu, 06 Jul 2023 06:09:12 GMT</pubDate>
            <description><![CDATA[<h2 id="문제--문자-개수-세기">문제 : 문자 개수 세기</h2>
<p>알파벳 대소문자로만 이루어진 문자열 my_string이 주어질 때, my_string에서 &#39;A&#39;의 개수, my_string에서 &#39;B&#39;의 개수,..., my_string에서 &#39;Z&#39;의 개수, my_string에서 &#39;a&#39;의 개수, my_string에서 &#39;b&#39;의 개수,..., my_string에서 &#39;z&#39;의 개수를 순서대로 담은 길이 52의 정수 배열을 return 하는 solution 함수를 작성해 주세요.</p>
<h3 id="입출력--예">입출력  예</h3>
<table>
<thead>
<tr>
<th>my_string</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;Programmers&quot;</td>
<td>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0]</td>
</tr>
</tbody></table>
<h2 id="풀이">풀이</h2>
<h3 id="풀이과정">풀이과정</h3>
<p>알파벳은 문자 그대로 사용될 수도 있고, ASCII (American Standard Code for Information Interchange) 또는 유니코드 표준에 따라 숫자로 표현될 수도 있다.
대문자 &#39;A&#39;는 ASCII 코드에서 65로 표현되고, 
소문자 &#39;a&#39;는 97로 표현된다.</p>
<h3 id="답">답</h3>
<pre><code>class Solution {
    public int[] solution(String my_string) {
      int[] answer = new int[52];

        for(char str : my_string.toCharArray()){
            if(str &gt;= &#39;A&#39; &amp;&amp; str&lt;= &#39;Z&#39;) { // 대문자일경우
                int index = str - &#39;A&#39;;
                answer[index]++;
            } else if (str &gt;= &#39;a&#39; &amp;&amp; str&lt;= &#39;z&#39;) { 
            //소문자일 경우, 27번 부터 시작이므로 26을 더함
                int index = str - &#39;a&#39; + 26;
                answer[index]++;
            }
        }

        return answer;
    }
}</code></pre><h2 id="문제--글자-지우기">문제 : 글자 지우기</h2>
<p>문자열 my_string과 정수 배열 indices가 주어질 때, my_string에서 indices의 원소에 해당하는 인덱스의 글자를 지우고 이어 붙인 문자열을 return 하는 solution 함수를 작성해 주세요.</p>
<h3 id="입출력--예-1">입출력  예</h3>
<table>
<thead>
<tr>
<th>my_string</th>
<th>indices</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;apporoograpemmemprs&quot;</td>
<td>[1, 16, 6, 15, 0, 10, 11, 3]</td>
<td>&quot;programmers&quot;</td>
</tr>
</tbody></table>
<h2 id="풀이-1">풀이</h2>
<h3 id="오답">오답</h3>
<pre><code>    static String solution(String my_string, int[] indices) {
        List&lt;Character&gt; list = new ArrayList&lt;&gt;();

        char[] charArray = my_string.toCharArray();

        for (int i=0; i&lt;charArray.length; i++) {
            list.add(charArray[i]);
        }
        for (int j=0; j&lt;indices.length; j++){
            ** list.remove(indices[j]); ** 틀림!
        }
        StringBuilder result = new StringBuilder();
        System.out.println(&quot;list : &quot; + list.toString());
        for (int i=0; i&lt;list.size(); i++) {
            result.append(list.get(i));
        }

        return result.toString();
    }
</code></pre><p>이렇게 풀었더니 결과가 이상했다.
<code>list : [p, o, r, o, r, a, p, e, m, e, p]</code> 
??!</p>
<h4 id="틀린-점">틀린 점</h4>
<p><code>list.remove(indices[j])</code> 에서 리스트의 원소를 삭제한 후에 <strong>인덱스가 변경</strong>되므로, 올바르게 동작하지 않는다. 이로 인해 잘못된 문자가 삭제되고 결과가 이상하게 나타났음!</p>
<h3 id="정답">정답(?)!</h3>
<p>삭제할 문자열을 건너뛰고 새로운문자열을 만들었다</p>
<pre><code>import java.util.ArrayList;
import java.util.List;


class Solution {
    public String solution(String my_string, int[] indices) {
         List&lt;Character&gt; list = new ArrayList&lt;&gt;();

        StringBuilder result = new StringBuilder();
        char[] charArray = my_string.toCharArray();


        for (int i=0; i&lt;charArray.length; i++) {
            boolean removeChar = false;
            for (int index : indices) {
                if (index == i) {
                    removeChar = true;
                    break;
                }
            }
            if (!removeChar) {
                result.append(charArray[i]);
            }
        }

        return result.toString();
    }
}</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[환경]]></title>
            <link>https://velog.io/@2-dean/%ED%99%98%EA%B2%BD</link>
            <guid>https://velog.io/@2-dean/%ED%99%98%EA%B2%BD</guid>
            <pubDate>Tue, 04 Jul 2023 09:05:24 GMT</pubDate>
            <description><![CDATA[<h1 id="환경과-변수">환경과 변수</h1>
<p>Environment</p>
<p>shell?
우리가 변수라고 부르는 key-value쌍의 세트를를 유지 관리 하는 것?</p>
<ul>
<li>Your home directory</li>
<li>Your working directoryu</li>
<li>The name of your shell</li>
<li>The name of the logged in user</li>
</ul>
<h3 id="printenv--내-쉘-환경의-모든-변수가-나옴-환경변수-출력">printenv : 내 쉘 환경의 모든 변수가 나옴 환경변수 출력</h3>
<pre><code>❯ printenv
USER=ddu
HOME=/Users/ddu
SHELL=/bin/zsh
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
TERM=xterm-256color</code></pre><p>왼쪽 변수에 오른쪽이 저장되어있다?</p>
<h2 id="parameter-expansion--매개변수-확장">Parameter Expansion : 매개변수 확장</h2>
<pre><code>❯ echo USER
USER
❯ echo $USER
ddu
❯ echo $user    ❯❯ not work
</code></pre><p>존재하지 않는 변수를 참조하려고 하면 아무 일도 일어나지 않음!</p>
<h2 id="defining-variables">Defining Variables</h2>
<pre><code>❯ variable=value

❯ color=&quot;purple&quot;
❯ num=821</code></pre><h3 id="사용예">사용예</h3>
<pre><code>~/Mystudy/Linux ❯ animal=nudibranch
~/Mystudy/Linux ❯ echo $animal
nudibranch</code></pre><p>-&gt; 지금 정의한 쉘변수는 local variable 처럼 쉘 세션에만 존재함</p>
<h3 id="환경변수-만들기">환경변수 만들기</h3>
<pre><code>❯ export variable=value ❯❯ 환경변수로 정의
❯ export 기존변수명          ❯❯ 환경변수로 바꾸기</code></pre><p>변수는 변경가능함 재할당 하면됨!</p>
<h2 id="startup-files">Startup Files</h2>
<p>.bashrc 파일을 편집해야함
.zshrc</p>
<h2 id="aliases">Aliases</h2>
<pre><code>❯ alias ll=&#39;ls -al&#39;</code></pre><p><strong>현재 쉘 세션에서만 적용됨</strong></p>
<h3 id="사용예-1">사용예</h3>
<pre><code>❯ alias ll=&#39;ls -al&#39;
❯ ll
total 9536
drwxr-x---+ 60 ddu   staff     1920  7  4 17:55 .
drwxr-xr-x   6 root  admin      192  6 10 00:31 ..
...

❯ type ll
ll is aliased to `ls -al&#39;</code></pre><p><a href="https://www.digitalocean.com/community/questions/what-are-your-favorite-bash-aliases">https://www.digitalocean.com/community/questions/what-are-your-favorite-bash-aliases</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Permission(권한)]]></title>
            <link>https://velog.io/@2-dean/Permission%EA%B6%8C%ED%95%9C</link>
            <guid>https://velog.io/@2-dean/Permission%EA%B6%8C%ED%95%9C</guid>
            <pubDate>Tue, 04 Jul 2023 07:48:40 GMT</pubDate>
            <description><![CDATA[<h1 id="chmod">chmod</h1>
<ul>
<li>who : 누구의 permission 을 변경?</li>
<li>what: 어떤 변경 ?  <code>+</code> or <code>-</code></li>
<li>which: 어떤 permission을 위해 그렇게 하는것?</li>
<li><blockquote>
<p><strong>누가 어떤 permission에 어떤 변경을 줄지</strong></p>
</blockquote>
<h2 id="who">who</h2>
</li>
<li><code>u</code> - user (파일주인)</li>
<li><code>g</code> - group(소유자 그룹 멤버)</li>
<li><code>o</code> - other</li>
<li><code>a</code> - all of the above (u,g,o)</li>
</ul>
<h2 id="what--기호">what : 기호</h2>
<ul>
<li><code>-</code> - removes the permission</li>
<li><code>+</code> - grants the permission</li>
<li><code>=</code> - set a permssion and removes others (덮어쓰기)</li>
</ul>
<h2 id="which">which</h2>
<ul>
<li><code>r</code> - read</li>
<li><code>w</code> - write</li>
<li><code>x</code> - execute</li>
</ul>
<h2 id="예시">예시</h2>
<pre><code>~/Mystudy/Linux/Permissions ❯ echo &quot;lol&quot; &gt; happy.txt
------------------------------------------------------
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-rw-r--r--  1 ddu  staff  4  7  4 15:17 happy.txt

~/Mystudy/Linux/Permissions ❯ chmod u+x happy.txt
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-rwxr--r--  1 ddu  staff  4  7  4 15:17 happy.txt

------------------------------------------------------
~/Mystudy/Linux/Permissions ❯ chmod a+w happy.txt
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-rw-rw-rw-  1 ddu  staff  4  7  4 15:17 happy.txt

------------------------------------------------------
~/Mystudy/Linux/Permissions ❯ chmod a-w happy.txt
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-r--r--r--  1 ddu  staff  4  7  4 15:17 happy.txt

------------------------------------------------------
#### 여러 permission 적용

~/Mystudy/Linux/Permissions ❯ chmod u+wx happy.txt
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-rwxr--r--  1 ddu  staff  4  7  4 15:17 happy.txt
~/Mystudy/Linux/Permissions ❯
</code></pre><h2 id="8진법으로도-표현-가능">8진법으로도 표현 가능</h2>
<table>
<thead>
<tr>
<th>Octal</th>
<th>Binary</th>
<th>File Mode</th>
</tr>
</thead>
<tbody><tr>
<td>0</td>
<td>000</td>
<td>---</td>
</tr>
<tr>
<td>1</td>
<td>001</td>
<td>--x</td>
</tr>
<tr>
<td>2</td>
<td>010</td>
<td>-w-</td>
</tr>
<tr>
<td>3</td>
<td>011</td>
<td>-wx</td>
</tr>
<tr>
<td>4</td>
<td>100</td>
<td>r--</td>
</tr>
<tr>
<td>5</td>
<td>101</td>
<td>r-x</td>
</tr>
<tr>
<td>6</td>
<td>110</td>
<td>rw-</td>
</tr>
<tr>
<td>7</td>
<td>111</td>
<td>rwx</td>
</tr>
</tbody></table>
<h3 id="사용-예">사용 예</h3>
<pre><code>chmod 755 file.txt</code></pre><p>user - 7 (rwx), group - 5(r-x), world -5(r-x)
권한 주겠다는 것임</p>
<pre><code>~/Mystudy/Linux/Permissions ❯ chmod 700 happy.txt
~/Mystudy/Linux/Permissions ❯ ls -l
total 8
-rwx------  1 ddu  staff  4  7  4 15:17 happy.txt</code></pre><h1 id="sudo">sudo</h1>
<h2 id="su--대체사용자">su : 대체사용자</h2>
<p>기본으로 전환할 사용자를 대신할 사용자를 설정 가능?
다른사용자로 로그인 하는 것과 같은 경험
작동방식 <code>su-사용자이름</code></p>
<pre><code>~/Mystudy/Linux/Permissions ❯ su - 2dean
Password:
2dean@dduui-MacBookPro ~ % pwd
/Users/2dean
2dean@dduui-MacBookPro ~ % whoami
2dean</code></pre><h3 id="su-사용자이름-과-su---사용자-이름-의-차이">su 사용자이름 과 su - 사용자 이름 의 차이</h3>
<p><code>su 사용자이름</code> :현재 위치에서 사용자만 변경 (디렉토리 위치를 변경하지않음) - 
환경이 섞이게 됨
<code>su - 사용자이름</code>: 새로운 사용자로 로그인 (새로운 사용자의 home directory로 이동됨)</p>
<h2 id="root-user">Root User</h2>
<h2 id="sudo--super-user-do">sudo : super user do~</h2>
<p>sudo를 사용해서 일반 사용자로서는 실행할 수 없는 커맨드를 실행함</p>
<p>첫번째 계정을 만든 사용자만 sudo permission 사용가능 </p>
<pre><code>~ ❯ sudo -l
Password:
User ddu may run the following commands on dduui-MacBookPro:
    (ALL) ALL

~ ❯ su - 2dean                                        
Password:
2dean@dduui-MacBookPro ~ % sudo -l
Password:
Sorry, user 2dean may not run sudo on dduui-MacBookPro.
2dean@dduui-MacBookPro ~ %    </code></pre><p><code>sudo</code>를 사용해 root 사용자로 실행하려는 커맨드를 실행함</p>
<h1 id="chown">chown</h1>
<p>Change Ownership</p>
<pre><code>&gt; chown USER[:GROUP] FILES
&gt; chown bojack file.txt
    -&gt; file.txt의 소유자를 bojack으로 변경</code></pre><h2 id="예시-1">예시</h2>
<pre><code>~/Mystudy/Linux ❯ ls -l
-rw-r--r--   1 ddu  staff      0 Jun 13 21:40 photo.txt

~/Mystudy/Linux ❯ chown 2dean photo.txt
chown: photo.txt: Operation not permitted

~/Mystudy/Linux ❯ sudo chown 2dean photo.txt
Password:
~/Mystudy/Linux ❯ ls -l
-rw-r--r--   1 2dean  staff      0 Jun 13 21:40 photo.txt</code></pre><h2 id="group-추가--mac에서-안됨">Group 추가 &gt; mac에서 안됨</h2>
<ul>
<li>Create Groups : <code>addgroup GROUPNAME</code></li>
<li>Adding Group Members : <code>adduser USER GROUP</code></li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[권한 기초]]></title>
            <link>https://velog.io/@2-dean/%EA%B6%8C%ED%95%9C-%EA%B8%B0%EC%B4%88</link>
            <guid>https://velog.io/@2-dean/%EA%B6%8C%ED%95%9C-%EA%B8%B0%EC%B4%88</guid>
            <pubDate>Tue, 20 Jun 2023 14:15:31 GMT</pubDate>
            <description><![CDATA[<h2 id="multiple-users">Multiple Users</h2>
<h3 id="권한-확인">권한 확인</h3>
<p><code>ls -l</code></p>
<pre><code>drwxr-xr-x   2 ddu  staff     64  5 28 16:19 Cleanup
drwxr-xr-x   3 ddu  staff     96  6 13 22:41 Exercise
-rw-r--r--@  1 ddu  staff  59108  5 28 16:28 Greatgatsby.txt
drwxr-xr-x   9 ddu  staff    288  6 13 22:16 MealDiary
drwxr-xr-x  11 ddu  staff    352  6 14 22:31 Planner</code></pre><p>위에서
<code>drwxr-xr-x</code> <code>-rw-r--r--@</code> 이런 것 들 </p>
<h2 id="파일-소유자-그룹-소유자">파일 소유자 그룹 소유자</h2>
<pre><code>drwxr-xr-x   2 ddu  staff     64  5 28 16:19 Cleanup
drwxr-xr-x   3 ddu  staff     96  6 13 22:41 Exercise
-rw-r--r--@  1 ddu  staff  59108  5 28 16:28 Greatgatsby.txt
drwxr-xr-x   9 ddu  staff    288  6 13 22:16 MealDiary
drwxr-xr-x  11 ddu  staff    352  6 14 22:31 Planner</code></pre><ul>
<li><p>파일소유자 : 첫번째로 나오는이름, 또는 단어가 이름인 사용자
  파일 소유자는 많은 권한이 있음!~!</p>
</li>
<li><p>그룹소유자 : 두번째로 나오는 이름<br>  그룹은 서로 다른 사용자들을 그룹화할 수 있음, 서로 다른 사용자이기 때문에 개별적으로 권한을 다르게 부여할 수 있음 </p>
</li>
</ul>
<h2 id="파일-속성-10-글자">파일 속성 10 글자</h2>
<p><code>drwxr-xr-x</code> 
<code>-rw-r--r--@</code>  이런 것 들 
각각의문자가 특정한 파일 유형을 알려줌</p>
<h3 id="첫번째-문자--파일유형">첫번째 문자 : 파일유형</h3>
<ul>
<li><strong><code>-</code></strong> : regular file</li>
<li><strong><code>d</code></strong> : directory</li>
<li><code>c</code> : charactor special file<ul>
<li>특수파일 예<pre><code>crw-------  1 root   wheel          0x23000000  6 19 23:50 auㅎㅁㅇㅎㅁ
crw-rw-rw-  1 root   wheel          0x22000003  6 19 23:50 auㄴㅇㅁㅎㄴㅇㅎㅁer</code></pre></li>
</ul>
</li>
<li><code>l</code> : symbolic link
심볼릭 링크 파일 예시<pre><code>    심볼릭 링크생성
    ~/Mystudy/Linux ❯ ln -s GreatGatsby.txt myGG
    확인
    ~/Mystudy/Linux ❯ ls -l
    lrwxr-xr-x   1 ddu  staff     15  6 20 22:25 myGG -&gt; GreatGatsby.txt</code></pre></li>
</ul>
<h3 id="나머지-9-문자---3부분으로-구분">나머지 9 문자 - 3부분으로 구분</h3>
<table>
<thead>
<tr>
<th></th>
<th>Owner</th>
<th>Group</th>
<th>World</th>
</tr>
</thead>
<tbody><tr>
<td>-</td>
<td>rw-</td>
<td>rw-</td>
<td>r--</td>
</tr>
</tbody></table>
<ul>
<li>첫 세글자 : 소유자에 대한 권한</li>
<li>두번째 세글자 : 그룹에 대한 권한</li>
<li>세번째 세글자 : 파일소유자도, 그룹소유자도 아닌 3자에 대한권한</li>
</ul>
<p><img src="https://velog.velcdn.com/images/2-dean/post/7f4c366d-f22a-4031-85e9-27ec1182aa0e/image.png" alt=""></p>
<h2 id="read-write-execute-permissions">read, write, execute permissions</h2>
<h3 id="r--read-permission">r : Read Permission</h3>
<ul>
<li>file : 파일을 읽음</li>
<li>directory : 디렉토리 내의 컨텐츠를 읽을 수 있음</li>
</ul>
<h3 id="w--write-permission">w : Write Permission</h3>
<ul>
<li>file : 파일생성, 내용수정, 변경포함. </li>
<li>directory : 이름 변경과 파일에 대한 삭제여부, directory 내에서의 이동과 삭제, 새파일의 생성과 이름 변경등의 작업</li>
</ul>
<h3 id="x--execute-permission">x : Execute Permission</h3>
<p><code>x</code> 나 <code>-</code>로 표시됨</p>
<ul>
<li>file : 실행 가능한 파일이고 프로그램으로 실행 가능하다</li>
<li>directory : directory로 들어갈 수 없음 cd 불가능 </li>
</ul>
<p>권한 없으면 Permission denied 오류!!</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[grep]]></title>
            <link>https://velog.io/@2-dean/grep</link>
            <guid>https://velog.io/@2-dean/grep</guid>
            <pubDate>Mon, 19 Jun 2023 14:39:51 GMT</pubDate>
            <description><![CDATA[<h2 id="grep">grep</h2>
<p>find나 locate같은 명령어의 파일 이름만이 아니고, 내부 정보를 포함합니다
파일의 내부를 검색하고 찾으려는 내용을 출력함 일치하는 행을 출력해줌</p>
<p><code>&gt;grep PATTERN FILE</code> </p>
<p>찾으려는 패턴을 파일에서 찾아줌</p>
<ul>
<li><p>예시</p>
<pre><code>    ~/Mystudy/Linux ❯ grep &quot;Chapter&quot; Greatgatsby.txt
    1. Chapter 1
    1. Chapter 2</code></pre></li>
<li><p>예시
<code>~/Mystudy/Linux ❯ grep &quot;Gatsby&quot; Greatgatsby.txt</code></p>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/2-dean/post/cf75519a-242e-46f7-8f35-04102834825e/image.png" alt=""></p>
<h3 id="options">Options</h3>
<p>grep은 대소문자를 구분한다</p>
<h4 id="i">i</h4>
<p>구분 하지 않으려면 -i 옵션을 준다</p>
<h4 id="w">w</h4>
<p>제공한 패턴이 <strong>정확히 일치</strong>하는 단어 찾기 (포함파는X)
<code>grep -w &quot;cat&quot; book.txt</code></p>
<h4 id="r">r</h4>
<p>재귀적 검색?
<code>grep -r &quot;chickin&quot;</code></p>
<p><code>grep -ri &quot;parm[ae]san&quot; MealDiary/</code>
    MealDiary/ 아래에서 &#39;parmasan&#39; 또는 &#39;parmesan&#39; 을 찾음</p>
<h4 id="c">c</h4>
<p>count</p>
<pre><code>~/Mystudy/Linux ❯ grep &quot;myself&quot; SongOfMyself.txt -ic
47
~/Mystudy/Linux ❯ grep &quot;I&quot; SongOfMyself.txt -c
439
~/Mystudy/Linux ❯ grep &quot;I&quot; SongOfMyself.txt -cw
392
~/Mystudy/Linux ❯ grep &quot;I&quot; SongOfMyself.txt -cw
</code></pre><h4 id="a-b">A, B</h4>
<p>-A num, --after-context=num
             Print num lines of trailing context after each match.  See also the
             -B and -C options.</p>
<p>-B num, --before-context=num
             Print num lines of leading context before each match.  See also the
             -A and -C options.</p>
<p><code>grep &quot;wagon&quot; SongOfMyself.txt -B4</code> : wagon 이전 4줄</p>
<h2 id="grep의-regex">grep의 Regex</h2>
<h3 id="">.</h3>
<p><code>.</code> = 글자 1개 </p>
<p><code>grep &quot;p....&quot; file.txt</code>
 p로 시작하고 다음 네글자 있는거 전부 출력</p>
<h3 id="-carot">^ (carot)</h3>
<p>행의 시작</p>
<ul>
<li><p>입력
<code>~/Mystudy/Linux ❯ grep &quot;^I&quot; SongOfMyself.txt -w</code></p>
</li>
<li><p>출력</p>
<pre><code>I celebrate myself, and sing myself,
I loafe and invite my soul,
I lean and loafe at my ease observing a spear of summer grass.
I, now thirty-seven years old in perfect health begin,
I harbor for good or bad, I permit to speak at every hazard,
I breathe the fragrance myself and know it and like it,
I will go to the bank by the wood and become undisguised and naked,
I am mad for it to be in contact with me.
I have heard what the talkers were talking, the talk of the beginning and the end,</code></pre></li>
</ul>
<h3 id="-1">$</h3>
<p>행의 끝 문장의 끝</p>
<ul>
<li>입력
  <code>~/Mystudy/Linux ❯ grep &quot;)$&quot; SongOfMyself.txt -w</code></li>
<li>출력<pre><code>You shall possess the good of the earth and sun, (there are millions of suns left,)
(They do not know how immortal, but I know.)
(He will never sleep any more as he did in the cot in his mother’s bed-room;)
The young fellow drives the express-wagon, (I love him, though I do not know him;)
The regatta is spread on the bay, the race is begun, (how the white sails sparkle!)</code></pre></li>
</ul>
<h2 id="abc">[abc]</h2>
<p>parmesan 예시</p>
<h2 id="확장정규식">확장정규식</h2>
<p><code>-E</code> 붙여야함</p>
<h3 id="--있거나-없거나">? : 있거나 없거나</h3>
<pre><code>~/Mystudy/Linux ❯ grep &quot;bird&quot; -w  SongOfMyself.txt
Where the mocking-bird sounds his delicious gurgles, cackles, screams, weeps,
Where the humming-bird shimmers, where the neck of the long-lived swan is curving and winding,

~/Mystudy/Linux ❯ grep &quot;birds&quot; -w  SongOfMyself.txt
I hear bravuras of birds, bustle of growing wheat, gossip of flames, clack of sticks cooking my meals,
And am stucco’d with quadrupeds and birds all over,
(They bore mites as for unfledg’d birds who have now to rise and fly and sing for themselves,)

~/Mystudy/Linux ❯ grep &quot;birds?&quot; -w  SongOfMyself.txt

### 확장정규식 사용
~/Mystudy/Linux ❯ grep &quot;birds?&quot; -wE  SongOfMyself.txt
I hear bravuras of birds, bustle of growing wheat, gossip of flames, clack of sticks cooking my meals,
And am stucco’d with quadrupeds and birds all over,
Where the mocking-bird sounds his delicious gurgles, cackles, screams, weeps,
Where the humming-bird shimmers, where the neck of the long-lived swan is curving and winding,
(They bore mites as for unfledg’d birds who have now to rise and fly and sing for themselves,)</code></pre><h3 id="-2">{}</h3>
<p><code>a{3}</code> = <code>aaa</code></p>
<p><code>[A-Z]{5}</code> = 대문자로 쓰여진 5개 글자</p>
<h2 id="piping-to-grep">Piping to Grep</h2>
<ul>
<li>프로세스 중에서 쉽게 찾기
<code>ps -aux | grep &quot;sound&quot;</code> </li>
</ul>
<ul>
<li>man 에서 원하는 부분 찾기<pre><code>~/Mystudy/Linux ❯ man grep | grep &quot;count&quot;                         
           Only a count of selected lines is written to standard output.
           file, starting at line 1.  The line number counter is reset for</code></pre></li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[찾기]]></title>
            <link>https://velog.io/@2-dean/%EC%B0%BE%EA%B8%B0</link>
            <guid>https://velog.io/@2-dean/%EC%B0%BE%EA%B8%B0</guid>
            <pubDate>Sat, 17 Jun 2023 06:05:51 GMT</pubDate>
            <description><![CDATA[<h2 id="locate">&gt;locate</h2>
<p>locate 데이터베이스는 파일 시스템의 색인 정보를 저장하며, 일반적으로 시스템에서 파일을 검색하기 전에 이 데이터베이스를 참조합니다.</p>
<pre><code> locate – find filenames quickly</code></pre><pre><code>     locate [-0Scims] [-l limit] [-d database] pattern ...</code></pre><h3 id="locate-오류">locate 오류!</h3>
<p>locate 입력했는데 </p>
<pre><code>User
WARNING: The locate database (/var/db/locate.database) does not exist.
To create the database, run the following command:

  sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist

Please be aware that the database can take some time to generate; once
the database has been created, this message will no longer appear.</code></pre><p>이런 오류가 나왔다!
해당 오류는 &quot;/var/db/locate.database&quot; 위치에 locate 데이터베이스가 존재하지 않아서였다</p>
<p><code>sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist</code></p>
<p>이 명령어 실행하고. 아무일이 없더라도... DB 설치중...이니 조금 기다리자
<code>Load failed: 37: Operation already in progress</code>
zzzz
설치가 다 되면 잘 나온다!</p>
<h3 id="location-option">location option</h3>
<ul>
<li><code>-i</code> 대소문자 구분 x</li>
<li><code>-l</code> 결과의 갯수 제한</li>
<li><code>-e</code> 현재 존재하는 파일인지 확인</li>
</ul>
<h2 id="find">find</h2>
<p>locate 보다 강력하지만 시간이 조금 걸림
실제로 디렉토리 전체나 컴퓨터 전체를 검색 
인자 없이 find를 실행하면, 현재 위치부터 시작해 하위 디렉토리의 모든 것들을 표시</p>
<h3 id="filtering">filtering</h3>
<ul>
<li><code>-type d</code> : directory</li>
<li><code>-name</code> &quot;&quot; 따옴표 사용, 대소문자 구분
예시 
홈 디렉토리의 모든 .txt 파일 검색<pre><code>dduui-MacBookPro:~ ddu$ find ~ -type f -name &quot;*.txt&quot;</code></pre></li>
<li><code>-size</code> 파일 사이즈로 필터링
  <code>find -size +1G</code></li>
<li><code>-user</code> 사용자!</li>
<li><code>-empty</code> 빈파일이나 디렉토리</li>
</ul>
<h2 id="timestamps">Timestamps</h2>
<ul>
<li>mtime : 파일 내용이 마지막으로 바뀐 시간</li>
<li>ctime : 파일의 이동, 이름변경, 권한변경시 갱신됨, 파일 내용 변경시에도 갱신됨</li>
<li>atime : 파일 접근 시간 </li>
</ul>
<h2 id="logical-operators">Logical Operators</h2>
<pre><code>- and 는 묵시적으로 사용하므로 생략함

- or  둘중 하나
&gt; find -name &quot;*chick*&quot; -or -name &quot;*kitty&quot; 

- not !
&gt; find -type -f -not -name &quot;*.html&quot;
 =&gt; find -type -f ! -name &quot;*.html&quot;
</code></pre><h2 id="-exec-command">-exec command{};</h2>
<p>find로 찾은 모든 것 대해서 어떤 명령을 수행하는 방법</p>
<p><code>-exec command{};</code></p>
<p><code>-ok</code> 실행여부 묻기</p>
<h2 id="xargs----딱-한번만-실행">xargs  - 딱 한번만 실행</h2>
<p>xargs로 실행했을 때는 조금 다릅니다, xargs는
표준 입력의 결과를 꾸러미 형식으로 바꿔서, 이를 딱 한 번만 실행합니다
-exec 보다 효율적일 수 있음 !</p>
<p>xargs 는 표준입력을 받아 인자목록으로 변환함. &gt;   전달가능 하고 표준입력이 불가능한 명령어에 이를 추가해 사용할 수 있음</p>
<p>ex)<code>echo hello | xargs mkdir</code></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[확장 (*, ?, [], {},"")]]></title>
            <link>https://velog.io/@2-dean/%ED%99%95%EC%9E%A5</link>
            <guid>https://velog.io/@2-dean/%ED%99%95%EC%9E%A5</guid>
            <pubDate>Tue, 13 Jun 2023 13:53:13 GMT</pubDate>
            <description><![CDATA[<h2 id="확장">확장</h2>
<p><code>*</code>  기호는 파일 이름에서 0개 ~ 전체 문자를 의미함
즉 모든 것에 해당</p>
<h2 id="the--wildcard">The <code>?</code> Wildcard</h2>
<p>The question mark(?) charactoer represent <strong>any single character</strong>.</p>
<p><code>ls app.??</code> 를 실행하면</p>
<p>app.뒤에 문자 두개가 오는 모든 파일만 출력.
확장자가 <code>.js, .py</code>처럼 두글자인 것만 가능하고 <code>.css나 .html</code>은 해당하지 않음</p>
<h2 id="range-wildcards-">Range Wildcards <code>[]</code></h2>
<p>문자의 범위를 나타냄
아무 한 글자만 일치하면 되는 ?와는 다르게 []는대문자 A에서 F사이의 문자라던지 숫자 1부터 9 혹은 0부터 9처럼 특정한 글자 중에서 일치해야 함.</p>
<h2 id="-not">^ not</h2>
<p>[A-Z]  : A ~ Z 까지 
[^A-Z] : 로 바꿔주면 대문자로 시작하지 않는 파일과 폴더들만 나타나게 됩니다 소문자나 특수문자등으로 시작하는 것</p>
<h2 id="-tilde">~ tilde</h2>
<p><code>~</code> : home directory 
<code>~</code> 를 사용해 확장 가능 
<code>~사용자</code> 를 사용해 다른 사용자로 확장 </p>
<h2 id="-brace-expansion-중괄호확장">{} Brace Expansion 중괄호확장</h2>
<p>중괄호 안에 <code>,</code>로 구분되어있는 값들은 각각 하나의 문자열이 되며, 중괄호 앞과 뒤에 있는 문자와 합쳐진다.</p>
<pre><code>입력: touch page{1,2,3}.txt

결과: page1.txt, page2.txt, page3.txt</code></pre><pre><code>ddu$ echo  {Mon,Tue,Wen,Thu,Fri}_Planner.txt

##결과
Mon_Planner.txt Tue_Planner.txt Wen_Planner.txt Thu_Planner.txt Fri_Planner.txt

dddu$ echo Dec_ {Mon,Tue,Wen,Thu,Fri}_Planner.txt

##결과
ddu$ ls
Dec_ Mon_Planner.txt Tue_Planner.txt Wen_Planner.txt Thu_Planner.txt Fri_Planner.txt


ddu$ echo  {Mon,Tue,Wen,Thu,Fri}_{AM,PM}.txt

##결과
ddu$ ls
Mon_AM.txt Mon_PM.txt Tue_AM.txt Tue_PM.txt Wen_AM.txt Wen_PM.txt Thu_AM.txt Thu_PM.txt Fri_AM.txt Fri_PM.txt


ddu$ touch  {Mon,Tue,Wen,Thu,Fri}_{AM,PM}.txt

##결과
ddu$ ls
Fri_AM.txt    Mon_AM.txt    Thu_AM.txt    Tue_AM.txt    Wen_AM.txt
Fri_PM.txt    Mon_PM.txt    Thu_PM.txt    Tue_PM.txt    Wen_PM.txt


</code></pre><h3 id="">{..}</h3>
<pre><code>mkdir jan{1..31}</code></pre><p>jan1 ~jan31 directory 생성</p>
<h3 id="startnumendnumnum간격">{startNum..endNum..num(간격)}</h3>
<pre><code>&gt; echo {2..10..1}

## 결과
&gt; 2,3,4,5,6,7,8,9,10

&gt; echo {2..10..1}

## 결과
&gt; 2,3,4,5,6,7,8,9,10</code></pre><p>{2..10..2}는 2부터 10까지 2의 간격을 의미 </p>
<h2 id="arithmetic-expansion">Arithmetic Expansion</h2>
<p><code>$((expression))</code>
쉘이 이 계산식을 확인하고 계산식에 사용한 기호에 따라 연산을 수행함 
+ 덧셈
- 뺄셈
* 곱셈
/ 나눗셈
** 지수연산 (10**3 =&gt; 10의 3제곱)
% modulo (나머지연산)
정수 연산만 함</p>
<h2 id="quoting">Quoting</h2>
<p><code>&quot;&quot;</code><br>-&gt; 쉘이 공복문자를 보존함 $ , \ , ` 3개 기호를 제외한 나머지 특수문자를 그대로 표현 </p>
<p><code>&#39;&#39;</code></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[조건문 :  간단한 논리연산]]></title>
            <link>https://velog.io/@2-dean/%EC%A1%B0%EA%B1%B4%EB%AC%B8-%EA%B0%84%EB%8B%A8%ED%95%9C-%EB%85%BC%EB%A6%AC%EC%97%B0%EC%82%B0</link>
            <guid>https://velog.io/@2-dean/%EC%A1%B0%EA%B1%B4%EB%AC%B8-%EA%B0%84%EB%8B%A8%ED%95%9C-%EB%85%BC%EB%A6%AC%EC%97%B0%EC%82%B0</guid>
            <pubDate>Mon, 12 Jun 2023 13:21:57 GMT</pubDate>
            <description><![CDATA[<h2 id="문제">문제</h2>
<p>boolean 변수 x1, x2, x3, x4가 매개변수로 주어질 때, 다음의 식의 true/false를 return 하는 solution 함수를 작성해 주세요.</p>
<ul>
<li>(x1 ∨ x2) ∧ (x3 ∨ x4)<h3 id="입출력예">입출력예</h3>
</li>
</ul>
<h3 id="∨과-∧의-진리표">∨과 ∧의 진리표</h3>
<table>
<thead>
<tr>
<th>x</th>
<th>y</th>
<th>x ∨ y</th>
<th>x ∧ y</th>
</tr>
</thead>
<tbody><tr>
<td>T</td>
<td>T</td>
<td>T</td>
<td>T</td>
</tr>
<tr>
<td>T</td>
<td>F</td>
<td>T</td>
<td>F</td>
</tr>
<tr>
<td>F</td>
<td>T</td>
<td>T</td>
<td>F</td>
</tr>
<tr>
<td>F</td>
<td>F</td>
<td>F</td>
<td>F</td>
</tr>
</tbody></table>
<h2 id="풀이">풀이</h2>
<pre><code>class Solution {
    public boolean solution(boolean x1, boolean x2, boolean x3, boolean x4) {
        boolean answer = true;
        boolean answer1 = true;
        boolean answer2 = true;


        if (x1 != x2) {
            answer1 = true;
        } else if (x1 &amp;&amp; x2) {
            answer1 = true;
        } else {
        // FF일때만  F
            answer1 = false;
        }

        if (x3 != x4) {
            answer2 = true;
        } else if (x3 &amp;&amp; x4) {
            answer2 = true;
        } else {
        // FF일때만  F
            answer2 = false;
        }

        if (answer1 &amp;&amp; answer2) {
            answer = true;
        } else {
            answer = false;
        }

        return answer;

    }
}</code></pre><h3 id="풀이과정">풀이과정</h3>
<ul>
<li>x∨y 는 F와 F일때만 F</li>
<li>x∧y 는 T와 T일때만 T!</li>
</ul>
<h3 id="알게된점">알게된점</h3>
<p>다른 사람 풀이를 보니!
내가 너무 바보같이 풀었다.. ㅎㅎ</p>
<pre><code>           //x∨y        x∨y
   return (x1||x2) &amp;&amp; (x3||x4);
              //x∧y ( T &amp;&amp; T 일때만 T)</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[해시 :  완주하지 못한 선수]]></title>
            <link>https://velog.io/@2-dean/%ED%95%B4%EC%8B%9C-%EC%99%84%EC%A3%BC%ED%95%98%EC%A7%80-%EB%AA%BB%ED%95%9C-%EC%84%A0%EC%88%98</link>
            <guid>https://velog.io/@2-dean/%ED%95%B4%EC%8B%9C-%EC%99%84%EC%A3%BC%ED%95%98%EC%A7%80-%EB%AA%BB%ED%95%9C-%EC%84%A0%EC%88%98</guid>
            <pubDate>Sun, 11 Jun 2023 08:00:35 GMT</pubDate>
            <description><![CDATA[<h2 id="문제">문제</h2>
<p>수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.</p>
<p>마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.</p>
<h4 id="제한사항">제한사항</h4>
<ul>
<li>마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.</li>
<li>completion의 길이는 participant의 길이보다 1 작습니다.</li>
<li>참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.</li>
<li>참가자 중에는 동명이인이 있을 수 있습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>participant</th>
<th>completion</th>
<th>return</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;leo&quot;, &quot;kiki&quot;, &quot;eden&quot;]</td>
<td>[&quot;eden&quot;, &quot;kiki&quot;]</td>
<td>&quot;leo&quot;</td>
</tr>
<tr>
<td>[&quot;marina&quot;, &quot;josipa&quot;, &quot;nikola&quot;, &quot;vinko&quot;, &quot;filipa&quot;]</td>
<td>[&quot;josipa&quot;, &quot;filipa&quot;, &quot;marina&quot;, &quot;nikola&quot;]</td>
<td>&quot;vinko&quot;</td>
</tr>
<tr>
<td>[&quot;mislav&quot;, &quot;stanko&quot;, &quot;mislav&quot;, &quot;ana&quot;]</td>
<td>[&quot;stanko&quot;, &quot;ana&quot;, &quot;mislav&quot;]</td>
<td>&quot;mislav&quot;</td>
</tr>
</tbody></table>
<h2 id="풀이">풀이</h2>
<pre><code>import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
  String answer = &quot;&quot;;
        Map&lt;String, Integer&gt; completeMap = new HashMap&lt;&gt;();

        //완주자 명단
        for (int i=0; i&lt;completion.length; i++) {
            if (completeMap.containsKey(completion[i])) {
                completeMap.put(completion[i], completeMap.get(completion[i]) + 1);
            } else {
                completeMap.put(completion[i], 1);
            }
        }

        for (int i = 0; i&lt; participant.length; i++) {
            if(completeMap.containsKey((participant[i]))){
                if (completeMap.get(participant[i]) &gt; 0) {
                    completeMap.put(participant[i], completeMap.get(participant[i]) - 1);
                } else {
                    // 완주 못함
                    answer = participant[i];
                    break;
                }
            } else {
                // 완주 못함
                answer = participant[i];
                break;
            }
        }

        return answer;
    }
}</code></pre><h2 id="내가-풀이를-못하는-중-ㅋ">내가 풀이를 못하는 중 ㅋ</h2>
<ol>
<li>완주자 명단을 Map에 추가한다. {이름, 1(count)} </li>
<li>완주자 명단에서 참가자의 이름이 있는지 확인한다. 없으면 미완주자</li>
<li>완주자 명단에 참가자의 이름이 있으면 
3-1. value가 0보다 크면 count - 1 해준다 {이름, 0}이 됨
3-2. value가 0보다 작으면 동명이인 완주자가 이미 있었던 것임 -&gt; 미완주자</li>
</ol>
<hr>
<p>넘 어려웠다!</p>
<h2 id="다른사람의-멋진-코드">다른사람의 멋진 코드</h2>
<pre><code> public String solution(String[] participant, String[] completion) {
        String answer = &quot;&quot;;
        HashMap&lt;String, Integer&gt; hm = new HashMap&lt;&gt;();
        for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);
        for (String player : completion) hm.put(player, hm.get(player) - 1);

        for (String key : hm.keySet()) {
            if (hm.get(key) != 0){
                answer = key;
            }
        }
        return answer;
    }</code></pre><ul>
<li><p><code>getOrDefault</code>
찾는 키가 존재한다면 찾는 키의 값을 반환하고 없다면 기본 값을 반환하는 메서드
   위 코드에서 동명이인을 확인하는데 사용함.
  참자자를 Map에 넣으면서 {이름, (기본값=0) + 1}의 형태로 넣어줌, -&gt; {이름, 1} 이됨
  동명이인이 있으면 {이름, (기본값=1) + 1}이 됨 .. 추가있으면 더 되고?
  완주자를 {이름, -1} 해주면서 완주자는 {이름, 0}이 됨 
  미 완주자는 {이름, !=0}이된다</p>
</li>
<li><p><code>keySet()</code> 
해당 맵에 포함된 모든 키(key)를 담은 Set 객체를 반환</p>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[해시 : 폰켓몬]]></title>
            <link>https://velog.io/@2-dean/%ED%95%B4%EC%8B%9C-%ED%8F%B0%EC%BC%93%EB%AA%AC</link>
            <guid>https://velog.io/@2-dean/%ED%95%B4%EC%8B%9C-%ED%8F%B0%EC%BC%93%EB%AA%AC</guid>
            <pubDate>Sat, 10 Jun 2023 15:02:04 GMT</pubDate>
            <description><![CDATA[<h2 id="문제">문제</h2>
<p>당신은 폰켓몬을 잡기 위한 오랜 여행 끝에, 홍 박사님의 연구실에 도착했습니다. 홍 박사님은 당신에게 자신의 연구실에 있는 총 N 마리의 폰켓몬 중에서 N/2마리를 가져가도 좋다고 했습니다.
홍 박사님 연구실의 폰켓몬은 종류에 따라 번호를 붙여 구분합니다. 따라서 같은 종류의 폰켓몬은 같은 번호를 가지고 있습니다. 예를 들어 연구실에 총 4마리의 폰켓몬이 있고, 각 폰켓몬의 종류 번호가 [3번, 1번, 2번, 3번]이라면 이는 3번 폰켓몬 두 마리, 1번 폰켓몬 한 마리, 2번 폰켓몬 한 마리가 있음을 나타냅니다. 이때, 4마리의 폰켓몬 중 2마리를 고르는 방법은 다음과 같이 6가지가 있습니다.</p>
<p>첫 번째(3번), 두 번째(1번) 폰켓몬을 선택
첫 번째(3번), 세 번째(2번) 폰켓몬을 선택
첫 번째(3번), 네 번째(3번) 폰켓몬을 선택
두 번째(1번), 세 번째(2번) 폰켓몬을 선택
두 번째(1번), 네 번째(3번) 폰켓몬을 선택
세 번째(2번), 네 번째(3번) 폰켓몬을 선택
이때, 첫 번째(3번) 폰켓몬과 네 번째(3번) 폰켓몬을 선택하는 방법은 한 종류(3번 폰켓몬 두 마리)의 폰켓몬만 가질 수 있지만, 다른 방법들은 모두 두 종류의 폰켓몬을 가질 수 있습니다. 따라서 위 예시에서 가질 수 있는 폰켓몬 종류 수의 최댓값은 2가 됩니다.
당신은 최대한 다양한 종류의 폰켓몬을 가지길 원하기 때문에, 최대한 많은 종류의 폰켓몬을 포함해서 N/2마리를 선택하려 합니다. N마리 폰켓몬의 종류 번호가 담긴 배열 nums가 매개변수로 주어질 때, N/2마리의 폰켓몬을 선택하는 방법 중, 가장 많은 종류의 폰켓몬을 선택하는 방법을 찾아, 그때의 폰켓몬 종류 번호의 개수를 return 하도록 solution 함수를 완성해주세요.</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>nums</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[3,1,2,3]</td>
<td>2</td>
</tr>
<tr>
<td>[3,3,3,2,2,4]</td>
<td>3</td>
</tr>
<tr>
<td>[3,3,3,2,2,2]</td>
<td>2</td>
</tr>
</tbody></table>
<h2 id="풀이">풀이</h2>
<pre><code>import java.util.HashMap;
import java.util.Map;

class Solution {
    public int solution(int[] nums) {
        int answer = 0;
        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();
        for (int i=0; i&lt;nums.length; i++) {
            map.put(nums[i], nums[i]);
        }

        if (map.size() &gt; nums.length/2) {
            answer = nums.length/2;
        } else  {
            answer =map.size();
        }
        return answer;
    }
}</code></pre><h3 id="풀이과정">풀이과정</h3>
<ol>
<li>폰켓몬 종류를 중복되지 않게 Map에 담는다.</li>
<li>고를 수 있는 폰켓몬의 숫자를 구한다 (nums.length/2)</li>
<li>폰켓몬 종류는 중복이 없으니, 
고를 수 있는 포켓몬 숫자보다 폰켓몬 종류가 많으면 고를 수 있는 폰켓몬 수를 반환, 
고를 수 있는 포켓몬 숫자보다 폰켓몬 종류가 적으면 폰켓몬 종류를 반환한다!</li>
</ol>
<p>헉 내가 <del>포</del>폰켓몬을 잡아버렸다🎱</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Pipe]]></title>
            <link>https://velog.io/@2-dean/Pipe</link>
            <guid>https://velog.io/@2-dean/Pipe</guid>
            <pubDate>Sat, 10 Jun 2023 12:08:52 GMT</pubDate>
            <description><![CDATA[<h2 id="pipe"><code>pipe</code></h2>
<p><code>&gt; command1 | command2</code>
두 명령어를 연결하기 위해 한 명령어의 표준 출력을 두번째 명령어의 표준 입력으로 이어줄 수 있다. (= 두개 이상의 명령어를 결합하여 사용할 수 있다) 
명령어 체인을 만들어 원하는 작업을 수행할 수 있다.
<code>|</code> 수직 막대 기호로 표시된다.</p>
<h2 id="리다이렉션과-파이프-차이">리다이렉션과 파이프 차이</h2>
<p>리다이렉션 <code>&gt;</code> 표준출력을 특정 파일로 출력
파이프 <code>|</code> 명령어와 다른 명령어를 연결해줌 연결에는 파일이 필요하지 않음! </p>
<h2 id="tee"><code>tee</code></h2>
<p>두 파이프 사이에 <code>tee</code>를 두면 첫번째 명령어의 <strong>결과를 받아서 다음 명령어로 넘겨줌</strong></p>
<h3 id="예">예</h3>
<p>colors.txt, words.txt 두개의 파일을 합쳐서 하나의 colorsNwords.txt 파일로 만들고 colorsNwords.txt 파일의 단어를 세는 작업을 한다면?</p>
<pre><code>ddu$ cat colors.txt words.txt | tee colorsNwords.txt | wc
      15      13      82</code></pre><pre><code>ddu$ cat colorsNwords.txt
red
orange
yellow
green
blue
indigo
violet

cat
Mizz
mouse
keyboard
shirts
velog</code></pre><p><code>wc</code> : word count</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[반복문 : 배열 만들기 4]]></title>
            <link>https://velog.io/@2-dean/%EB%B0%98%EB%B3%B5%EB%AC%B8-%EB%B0%B0%EC%97%B4-%EB%A7%8C%EB%93%A4%EA%B8%B0-4</link>
            <guid>https://velog.io/@2-dean/%EB%B0%98%EB%B3%B5%EB%AC%B8-%EB%B0%B0%EC%97%B4-%EB%A7%8C%EB%93%A4%EA%B8%B0-4</guid>
            <pubDate>Sat, 10 Jun 2023 07:39:51 GMT</pubDate>
            <description><![CDATA[<h2 id="문제">문제</h2>
<p>정수 배열 arr가 주어집니다. arr를 이용해 새로운 배열 stk를 만드려고 합니다.</p>
<p>변수 i를 만들어 초기값을 0으로 설정한 후 i가 arr의 길이보다 작으면 다음 작업을 반복합니다.</p>
<p>만약 stk가 <strong>빈 배열이라면 arr[i]를 stk에 추가하고 i에 1을 더합</strong>니다.
stk에 원소가 있고, <strong>stk의 마지막 원소가 arr[i]보다 작으면 arr[i]를 stk의 뒤에 추가하고 i에 1을 더합니다</strong>.
stk에 원소가 있는데 <strong>stk의 마지막 원소가 arr[i]보다 크거나 같으면 stk의 마지막 원소를 stk에서 제거합니다.</strong>
위 작업을 마친 후 만들어진 stk를 return 하는 solution 함수를 완성해 주세요.</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>arr</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[1, 4, 2, 5, 3]</td>
<td>[1, 2, 3]</td>
</tr>
<tr>
<td>### 문제해석</td>
<td></td>
</tr>
<tr>
<td>문제 순서대로 풀면된다!</td>
<td></td>
</tr>
</tbody></table>
<h2 id="풀이">풀이</h2>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


class Solution {
    public int[] solution(int[] arr) {
          List&lt;Integer&gt; stk = new ArrayList&lt;&gt;();

        for (int i=0; i&lt;arr.length; i++){
            if (stk.size() == 0) {
                stk.add(arr[i]);
            } else {
                if (stk.get(stk.size()-1) &lt; arr[i]) {
                    //stk의 마지막 원소가 arr[i]보다 작으면 arr[i]를 stk의 뒤에 추가하고 i에 1을 더합니다.
                    stk.add(arr[i]);
                } else {
                    //stk의 마지막 원소가 arr[i]보다 크거나 같으면 stk의 마지막 원소를 stk에서 제거
                    stk.remove(stk.size()-1);
                    i--; // 여기서는 i에 1을 추가하지 않음! 미리 빼준다
                }
            }
        }
        int[] result = new int[stk.size()];
        for (int j=0; j&lt;stk.size(); j++) {
            result[j] = stk.get(j);
        }
        return result;
    }
}</code></pre><h3 id="나의-실수">나의 실수</h3>
<p>너무 친절한 문제인데 결과값이 이상해서 왜그러지? 했는데...</p>
<blockquote>
<p><strong>stk의 마지막 원소가 arr[i]보다 크거나 같으면 stk의 마지막 원소를 stk에서 제거합니다.</strong></p>
</blockquote>
<p>이때는 i를 1 증가시키지 않는다!😇 문제를 잘 읽자...^^;</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[반복문 : 콜라츠 수열 만들기]]></title>
            <link>https://velog.io/@2-dean/%EB%B0%98%EB%B3%B5%EB%AC%B8-%EC%BD%9C%EB%9D%BC%EC%B8%A0-%EC%88%98%EC%97%B4-%EB%A7%8C%EB%93%A4%EA%B8%B0</link>
            <guid>https://velog.io/@2-dean/%EB%B0%98%EB%B3%B5%EB%AC%B8-%EC%BD%9C%EB%9D%BC%EC%B8%A0-%EC%88%98%EC%97%B4-%EB%A7%8C%EB%93%A4%EA%B8%B0</guid>
            <pubDate>Sat, 10 Jun 2023 05:49:30 GMT</pubDate>
            <description><![CDATA[<h2 id="문제">문제</h2>
<p>모든 자연수 x에 대해서 현재 값이 x이면 x가 짝수일 때는 2로 나누고, x가 홀수일 때는 3 * x + 1로 바꾸는 계산을 계속해서 반복하면 언젠가는 반드시 x가 1이 되는지 묻는 문제를 콜라츠 문제라고 부릅니다.</p>
<p>그리고 위 과정에서 거쳐간 모든 수를 기록한 수열을 콜라츠 수열이라고 부릅니다.</p>
<p>계산 결과 1,000 보다 작거나 같은 수에 대해서는 <strong>전부 언젠가 1에 도달</strong>한다는 것이 알려져 있습니다.</p>
<p>임의의 1,000 보다 작거나 같은 양의 정수 n이 주어질 때 초기값이 n인 콜라츠 수열을 return 하는 solution 함수를 완성해 주세요.</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>10</td>
<td>[10, 5, 16, 8, 4, 2, 1]</td>
</tr>
<tr>
<td>### 문제 해석</td>
<td></td>
</tr>
</tbody></table>
<ol>
<li>n이 1보다 클때 list에 담아준다.</li>
<li>n이 홀수, 짝수 일때 n의 값을 바꾸고 list에 담는다</li>
<li>n이 1이 되면 반복문이 종료된다.</li>
</ol>
<h4 id="고민">고민</h4>
<p>for 문으로 n이 1씩 작아질때마다 카운트를 해야하나? 근데 그건 아닌 것 같아서
while 문으로 1보다 큰 동안 반복문을 돌리려고 했다.</p>
<pre><code>while(n &gt; 0) {
    list.add(n); // 왜 여기에서 담았지?ㅎㅎ
    if (n % 2 == 0) {
        n /= 2;
    } else {
        n = 3 * n + 1;
    }        
}</code></pre><p>이렇게 하니까 자꾸 메모리 한도 초과가 생겼다.😨
알고보니 n이 1보다 더 작아지지 않아서 무한루프가 발생한다.
그래서 n != 1 때로 하고, 초기값도 담고, 마지막에 1이 됐을때도 담아야하니
list에 추가하는 부분을 반복문 시작전, 조건문 끝에 뒀다.</p>
<h2 id="풀이">풀이</h2>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public int[] solution(int n) {
       List&lt;Integer&gt; list = new ArrayList&lt;&gt;();

        // 초기값 담기
        list.add(n);
        while(n != 1 ) {

            // n의 짝수, 홀수 구분
            if (n % 2 == 0) {
                // n이 짝수일때 2로 나눔
                n /= 2;
            } else {
                // n이 홀수일 때 3 *  n + 1 로 바꾸기
                n = 3 * n + 1;
            }
            list.add(n);
        }


        int[] answer = new int[list.size()];
        for (int i = 0; i &lt; list.size(); i++ ){
            answer[i] = list.get(i);
        }

        return answer;
    }
}</code></pre><p>이렇게 하니 잘 된다!
당연한거지만 필요한 값을 어디서 저장할지도 참 중요하다 😇 열공하자</p>
]]></description>
        </item>
    </channel>
</rss>