Charlloss Dev

Charlloss'Dev Technology & TIL(Today I Learn) Blog

All posts in one long list


Count Valleys

Count Valleys

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'countingValleys' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER steps
     *  2. STRING path
     */

    public static int countingValleys(int steps, String path) {
    // Write your code here

        int v = 0;     // # of valleys
        int lvl = 0;   // current level

        int num = 1;

        for (char c : path.toCharArray()) {
            if (c == 'U') ++lvl;
            if (c == 'D') --lvl;

            if (lvl == 0 && c == 'U') ++v; // up check
        }

        return v;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int steps = Integer.parseInt(bufferedReader.readLine().trim());

        String path = bufferedReader.readLine();

        int result = Result.countingValleys(steps, path);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Pc X-Y Coordinates

Pc X-Y Coordinates

$활성 창$ 개념은 사용중인 컴퓨터와 사용자 간의 상화작용할 수 있는 상태를 나타내며, 작업표시줄 아이콘으 ㅣ배경색으로 알 수 있다.

3가지 좌표 기준

PC에서는 특정 위치를 표현하기 위해 2차원 좌표를 사용한다. 2차원 좌표를 표현하는 체계가 총 3가지가 존재하며, 이 3가지 모두 어느 상황에서도 오른쪽 이동은 X방향으로 증가, 아래쪽 이동은 Y방향으로 증가 라는 조건을 가진다.

이 3가지 좌표 체계는 좌표의 원점(0, 0)을 기준을 어디로 설정하는지에 따라 다르게 사용한다.

  1. 스크린 좌표(절대 좌표): 모니터 좌측 상단이 원점(0, 0)
  2. 상대 좌표: 활성 창의 좌측 상단이 원점(0, 0)
  3. 클라이언트 좌표: 상대 좌표와 비슷하지만, 프로그램 창의 제목과 메뉴 바 부분을 제외한 원점

좌표 기준 설정

CoordMode, TargetType [,RelativeTo]

TargetType: 좌표 값 설정 매개변수

  • Pixel
  • Mouse

RelativeTo: 좌표 체계 타입 설정 매개변수

  • Screen
  • Relative
  • Client

Default 설정

  • CoordMode를 사용하지 않는다면, 기본 좌표 체계는 상대 좌표입니다.
  • RelativeTo 매개변수를 생략하고 TargetType 매개변수만 써준다면 스크린 좌표로 설정됩니다.

MouseMove

MouseMove, X, Y [, Speed, Relative]

X, Y: 이동하려는 X, Y 좌표 Speed: 마우스가 이동하는 속도로 0 ~ 100 까지 범위를 가진다. Relative: 매개변수값을 R을 입력하면, 지정한 좌표 체꼐를 무시하고 현재 마우스 위치 기준으로 이벤트 함수가 실행된다.

CoordMode, Mouse, Screen

F1::
MouseMove, 500, 500
Sleep, 500
MouseMove, 700, 500
Sleep, 500
MouseMove, 700, 700
Sleep, 500
MouseMove, 500, 700
Sleep, 500
MouseMove, 500, 500
return

F2::
ExitApp

MouseClick

MouseClick [, WhichButton, X, Y, ClickCount, Speed, DownOrUp, Relative]

MouseClick [, WhichButton, X, Y, ClickCount]

WhichButton: Left, Middle, Right 매개변수로 마우스 클릭 대상(우클릭, 좌클링, 휠클릭) X, Y: X, Y 좌표 ClickCount: 클릭 횟수

Default Setting

  • MouseMove와 MouseClick의 Speed 매개변수는 2가 기본 속도이며, 0이 즉시 이동입니다.
  • MouseClick의 WhichButtons 매개변수에는 Left Middle Right를 줄여서 L M R로 쓸 수 있습니다.
  • MouseClick의 WhichButtons 매개변수에 마우스의 편의 키를 지정하고 싶다면 X1, X2…로 써주시면 됩니다.
  • MouseClick의 모든 파라미터를 생략하면 Send, {LButton}과 동일합니다.

MouseGetPos

현재 마우스의 좌표를 가져오는 이벤트함수

MouseGetPos [, OutputVarX, OutputVarY]

OutputVarX: 현재 마우스 X좌표 OutputVarY: 현재 마우스 Y좌표

CoordMode, Mouse, Screen
MouseGetPos, screenX, screenY
CoordMode, Mouse, Relative
MouseGetPos, relativeX, relativeY
CoordMode, Mouse, Client
MouseGetPos, clientX, clientY
MsgBox, 현재 마우스 좌표`n`n절대 좌표: %screenX%`, %screenY%`n상대 좌표: %relativeX%`, %relativeY%`n클라이언트 좌표: %clientX%`, %clientY%

MsgBox, % "현재 마우스 좌표`n`n절대 좌표: " screenX ", " screenY "`n상대 좌표: " relativeX ", " relativeY "`n클라이언트 좌표: " clientX ", " clientY

Exitapp

ExitApp & Return

ExitApp & Return

ExitApp

핫키와 핫스트링을 사용했을 때, 사용을 중지하려면, 오토핫키를 강제로 중지해야 했다.

그 과정을 자동으로 해주는 명령어가 ExitApp로 매개변수는 없이 단일 명령어로 사용한다.

$e.i):$

MsgBox, 여기는 실행되고요
ExitApp
MsgBox, 여기는 실행 안됩니다.

아래쪽 MsgBox가 실행되기 전에 오토핫키 스크립트가 종료된다.

ESC::
MsgBox, ESC 핫키를 눌렀습니다.
ExitApp

위와 같이 응용하여 사용한다.

Return

반면 return은, 스크립트가 정지되긴 하지만 종료되지 않는 구문으로, 기존에 ExitApp을 쓰지 않고 핫키를 사용했을 때와 동일한 효과를 준다.

F1::
MsgBox, F1을 눌렀습니다

F2::
MsgBox, F2를 눌렀습니다

F3::
Exitapp
  • F1을 누르면 대화 상자가 두번 나오고 오토핫키 스크립트가 종료되는 것을 볼 수 있다.
  • 위 구문에서 원하는 것은 F1을 누르면 F1 대화상자만, F2를 누르면 F2 대화상자만 출력하고, F3을 눌렀을 때 종료하고 싶다.
  • 이러한 사항일 경우에 Return을 사용하여 처리할 수 있다.
F1::
MsgBox, F1을 눌렀습니다
return

F2::
MsgBox, F2를 눌렀습니다
return

F3::
Exitapp
  • F1을 누르면 F1 대화상자만 출력
  • F2를 누르면 F2 대화상자만 출력
  • F3를 누르면 오토핫키 스크립트 종료

이러한 방법으로 사용하는 기능이다.

Escape Sequence

Escape Sequence

오토핫키에서는 매개변수의 구분을 ,, 변수의 사용은 %를 사용한다. 그렇다면 아래와 같이 해당 기호를 출력하려면 어떻게 해야 할까?

MsgBox, ,% ;이렇게 코딩하면 에러가 날것이다.

이럴 때 필요한 것이 $이스케이프$ $문자$이다.

이스케이프 문자

  1. 이스케이프 문자는 뒤에 오는 문자가 특수한 기능을 하는 문자일 경우, 해당 특수한 기능을 없애버리는 효과를 준다.
  2. 오토핫키에서 이스케이프 문자는 $`$이다.

즉 특수한 기능을 했던 콤마($,$)와 퍼센트(%)앞에 $`$를 붙여준다면 해당 콤마와 퍼센트는 특수한 기능을 하는 문자가 아닌, 글자(문자) 로서 작동하게 됩니다.

MsgBox, `,%` ;특수 기능을 하는 예약어가 아닌, 문자로 취급되어 위와 같이 출력이 된다.

이스케이프 시퀀스

반대로, 특수한 기능을 하지 않는 문자가 이스케이프 문자 뒤에 온다면, $특수한 기능을 하는 문자$로 변하게 된다.

MsgBox, 안녕하세요 'n 저는 안종웅입니다.

이렇듯 `n은 개행을 의미한다.

  • 여기서 중요한 점은 이스케이프 스퀀스는 문자열 취급이기 때문에 사용할 때 주의해야한다.
var := 5
MsgBox, % "책상 위에 사과가" `n var "개 있습니다."
→ 오류

var := 5
MsgBox, % "책상 위에 사과가`n" var "개 있습니다."
→ 정상 작동!

Sleep & Send

Sleep & Send

Send

키보드에 있는 키를 입력해주는 명령어로, 직접 키를 누르지 않아도 키를 누른 효과를 볼 수 있다.

Send, 'Keys'

Keys: 입력을 하려는 키 정보를 가진 매개변수 누를 키는 기본적으로 중괄호를 감싼 포맷으로 사용해야 한다.

$e.i):$

Send, {A}
Send, {Enter}
Send, {Tab}
Send, {Ctrl}

매개변수 키를 입력할 때, 핫키와 핫스트링 조합키도 역시 사용가능하다. 이때 주의할 점은 조합키는 항상 소문자를 사용해야 한다.

Send, ^{a}
return

^A::
MsgBox, Ctrl + A를 눌렀습니다.
ExitApp

Send Detail

Send 이벤트 함수에 대해서 특이사항

  • 조합키를 입력하지 않고, ! + ^ #을 그대로 출력하고 싶은 경우 Send를 SendRaw를 사용
  • 키를 누르는 동작과, 떼는 동작을 따로 구분할 수 있다. 누르는 것은 {‘Keys’ Down}, 떼는 건 {‘Keys’ Up} 이다.(중간에 띄어쓰기는 필수이다.)
  • 한영키는 {VK15}이다.
  • 조합키는 !a나, !{a}의 꼴을 모두 허용한다. 그러나 조합키에서 대문자 사용은 불가능 하다.
  • 키 이름 뒤에 숫자를 적어서 중복 입력을 허용 가능하다.
    Send, {A 5}
    
    • A키 5번 입력

Sleep

Sleep은 스크립트에 지연 시간($딜레이$)을 제공하는 명령어이다.

Sleep, DelayInMilliseconds

DelayInMilliseconds: 딜레이 시간을 입력하는 매개변수로, 시간 단위는 밀리초 이다. 1초 = 1000 밀리초 이다.

Send, {A}
Sleep, 1000
Send, {AA}
Sleep, 1000
ExitApp

;문제1.
; ㄱ. 조합키는 항상 소문자이어야 한다.

;문제2.
;ㄱ: 따옴표로 감싸지 않아도 문자열 표현이 가능하다
;ㄹ: 밀리초 단위이다.

;문제3.
F1::
Sleep 1000
SendRaw, 3 + 2 = 5이고
Sleep 1000
Send, {Enter}3 * 2 = 6이다.

ExipApp

Hotkey & HotString

Hotkey & HotString

핫키와 핫스트링은 사용 시 스크립트가 끝나도 자동으로 종료되지 않는다. 사용 후 종료하려면 작업 표시줄 트레이 아이콘을 우클릭하셔서 Exit 종료를 실행해주어야 한다.

HotKey

핫키는 단축키 등록으로, 어떤 키를 눌럿을 때, 동작이 실행되도록 하는 이벤트 등록 이다.

사용 문법은 아래와 같다.

  • $Key::$

즉 A키를 눌렀을때, 대화 상자를 출력한다면,

A::
MsgBox, A Key Click

HotString

핫스트링은 특정 문자를 입력했을 때, 동작이 실행되도록 한다. 중요한 점은 영어만 인식한다.

사용 문법은 아래오 같다.

  • $::String::$

즉 apple을 썻을 때 대화상자를 출력한다면,

::apple::
MsgBox, 사과입력!

입력할 수 있는 창 뿐만 아니라, 바탕화면에서 입력하여도 실행된다.

HotKey + HotString

$Ctrl$ + $C$ $or$ $Shift$ + $F5$ 같이 단축키 조합도 사용이 가능하다. 아래 표와 같이 사용을 할 수 있다.

^A::
→ Ctrl + A를 눌렀을 때

+!Z::
→ Shift + Alt + Z를 눌렀을 때

Variable & Operator

Variable & Operator

Variable

변수는 사전적 의미로는 바뀔 수 있는 수입니다. 오토핫키 및 다른 프로그래밍 언어에서도 마찬가지입니다. 변수 안의 수는 언제든지 바뀔 수 있습니다.

저는 조금 다르게 설명해보겠습니다. 변수는 수나 문자에 이름을 붙이는 것입니다. 아래와 같이 말입니다.

숫자 “36000”에 “가격”이라는 이름을 붙일 수 있습니다. 여기서 “가격”은 변수, “36000”은 값이라고 할 수 있습니다.

문장 “동해물과 백두산이 마르고 닳도록”에 “애국가”라는 이름을 붙일 수 있습니다. “애국가”는 변수, “동해물과 백두산이 마르고 닳도록”은 값이 됩니다.

Why Uss Variable

사실 굳이 써야할 이유를 못 느끼시는 분들이 많으실겁니다. 그렇지만 아래 글을 MsgBox로 출력하는 경우를 상상해봅시다.

그러던 어느날 김대감의 독자인 김수한무 거북이와 두루미 삼천갑자 동방삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이가 우물에 빠지자 기겁한 하인이 김대감에게 “마님!! 글쎄 김수한무 거북이와 두루미 삼천갑자 동방삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이 도련님이 우물에 빠졌어요!” 라고 보고했고, 대감도 크게 놀라 “아니 우리 오대 독자 김수한무 거북이와 두루미 삼천갑자 동방삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이가 우물에 빠졌다고?

이는 다음과 같이 변수로 줄여서 써볼 수 있습니다. (김수한무 ~ 돌돌이를 name이라는 변수에 담았습니다.)

그러던 어느날 name가 우물에 빠지자 기겁한 하인이 김대감에게 “마님!! 글쎄 name 도련님이 우물에 빠졌어요!” 라고 보고했고, 대감도 크게 놀라 “아니 우리 오대 독자 name 가 우물에 빠졌다고?


훨씬 읽기 편해졌지요.

만약에 김수한무 ~ 돌돌이의 이름이 바뀌었다고 가정하면, 원래 글에서는 일일이 하나씩 문장을 다시 입력해주어야 했지만, 변수를 사용한 글에서는 name 변수의 값만 바꿔주면 세 군데 모두가 바뀐 효과를 낼 수 있습니다.

$e.i:$

name := "김수한무 거북이와 두루미 삼천갑자 동방삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이가"

MsgBox %name%

Operator

연산자는 이름에서 알 수 있듯이, 연산자는 “연산”을 하기 위해 사용되는 문자입니다. 연산이라고 해서 숫자 계산만 생각하시면 안되고, 여러가지 용도로 사용됩니다.

연산자는 이럴 때 씁니다.

  • 값을 변수에 대입할 때
  • 값끼리 더하거나, 빼거나, 곱하거나, 나눌 때
  • 값끼리 비교할 때
  • 기타 등등

연산자 종류

  • 대입 연산자: 변수의 값을 넣는 연산자(2가지 종류)
    • $:=$
      • 오른쪽에 있는 식을 왼쪽에 대입한다
      • var1 := 10
        
      • var2 := "신에게는 아직" var1 "척의 배가 남아있습니다"
        
    • $.=$
      • 뒤에 오는 값을 현재 가지고 있는 값에 ‘붙이는’ 역할
      • var3 := 1
        
      • var3 .= var1
        

        var4의 값은 3이 아닌, 초기값 10 + var1을 더한 13이다

  • 산술 연산자: 값을 계산해주는 산술 연산자
    • var := 2 + 3
      
    • 대입과 연산을 하나로 묶은 산술-대입 연산자
      • +=
      • -=
      • *=
      • /=
  • 비교 연산자
    • >
    • <
    • >=
    • <=
    • =
    • <> : 다르다
  • 논리 연산자
    • &&
    • ||
    • !
  • 증감 연산자
    • ++
    • --

변수 응용 사용


var := 100
MsgBox, %var% // 100 출력

;만약 변수가 많아 진다면?
MsgBox, %a% %b% %c% %d% %e% %f% %g% %h% %i% %j% ;스크립트가 너무 길어지고 관리가 어렵다

;그럴때를 위해 변수는 아래처럼 '%'를 한번만 쓸수 잇다.
MsgBox, % a b c d e f g h i j
;이 때, 변수와 변수 사이는 띄어쓰기로 구분해야하며,
;%와 첫 변수 사이도 무조건 띄워주어야 한다.

;에러1
MsgBox, % abcdefghij ;변수 abcdefghij를 출력한다.

;에러2
MsgBox, %a b c d e f g h i j ;오류로 인해 실행되지 않는다.(닫는 %가 없기 떄문에)

a := 1
b := 1
c := "귀요미"
MsgBox, % a " + " b " = " c
MsgBox, %a% + %b% = %c%
;위 2가지 방식을 혼용하면 에러

;에러3
MsgBox, %a% + %b% = % c "입니다." ;변수 %a% 방식과, % c 방식 혼용으로 에러

Programming

AutoHotKey MsgBox

MsgBox

원하는 메세지 알림창을 호출하는 기능

MsgBox라는 명령어에 우선 소개를 해드리겠습니다. MsgBox는 사용 방법이 두 가지인데요, 그중 쉬운 편인 첫 번째 방법을 먼저 소개해드리겠습니다.

  1. 설정한 메세지를 출력하는 MsgBox 문법
    MsgBox, Text
    
  2. 디테일한 설정이 가능한 MsgBox 문법
    MsgBox [, Options, Title, Text, Timeout]
    

위 문법에서 매개변수에 둘러싸여 있는 [대활호] 는 해당 매개변수를 생략해도 되는 부분이다.

MsgBox [, Options, Title, Text, Timeout]

  • Option 매개변수는 버튼 유형과 MsgBox의 특성을 설정한다. 또한 다른 유형의 옵션끼리는 옵션 고유 번호를 더하여 중복 옵션을 구현할 수 있다. $e.i:$ 예/아니오 버튼과, 금지 아이콘을 가진 대화 상자를 출력하고 싶으면, $4 + 16=20$을 적용하면 된다.
  • Title 매개변수의 속성은 대화 상자의 제목을 설정한다.
  • Text 매개변수의 속성은 대화 상자의 내용을 설정한다.
  • Timeout 매개변수의 속성은 대화 상자가 자동으로 닫히는 시간을 설정한다.
    • 시간단위는 $(초: Second)$.

IfMsgBox

MsbBox 버튼의 조건문으로, MsgBox의 버튼에 따라서 다른 행동을 하는 대화 상자 입니다.

IfMsgBox, ButtonName
  • 필수 파라메터 ButtonName을 설정해야하며, ButtonName은 MsgBox의 버튼으로, ButtonName은 아래 표와 같다.

  • IfMsgBox 문법

    MsgBox [, Option, Title, Text, Timeout]
    IfMsgBox, ButtonName
    {
      // Context
    }
    

    $e.i:$ 대화 상자 Option을 4로 설정하면, 예/ 아니오 2개의 선택지가 있는 대화 상자가 나올때

    MsgBox, 4, 제목, 내용
    IfMsgBox, Yes
    {
    MsgBox, 예를 선택하였습니다.
    }
    IfMsgBox, No
    {
    MsgBox, 아니오를 선택하였습니다.
    }
    

Programming

MsgBox, 한동안 달콤한 미소가 피어나는 때가 오면
MsgBox, 사랑은 나와 사랑에 빠지리

MsgBox, 4, 프로그래밍 문제(1), 강아지/선인장/사자/해바라기, 5
IfMsgBox, Yes
{
    MsgBox 강아지/사자
}
IfMsgBox, No
{
    MsgBox 선인장/해바라기
}

MsgBox, 52, 프로그래밍 문제(1), 강아지/선인장/사자/해바라기, 5
IfMsgBox, Yes
{
    MsgBox 강아지/사자
}
IfMsgBox, No
{
    MsgBox 선인장/해바라기
}

Binary Calculator

Binary Calculator

Task

Implement a simple calculator that performs the following operations on binary numbers: addition, subtraction, multiplication, and division. Note that division operation must be integer division only;

The calculator’s initial state must look like this:

  • Element IDs. Each element in the document must have an id, specified below:
  • Styling. The document’s elements must have the following styles:

  • body has a width of 33%.
  • res has a background-color of lightgray, a border that is solid, a height of 48px, and a font-size of 20px.
  • btn0 and btn1 have a background-color of lightgreen and a color of brown.
  • btnClr and btnEql have a background-color of darkgreen and a color of white.
  • btnSum, btnSub, btnMul, and btnDiv have a background-color of black, a color of red.
  • All the buttons in btns have a width of 25%, a height of 36px, a font-size of 18px, margin of 0px, and float value left.

Constraints

All expressions in the test dataset are entered in the form $Operater1 -> Operator -> Operator2$ , where $Operator1$ is the first binary number, $Operator2$ is the second binary number, and $Operator$ is in the set {+, -, *, /, =}. Both operands will always be positive integers when converted from base-$2$ to base-$10$. All expressions will be valid.

Dev

index.html

<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Binary Calculator</title>
        <link rel="stylesheet" href="css/binaryCalculator.css" type="text/css">
    </head>
    <body>
        <div id="container">
            <div id="res"></div>
            <div id="btns">
              <button id="btn0" class="numberic" onclick="clickNumber(0)">0</button>
              <button id="btn1" class="numberic" onclick="clickNumber(1)">1</button>
              <button id="btnClr" onclick="clickClear()">C</button>
              <button id="btnEql" onclick="clickResult()">=</button>
              <button id="btnSum" onclick="clickOperation('+')">+</button>
              <button id="btnSub" onclick="clickOperation('-')">-</button>
              <button id="btnMul" onclick="clickOperation('*')">*</button>
              <button id="btnDiv" onclick="clickOperation('/')">/</button>
            </div>        
          </div>
        <script src="js/binaryCalculator.js" type="text/javascript"></script>
    </body>
</html>

binaryCalculator.css

body {
  width: 33%;
}

#res {
  background-color: lightgray;
  border: solid;
  height: 48px;
  font-size: 20px;
}

#btns button {
  width: 25%;
  height: 36px;
  font-size: 18px;
  margin:0;
  float: left;
}

#btn0, #btn1 {
  background-color: lightgreen;
  color: brown;
}

#btnClr, #btnEql {
  background-color: darkgreen;
  color: white;
}

#btnSum, #btnSub, #btnMul, #btnDiv {
  background-color: black;
  color: red;
}

binaryCalculator.js


var operatorValue = '';

function calculator(firstNum, secondNum, operator) {

    var result = 0;

    switch(operator) {
        case '+':
            result = eval(firstNum + secondNum);
            break;
        case '-':
            result = eval(firstNum - secondNum);
            break;
        case '*':
            result = eval(firstNum * secondNum);
            break;
        default:
            result = eval(firstNum / secondNum);
            break;
    }

    return result;
}

function clickNumber(number) {
    document.getElementById('res').innerHTML += number;
}

function clickClear() {
    document.getElementById('res').innerHTML = "";
    operatorValue = '';
}

function clickOperation(operator) {

    if (operatorValue === '') {
        document.getElementById('res').innerHTML += operator;
        operatorState = operator;
    }
}

function clickResult() {
    if (operatorState !== '') {
        var numbers = document.getElementById('res').innerHTML.split(operatorState);

        document.getElementById('res').innerHTML = eval(parseInt(numbers[0], 2) + operatorState + parseInt(numbers[1], 2)).toString(2);

        operatorValue = '';
    }
}

Css Container

Css Container

Task

We want to create nine buttons enclosed in a div, laid out so they form a grid. Each button has a distinct label from to , and the labels on the outer buttons must rotate in the clockwise direction each time we click the middle button.

Complete the code in the editor so that it satisfies the following criteria:

  • Initial State. The initial layout looks like this:

  • Element IDs. Each element in the document must have an id, specified below:

    • The button container div’s id must be btns.
    • The initial innerHTML labels must have the following button ids:
    innerHTML id
    1 btn1
    2 btn2
    3 btn3
    4 btn4
    5 btn5
    6 btn6
    7 btn7
    8 btn8
    9 btn9
  • Styling. The document’s elements must have the following styles:
    • The width of btns is , relative to the document body’s width.
    • Each button (i.e., btn1 through btn9) satisfies the following:
      • The width is , relative to its container width.
      • The height is 48px.
      • The font-size is 24px.
  • Behavior. Each time btn5 is clicked, the innerHTML text on the grid’s outer buttons (i.e., bt1, btn2, btn3, btn4, btn6, btn7, btn8, btn9) must rotate in the clockwise direction. Do not update the button id’s.

Explanation

Initially, the buttons look like this:

After clicking btn5 time, they look like this:click1

After clicking btn5 more time (for a total of clicks), they look like this:click2

Dev

index.HTML

<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Buttons Grid</title>
        <link rel="stylesheet" href="css/buttonsGrid.css" type="text/css">
    </head>
    <body>
        <script src="js/buttonsGrid.js" type="text/javascript"> </script>
    </body>
</html>

buttonGrid.CSS

#btns {
    width: 75%;
}
.btn {
    width: 30%;
    height: 48px;
    font-size: 24px;
}

buttonGrid.js

var container = document.createElement('div');
container.className = 'buttonContainer';
container.id = 'btns';

var button = [9];

for (var i = 0; i < 9; i++) {
    button[i] = document.createElement('button');
    button[i].className = 'button';
    button[i].id = 'btn' + (i + 1);
    button[i].innerHTML = (i + 1);

    container.appendChild(button[i]);
}

document.body.appendChild(container);

function getNextLabel(value) {
    var labelData = [1, 4, 7, 8, 9, 6, 3, 2];

    return labelData[(labelData.indexOf(+(value)) + 1) % labelData.length];
}

function updateLabel() {

    for (var i = 0; i < 9; i++) {
        if (i != 4) {
            button[i].innerHTML = getNextLabel(button[i].innerHTML);
        }
    }
}

btn5.addEventListener('click', function() {

    updateLabel();
});

Create Css in Javascript

Create Css in Javascript

Task

Complete the code in the editor so that it creates a clickable button satisfying the following properties:

  • The button’s id is btn.
  • The button’s initial text label is . After each click, the button must increment by . Recall that the button’s text label is the JS object’s innerHTML property.
  • The button has the following style properties:
    • A width of 96px.
    • A height of 48px.
    • The font-size attribute is 24px.

Submissions

This is a new style of challenge involving Front-End rendering. It may take up to seconds to see the result of your code, so please be patient after clicking Submit. The Submissions page contains screenshots to help you gauge how well you did.

Dev

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Button</title>
        <style>
          #btn {
              width: 96px;
              height: 48px;
              font-size: 24px;
          }
        </style>
    </head>
    <body>
        <button id="btn">0</button>
        <script type="text/javascript">
        /* Create a button */
        var buttonCounter = document.getElementById('btn');

        /* What to do when the button is clicked */
        buttonCounter.addEventListener('click', function() {
            /* Increment number on button's label by 1 */
            buttonCounter.innerHTML = +(buttonCounter.innerHTML) + 1;
        });
        </script>
    </body>
</html>

Css Basics in Javascript

In this article, we discuss some basics of writing JS (JavaScript) and CSS code in an HTML file. Note that we assume a certain level of basic HTML knowledge.

Templates

Basic Format

We use the following template to write JavaScript and CSS code to an HTML file:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>

        <style>
            /* Write CSS styles here */
        </style>
    </head>
    <body>
        <script>
            /* Write JS code here */
        </script>
    </body>
</html>

We write our CSS style code between thetags, and our JS code between the tags.

Note: Any text between is considered to be an HTML comment. These comments won’t render on the webpage, but we can read them if we view the page’s source code. For content between tags that contain actual code (i.e., style and script), we enclose comments between /* and */

Working with Separate Documents

In an instance where all our code is located in separate files (i.e., we have a .html file with our HTML, a .css file with our CSS, and a .js file with our JS code), we use this template to tell our HTML file where to find the JS and CSS files:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>

        <!-- Link to the style sheet in the 'head' section -->
        <link rel="stylesheet" href="css-file-path" type="text/css">
    </head>

    <body>
        <!-- Link to the JS code in the 'body' section -->
        <script src="js-file-path" type="text/javascript">
        </script>
    </body>
</html>

Let’s look at what this code does:

  • By putting <link rel="stylesheet" href="css-file-path" type="text/css">, where css-file-path is the path of the .css file, in the head section (i.e., between the <head> and </head> tags), we’re telling the document to use the style sheet at the location referenced by the href attribute.
  • By putting <script src="js-file-path" type="text/javascript">, where js-file-path is the path of the .js file, in the body section (i.e., between the <body> and </body> tags), we’re saying that we want to run a script using the JS code at the location referenced by the src attribute.

Create css basic in Javascript with button tag

We use the <button> tag to create a clickable button that has the following optional attributes:

  • id: the button’s unique identifier within the page
  • class: the CSS class(es) used to style the button

The text enclosed between the button’s opening (<button>) and closing (</button>) tags is the label that displays on the button. We can also access this text using the innerHTML property of the JS button object (see the JavaScript section below). The basic syntax for an HTML button looks like this:

<button id="buttonIdentifier" class="buttonStyleClass">Click Me</button>

Consider the following code:

var clickMeButton = document.createElement('button');
clickMeButton.id = 'myButton';
clickMeButton.innerHTML = 'Click Me';
clickMeButton.style.background = '#4FFF8F';
document.body.appendChild(clickMeButton);

Now, let’s walk through what it does:

  1. document.createElement(‘Button’) creates a clickable button object (createElement(‘Button’)) referenced by the variable name .
  2. clickMeButton.id = ‘myButton’ sets the button’s id to be myButton.
  3. clickMeButton.innerHTML = ‘Click Me’ sets the button’s inner HTML (i.e., the label we normally see between the HTML button tags) to say “Click Me”.
  4. clickMeButton.style.background = ‘#4FFF8F’ sets the button’s background color to green. To style multiple attributes of our button using a style class, we would write clickMeButton.className = ‘myStyleClassName’ instead.
  5. document.body.appendChild(clickMeButton) appends to the body of the document as a child. Let’s say we want to modify the label on an HTML button element with the id myButton. We simply use the getElementById method and pass the desired element’s id as an argument:

Styling Buttons with Css

First, we want to define the style constraints for our button. We can do this in either of the two ways below.

  1. Using an ID Selector For instances where we want to apply a style to a single element within an HTML page, we use a CSS id selector using the syntax #identifier (where is the id of the element to style within the page). We then follow it with a pair of curly braces that contain the desired style constraints for all elements within the container that has that identifier. For example:
    #myButtonId {
     /* Set the background color to a shade of green */
     background: #4FFF8F;
     /* Center-align the text */
     text-align: center;
     /* Set the cursor to be a pointer */
     cursor: pointer;
    }
    
  2. Using a Class Selector For instances where we want to apply the same styling to multiple elements, we define a CSS class using the syntax .className (where is the name of our class). We then follow it with a pair of curly braces that contain the desired style constraints for all elements of that class. For example:
    .myStyleClass {
     /* Set the background color to a shade of green */
     background: #4FFF8F;
     /* Center-align the text */
     text-align: center;
     /* Set the cursor to be a pointer */
     cursor: pointer;
    }
    

Regular Expressions 3

Regular Expressions 3

Task

Complete the function in the editor below by returning a RegExp object, , that matches every integer in some string .

Constraints

The length of string is . It’s guaranteed that string contains at least one integer.

Output Format

The function must return a RegExp object that matches every integer in some string .

Sample Input 0

102, 1948948 and 1.3 and 4.5

Sample Output 0

102
1948948
1
3
4
5

Explanation 0

When we call match on string and pass the correct RegExp as our argument, it returns the following array of results: [ ‘102’, ‘1948948’, ‘1’, ‘3’, ‘4’, ‘5’ ].

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match ALL occurrences of numbers in a string.
     */

    const re = /\d+/g;
    /*
     * Do not remove the return statement
     */
    return re;
}

Regular Expressions 2

Regular Expressions 2

Task

Complete the function in the editor below by returning a RegExp object, , that matches any string satisfying both of the following conditions:

  • String starts with the prefix Mr., Mrs., Ms., Dr., or Er.
  • The remainder of string (i.e., the rest of the string after the prefix) consists of one or more upper and/or lowercase English alphabetic letters (i.e., [a-z] and [A-Z]).

Constraints

  • The length of string $s$ is $\ge 3$.

Output Format

The function must return a RegExp object that matches any string satisfying both of the given conditions.

Sample Input 0

Mr.X

Sample Output 0

true

Explanation 0

This string starts with Mr., followed by an English alphabetic letter (X).

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.',
     * followed by one or more letters.
     */

    const re = new RegExp('^(Mr|Mrs|Ms|Dr|Er)\\.[a-zA-Z]+$');

    /*
     * Do not remove the return statement
     */
    return re;
}


function main() {
    const re = regexVar();
    const s = readLine();

    console.log(!!s.match(re));
}

Regular Expressions 1

Regular Expressions 1

Task

Complete the function in the editor below by returning a RegExp object, , that matches any string that begins and ends with the same vowel. Recall that the English vowels are a, e, i, o, and u.

Constraints

The length of string is . String consists of lowercase letters only (i.e., [a-z]).

Output Format

The function must return a RegExp object that matches any string beginning with and ending in the same vowel.

Sample Input 0

bcd

Sample Output 0

false

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
     */
    const re = new RegExp('^([aeiou]).*\\1$');

    /*
     * Do not remove the return statement
     */
    return re;
}

Regular Expressions in JavaScript

A Regular Expression, or RegEx, is a pattern used to match character combinations in a string. In JavaScript, regular expressions are also objects. We’ll start by giving some basic examples, and then explain the syntax needed to construct and understand RegExes in further detail.

Creating a Regular Expression

A regular expression consists of a pattern string and, potentially, a flag specifying further detail on how the pattern should be matched. We construct regular expressions by using regular expression literals or RegExp class objects.

Regular Expression Patterns

We generally construct RegEx patterns using the basic characters we wish to match (e.g., abc), or a combination of basic and special characters (e.g., ab\*c or (\d+)\.\d\*).

Regular Expression Literal

A regular expression literal is a RegEx pattern encosed within forward slashes:

const re = /ab + c/;

This RegEx above matches the character a, followed by one or more instances of the character b, followed by the character c.

RegExp Objects

We can write a regular expression string and pass it as an argument toi the RegExp construct:

const re = new RegExp('ab+c');

// result same
const reg = /(.).*\1/;
const reg = new RegExp('(.).*\1' );
asdlp;fjlask;dkfjkxptmxm xptmxm vka vmfptmx dkasdflkjsdaflkjasdflklsdjflkasjdf

Flags

To create a RegExp object, we use this syntax:

new RegExp(pattern[, flags])

To create a regular expression literal, we use this syntax:

/pattern/flags

If specified, flags can have any combination of the following values:

  • $g$: global match.
  • $i$: ignore case.
  • $m$: multiline. Trates beginning(^) and end ($) characters as working over multiple lines.
  • $u$: unicode. Treat pattern as a sequence of unicode code points.
  • $y$: sticky. Matches only from the idex indicated by the lastIndex porperty of this regular expression in the target string.

Special Characters in Regular Expressions

  • Character Classes
  • Character Sets
  • Alteration
  • Boundaries
  • Grouping and back references
  • Quantifiers
  • Assertions

Character Classes

This is not a class in the traditional sense, but rather a term that refers to a set of one or more characters that can be used to match a single character from some input string. Here are the basic forms:

  • Enclosed within square brackets. Specify the what you’d like your expression to match within square brackets; for example, [a-f] will match any lowercase a through f character.
  • Predefined: These consist of a backslash character () followed by a letter. The table below shows some predefined character classes and the characters they match.
Character Matches
^ Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.
$ Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.
\b A zero-width word boundary, such as between a letter and a space.
\B Matches a zero-width non-word boundary, such as between two letters or between two spaces.
Grouping and back references
  • (a): Matches a and remembers the match. These are called capturing groups.

  • (?:a): Matches a but does not remember the match. These are called non-capturing groups.

  • \n: Here n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression.

Quantifiers
  • a*: Matches the preceding item a, 0 or more times.

  • a+: Matches the preceding item a, 1 or more times.

  • a?: Matches the preceding item a, 0 or 1 time.

  • a{n}: Here n is a positive integer. Matches exactly n occurrences of the preceding item a.

  • a{n, }: Here n is a positive integer. Matches at least n occurrences of the preceding item a.

  • a{n, m}: Here n and m are positive integers. Matches at least n and at most m occurrences of the preceding item a.

Assertions
  • a(?=b): Matches a only if a is followed by b.

  • a(?!b): Matches a only if a is not followed by b.

Working with Regular Expressions

Regular expressions are used with the RegExp methods:

  • test: The test() method executes a search for a match between a regular expression and a specified string. Returns true or false
  • exec: The exec() method executes a search for a match in a specified string. Returns a result array or null.

and with the String methods:

  • match: The match() method retrieves the matches when matching a string against a regular expression.
  • search: The search() method executes a search for a match between a regular expression and this String object. If successful, search() returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1
  • split: The split() method splits a String object into an array of strings by separating the string into substrings. Separator specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.
  • replace:The replace(pattern, replacement) method returns a new string where some (or all) occurrences of a matched have been replaced with a substring.
    • pattern: This value can be a string or a RegExp object to match against the calling string.
    • replacement: This value can be a substring to replace the match with, or it can be a function to invoke that generates the replacement substring.

Sock Merchant

Between Two Sets

You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array

Function Description

Complete the getTotalX function in the editor below. It should return the number of integers that are betwen the sets.

getTotalX has the following parameter(s):

  • a: an array of integers
  • b: an array of integers

Input Format

The first line contains two space-separated integers, $n$ and $m$, the number of elements in array and the number of elements in array $b$. The second line contains $n$ distinct space-separated integers describing $a[i]$ where $0 \le i < n$. The third line contains $m$ distinct space-separated integers describing $b[j]$ where $0 \le j < m$.

Output Format

Print the number of integers that are considered to be between $a$ and $b$.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'getTotalX' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY a
     *  2. INTEGER_ARRAY b
     */

    public static int getTotalX(List<Integer> a, List<Integer> b) {
    // Write your code here
        int lcmVal = getLcm(a), gcdVal = getGcd(b);
        int count = 0;
        for (int i = lcmVal, j = 2; i <= gcdVal; i= lcmVal*j, j++) {
            if((gcdVal%i) == 0) count++;
        }
        return count;
    }

    public static int getLcm(List<Integer> input) {

        int resultLcm = input.get(0);

        for (int i = 1; i < input.size(); i++) {
            resultLcm = lcm(resultLcm, input.get(i));
        }    
        return resultLcm;
    }

    public static int getGcd(List<Integer> input) {

        int resultGcd = input.get(0);

        for (int i = 1; i < input.size(); i++) {
            resultGcd = gcd(resultGcd, input.get(i));
        }

        return resultGcd;
    }

    // 최소 공배수
    public static int lcm(int a, int b) {
        return a * b / gcd(a,b);
    }

    // 최대 공약수
    public static int gcd(int a, int b) {
        while (b > 0)
        {
            int tmp = a;
            a = b;
            b = tmp%b;
        }
        return a;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(firstMultipleInput[0]);

        int m = Integer.parseInt(firstMultipleInput[1]);

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> brr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        int total = Result.getTotalX(arr, brr);

        bufferedWriter.write(String.valueOf(total));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Get GCD & LCM


// GCD: 최대 공약수
public static int gcd(int a, int b) {
    while (b > 0)
    {
        int tmp = a;
        a = b;
        b = tmp%b;
    }
    return a;
}

// LCM: 최소 공배수
public static int lcm(int a, int b) {
    return a * b / gcd(a,b);
}

Get GCD & LCM With List

public static int getLcm(List<Integer> input) {

    int resultLcm = input.get(0);

    for (int i = 1; i < input.size(); i++) {
        resultLcm = lcm(resultLcm, input.get(i));
    }    
    return resultLcm;
}

public static int getGcd(List<Integer> input) {

    int resultGcd = input.get(0);

    for (int i = 1; i < input.size(); i++) {
        resultGcd = gcd(resultGcd, input.get(i));
    }

    return resultGcd;
}

Javascript Dates

Javascript Dates

Given a date string, $dataString$, in the format MM/DD/YYYY, find and return the day name for that date. Each day name must be one of the following strings: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, or Saturday. For example, the day name for the date 12/07/2016 is Wednesday.

Input Format

Locked stub code in the editor reads the following input from stdin: The first line contains an integer, $d$, denoting the number of dates to check. Each line $i$ of the $d$ subsequent lines contains a date in MM/DD/YYYY format; each date denotes some $dataString$ that is passed to the function.

Constraints

It is guaranteed that the input only consists of valid dates.

Output Format

The function must return a string denoting the day of the week corresponding to the date denoted by $dataString$.

Sample Input 0

2
10/11/2009
11/10/2010

Sample Output 0

Sunday
Wednesday

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
function getDayName(dateString) {
    let dayName = new Date(dateString).toString().split(" ")[0];
    // Write your code here
    switch(dayName) {
        case "Sun":
            dayName = "Sunday";
            break;
         case "Mon":
            dayName = "Monday";
            break;
        case "Tue":
            dayName = "Tuesday";
            break;
        case "Wed":
            dayName = "Wednesday";
            break;
        case "Thu":
            dayName = "Thursday";
            break;
        case "Fri":
            dayName = "Friday";
            break;
        default:
            dayName = "Saturday";
            break;           
    }

    return dayName;
}


function main() {
    const d = +(readLine());

    for (let i = 0; i < d; i++) {
        const date = readLine();

        console.log(getDayName(date));
    }
}

Dates in Javascript

A Javascript date instance represents a single moment in time based on the number of milliseconds elapsed since $1$ $January,$ $1970 UTC$

Create Date Instance

There are four constructors we can use to create a $Date$ $Object$, defined below.

  1. Using $new \ Date()$ The default constructor creates a Javascript Date object for the current date and time(according to your system settings.)

  2. Using $new \ Date(value)$ This constructor has a parameter, $value$, which is an integer representing the number of milliseconds elapsed since $1 \ January \ 1970 \ 00:00:00 \ UTC$ (this is a Unix Epoch, though you should keep in mind that most Unix timestamp functions count in seconds).

  3. Using $new \ Date(dateString)$ This constructor has a parameter, $dateString$, which is a String describing a date. The $dateString$ must be in a format recognized by the Date.parse() function, such as MM/DD/YYYY or Month Day, Year. For example, 01/01/1980 and Jan 1, 1980 are both strings that can be successfully parsed using the parse function.

  4. Using new Date(year, month, day, hour, minutes, seconds, milliseconds) This constructor has the following parameters:

    • year: An integer denoting the calendar year. Values from 0 through 99 map to the years $1900$ through $1999$.
    • month: A one or two digit integer denoting the zero-indexed month. This means that 0 denotes January and 11 denotes December.
    • day: Optional. An integer denoting the specific day number within the calendar month.
    • hour: Optional. An integer denoting the hour of the day.
    • minutes: Optional. An integer denoting the minute segment of a time.
    • seconds: Optional. An integer denoting the second segment of a time.
    • milliseconds: Optional. An integer denoting the millisecond segment of a time.

Date $get$ Methods

  1. Date.getTime() Get the time in milliseconds elapsed since $January \ 1, 1970$.

  2. Date.getFullYear() Get the four-digit year ($yyyy$).

  3. Date.getMonth() Get the Date object’s month as a zero-indexed number (0-11).

  4. Date.getDate() Get the Date object’s day as a number (1-31).

  5. Date.getDay() Get the Date object’s weekday as a number (0-6).

  6. Date.getHours() Get the Date object’s hour (0-23).

  7. Date.getMinutes() Get the Date object’s minutes (0-59)

  8. Date.getSeconds() Get the Date object’s seconds (0-59).

  9. Date.getMilliseconds() Get the Date object’s milliseconds (0-999).

Javascript Dates

Javascript Dates

Given a date string, $dataString$, in the format MM/DD/YYYY, find and return the day name for that date. Each day name must be one of the following strings: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, or Saturday. For example, the day name for the date 12/07/2016 is Wednesday.

Input Format

Locked stub code in the editor reads the following input from stdin: The first line contains an integer, $d$, denoting the number of dates to check. Each line $i$ of the $d$ subsequent lines contains a date in MM/DD/YYYY format; each date denotes some $dataString$ that is passed to the function.

Constraints

It is guaranteed that the input only consists of valid dates.

Output Format

The function must return a string denoting the day of the week corresponding to the date denoted by $dataString$.

Sample Input 0

2
10/11/2009
11/10/2010

Sample Output 0

Sunday
Wednesday

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
function getDayName(dateString) {
    let dayName = new Date(dateString).toString().split(" ")[0];
    // Write your code here
    switch(dayName) {
        case "Sun":
            dayName = "Sunday";
            break;
         case "Mon":
            dayName = "Monday";
            break;
        case "Tue":
            dayName = "Tuesday";
            break;
        case "Wed":
            dayName = "Wednesday";
            break;
        case "Thu":
            dayName = "Thursday";
            break;
        case "Fri":
            dayName = "Friday";
            break;
        default:
            dayName = "Saturday";
            break;           
    }

    return dayName;
}


function main() {
    const d = +(readLine());

    for (let i = 0; i < d; i++) {
        const date = readLine();

        console.log(getDayName(date));
    }
}

Dates in Javascript

A Javascript date instance represents a single moment in time based on the number of milliseconds elapsed since $1$ $January,$ $1970 UTC$

Create Date Instance

There are four constructors we can use to create a $Date$ $Object$, defined below.

  1. Using $new \ Date()$ The default constructor creates a Javascript Date object for the current date and time(according to your system settings.)

  2. Using $new \ Date(value)$ This constructor has a parameter, $value$, which is an integer representing the number of milliseconds elapsed since $1 \ January \ 1970 \ 00:00:00 \ UTC$ (this is a Unix Epoch, though you should keep in mind that most Unix timestamp functions count in seconds).

  3. Using $new \ Date(dateString)$ This constructor has a parameter, $dateString$, which is a String describing a date. The $dateString$ must be in a format recognized by the Date.parse() function, such as MM/DD/YYYY or Month Day, Year. For example, 01/01/1980 and Jan 1, 1980 are both strings that can be successfully parsed using the parse function.

  4. Using new Date(year, month, day, hour, minutes, seconds, milliseconds) This constructor has the following parameters:

    • year: An integer denoting the calendar year. Values from 0 through 99 map to the years $1900$ through $1999$.
    • month: A one or two digit integer denoting the zero-indexed month. This means that 0 denotes January and 11 denotes December.
    • day: Optional. An integer denoting the specific day number within the calendar month.
    • hour: Optional. An integer denoting the hour of the day.
    • minutes: Optional. An integer denoting the minute segment of a time.
    • seconds: Optional. An integer denoting the second segment of a time.
    • milliseconds: Optional. An integer denoting the millisecond segment of a time.

Date $get$ Methods

  1. Date.getTime() Get the time in milliseconds elapsed since $January \ 1, 1970$.

  2. Date.getFullYear() Get the four-digit year ($yyyy$).

  3. Date.getMonth() Get the Date object’s month as a zero-indexed number (0-11).

  4. Date.getDate() Get the Date object’s day as a number (1-31).

  5. Date.getDay() Get the Date object’s weekday as a number (0-6).

  6. Date.getHours() Get the Date object’s hour (0-23).

  7. Date.getMinutes() Get the Date object’s minutes (0-59)

  8. Date.getSeconds() Get the Date object’s seconds (0-59).

  9. Date.getMilliseconds() Get the Date object’s milliseconds (0-999).

Bitwise Operators

Bitwise Operators

We define $S$ to be a sequence of distinct sequential integers from $1$ to $n$; in other words, $S=(1,2,3,4,5…,n)$. We want to know the maximum bitwise AND value of any two integers, $a$ and $b$ (where $a<b$ ), in sequence $S$ that is also less than a given integer, $k$.

Complete the function in the editor so that given $n$ and $k$, it returns the maximum $a$ & $b < k$.

Input Format

The first line contains an integer, $q$, denoting the number of function calls. Each of the $q$ subsequent lines defines a dataset for a function call in the form of two space-separated integers describing the respective values of $n$ and $k$.

Constraints

  • $1 \le q \le 10^3$
  • $2 \le n \le 10^3$
  • $2 \le k \le n$

Output Format

Return the maximum possible value of $a$ & $b$ < kfor any $a<b$ in sequence $S$.

Sample Input 0

3
5 2
8 5
2 2

Sample Output 0

1
4
0

Explanation 0

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function getMaxLessThanK(n, k) {
    let resultVal = 0;
    for (let i = 1; i < n; i++) {
        for (let j = i+1; j <= n; j++) {
            const temp = i & j;
            if (temp < k) temp > resultVal ? resultVal = temp : '';
        }
    }
    return resultVal;
}


function main() {
    const q = +(readLine());

    for (let i = 0; i < q; i++) {
        const [n, k] = readLine().split(' ').map(Number);

        console.log(getMaxLessThanK(n, k));
    }
}

Bitwise Operators in Javascript

Before discussing bitwise operators, let’s review the following:

  • Binary numbers
  • Base-10(decimal number) to base-2(binary number) conversions.
  • Base-2(binary number) to base-10(decimal number) conversions.
  • Representing negatibe base-10 numbers in base-2

Binary Numbers and Bit Manipulation

This article provides some additional background on these topics

Euclidean algorithm

Euclidean algorithm

유클리드 호제법은 2개의 자연수 또는 정식의 최대공약수를 구하는 알고리즘의 하나이다.

호제법이란 말은 두 수가 서로 상대방 수를 나누어서 결국 원하는 수를 얻는 알고리즘을 나타낸다.

2개의 자연수(또는 정식) a, b에 대해서 a를 b로 나눈 나머지를 r이라 하면(단, a>b), a와 b의 최대공약수는 b와 r의 최대공약수와 같다. 이 성질에 따라, b를 r로 나눈 나머지 r’를 구하고, 다시 r을 r’로 나눈 나머지를 구하는 과정을 반복하여 나머지가 0이 되었을 때 나누는 수가 a와 b의 최대공약수이다. 이는 명시적으로 기술된 가장 오래된 알고리즘으로서도 알려져 있으며, 기원전 300년경에 쓰인 유클리드의 《원론》 제7권, 명제 1부터 3까지에 해당한다.

최대 공약수

예시

1071과 1029의 최대공약수를 구하면,

  • 1071은 1029로 나누어떨어지지 않기 때문에, 1071을 1029로 나눈 나머지를 구한다. => 42
  • 1029는 42로 나누어떨어지지 않기 때문에, 1029를 42로 나눈 나머지를 구한다. => 21
  • 42는 21로 나누어떨어진다. 따라서, 최대공약수는 21이다.

78696과 19332의 최대공약수를 구하면

78696 = 19332×4 + 1368
19332 = 1368×14 + 180
 1368 = 180×7 + 108
  180 = 108×1 + 72
  108 = 72×1 + 36
   72 = 36×2 // MOD = 0

따라서, 최대공약수는 36이다

코드

재귀 호출로 해결 가능

아래 코드는 b가 0이 될때까지 계속해서 재귀 호출을 해주고, 0이 되면 a를 반환한다.

int gcd(int a, int b)
{
    /*
     * eqaul logic
     * if (b==0) return a;
     * gcd(b, a%b)
    */
	return b ? gcd(b, a%b) : a;
}

재귀 호출이 문제가 된다면

int gcd(int a, int b)
{
    while (b > 0)
    {
        int tmp = a;
        a = b;
        b = tmp%b;
    }
    return a;
}

최소공배수

최소공배수는 최대공약수와는 반대로, 두 정수가 공통적으로 가지는 배수 중 가장 작은 값을 의미합니다. 최소공배수는 최대공약수와 밀접한 관계가 있는데, 정수 a, b의 최대공약수 G = gcd(a, b)에 대하여 아래의 식을 만족하는 정수 x와 y가 존재합니다. $a = Gx$, $b = Gy$ (단, x, y는 정수) 이 때 a * b = GGx*y 임을 알 수 있고, G는 두 수의 최대 공약수이며 x와 y는 서로소인 관계를 가집니다. 집합적으로 생각하면, a와 b의 합집합은 G, x, y이고 이 세 수를 곱한 Gxy가 최소공배수가 됨을 알 수 있습니다.

  1. a * b = GGx*y
  2. a * b / G = GGx*y / G (양변에 최소 공약수를 나누어 줌)
  3. a * b / G = Gxy(최소공배수)
  4. 최소공배수 = a * b / G

그러므로 두 수의 최소공배수 L = lcm(a, b)은 L= lcm(a, b)= a * b / gcd(a, b)이 성립합니다.

최대공약수와 최소공약수 사이의 관계와 유클리드 호제법을 활용해 구할 수도 있습니다

int lcm(int a, int b)
{
	return a * b / gcd(a,b);
}

Between Two Sets

Between Two Sets

You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array

Function Description

Complete the getTotalX function in the editor below. It should return the number of integers that are betwen the sets.

getTotalX has the following parameter(s):

  • a: an array of integers
  • b: an array of integers

Input Format

The first line contains two space-separated integers, $n$ and $m$, the number of elements in array and the number of elements in array $b$. The second line contains $n$ distinct space-separated integers describing $a[i]$ where $0 \le i < n$. The third line contains $m$ distinct space-separated integers describing $b[j]$ where $0 \le j < m$.

Output Format

Print the number of integers that are considered to be between $a$ and $b$.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'getTotalX' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY a
     *  2. INTEGER_ARRAY b
     */

    public static int getTotalX(List<Integer> a, List<Integer> b) {
    // Write your code here
        int lcmVal = getLcm(a), gcdVal = getGcd(b);
        int count = 0;
        for (int i = lcmVal, j = 2; i <= gcdVal; i= lcmVal*j, j++) {
            if((gcdVal%i) == 0) count++;
        }
        return count;
    }

    public static int getLcm(List<Integer> input) {

        int resultLcm = input.get(0);

        for (int i = 1; i < input.size(); i++) {
            resultLcm = lcm(resultLcm, input.get(i));
        }    
        return resultLcm;
    }

    public static int getGcd(List<Integer> input) {

        int resultGcd = input.get(0);

        for (int i = 1; i < input.size(); i++) {
            resultGcd = gcd(resultGcd, input.get(i));
        }

        return resultGcd;
    }

    // 최소 공배수
    public static int lcm(int a, int b) {
        return a * b / gcd(a,b);
    }

    // 최대 공약수
    public static int gcd(int a, int b) {
        while (b > 0)
        {
            int tmp = a;
            a = b;
            b = tmp%b;
        }
        return a;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(firstMultipleInput[0]);

        int m = Integer.parseInt(firstMultipleInput[1]);

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> brr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        int total = Result.getTotalX(arr, brr);

        bufferedWriter.write(String.valueOf(total));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Study

Get GCD & LCM


// GCD: 최대 공약수
public static int gcd(int a, int b) {
    while (b > 0)
    {
        int tmp = a;
        a = b;
        b = tmp%b;
    }
    return a;
}

// LCM: 최소 공배수
public static int lcm(int a, int b) {
    return a * b / gcd(a,b);
}

Get GCD & LCM With List

public static int getLcm(List<Integer> input) {

    int resultLcm = input.get(0);

    for (int i = 1; i < input.size(); i++) {
        resultLcm = lcm(resultLcm, input.get(i));
    }    
    return resultLcm;
}

public static int getGcd(List<Integer> input) {

    int resultGcd = input.get(0);

    for (int i = 1; i < input.size(); i++) {
        resultGcd = gcd(resultGcd, input.get(i));
    }

    return resultGcd;
}

Template Literals

Template Literals

Task

The code in the editor has a tagged template literal that passes the area and perimeter of a rectangle to a tag function named sides. Recall that the first argument of a tag function is an array of string literals from the template, and the subsequent values are the template’s respective expression values.

Complete the function in the editor so that it does the following:

  1. Finds the inital values of $s1$ and $s2$ by plugging the area and perimeter values into the formula:
  • $ s = \frac{P \pm \sqrt{P^2 - 16 \cdot A}}{4}$ where $A$ is the rectangles’s area and $P$ is its perimeter.
  1. Creates an array consisting of $s1$ and $s2$ and sorts it in ascending order.
  2. Returns the sorted array.

Input Format

The first line contains an integer denoting $s1$. The second line contains an integer denoting $s2$.

Constraints

  • $ 1 \le s1, s2 \le 100 $

Output Format

Return an array consisting of $s1$ and $s2$ sorted in ascending order.

Dev


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Determine the original side lengths and return an array:
 * - The first element is the length of the shorter side
 * - The second element is the length of the longer side
 *
 * Parameter(s):
 * literals: The tagged template literal's array of strings.
 * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]).
 */
function sides(literals, ...expressions) {
    const A = expressions[0];
    const P = expressions[1];

    const s1 = (P + Math.sqrt(Math.pow(P, 2) - 16 * A))/4;
    const s2 = (P - Math.sqrt(Math.pow(P, 2) - 16 * A))/4;

    return [s1, s2].sort();
}


function main() {
    let s1 = +(readLine());
    let s2 = +(readLine());

    [s1, s2] = [s1, s2].sort();

    const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`;

    console.log((s1 === x) ? s1 : -1);
    console.log((s2 === y) ? s2 : -1);
}

Javascript: Template Literals

Template literals

Template literals(formerly known as template strings) are string literals that allow for embedded expressions. We typically use them to express strings spanning multiple lines or for string interpolation, which essentially allows us to create a template with one or more placeholders for inserting variable text at a later time.

While traditional strings are wrapped in single or double quotes, template literals are wrapped in backtick (') characters. A template literal can contain placeholders, which are preceded by a dollar sign ($) and wrapped in curly braces ({}). For example, in the template literal ${expression}, the $expreesion$ text between the placeholders is passed to a function. The default function simply concatenates the template literal’s parts into a single string.

Any time we see an expression preceding a template literal, we call the expression a tag and the template string a tagged template literal. In these instances, we call the tag expression (typically a function) with the processed template literal, which we can then manipulate before outputting the final string.

Expression Interpolation

Print a Line Using Normal Strings

const a = 2;
const b = 3;

console.log(
  'The sum of a and b is' + (a + b) + '.\n'
  + 'The product of a and b is' + (a * b) + '.'
);

Print a Line Using Template Literals

const a = 2;
const b = 3;

console.log('The sum of a and b is ${a + b}.
The product of a and b is ${a * b}.');

Result

The sum of a and b is 5. The product of a and b is 6.

Tagged template Literals

Tagged template literals allow us to use a function to modify the output of a template literal. in this construct:

  1. The first argument contains an array of string literals.
  2. The subsequently processed arguments are the values of the substitution expressions.

After processing all the arguments, the function returns the manipulated string.

var a = 5;
var b = 10;

function foo(strings, ...values) {
    console.log("." + strings[0] + ".");
    console.log("." + strings[1] + ".");
    console.log("." + strings[2] + ".");
    console.log("." + strings[3] + ".");
    console.log(values[0]);
    console.log(values[1]);
    console.log(values[2]);
}

foo 'sum  ${a + b}
Product   ${a * b}
Division  ${b / a}';

Result

.Sum . . Product . . Division . .. 15 50 2

foo 'sum  ${a + b} Product ${a * b} Division  ${b / a}';

Result

.Sum . .Product . .Division . .. 6 5 0.2

Now we can see that, the total number of string literals is one more than the number of total cooked expressions. The first string literal is the string before the first cooked expression, the last string literal is the string after the last cooked expression and other literals are in between the cooked expressions.

We can also return from tagged templates:

var a = 5;
var b = 10;

function foo(strings, ...values) {
    let a = values[0];
    let b = values[1];

    return `Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
}

console.log(foo`Num1 ${a + 10}
Num2 ${b * 2}
Num3 ${b / a}`);

Result

Sum 35 Product 300 Division 1.3333333333333333

Inheritance

Inheritance

In this challenge, we practive implementing inheritance and use Javascript prototypes to add a new method to an existing prototype. Check out the attached Classes tutorial to refresh what we’ve learned about these topics.

Task

We provide the implementanion for a Ractangle class in the editor. Perform the following tasks:

  1. Add an are method to Rectangle prototype.
  2. Create a Square class that satisfiles the follwing
    • It is a subclass of Rectangle.
    • It contains a constructor and no other methods.
    • It can use the Ractangle class area method to print the area of a Square object.

Locked code in the editor tests the class and method implementations and prints the area values to STDOUT.

Dev


class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
}

/*
 *  Write code that adds an 'area' method to the Rectangle class' prototype
 */
Rectangle.prototype.area = function() {
    return this.w * this.h;
}
/*
 * Create a Square class that inherits from Rectangle and implement its class constructor
 */
class Square extends Rectangle {
    constructor(w) {
        super(w, w);
    }
}


if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) {
    const rec = new Rectangle(3, 4);
    const sqr = new Square(3);

    console.log(rec.area());
    console.log(sqr.area());
} else {
    console.log(-1);
    console.log(-1);
}

Conclusion

ES6 Javascript 문법이 자바랑 비슷해 지면서 클래스 관련 코드들이 가독성이 좋아진거 같아 배우고, 사용하기 훨신 편하게 느껴졌습니다.

Arrow Functions

Arrow Functions

Task

Complete the function in the editor. It has one parameter: an array, $nums$. It must iterate through the array performing one of the following actions on each element:

  • If the element is even, multiply the element by 2.
  • If the element is odd, multiply the element by 3. The function must then return the modified array.

Input Format

The first line contains an integer, $n$, denothing the size of $nums$ The second line contains $n$ space-separated integers describing the respective elements of $nums$.

Constraints

  • $1 \le n \le 10$
  • $1 \le nums \le 100$, where $nums$, is the $i^{th}$ element of $nums$.

Output Format

Return the modified array where every even element is doubled and every odd elements is tripled.

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Modify and return the array so that all even elements are doubled and all odd elements are tripled.
 *
 * Parameter(s):
 * nums: An array of numbers.
 */
function modifyArray(nums) {
    for (const i in nums) {
        (nums[i] % 2 === 0) ? nums[i] *= 2 : nums[i] *= 3;
    }

    return nums;
}


function main() {
    const n = +(readLine());
    const a = readLine().split(' ').map(Number);

    console.log(modifyArray(a).toString().split(',').join(' '));
}

Arrow Functions in Javascript

Arrow Functions

There expressions lexically bind the $this$ value while using less syntax than a typical function expression. Arrow functions are always anonymous.

  • Here are some basic examples of arrow function syntax:
    (parameter) => {statements}
    parameter => {statements}
    parameter => expression
    parameter => {return expression}
    
    (param1, param2, ..., paramN) => {statements}
    (param1, param2, ..., paramN) => expression
    (param1, param2, ..., paramN) => {return expression}
    
  • Let’s look at some simple ways to apply this syntax:
    'use strict';
    
    const makeArray = (...values) => { return values };
    console.log('Array:', makeArray(1, 2, 3, 4));
    console.log('Array:', makeArray(1, 2, 3, 4, 5, 6));
    
    const getSum = (a, b) => { return a + b };
    console.log('1 + 2 =', getSum(1, 2));
    
    const greeting = 'Hello, World.';
    const capitalize = (myString) => { return myString.toUpperCase() };
    console.log(greeting, '=>', capitalize(greeting));
    

Using Arrow Functions

Let’s look at some ways we can use arrow functions to make our code shorter.

  • Sum the Elements of an Array while we can certainly iterate over an array and sum each value, we can also use the reduce function.
    'use strict';
    
    const arr = [1, 2, 3, 4, 5];
    
    // Basic function
    const sum = arr.reduce(function (a, b) {
        return a + b;
    }, 0);
    
    // Now, let's reduce the length of our code using an arrow function:
    const sum = arr.reduce((a, b) => { return a + b }, 0);
    
    // Let's further reduce it by getting rid of the return:
    const sum = arr.reduce((a, b) => a + b, 0);
    
    console.log('Array:', arr);
    console.log('Sum:', sum);
    
    • Result

      Array: [ 1, 2, 3, 4, 5 ] Sum: 15

  • Find the Length of Strings in an Array Let’s take an array of strings and use if to create a new array containing the respective lengths of its elements.
    'use strict';
    
    const arr = ['first', 'second', 'third', 'fourth', 'fifth'];
    
    // Basic function
    const len = arr.map(function(s) { return s.length });
    
    // Now, let's reduce the length of our code using an arrow function:
    const len = arr.map(s => s.length);
    
    console.log('Array:', arr);
    console.log('Lengths:', len);
    
    • Result

      Array: [ ‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’ ] Lengths: [ 5, 6, 5, 6, 5 ]

  • Find Array Elements Greater Than a Value Let’s find all the elements in an array that are greater than 3 and add them to a new array. ```js ‘use strict’;

const arr = [1, 2, 3, 4, 5];

// Basic function const greaterThan3 = arr.filter(function(a) { return a > 3; });

// Now, let’s reduce the length of our code using an arrow function: const greaterThan3 = arr.filter(a => a > 3);

console.log(‘Array’, arr); console.log(‘Elements greater Than 3: ‘, greaterThan3); ```

Kangaroo

Kangaroo

You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity).

  • The first kangaroo starts at location $x1$ and moves at a rate of $v1$ meters per jump.
  • The second kangaroo starts at location $x2$ and moves at a rate of $v2$ meters per jump. You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

Function Description

Complete the function kangaroo in the editor below. It should return YES if they reach the same position at the same time, or NO if they don’t.

kangaroo has the following parameter(s):

  • x1, v1: integers, starting position and jump distance for kangaroo 1
  • x2, v2: integers, starting position and jump distance for kangaroo 2

Input Format

A single line of four space-separated integers denoting the respective values of $x1$, $v1$, $x2$, and $v2$.

Constraints

  • $0 < x1 < x2 < 10000$
  • $1 < v1 < 10000$
  • $1 < v2 < 10000$

Output Format

Print YES if they can land on the same location at the same time; otherwise, print NO.

Note: The two kangaroos must land at the same location after making the same number of jumps.

Explanation

The two kangaroos jump through the following sequence of locations:

From the image, it is clear that the kangaroos meet at the same location (number $12$ on the number line) after same number of jumps ($4$ jumps), and we print YES.

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the kangaroo function below.
    static String kangaroo(int x1, int v1, int x2, int v2) {

        if( ( x1 < x2 && v1 > v2 ) || ( x1 > x2 && v1 < v2 ) ) {
            if( Math.abs(x1-x2)%Math.abs(v1-v2) == 0) return "YES";
        }      

        return "NO";
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] x1V1X2V2 = scanner.nextLine().split(" ");

        int x1 = Integer.parseInt(x1V1X2V2[0]);

        int v1 = Integer.parseInt(x1V1X2V2[1]);

        int x2 = Integer.parseInt(x1V1X2V2[2]);

        int v2 = Integer.parseInt(x1V1X2V2[3]);

        String result = kangaroo(x1, v1, x2, v2);

        bufferedWriter.write(result);
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

Classes

Classes

Create a Polygon class that has the following properties:

  • A constructor that takes an array of integer values describing the lengths of the polygon’s sides.
  • A perimeter() method that returns the polygon’s perimeter.

Locked code in the editor tests the Polygon constructor and the perimeter method. Note: The perimeter method must be lowercase and spelled correctly.

Input Format

There is no input for this challenge.

Output Format

The perimeter method must return the polygon’s perimeter using the side length array passed to the constructor.

Dev

/*
 * Implement a Polygon class with the following properties:
 * 1. A constructor that takes an array of integer side lengths.
 * 2. A 'perimeter' method that returns the sum of the Polygon's side lengths.
 */

class Polygon {
    constructor(arr) {
        this.arr = arr;
    }

    perimeter() {
        let sum = 0;

        for (const i in this.arr) {
            sum += this.arr[i];
        }

        return sum;
    }

}

const rectangle = new Polygon([10, 20, 10, 20]);
const square = new Polygon([10, 10, 10, 10]);
const pentagon = new Polygon([10, 20, 30, 40, 43]);

console.log(rectangle.perimeter());
console.log(square.perimeter());
console.log(pentagon.perimeter());

Classes in Javascript

Function Classes

we’ll discuss some of the ways we can use functions to simulate the behavior of classes.

Using Functions

  1. Define a normal Javascript function.
  2. Create an object by using the Keywords.
  3. Define properties and methods for a created object using the this keyword.
'use strict';

function Fruit (type) {
    this.type = type;
    this.color = 'unknown';
    this.getInformation = getFruitInformation;
}

function getFruitInformation() {
    return 'This ' + this.type + ' is ' + this.color + '.';
}

let lime = new Fruit('Mexican lime');
console.log(lime.getInformation());

lime.color = 'green';
console.log(lime.getInformation());

The Prototype Property

he drawback of internally defining the getInformation function is that it recreates that function every time we create a new Fruit object. Fortunately, every function in JavaScript has something called a prototype property, which is empty by default. We can think of a function’s prototype as an object blueprint or paradigm; when we add methods and properties to the prototype, they are accessible to all instances of that function. This is especially useful for inheritance (discussed below).

We can add a function to our constructor function’s prototype like so:

'use strict';

function Fruit (type) {
    this.type = type;
    this.color = 'unknown';
}

Fruit.prototype.getInformation = function() {
    return 'This ' + this.type + ' is ' + this.color + '.';
}

let lime = new Fruit('Mexican lime');
console.log(lime.getInformation());

lime.color = 'green';
console.log(lime.getInformation());

Using Object Literals

We can use object literals to define an object’s properties and functions by initializing a variable with a comma-separated list of property-value pairs enclosed in curly braces.

'use strict';

let lime = {
    type: 'Mexican lime',
    color: 'green',
    getInformation: function() {
        return 'This ' + this.type + ' is ' + this.color + '.';
    }
}

console.log(lime.getInformation());

lime.color = 'yellow';
console.log(lime.getInformation());

Singleton Class Using a Function

A singleton class is a design pattern that restricts a class to a single instance. When we assign the value of new function(){…} to a variable, the following happens:

  1. We define an anonymous constructor function.
  2. We invoke the anonymous constructor function with the new keyword.
'use strict';

let lime = new function() {
    this.type = 'Mexican lime';
    this.color = 'green';
    this.getInformation = function() {
        return 'This ' + this.type + ' is ' + this.color + '.';
    };
}

console.log(lime.getInformation());

lime.color = 'yellow';
console.log(lime.getInformation());

Classes

JavaScript classes, introduced in ECMAScript 6, are essentially syntactic sugar over JavaScript’s existing prototype-based inheritance that don’t actually introduce a new object-oriented inheritance model. This syntax is a means of more simply and clearly creating objects and deal with inheritance.

Class Declartions

One way to define a class is using a class declaration. To declare a class, we use the class keyword and follow it with the class’ name. Ideally, we always write class names in TitleCase.

class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}

let p = new Polygon(1, 2);
console.log('Polygon p:', p);
try {
    let p = new Polygon(1, 2);
    console.log('Polygon p:', p);
}
catch (exception) {
    console.log(exception.name + ': ' + exception.message);
}
class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}

p = new Polygon(1, 2);
console.log('Polygon p:', p);

Class Expression

Class expressions are another way to define a class, and they can be either named or unnamed. The name given to a named class expression is local to the class body.

let Polygon = class {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
};

console.log('Polygon:', Polygon);
let p = new Polygon(1, 2);
console.log('p:', p);

Named Class Expression

let Polygon = class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
};

console.log('Polygon:', Polygon);
let p = new Polygon(1, 2);
console.log('p:', p);

The Constructor Method

  • The constructor method is a special method we use to create and initialize objects of a class.
  • A class can only have one special method with the name constructor, and attempting to write a class containing more than one constructor method will throw a SyntaxError.
  • To implement inheritance, we can use the super keyword in a constructor to call a parent class constructor.

Prototype Methods

'use strict';

class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    getArea() {
        return this.height * this.width;
    }
}

const square = new Polygon(10, 10);

console.log(square.getArea());

Static Methods

tatic methods are methods relevant to all instances of a class — not just any one instance. These methods receive information from their arguments and not a class instance, which allows us to invoke a class’ static methods without creating an instance of the class. In fact, we actually can’t call a static method on an instantiated class object (attempting to do so throws a TypeError).

We define a class’ static methods using the static keyword. We typically use these methods to create utility functions for applications, as they can’t be called on class objects.

'use strict';

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    static distance(a, b) {
        const dx = a.x - b.x;
        const dy = a.y - b.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

// The correct way to call a static method
console.log(Point.distance(p1, p2));

// Attempt to call a static method on an instance of the class
try {
    console.log(p1.distance(p1, p2));
}
catch (exception) {
    console.log(exception.name + ': ' + exception.message);
}

Subclassing with the $extends$ Keywords

We use the extends keyword in class declarations or class expressions to create a child class (i.e., subclass).


'use strict';

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(this.name, 'speaks.');
    }
}

class Dog extends Animal {
    speak() {
        console.log(this.name, 'barks.');
    }
}

let spot = new Dog('Spot');
spot.speak();

spot = new Animal('Spot');
spot.speak();

Spot barks. Spot speaks.

Superclass Calls Using the $super$ Keyword

We use the super keyword to call functions on an object’s parent.

'use strict';

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(this.name, 'speaks.');
    }
}

class Dog extends Animal {
    speak() {
        super.speak();
        console.log(this.name, 'barks.');
    }
}

let spot = new Dog('Spot');
spot.speak();

Spot speaks. Spot barks.

Extending an Object

The ability to extend multiple classes from the same superclass (or model multiple object types after the same prototype) is powerful because it provides us with certain implied guarantees about the basic functionality of the subclasses; as extensions of the parent class, subclasses are guaranteed to (at minimum) have the superclass’ fields, methods, and functions.

'use strict';

class Animal {
    constructor(name) {
        this.animalType = 'Animal'
        this.name = name;
    }
    type() {
        console.log(this.name, 'is type', this.animalType);
    }
    speak() {
        console.log(this.name, 'speaks.');
    }
}

class Dog extends Animal {
    constructor(name, collarColor) {
        super(name);
        this.animalType = 'Dog';
        this.collarColor = collarColor;
    }
    speak() {
        console.log(this.name, 'barks.');
    }
    collar() {
        console.log(this.name, 'has a', this.collarColor, 'collar.');
    }
}

let spot = new Dog('Spot', 'red');
spot.type();
spot.speak();
spot.collar();

// Because the Animal constructor only expects one argument,
// only the first value passed to it is used
spot = new Animal('Spot', 'white');
spot.type();
spot.speak();
try {
    spot.collar();
}
catch (exception) {
    console.log(exception.name + ': ' + exception.message
    + ' (collar is a method of Dog, not Animal).');
}

Spot is type Dog Spot barks. Spot has a red collar. Spot is type Animal Spot speaks. TypeError: spot.collar is not a function (collar is a method of Dog, not Animal).

Count objects

Count objects

Complete the function in the editor. It has one parameter: an array, $a$, of objects. Each object in the array has two integer properties denoted by $x$ and $y$. The function must return a count of all such objects $a$ in array $a$ that satisfy $o.x == o.y$.

##Input Format

The first line contains an integer denoting $n$. Each of the $n$ subsequent lines contains two space-separated integers describing the values of $a$ and $y$.

Constraints

  • $5 < n < 10$
  • $1 < x, y < 100$

Output Format

Return a count of the total number of objects $o$ such that $o.x == o.y$. Locked stub code in the editor prints the returned value to $STDOUT$.

Dev


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Return a count of the total number of objects 'o' satisfying o.x == o.y.
 *
 * Parameter(s):
 * objects: an array of objects with integer properties 'x' and 'y'
 */
function getCount(objects) {

    let count = 0;

    // i : objects is index
    for (const i in objects) {

        if (objects[i].x === objects[i].y) count++;
    }

    return count;
}


function main() {
    const n = +(readLine());
    let objects = [];

    for (let i = 0; i < n; i++) {
        const [a, b] = readLine().split(' ');

        objects.push({x: +(a), y: +(b)});
    }

    console.log(getCount(objects));
}

Create a Rectangle Object

Create a Rectangle Object

Complete the function in the editor. It has two parameters: $a$ and $b$. It must return an object modeling a rectangle that has the following properties:

  • $length$: This value is equal to $a$.
  • $width$: This value is equal to $b$.
  • $perimeter$: This value is equal to $2*(a + b)$
  • $area$: This value is equal to $a * b$

Note: The names of the object’s properties must be spelled correctly to pass this challenge.

Input Format

The first line contains an integer denoting $a$. The second line contains an integer denoting $b$.

Constraints

$ 1 < a, b < 100

Output Format

Return a object that has the properties specified above. Locked code in the editor prints the returned object’s $length$, $width$, , and to STDOUT.

Dev


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the Rectangle function
 */
function Rectangle(a, b) {

    const rectangle = {
        length: a,
        width: b,
        perimeter: 2*(a + b),
        area: (a * b)
    }

    return rectangle;
}

function main() {
    const a = +(readLine());
    const b = +(readLine());

    const rec = new Rectangle(a, b);

    console.log(rec.length);
    console.log(rec.width);
    console.log(rec.perimeter);
    console.log(rec.area);
}

Study

1. Use a Constructor Function;

function Rectangle(a, b) {
    return {
        get length() { return a; },
        get width() { return b; },
        get perimeter() { return 2 * (a + b); },
        get area() { return a * b; }
    }
}
function Rectangle(a, b) {
    // Set the object's properties
    this.length = a;
    this.width = b;
    this.perimeter = 2 * a + 2 * b;
    this.area = a * b;

    // This isn't necessary, but it prevents new properties from being added
    // It also prevents the properties we've already set from being modified
    Object.freeze(this);
}
function Rectangle(a, b) {
    Object.defineProperty(this, 'length', {
        get: () => {
            return a;
        }
    });

    Object.defineProperty(this, 'width', {
        get: () => {
            return b;
        }
    });

    Object.defineProperty(this, 'perimeter', {
        get: () => {
            return 2 * (a + b);
        }
    });

    Object.defineProperty(this, 'area', {
        get: () => {
            return a * b;
        }
    });
}
  1. Use an Object Initializer / Object Literal
let myObject = {
    property1: 1,
    property2: 2
    // ... and so on
}
console.log(myObject)
// This prints:
// { property1: 1, property2: 2 }
function Rectangle(a, b) {
    const rectangle = {
        length: a,
        width: b,
        perimeter: 2 * (a + b),
        area: a * b
    };

    return rectangle;
}

Throw

Throw

Complete the isPositive function below. It has one integer parameter, $a$. If the value of $a$ is positive, it must return the string YES. Otherwise, it must throw an Error according to the following rules:

  • If $a$ is $0$, throw an Error with $message=$ Zero Error.
  • If $a$ is negative, throw an Error with $message=$ Negative Error.

Input Format

Locked stub code in the editor reads the following input from stdin and passes each value of $a$ to the function as an argument: The first line is an integer, $n$, denoting the number of times the function will be called with some $a$. Each line $i$ of the $n$ subsequent lines contains an integer denoting some $a$.

Constraints

  • $1 < n < 5$
  • $-100 < a < 100$

Output Format

If the value of $a$ is positive, the function must return the string YES. Otherwise, it must throw an Error according to the following rules:

  • If $a$ is $0$, throw an Error with $message=$ Zero Error.
  • If $a$ is negative, throw an Error with $message=$ Negative Error.

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the isPositive function.
 * If 'a' is positive, return "YES".
 * If 'a' is 0, throw an Error with the message "Zero Error"
 * If 'a' is negative, throw an Error with the message "Negative Error"
 */
function isPositive(a) {

    if (a > 0) return 'YES';
    else throw Error((a === 0) ? 'Zero Error' : 'Negative Error');
}

function main() {
    const n = +(readLine());

    for (let i = 0; i < n; i++) {
        const a = +(readLine());

        try {
            console.log(isPositive(a));
        } catch (e) {
            console.log(e.message);
        }
    }
}

Conclusion

단순하고 심플한 문제였습니다. 다만 깔끔하게 코딩한거 같아서 만족스러운 해답이라고 생각합니다.

Araays

Araays

Task

Complete the getSecondLargest function in the editor below. It has one parameter: an array, $nums$, of $n$ numbers. The function must find and return the second largest number in $nums$.

Input Format

Locked stub code in the editor reads the following input from stdin and passes it to the function: The first line contains an integer, $n$, denoting the size of the $nums$ array. The second line contains $n$ space-separated numbers describing the elements in $nums$.

Constraints

  • $1 < n < 10$
  • $0 < nums < 100$, where $nums$, is the number at index $i$.
  • The numbers in $nums$ are not distinct.

Output Format

Return the value of the second largest number in the $nums$ array.

Sample Input

5
2 3 6 6 5

Sample Output

5

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/**
*   Return the second largest number in the array.
*   @param {Number[]} nums - An array of numbers.
*   @return {Number} The second largest number in the array.
**/
function getSecondLargest(nums) {
    // Complete the function
    let firstBigNum = 0, secondBigNum = 0;

    for (const num in nums) {
        if (firstBigNum < nums[num]) {

            if (firstBigNum > secondBigNum) {
                secondBigNum = firstBigNum;
            }
            firstBigNum = nums[num];
        } else if (firstBigNum != nums[num]) {
            if (secondBigNum < nums[num]) {
                secondBigNum = nums[num];
            }
        }
    }

    return secondBigNum;
}

Study

Java 향상된 for문과 Javascript 향상된 for문이 헷갈려 당황했다.

int[] s = {2, 13, 45, 65 ,45};
for(int i : s) {
   System.out.println(i);
 }
 const s = [2, 13, 45, 65, 45];
 for (const i in s) {
   console.log(s[i]);
 }

js에서 향상된 for문은 배열의 요소가 아닌 인덱스를 가져온다.

Loops

Loops

Task

Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string, $s$, consisting of lowercase English alphabetic letters (i.e., a through z). The function must do the following:

  1. First, print each vowel in $s$ on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in $s$.
  2. Second, print each consonant (i.e., non-vowel) in $s$ on a new line in the same order as it appeared in $s$.

Input Format

Locked stub code in the editor reads string $s$ from stdin and passes it to the function.

Output Format

First, print each vowel in $s$ on a new line (in the same order as they appeared in $s$). Second, print each consonant (i.e., non-vowel) in $s$ on a new line (in the same order as they appeared in $s$).

Sample Input 0

javaScript

Sample Output 0

a
a
i
o
o
j
v
s
c
r
p
t
l
p
s

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the vowelsAndConsonants function.
 * Print your output using 'console.log()'.
 */
function vowelsAndConsonants(s) {
    const vewels = ['a', 'e', 'i', 'o', 'u'];

    let sArray = s.split("");
    for (let i = 0; i < sArray.length; i++) {
        for (let j = 0; j < vewels.length; j++) {
            if (sArray[i] === vewels[j]) {
                console.log(sArray[i]);
                break;
            }
        }
    }

    for (let k = 0; k < sArray.length; k++) {
        for (let j = 0; j < vewels.length; j++) {
            if (sArray[k] === vewels[j]) {
                break;
            }

            if (j === 4) console.log(sArray[k]);
        }
    }
}

Study

Javascript 문자열 자르기

splice

splice는 특정 시작 인덱스부터 끝 인덱스까지에 값을 추가하거나 그 자리에 있는 값을 삭제할 수 있는 메서드이다.

myArray = [1, 2, 3, 4, 5];
myArray.splice(2, 3);

Return [1, 2]

var arr = ["A","C","D","A","E","F","A"];

var arr_splice = arr.splice(1,3); // 1번부터 3개의 ["C","D","A"]를 꺼낸다. 리턴값은 꺼낸값
console.log(arr); // ["A", "E", "F", "A"]

var arr2 = ["A","C","D","A","E","F","A"];
var arr2_splice = arr2.splice(1,3,"a"); // 1번부터 3개의 ["C","D","A"]를 삭제하고 그자리에 "a"를 삽입한다. 리턴값은 꺼낸값
console.log(arr2); // ["A", "a", "E", "F", "A"]

3번째 인자값에 값을 전달하면 삭제한 위치에 전달된 값을 전달한다

인자값을 하나만 전달하면 그 인덱스를 포함한 뒤에있는 모든 원소를 삭제한다.

var arr = ["A","C","D","A","E","F","A"];

arr.splice(3); // 3번 인덱스를 포함한 뒤의 모든 원소 ["A","E","F","A"] 제거
console.log(arr); // ["A", "C", "D"]

indexOf와 결합해서 사용하면 특정 값을 찾아 삭제하거나 변경할수도 있다.

// 삭제
var arr = ["A","C","D","A","E","F","A"];

arr.splice(arr.indexOf("A"),1); // "A"를 찾아서 삭제한다.
console.log(arr); // ["C", "D", "A", "E", "F", "A"]
// 변경
var arr = ["A","C","D","A","E","F","A"];

arr.splice(arr.indexOf("A"),1,"a"); // "A"를 찾아서 "a"로 변경한다.
console.log(arr); // ["a", "C", "D", "A", "E", "F", "A"]

값이 여러개가 포함되어 있을경우 반복문 루프를 돌려서 모두 삭제할 수도 있다.

for(let i = 0; i < vewels.length ; i++) {

    while(true) {
        const search = sArray.indexOf(vewels[i]);

        if (search != -1) {
            console.log(vewels[i]);
            sArray.splice(search, 1);
        }
        else break;
    }
}

Conclusion

억지로 결과를 뽑아냈다. 문자열 길이로 반복문 제어 중 모음을 먼저 출력하고 출력한 모음을 배열에서 삭제하는 바람에 원하는 결과가 제대로 나오지 않았다. 굉장히 초보적인 실수였지만, 당황스럽게 문제를 바로 발견하지 못하였다.


문자열을 삭제하지 않고, 재배열하여 출력하는 방법이 더 효율적일거 같다.

Conditional Statement Swithch

Conditional Statement Swithch

Task

Complete the getLetter(s) function in the editor. It has one parameter: a string, $s$, consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:

Hint: You can get the letter at some index in using the syntax s[i] or s.charAt(i).

Input Format

Stub code in the editor reads a single string denoting from stdin.

Constraints

  • $ 1 < s < 100$, where $ s $ is the length of $s$.
  • String $s$ contains lowercase English alphabetic letters only.

Output Format

Return either A, B, C, or D according to the criteria given above.

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function getLetter(s) {
    let letter;

    // Write your code here
    switch(s.charAt(0)) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            letter = 'A';
            break;
        case 'b':
        case 'c':
        case 'd':
        case 'f':
        case 'g':
            letter = 'B';
            break;
        case 'h':
        case 'j':
        case 'k':
        case 'l':
        case 'm':
            letter = 'C';
            break;
        default:
            letter = 'D';
            break;''
    }

    return letter;
}

Javascript Switch Syntax

switch(expression) {
  case 'a':
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Conditional Statements: If-else

Conditional Statements: If-else

Task

Complete the getGrade(score) function in the editor. It has one parameter: an integer, $score$, denoting the number of points Julia earned on an exam. It must return the letter corresponding to her $grade$ according to the following rules:

Input Format

Stub code in the editor reads a single integer denoting $score$ from stdin and passes it to the function.

Constraints

$ 0 < score < 30$

Output Format

The function must return the value of $grade$ (i.e., the letter grade) that Julia earned on the exam.

Input

11

Output

D

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function getGrade(score) {
    let grade;
    // Write your code here
    if      (score > 25) grade = 'A';
    else if (score > 20) grade = 'B';
    else if (score > 15) grade = 'C';
    else if (score > 10) grade = 'D';
    else if (score > 5)  grade = 'E';
    else                 grade = 'F';

    return grade;
}

Apple & Orange

Apple & Orange

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where $s$ is the start point, and $t$ is the endpoint. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point $a$, and the orange tree is at point $b$.

When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis. A negative value of means the fruit fell units to the tree’s left, and a positive value of means it falls units to the tree’s right.

Function Description

Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam’s house, each on a separate line.

countApplesAndOranges has the following parameter(s):

  • s: integer, starting point of Sam’s house location.
  • t: integer, ending location of Sam’s house location.
  • a: integer, location of the Apple tree.
  • b: integer, location of the Orange tree.
  • apples: integer array, distances at which each apple falls from the tree.
  • oranges: integer array, distances at which each orange falls from the tree.

Input Format

The first line contains two space-separated integers denoting the respective values of $s$ and $t$. The second line contains two space-separated integers denoting the respective values of $a$ and $b$. The third line contains two space-separated integers denoting the respective values of $m$ and $n$. The fourth line contains $m$ space-separated integers denoting the respective distances that each apple falls from point $a$. The fifth line contains $n$ space-separated integers denoting the respective distances that each orange falls from point $b$.

Constraints

  • $1 < s,t,a,b,m,n < 10^5$
  • $-10^5 < d < 10^5$
  • $a < s < t < b$

Output Format

Print two integers on two different lines:

  1. The first integer: the number of apples that fall on Sam’s house.
  2. The second integer: the number of oranges that fall on Sam’s house.

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the countApplesAndOranges function below.
    static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {

        int appleCount = 0, orangeCount = 0;

        for (int i = 0; i < apples.length; i++) {
            int axis = apples[i] + a;
            if (axis >= s && axis <= t) appleCount++;
        }

        System.out.println(appleCount);

        for (int i = 0; i < oranges.length; i++) {
            int axis = oranges[i] + b;
            if (axis >= s && axis <= t) orangeCount++;
        }

        System.out.println(orangeCount);
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] st = scanner.nextLine().split(" ");

        int s = Integer.parseInt(st[0]);

        int t = Integer.parseInt(st[1]);

        String[] ab = scanner.nextLine().split(" ");

        int a = Integer.parseInt(ab[0]);

        int b = Integer.parseInt(ab[1]);

        String[] mn = scanner.nextLine().split(" ");

        int m = Integer.parseInt(mn[0]);

        int n = Integer.parseInt(mn[1]);

        int[] apples = new int[m];

        String[] applesItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < m; i++) {
            int applesItem = Integer.parseInt(applesItems[i]);
            apples[i] = applesItem;
        }

        int[] oranges = new int[n];

        String[] orangesItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int orangesItem = Integer.parseInt(orangesItems[i]);
            oranges[i] = orangesItem;
        }

        countApplesAndOranges(s, t, a, b, apples, oranges);

        scanner.close();
    }
}

Conclusion

이해하면 굉장히 쉬운 문제였지만, 문제를 이해못해서 처음에 조금 헤맸다. 영어라 당황하지 말고 천천히 이해하면 쉬운 문제.

Grading Students

Grading Students

HackerLand University has the following grading policy:

  • Every student receives a in the inclusive range from $0$ to $100$.
  • Any $grade$ less than $40$ is a failing grade.

Sam is a professor at the university and likes to round each student’s $grade$ according to these rules:

  • If the difference between the $grade$ and the next multiple of $5$ is less than $3$, round $grade$ up to the next multiple of $5$.
  • If the value of $grade$ is less than $38$, no rounding occurs as the result will still be a failing grade.

For example, $grade = 84$ will be rounded to $85$ but $grade=29$ will not be rounded because the rounding would result in a number that is less than $40$. Given the initial value of $grade$ for each of Sam’s $n$ students, write code to automate the rounding process.

Function Description

Complete the function gradingStudents in the editor below. It should return an integer array consisting of rounded grades.

gradingStudents has the following parameter(s):

  • grades: an array of integers representing grades before rounding

Input Format

The first line contains a single integer, $n$, the number of students. Each line $i$ of the $n$ subsequent lines contains a single integer, $grade[i]$, denoting student ‘s grade.

Constraints

  • $ 1 < n < 60 $
  • $ 0 < grade[i] < 100 $

Output Foramt

For each , print the rounded grade on a new line.

Input

4
73
67
38
33

Output

75
67
40
33
```a

# Dev

```java
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*  
     * Complete the 'gradingStudents' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts INTEGER_ARRAY grades as parameter.
     */

    public static List<Integer> gradingStudents(List<Integer> grades) {
    // Write your code here
        List<Integer> result = new ArrayList<Integer>();

        for (Integer grade : grades ) {

            int num = (int)grade/10;

            if (38 > grade) result.add(grade);
            else if ( grade % 10 == 3 || grade % 10 == 4) result.add(num * 10 + 5);
            else if ( grade % 10 == 8 || grade % 10 == 9) result.add(num * 10 + 10);
            else result.add(grade);
        }

        return result;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int gradesCount = Integer.parseInt(bufferedReader.readLine().trim());

        List<Integer> grades = IntStream.range(0, gradesCount).mapToObj(i -> {
            try {
                return bufferedReader.readLine().replaceAll("\\s+$", "");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        })
            .map(String::trim)
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> result = Result.gradingStudents(grades);

        bufferedWriter.write(
            result.stream()
                .map(Object::toString)
                .collect(joining("\n"))
            + "\n"
        );

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Let & Const With Javascript Variable

Let & Const

Task

  1. Declare a constant variable, $PI$ , and assign it the value Math.PI. You will not pass this challenge unless the variable is declared as a constant and named PI (uppercase).
  2. Read a number, $r$ , denoting the radius of a circle from stdin.
  3. Use $PI$ and $r$ to calculate the $area$ and $perimeter$ of a circle having radius $r$.
  4. Print $area$ as the first line of output and print $perimeter$ as the second line of output.

Input Format

A single integer $r$, denoting the radius of a circle

Constraints

  • $ 0 < r < 100
  • $r$ is a floating-point number scaled to at most 3 decimal places.

Output Format

print the following two line:

  1. On the first line, print the $area$ of the circle having radius $r$.
  2. On the second line, print the $perimeter$ of the circle having radius $r$.

Input

2.6

Output

21.237166338267002
16.336281798666924

Explanation

Given the radius $r = 2.6$ we calculate the following:

  • $area = pi * r = 21.237166338267002 $
  • $perimeter = 2 * pi * r = 16.336281798666924$

We then print $area$ as our first line of output and $perimeter$ as our second line of output.

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    // Write your code here. Read input using 'readLine()' and print output using 'console.log()'.
    const PI = Math.PI;
    const r = readLine();
    // Print the area of the circle:
    console.log(PI * r * r)
    // Print the perimeter of the circle:
    console.log(PI * r * 2)
    try {    
        // Attempt to redefine the value of constant variable PI
        PI = 0;
        // Attempt to print the value of PI
        console.log(PI);
    } catch(error) {
        console.error("You correctly declared 'PI' as a constant.");
    }
}

Conclusion

Javascript에 변수 선언 방식인 var let const에 각각 차이점을 알아보자

Javascript의 변수 선언과, 이들의 차이점을 이해하려면 HoistingScope 의 개녕이 필요하다.

var-let-const 차이점

Javascript의 변수 정의의 비교 키워드는 3가지

  1. 변수 값의 변환
  2. 변수의 유효범위
  3. 호이스팅

1. 변수 값의 변환

기존의 Javascript를 사용하면서 가장 문제가 있다고 느낀점은 변수 선언 방식이다.

var를 사용하는 변수 선언의 경우 할당되는 값이 유동적으로 변경될 수 있는 단점을 가지고 있다.

var name = "Marcus";
console.log(name);

var name = "Jogeonsang";
console.log(name);

------------------------
output: Marcus
output: Jogeonsang

다음과 같이 name이라는 변수를 2번 선언했는데도 에러가 나오지않고 각기 다른 값이 출력되는걸 볼 수 있다.

하지만 ES6 업데이트 이후로 추가된 변수 선언 방식인 let과 const는 var와 같은 선언 방식을 막고있다.

let name = "Marcus";
console.log(name);

let name = "Jogeonsang";
console.log(name);
output: Identifier 'name' has already been declared

위와 같이 let을 사용했을 경우에는 name이 이미 선언되었다는 에러 메시지가 나오는걸 볼 수 있다. 위에 코드에는 let만 케이스로 집어넣었지만 const도 마찬가지로 변수 재할당이 안된다는 특징을 가지고있다.


그럴다면 letconst는 어떤 차이가 있을까?

letconst 차이점은 immutable 여부이다.

let은 변수에 재할당이 가능하지만,

const는 변수는 재선언, 재할당이 모두 불가능하다.

let

// let
let testCase = 'let' // output: let
let testCase = 'let2' // output: Uncaught SyntaxError: Identifier 'testCase' has already been declared
testCase = 'let3' // output: let3

const

const testCase = 'const' // output: const
const testCase = 'const2' // output: Uncaught SyntaxError: Identifier 'testCase' has already been declared
testCase = 'const3' // output: Uncaught TypeError:Assignment to constant variable.

위에 코드에서 ReferenceError가 발생한 이유는 tdz(temporal dead zone)때문이다.

temporal dead zone

let은 값을 할당하기전에 변수가 선언 되어있어야 하는데 그렇지 않기 때문에 에러가 난다.

이건 const도 마찬가지인데 좀 더 엄격하다.

// let은 선언하고 나중에 값을 할당이 가능하지만
let dd
dd = 'test'

// const 선언과 동시에 값을 할당 해야한다.
const aa // Missing initializer in const declaration

이렇게 javascript에 tdz가 필요한 이유는 동적언어이다 보니깐 runtime type check 가 필요해서이다.

2. 변수의 유효범위

Javascript에서 변수들의 스코프(유효범위) 에 대해서, var는 함수 스코프(Function Scope)를 가지고, let, const는 블럭 스코프(Block Scope)를 가지게 된다.

var

var foo = "This is String.";
if(typeof foo === 'string'){
    var result = true;
} else {
  var result = false;
}

console.log(result);    // result : true

let, const

var foo = "This is String.";
if(typeof foo === 'string'){
    const result = true;
} else {
  const result = false;
}

console.log(result);    // result : result is not defined

Functions

Functions

Task

Implement a function named factorial that has one parameter: an integer $n$. It must return the value of $n!$ (i.e., $n$ factorial).

Input Format

Locked stub code in the editor reads a single integer, $n$, from stdin and passes it to a function named factorial.

Constraints

$ 1 < n < 10 $

Output Format

The funciton must return the value of $n!$.

Input

4

Output

24

Explanation

we return the value of $4! = 4 * 3 * 2 * 1 = 24$

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}
/*
 * Create the function factorial here
 */

function factorial(n) {

    let i, result = n;

    for (i = n -1; i >= 1; i--) {
        result *= i;
    }

    return result;
}


function main() {
    const n = +(readLine());

    console.log(factorial(n));
}

Arithmetic Operators

Arithmetic Operators

Task

Complete the following functions in the editor below:

  1. getArea(length, width): Calculate and return the area of a rectangle having sides $length$ and $width$.
  2. getPerimeter(length, width): Calculate and return the perimeter of a rectangle having sides $length$ and $width$.

The values returned by these functions are printed to stdout by locked stub code in the editor.

Input Format

Constrains

  • $ 1 < length, width < 1000$
  • $length$ and $width$ are scaled to at most three decimal places.

Output Format

Function Retunr type Description
getArea Number The area of a rectangle having sides $length$ and $width$.
getPerimeter Number The perimeter of a rectangle having sides $length$ and $width$.

Input

3
4.5

Output

13.5
15

Explanation

The area of the rectangle is $length * width = 3 * 4.5 = 13.5$ The perimeter of the rectangle is $2 (length + width) = 2 (3 + 4.5) = 15$

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/**
*   Calculate the area of a rectangle.
*
*   length: The length of the rectangle.
*   width: The width of the rectangle.
*   
*	Return a number denoting the rectangle's area.
**/
function getArea(length, width) {
    let area = length * width;
    // Write your code here

    return area;
}

/**
*   Calculate the perimeter of a rectangle.
*
*	length: The length of the rectangle.
*   width: The width of the rectangle.
*   
*	Return a number denoting the perimeter of a rectangle.
**/
function getPerimeter(length, width) {
    let perimeter = 2 * (length + width);
    // Write your code here

    return perimeter;
}

Hello, World

Hello, World

Overview: 10 Days of JavaScript

This series focuses on learning and practicing JavaScript. Each challenge comes with a tutorial article, and you can view these articles by clicking either the Topics tab along the top or the article icon in the right-hand menu.

Objective

In this challenge, we review some basic concepts that will get you started with this series. Check out the tutorial to learn more about JavaScript’s lexical structure.

Task

A greeting function is provided for ou in the editor below. It has one parameter, $parameter Variable$. Perform the following tasks to complete this challenge:

  1. Use $console.log()$ to print ‘Hello, World!’ on a new line in the console, which is also known as stdout or standard output. The code for this portion of the task is already provided in the editor.
  2. Use $console.log()$ to print the contents of $parameter Variable$ ($i.e:$ the argument passed to main). You’ve got this!

Input Format

Data Type Parameter Description
string $parameter Variable$ A single line of text containing one or more space-separated words.

Outpur Format

print the following two lines of output:

  1. On the first line, print ‘Hello, World!’ (this is provided for you in the editor)
  2. On the second line, print the contents of $parameter Variable$.

Input

Welcome to 10 Days of Javascript!

Output

Hello, World!
Welcome to 10 Days of Javascript!

Explanation

We print two lines of output:

  1. We printed the literal string $Hello, World!$ using the code provided in the Editor
  2. the value of $parameter Variable$ passed to our main function in this Sample case was ‘Welcome to 10 Days of Javascript!’. We then passed our variable to console.log, which printed the contents of $parameter Variable$.

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/**
*   A line of code that prints "Hello, World!" on a new line is provided in the editor.
*   Write a second line of code that prints the contents of 'parameterVariable' on a new line.
*
*	Parameter:
*   parameterVariable - A string of text.
**/
function greeting(parameterVariable) {
    // This line prints 'Hello, World!' to the console:
    console.log('Hello, World!');

    // Write a line of code that prints parameterVariable to stdout using console.log:
    console.log(parameterVariable);

}

Javascript Data Types

Data Types

Task

Variables named $firstInteger$, $firstDecimal$ and $firstString$ are declared for you in the editor below. You must use the $+$ operator to perform the following sequence of operations:

  1. Convert $secondInteger$ to an integer(Number type), then sum it with $firstInteger$ and print the result on a new line using console.log()

  2. Convert $secondInteger$ to an floating-point number (Number type), then sum it with $firstDecimal$ and print result on a new line using console.log()

  3. Print the concatenation of $firstString$ and $secondString$ on a new line using console.log(). Note that $firstString$ must be printed first.

Input Format

Data Type Parameter Description
string $secondInteger$ The string representation an integer you must sum with $firstInteger$.
string $secondDeciaml$ The string representation of a floating-point number you must sum with $firstDecimal$
string $secondString$ A string of one or more space-separated word you must append to $secondString$

Output Format

print the following three line of output:

  1. On the first line, print the sum of $firstInteger$ and the integer representation of $secondInteger$.
  2. On the second line, print the sum of $firstDecimal$ and the floating-point representation of $secondDeciaml$.
  3. On the third line, print $firstString$ concatenated with $secondString$. You must print $firstString$ before $secondString$.

Input

12
4.32
is the best place to learn and practice coding!

Output

16
8.32
HackerRank is the best place to learn and practice coding!

Dev

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();    
});

function readLine() {
    return inputString[currentLine++];
}

/**
*   The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them.
*   Print three lines:
*   1. The sum of 'firstInteger' and the Number representation of 'secondInteger'.
*   2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'.
*   3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first).
*
*	Parameter(s):
*   secondInteger - The string representation of an integer.
*   secondDecimal - The string representation of a floating-point number.
*   secondString - A string consisting of one or more space-separated words.
**/
function performOperation(secondInteger, secondDecimal, secondString) {
    // Declare a variable named 'firstInteger' and initialize with integer value 4.
    const firstInteger = 4;

    // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0.
    const firstDecimal = 4.0;

    // Declare a variable named 'firstString' and initialize with the string "HackerRank".
    const firstString = 'HackerRank ';

    // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number        type) on a new line.
    console.log(firstInteger + parseInt(secondInteger));

    // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number            type) on a new line.
    console.log(firstDecimal + parseFloat(secondDecimal));

    // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The        variable 'firstString' must be printed first.
    console.log(firstString + secondString);
}

Time Conversion

Time Conversion

https://www.hackerrank.com/challenges/time-conversion/problem?h_r=next-challenge&h_v=zen

Given a time in $12$-hour AM/PM format, convert it to military (24-hour) time.

Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

s: a string representing time in 12 hour format

Input Format

A single string $8$ containing a time in $12$-hour clock format($i.e$: $hh:mm:ssAM$ or $hh:mm:ssPM$), where $01 ≤ hh ≤ 12$ and $00 ≤ mm, ss ≤ 59$

Constraints

All input times are vaild

Output Format

Convert and print the given time in $24-$hour format, where $00 ≤ hh ≤ 23$.

Input

07:05:45PM

Output

19:05:45

Dev

import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    /*
     * Complete the timeConversion function below.
     */
    static String timeConversion(String s) {

        // time split hh mm ss
        String[] timeArr = s.split(":");
        int hour = Integer.parseInt(timeArr[0]) + 12;

        // check 'PM' or 'AM'
        if (timeArr[2].contains("PM")) {    

            if (hour == 24) timeArr[0] = "12";
            else timeArr[0] = Integer.toString(hour);
        } else {

            if (hour == 24) timeArr[0] = "00";
        }

        // delete text 'PM' or 'AM'
        timeArr[2] = timeArr[2].substring(0, 2);

        // return conversion time
        return timeArr[0] + ":" + timeArr[1] + ":" + timeArr[2];
    }

    private static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s = scan.nextLine();

        String result = timeConversion(s);

        bw.write(result);
        bw.newLine();

        bw.close();
    }
}

Conclusion

코드가 조금 지저분해보여서 다시 한번 정리해봐야할 필요성이 있음

Birthday Cake Candles

Birthday Cake Candles

https://www.hackerrank.com/challenges/birthday-cake-candles/problem

You are in charge of the cake for your niece’s birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 4, 4, 1, 2, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are 2 such candles.

Function Description

Complete the function birthday Cake Canles in the editor below. It must return an integer representing the number of candles she can blow out. birthday cake candles has the following parameter(s):

  • ar: an array of integers representing candle heights

Input Format

the first line contains a single integer, $n$, denoting the number of candles on the cake. the second line contains $n$ space-separated integers, where each integer $i$ describes the height of candle $i$.

Constraints

  • $ 1 ≤ n ≤ 10^5$
  • $ 1 ≤ ar[i] ≤ 10^7$

Output Format

Return the number of canles that can be blown out on a new line.

Input

4
3 2 1 3

Output

2

Explanation

We have on candle of height $1$, one candle of height $2$, and two candles of height $3$. Your niece only blows out the tallest candles, meaning the cnadles where $height = 3$. Because there are $2$ such candles, we print $2$ on a new line.

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the birthdayCakeCandles function below.
    static int birthdayCakeCandles(int[] ar) {

        int maxValue = 0, count = 0;

        for (int i : ar) {
            if (i > maxValue) maxValue = i;
        }

        for (int i : ar) {
            if ( i == maxValue) count++;
        }

        return count;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int arCount = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] ar = new int[arCount];

        String[] arItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < arCount; i++) {
            int arItem = Integer.parseInt(arItems[i]);
            ar[i] = arItem;
        }

        int result = birthdayCakeCandles(ar);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

Conclusion

문제는 너무 간단했지만, 문제를 해석하고, 이해하는데 시간이 많이 걸렸습니다.

Mini Max Sum

Mini-Max Sum

https://www.hackerrank.com/challenges/mini-max-sum/problem

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

For example, $ arr = [1, 3, 5, 7, 9] $ . Our minimum sum is $ 1 + 3 + 5 + 7 $ and our maximum sum is $ 3 + 5 + 7 + 9 $. We would print

16 24

Function Description

Complete the miniMaxSum function in the editor below. It should print two space-separated integers on one line: the minimum sum and the maximum sum of $ 4 $ of $ 5 $ elements.

miniMaxSum has the following parameter(s):

arr: an array of $ 5 $ integers

Input Format

A single line of five space-separated integers.

Constraints

$ 1 ≤ arr[i] ≤ 10^9 $

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

Input

1 2 3 4 5

Output

10 14

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the miniMaxSum function below.
    static void miniMaxSum(int[] arr) {

        // max, min value set
        int maxNum = 0, minNum = (int)Math.pow(10, 9);
        long sum = 0;

        // find max, min & sum
        for (int i : arr) {

            if (i > maxNum) maxNum = i;
            if (i < minNum) minNum = i;

            sum += i;
        }

        // calculated
        System.out.printf("%d %d", sum - maxNum, sum - minNum);
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int[] arr = new int[5];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < 5; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        miniMaxSum(arr);

        scanner.close();
    }
}

Conclusion

탐색 알고리즘 없이 간단하게 값을 계산하였다.

알고리즘 공부를 하면서 가장 고민되는 것이 이러한 상황에 선택에 기로가 생기는게 아닌가 싶다.

탐색 알고리즘 사용 우뮤에 따라서 효율성, 또는 성능 및 속도가 차이가 날것이기 때문에 고민이 된다.

답만 내는 코딩보다는 과정을 계속 고민해 보는 좋은 경험이 된다.

그리고 마지막 계산에 대해서 데이터 타입에 대한 고민이 반드시 필요한 과제였다.

Staircase

Staircase

https://www.hackerrank.com/challenges/staircase/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen

Consider a staircase of size : $n = 4$

    #
   ##
  ###
 ####

Observe that its base and height are both equal to $n$, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces.

Write a program that prints a staircase of size $n$.

Input

6

Output

     #
    ##
   ###
  ####
 #####
######

Explanation

The staircase is right-aligned, composed of # symbols and spaces, and has a height and width $n = 6$.

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the staircase function below.
    static void staircase(int n) {

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (n-i-1 > j) System.out.print(" ");
                else System.out.print("#");  

            }
            System.out.println();
        }
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        staircase(n);

        scanner.close();
    }
}

Plus Minus Zero

Plus Minus Zero

Input

6
-4 3 -9 0 4 1

Output

0.500000
0.333333
0.166667

Explanation

There are $3$ positive numbers $2$, negative numbers, $1$ and zero in the array. The proportions of occurrence are positive: ${3\over 6} = 0.500000$ , negative: ${2\over 6} = 0.333333$ and zeros: ${1\over 6} = 0.166667$.

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the plusMinus function below.
    static void plusMinus(int[] arr) {

        double     arrLength = arr.length;
        double  positive = 0, negative = 0, zero = 0;


        for (int i = 0; i < arrLength; i++) {
            if      (arr[i] > 0) positive += 1/arrLength;
            else if (arr[i] < 0) negative += 1/arrLength;
            else                 zero     += 1/arrLength;
        }

        System.out.println(String.format("%.6f", positive));
        System.out.println(String.format("%.6f", negative));
        System.out.println(String.format("%.6f", zero));

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        plusMinus(arr);

        scanner.close();
    }
}

Conclusion

양수, 음수, 0 3가지의 백분률을 출력하는 간단한 문제로 3가지의 확률이 1이 넘으면 안되기 때문에 마지막에 출력을 할 때, 소수점 마지막 자리가 신경이 쓰였다.

처음에는 확률이 1이 넘는지를 확인해서 넘으면 소수점 처리를 해주려고 했는데, 자바에서 자동으로 자리수를 자르니까 소수점을 반올림해주어 문제가 생기지 않았다.

생각보다 간단한 문제도 고민을 해야하는 부분이 많은게 흥미롭다.

Diagonal Difference

Diagonal Difference

https://www.hackerrank.com/challenges/diagonal-difference/problem

Input

3
11 2 4
4 5 6
10 8 -12

Output

15

Explanation

The primary diagonal is:

11
   5
     -12

Sum across the primary diagonal: 11 + 5 - 12 = 4

The secondary diagonal is:

     4
   5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19 Difference: |4 - 19| = 15

Dev

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'diagonalDifference' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts 2D_INTEGER_ARRAY arr as parameter.
     */

    public static int diagonalDifference(List<List<Integer>> arr) {

        int arrLength = arr.size(); // input arr size
        int primaryDiag = 0, secondDiag = 0;

        for (int i = 0; i < arrLength; i++) {
            primaryDiag += arr.get(i).get(i);
            secondDiag  += arr.get(arrLength - 1 - i).get(i);
        }

        return Math.abs(primaryDiag - secondDiag);
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<List<Integer>> arr = new ArrayList<>();

        IntStream.range(0, n).forEach(i -> {
            try {
                arr.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        int result = Result.diagonalDifference(arr);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Very Big Sum

아직은 기초 알고리즘이지만, 간단한 로직 보다 더 효율적인 로직을 생각하려고 노력하다 보니 은근히 결과가 신경쓰인다.

Very Big Sum

https://www.hackerrank.com/challenges/a-very-big-sum/problem

Input Format

Output

Code

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the aVeryBigSum function below.
    static long aVeryBigSum(long[] ar) {

        long resultValue = 0;

        for (int i = 0; i < ar.length; i++) {
            resultValue += ar[i];
        }

        return resultValue;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int arCount = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        long[] ar = new long[arCount];

        String[] arItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < arCount; i++) {
            long arItem = Long.parseLong(arItems[i]);
            ar[i] = arItem;
        }

        long result = aVeryBigSum(ar);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

Compare The Triplets

카카오 코딩 테스트를 계기로 알고리즘 공부를 시작했다. 개인적인 기록과 블로그 포스팅 겸 정리해서 올려보려고 한다.

Compare the Triplets

https://www.hackerrank.com/challenges/compare-the-triplets/problem

Input Format

Output Result

Dev Code

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {

    // Complete the compareTriplets function below.
    static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) {

        List<Integer> scoreResult = new ArrayList<Integer>();
        int aScore = 0, bScore = 0;

        if (a.size() == b.size()) {
            for (int i = 0; i < a.size(); i++) {
                if (a.get(i) > b.get(i)) {
                    aScore++;
                } else if (a.get(i) < b.get(i)) {
                    bScore++;
                }
            }
        }

        scoreResult.add(aScore);
        scoreResult.add(bScore);

        return scoreResult;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> b = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> result = compareTriplets(a, b);

        bufferedWriter.write(
            result.stream()
                .map(Object::toString)
                .collect(joining(" "))
            + "\n"
        );

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Conclusion

Java8에 대한 개념이 없어 코드가 굉장히 어렵게 보인다. Java8에 어떤 기능이 추가됬으며, 무엇이 강점인지 찾아보고, Java8 부터 14버전까지 Java의 새로운 개념들에 대해 학습을 시작했다.