push 전 commit을 수정하는 경우

1. 가장 최근의 commit을 수정하는 경우

git commit --amend

위 명령어를 입력하면 다음과 같이 뜬다

"commit한 메시지"

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Mon Sep 4 15:33:01 2023 +0900
#
# On branch main
# Your branch is up to date with 'origin/main'.
#
# Changes to be committed:
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       modified:   ~
#       new file:   ~
#

메시지 수정 후 esc, :wq를 순서대로 입력해서 수정하는 창을 닫으면 된다.

 

2. 오래된 commit을 수정하는 경우

command line에 git log를 입력하면 로그를 볼 수 있다.

commit ~ (HEAD -> main)
Author: ~
Date:   Mon Sep 4 15:33:01 2023 +0900

    About 디자인 변경

commit ~
Author: ~
Date:   Sun Sep 3 19:49:19 2023 +0900

    디자인 수정

commit ~
Author: ~
Date:   Sat Sep 2 00:17:20 2023 +0900

    반응형 수정

commit ~
Author: ~
Date:   Fri Sep 1 23:31:20 2023 +0900

    About 파트 디자인 변경
:

위에서 두 번째 commit을 수정해야 한다면 다음과 같이 입력하면 가장 최근의 commit 2개를 보여준다.

git rebase -i HEAD~2

# HEAD~n -> head에서 n번째 메시지 수정
pick e05b90d 디자인 수정
pick 5808bb7 About 디자인 변경

# Rebase 418234b..5808bb7 onto 418234b (2 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but
#                    opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
#         create a merge commit using the original merge commit's
#         message (or the oneline, if no original merge commit was
.git/rebase-merge/git-rebase-todo [unix] (15:59 04/09/2023)              1,1 Top
<eact/portfolio/.git/rebase-merge/git-rebase-todo" [unix] 33L, 1547B

수정하고 싶은 commit 옆의 pick을 reword로 바꾼 후, esc, :wq를 순서대로 입력하면, commit을 수정할 수 있는 창이 뜬다.

메시지를 수정한 후, 똑같이 esc, :wq를 입력하여 저장해주면 된다.

 

이미 push가 끝난 commit을 수정하는 경우

위에서 commit 메시지 수정이 끝났다면, 다음과 같이 입력한다.

git push "리모트 이름" "브랜치" --force

수정한 메시지를 force를 통해 강제로 push하는 방법이다.

force는 최대한 사용하지 않는 게 좋으니 commit message는 꼭! 한번 더 확인한 후 push하자.

오류 내용

npm: 'npm' 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다

 

 

 

해결 방법

1. Node.js 설치 확인

설치되어 있지 않은 경우, 먼저, Node.js 홈페이지에 들어간다.

https://nodejs.org/ko

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

필요한 버전을 다운받는다.

환경변수의 path에 Node.js를 다운받은 경로를 추가한다!

보통 C:\Program Files\nodejs\ 이다.

Node.js 설치가 완료되었다면 cmd에서 node -v와 npm -v를 입력해 확인해보자

굿

 

 

+) 'npm'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다.

오류 내용

'npm'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다.

visual studio의 터미널이 power shell로 되어있을 때, 발생하는 에러이다.

 

해결 방법

1. Ctrl + Shift + P

2. Terminal: Select Default Profile 클릭

Command Prompt를 클릭 후, 터미널을 다시 열어준다.

문제 설명

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.

1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.

2에서 나온 배열의 3번째 숫자는 5입니다.

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

 

제한사항

array의 길이는 1 이상 100 이하입니다.

array의 각 원소는 1 이상 100 이하입니다.

commands의 길이는 1 이상 50 이하입니다.

commands의 각 원소는 길이가 3입니다.

 

ex)

array: [1, 5, 2, 6, 3, 7, 4]

commands: [[2, 5, 3], [4, 4, 1], [1, 7, 3]]

return: [5, 6, 3]

 

나의 풀이

function solution(array, commands) {
	// return할 array answer 배열을 생성한다
    var answer = []
    for(let i=0; i<commands.length; i++) {
    	// array를 commands[i][0]-1번째부터 commands[i][1]까지 slice 후, 오름차순 정렬 후 arr에 할당
        var arr = array.slice(commands[i][0]-1, commands[i][1]).sort((a,b)=>{return a-b})
        // arr의 commands[i][2]-1번째 원소를 answer 배열에 push
        answer.push(arr[commands[i][2]-1])
    }
    // answer을 리턴
    return answer
}

slice와 sort를 이용하여 해결했다.

처음에는 array.slice(...).sort()만 사용했다가 error가 발생했다.

sort()는 파라미터를 생략하면 문자열의 유니코드 포인트 순서를 따라서 정렬하기 때문에 숫자를 정렬할 경우, 문자열을 반환하기 때문에 조건을 따로 주는 것이 좋다.

 

원래 코드

...
var arr = array.slice(commands[i][0]-1, commands[i][1]).sort()
...

 

변경 후 코드

...
var arr = array.slice(commands[i][0]-1, commands[i][1]).sort((a,b)=>{return a-b})
...

👍

문제 설명

숫자로 이루어진 문자열 t와 p가 주어질 때, t에서 p와 길이가 같은 부분문자열 중에서, 이 부분문자열이 나타내는 수가 p가 나타내는 수보다 작거나 같은 것이 나오는 횟수를 return하는 함수 solution을 완성하세요.

예를 들어, t="3141592"이고 p="271" 인 경우, t의 길이가 3인 부분 문자열은 314, 141, 415, 159, 592입니다. 이 문자열이 나타내는 수 중 271보다 작거나 같은 수는 141, 159 2개 입니다.

 

제한 사항

  • 1 ≤ p의 길이 ≤ 18
  • p의 길이 ≤ t의 길이 ≤ 10,000
  • t와 p는 숫자로만 이루어진 문자열이며, 0으로 시작하지 않습니다.

 

ex)

t: "3141592"

p: "271"

result: 2

 

나의 solution

function solution(t, p) {
	// answer 배열 생성
    var answer = [];
    for(let i=0; i<t.length; i++) {
        var ele = t.slice(i, i+p.length)
        // 배열에 들어갈 ele의 길이는 p의 길이와 같고 ele의 값은 p보다 작거나 같아야 한다
        if(ele.length===p.length && ele<=p) answer.push(ele)
    }
    // 배열의 길이를 리턴
    return answer.length
}

 

Description

1. slice 메소드를 사용하면 간단하게 해결할 수 있다.

// slice 메소드는 배열의 begin index부터 end index까지(end index는 포함x)에 대한 복사본을 새로운 배열로 반환한다.

array = ['world','earth','sun','moon','mars']

console.log(array.slice(2));
// ['sun','moon','mars']

console.log(array.slice(2, 4));
// Expected output: Array ['sun','moon']

console.log(array.slice(-2));
// Expected output: Array ['moon','mars']

console.log(array.slice(2, -1));
// Expected output: Array ['sun','moon']

헷갈릴 수도 있는 splice 메소드는 아래와 같다.

// splice 메소드는 원본 배열에서 새로운 요소를 추가, 삭제, 교체하여 새로운 배열을 리턴한다.

array = ['world','earth','sun','moon','mars']

// 삭제(시작 index가 음수일 경우 뒤에서부터 요소를 센다)
array.splice(2, 1) // index 2부터 1개의 요소 제거
console.log(array) // ['world','earth','moon','mars']

// 추가
array.splice(2,0,'venus')
console.log(array) // ['world','earth','venus','sun','moon','mars']

2. 문자열 t를 i 인덱스부터 i+p.length 인덱스까지 잘라 변수 ele에 할당한다.

3. ele의 길이가 p의 길이와 같고 ele의 값이 p보다 작거나 같으면 answer 배열에 추가한다.

4. 마지막으로, answer 배열의 길이를 리턴한다.

기술 스택: React.js

배포 링크: https://kosy0907.github.io/EV-map/

소스코드 링크: https://github.com/kosy0907/EV-map (Private)

 

소개

서울시 내 지하철역 근처의 교통약자용 엘리베이터 위치를 지도에 표시해주는 웹 사이트이다.

이 프로젝트는 2021년, 내가 다리를 다쳤을 때 지하철 이용에 불편을 느낀 경험을 살려 진행했다.

 

기능

- 지하철역 근처의 교통약자용 엘리베이터 위치 표시

- 역 이름 검색

 

개발기간

2022.01.21 ~ 2022.01.30

 

사용 API

Geolocation API

 

디자인 -> 구현 순서로 진행

figma

지도로 화면을 채우고 search form을 넣으면 디자인은 끝이다.

  • Map Component
    • Search Component: 검색창
    • KaKaoMapScript Component: API와 지도

 

1. 데이터 가져오기

공공데이터포털의 서울특별시 지하철역 엘리베이터 위치정보 파일을 사용했다.

해당 데이터는 서울시 내 지하철역 주변의 교통약자용 엘리베이터 정보를 제공한다.

https://www.data.go.kr/tcs/dss/selectFileDataDetailView.do?publicDataPk=15098148 

 

서울특별시_지하철역 엘리베이터 위치정보_20220111

서울시 내 지하철역 주변의 교통약자용 엘리베이터 위치를 제공합니다. 좌표계는 WGS84을 사용합니다.<br/>노드링크 유형, 노드 WKT, 노드 ID, 노드 유형 코드, 시군구코드, 시군구명, 읍면동코드, 읍

www.data.go.kr

가져온 데이터는 src/data/elevatorLocation.js에 JSON 객체 형태로 저장한다.

// elevatorLocation.js
export const elevatorLocation =
{
  "DESCRIPTION": { "NODE_WKT": "노드 WKT", "SW_NM": "지하철역명", "SW_CD": "지하철역코드", "SGG_NM": "시군구명", "SGG_CD": "시군구코드", "NODE_ID": "노드 ID", "NODE_CODE": "노드 유형 코드", "EMD_NM": "읍면동명", "TYPE": "노드링크 유형", "EMD_CD": "읍면동코드" },
  "DATA": [
          { "sgg_cd": "1111000000", "emd_nm": "종로2가", "node_code": "0", "emd_cd": "1111013800", "node_wkt": "POINT(126.98397877663305 37.57010684982412)", "sgg_nm": "종로구", "type": "NODE", "sw_nm": null, "sw_cd": null, "node_id": 86879 },
          { "sgg_cd": "1111000000", "emd_nm": "숭인동", "node_code": "0", "emd_cd": "1111017500", "node_wkt": "POINT(127.01744971746365 37.57329704981851)", "sgg_nm": "종로구", "type": "NODE", "sw_nm": "동묘앞", "sw_cd": "268", "node_id": 212659 }
}

 

2. 틀 제작

2-1. 프로젝트 생성

create react-app ev-map

2-2. 지도를 표시할 Map Component 작성

// Map.js

import React from 'react';

const Map = () => {
    return (
        <div>
            <Search/> // 검색창
            <KakaoMapScript/> // api & 지도
        </div>
    );
};

export default Map;

 

3. api 가져오기

KaKao Map api를 이용할 것이므로 KaKao Developers에 로그인 후, 애플리케이션을 추가한다.

https://developers.kakao.com/

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

애플리케이션을 등록하면 api key를 발급받을 수 있다.

보안을 위해 .env 파일을 생성한 후, api key를 넣자.

// .env
REACT_APP_KAKAO_KEY = <api key>

index.html에 script 추가도 잊지 말자.

<!DOCTYPE html>
...
    <script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=%REACT_APP_KAKAO_KEY%"></script>
...
</html>

kaKaoScript.js 파일을 생성하고 api를 가져온다.

// kaKaoScript.js
import react from "react";
import styled from "styled-components";
const { kakao } = window;

const MapDiv = styled.div`
    width: '100%',
    height: '100vh'
`

export default function KakaoMapScript({ searchText }) {

    useEffect(() => {
        // kakao map
        const container = document.getElementById('kakao-map');
        const options = {
            center: new kakao.maps.LatLng(37.566826, 126.9786567),
            level: 3
        };
        const map = new kakao.maps.Map(container, options);

    return (
        <MapDiv id="kakao-map" style={{ width: "100%", height: "100vh" }} />
    )
}

 

 

4. 지도에 marker 추가

4-1. 현재 내 위치 표시

geolocation api를 사용하여 현재 내 위치를 지도에 표시할 수 있다.

PC 환경에서는 내 위치를 제대로 잡지 못하지만, 모바일 환경에서는 정확하게 잡는 편이다.

// kakaoScript.js
	...
    	const getCurrentPos = () => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function (position) {
                        var lat = position.coords.latitude;
                        var lon = position.coords.longitude;
                        // 내 현재 위치를 kakao map에 표시한다.
                        var currentPos = new kakao.maps.LatLng(lat, lon);
                        var marker = new kakao.maps.Marker({
                            map: map,
                            position: currentPos,
                            image: new kakao.maps.MarkerImage(
                                "https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png",
                                new kakao.maps.Size(24, 35),
                                { offset: new kakao.maps.Point(13, 35) }
                            )
                        });
                        map.setCenter(currentPos);
                    },
                    // 위치를 가져올 수 없는 경우, 카카오 본사로 위치를 잡는다.
                    function (err) {
                        options.center = new kakao.maps.LatLng(37.566826, 126.9786567);
                        const map = new kakao.maps.Map(container, options);
                    })
            }
        }
        getCurrentPos();
        ...

4-2. 엘리베이터 위치 표시

markers 리스트를 생성하고 elevatorLocation.js의 데이터를 전처리해서 위도(lat), 경도(lng)를 뽑아내서 kaka.maps.Marker의 position에 넣는다.

useEffect(()=>{
...
       const markers = [];
        for (var i = 0; i < elevatorLocation.DATA.length; i++) {
            var point = elevatorLocation.DATA[i].node_wkt
                .split("(")[1]
                .split(")")[0]
                .split(" ");

            var latlng = new kakao.maps.LatLng(
                parseFloat(point[1]),
                parseFloat(point[0])
            );

            var marker = new kakao.maps.Marker({
                position: latlng,
                clickable: false,
            });
            markers.push(marker);
        }
        return markers;
    }, []);
...
})

 

5. 검색 기능 추가

5-1. Map.js 수정

Search.js에서 searchText state를 업데이트 할 수 있도록 setSearchText를 props로 전달한다.

KaKaoMapScript Componenent에는 searchText를 props로 전달한다.

// Map.js

import React, { useEffect, useState } from 'react';
import KakaoMapScript from './kakaoScript';
import Search from './Search';
const { kakao } = window;

const Map = () => {
    const [searchText, setSearchText] = useState('');

    return (
        <div>
            <Search setSearchText={setSearchText} searchText={searchText} />
            <KakaoMapScript searchText={searchText} />
        </div>
    );
};

export default Map;

5-2. Search Component 작성

import React, { useState } from 'react';
import styled from 'styled-components';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSearch } from '@fortawesome/free-solid-svg-icons';

const SearchContainer = styled.div`
    ...
`

const Form = styled.form`
    ...
`

const Input = styled.input`
    ...
`

const SearchBtn = styled.button`
    ...
`

const Search = (props) => {
    const [inputText, setInputText] = useState('');
	// InputText를 입력한 value로 설정
    const handleInputChange = (e) => {
        e.preventDefault();
        setInputText(e.target.value);
    }
	// SearchText를 inputText로 설정
    const handleSubmit = (e) => {
        e.preventDefault();
        props.setSearchText(inputText);
    }
	// input 창이 비어있는 경우
    const textChecker = (e) => {
        if (inputText === '') {
            alert('검색어를 입력해주세요!');
        }
    }

    return (
        <SearchContainer>
            <Form onSubmit={handleSubmit}>
                <Input type='text' value={inputText} onChange={handleInputChange} placeholder='역명을 입력하세요! ex) 혜화' />
                <SearchBtn type='submit' onClick={textChecker}><FontAwesomeIcon icon={faSearch} /></SearchBtn>
            </Form>
        </SearchContainer>
    );
}

export default Search;

여기서 검색창에 텍스트를 입력할 때마다 속도가 느려지는 문제가 발생했다.

텍스트를 입력할 때마다 위치를 나타내는 marker가 제렌더링 되는 것이 원인이었다.

useEffect 안에 넣지 말고 useMemo를 사용하여 해결한다.

// kakaoScript.js
...
const markers = useMemo(() => {
        const markers = [];
        for (var i = 0; i < elevatorLocation.DATA.length; i++) {
            var point = elevatorLocation.DATA[i].node_wkt
                .split("(")[1]
                .split(")")[0]
                .split(" ");

            var latlng = new kakao.maps.LatLng(
                parseFloat(point[1]),
                parseFloat(point[0])
            );

            var marker = new kakao.maps.Marker({
                position: latlng,
                clickable: false,
            });
            markers.push(marker);
        }
        return markers;
    }, []);
...
useEffect(() => {
            // kakao map
            const container = document.getElementById('kakao-map');
            const options = {
                center: new kakao.maps.LatLng(37.566826, 126.9786567),
                level: 3
            };
            const newMap = new kakao.maps.Map(container, options);
            setMap(newMap);

            for (var j = 0; j < markers.length; j++) {
                markers[j].setMap(newMap);
            }
          )
...

여기서 문제가 하나 더 생긴다.

Cannot read property 'map' of undefined

map이 완전히 로드되지 않은 상태일 때, 함수에서 map을 호출하기 때문에 발생하는 error이다.

마커를 설정하는 코드를 별도의 useMemo 후크로 이동하여 구성 요소를 마운트할 때 한 번만 호출하도록 수정한다.

또한, map이 로드되면 함수를 호출하도록 kakao.maps.load() 안에 api를 호출 함수를 넣는다.

    ...
    const markers = useMemo(() => {
        const markers = [];
        for (var i = 0; i < elevatorLocation.DATA.length; i++) {
            var point = elevatorLocation.DATA[i].node_wkt
                .split("(")[1]
                .split(")")[0]
                .split(" ");

            var latlng = new kakao.maps.LatLng(
                parseFloat(point[1]),
                parseFloat(point[0])
            );

            var marker = new kakao.maps.Marker({
                position: latlng,
                clickable: false,
            });
            markers.push(marker);
        }
        return markers;
    }, []);
    ...
useEffect(() => {
        kakao.maps.load(() => {
            ...
	// searchText가 있을 때, elevatorLocation DATA의 sw_nm과 searchText가 같으면 해당하는 위도, 경도를 찾아 지도 이동
         	if (searchText) {
                const filteredLocations = elevatorLocation.DATA.filter(location => {
                    const regex = new RegExp(searchText.replace('역', '') + '역?');
                    if (location.sw_nm === null) {
                        return regex.test(location.emd_nm);
                    } else {
                        return regex.test(location.sw_nm);
                    }
                });

                if (filteredLocations.length > 0) {
                    const regex = /\d+\.\d+/g;
                    const filteredPoint = filteredLocations[0].node_wkt.match(regex);
                    console.log(filteredPoint);
                    const moveLotation = new kakao.maps.LatLng(parseFloat(filteredPoint[1]), parseFloat(filteredPoint[0]));
                    console.log(moveLotation);
                    kakao.maps.event.addListener(newMap, 'tilesloaded', function () {
                        newMap.panTo(moveLotation);
                    }
                    )
                } else {
                    alert('결과를 찾을 수 없습니다!')
                }
        })
    }, [searchText, markers]);

 

6. 배포

배포는 GitHub Pages를 이용했다.

GitHub Pages - GitHub Repository의 프로젝트를 호스팅해주는 기능

배포 방법은 다음과 같다.

1. 레포지토리(public)를 생성하고 프로젝트를 commit, push

2. 배포하고 싶은 프로젝트에 gh-pages를 설치한다.

npm install gh-pages --save-dev
or
yarn add gh-pages --save-dev

3. package.json 수정

  • "homepage": "https://<git ID>.github.io/<project name>"
  • "predeploy": "npm run build"m
  • "deploy": "gh-pages -d build"
{
  "homepage": "https://kosy0907.github.io/EV-map",
  "name": "ev-map",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    ...
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  ...
npm run deploy

배포가 완료되면, Environment가 active 상태로 설정된다.

Environments를 클릭하면 배포 히스토리를 확인할 수 있다.

View deployment를 클릭해보자.

 

'React.js > Project' 카테고리의 다른 글

포트폴리오 웹사이트 제작기  (0) 2023.04.08

문제 설명

두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. 예를 들어 두 수 3, 12의 최대공약수는 3, 최소공배수는 12이므로 solution(3, 12)는 [3, 12]를 반환해야 합니다.

 

제한 사항

두 수는 1이상 1000000이하의 자연수입니다.

 

ex)

n: 3, m: 12, return [3, 12]

 

 

최대 공약수: 두 수 n, m의 공통된 약수 중에서 가장 큰 수

최소 공배수: 두 수 n, m의 공통된 배수 중에서 가장 작은 수

 

이 문제를 풀기 위해서는 다음과 같은 원리를 이용할 수 있다.

- 유클리드 호제법

- num1 * num2 = gcd * lcm

 

유클리드 호제법

1. n>m일 때, 큰 수(n)를 작은 수(m)로 나눈다. (n % m = R1)

2. 나누는 수 m을 나눈 나머지 R1로 나눈다. (m % R1 = R2)

3. R1을 R2로 나눈다. (R1 % R2 = R3)

이 과정을 반복해서 Rn이 0이 된다면 나누는 수(Rn-1)가 최대공약수이다.

 

Answer

function solution(n, m) {
    const gcd = (a, b) => a%b === 0 ? b : gcd(b, a%b);
    const lcm = (a, b) => (a*b) / gcd(a,b);
    
    return [gcd(n,m), lcm(n,m)]
}

문제설명

행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요.

 

제한 조건

행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다.

 

ex)

arr1: [[1,3], [2,4]]

arr2: [[3,5], [7,8]]

return: [[4,8], [9,12]]

 

function solution(arr1, arr2) {
    var answer = [];
    for(let i = 0; i<arr1.length; i++) {
        var sum = [];
        for(let j = 0; j<arr1[i].length; j++) {
            console.log(arr1[i][j]+arr2[i][j]);
            sum.push(arr1[i][j]+arr2[i][j])
        }
        answer.push(sum);
    } return answer;
}

빈 배열 answer을 생성하고 for문을 통해 두 개의 배열을 같은 인덱스끼리 더해준다.

문제설명

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.

 

제한사항

s는 길이 1 이상, 길이 8 이하인 문자열입니다.

s는 영문 알파벳 대소문자 또는 0부터 9까지 숫자로 이루어져 있습니다.

 

function solution(s) {
	// s의 length가 4 또는 6
    if (s.length == 4 || s.length == 6) {
    	// 문자열 분해 후, isNaN으로 검사
        return s.split('').every(c => !isNaN(c))
    } else {
        return false;
    }
}

 

isNaN()

타입이 숫자인지 아닌지 판별하는 함수로 많이 쓰인다.

 

every()

모든 원소가 주어진 조건에 맞는지 확인하는 함수

isNaN만 사용하게 되면 E가 붙은 지수도 숫자로 인식할 수 있기 때문에 every를 사용하여 하나하나 검사한 후, return한다.

+ Recent posts