코테 준비 | Draw The Triangle 1/Draw The Triangle 2 (SET @ / REPEAT)

2025. 2. 10. 10:56·SQL
 

Draw The Triangle 1 | HackerRank

Draw the triangle pattern using asterisks.

www.hackerrank.com

☑️  Draw The Triangle 1

[문제]

  • '*' 특수문자 반복하여 직각 삼각형 구현하는 문제

[문제 풀이]

내 코드

SELECT REPEAT('* ',20) 
UNION ALL SELECT REPEAT('* ',19) UNION ALL SELECT REPEAT('* ',18) UNION ALL SELECT REPEAT('* ',17) 
UNION ALL SELECT REPEAT('* ',16) UNION ALL SELECT REPEAT('* ',15) UNION ALL SELECT REPEAT('* ',14)
UNION ALL SELECT REPEAT('* ',13) UNION ALL SELECT REPEAT('* ',12) UNION ALL SELECT REPEAT('* ',11)
UNION ALL SELECT REPEAT('* ',10) UNION ALL SELECT REPEAT('* ',9) UNION ALL SELECT REPEAT('* ',8)
UNION ALL SELECT REPEAT('* ',7) UNION ALL SELECT REPEAT('* ',6) UNION ALL SELECT REPEAT('* ',5) 
UNION ALL SELECT REPEAT('* ',4) UNION ALL SELECT REPEAT('* ',3) UNION ALL SELECT REPEAT('* ',2) 
UNION ALL SELECT REPEAT('* ',1)

 

수정 코드 

SET @num = 21;
SELECT REPEAT('* ', @num:=@num-1)
FROM information_schema.tables
LIMIT 20;

 

이슈 및 해결 과정

  • 아이디어 : REPEAT 함수 & UNION ALL 병합
    • REPEAT 함수 활용하여 '*' 개별 행 생성 
    • UNION ALL 로 병합
    • 정답으로 처리 되나, 코드 중복 & 깔끔하지 못한 쿼리 
  • 수정 아이디어 :  SET @(사용자 정의 함수) & REPEAT 활용
    • `SET @`  : 사용자 정의 변수 (user-defined Variable) 할당 해 주는 로컬 함수 활용
    • `SET @num =21` ; num 로컬 변수에 초기값 21 할당
    • REPEAT('* ', @num := @num-1) : 로컬 변수에 num-1 재 할당 및 repeat 값 출력
    • LIMIT 으로 출력 행 수 조절 
    • FROM inoformation_schema.tables : 테이블 명이 없으면 LIMIT이 작동하지 않기 때문에, 임의로 모든 데이터베이스의 테이블 정보를 포함하고 있는 시스템 뷰 사용

 

 

Draw The Triangle 2 | HackerRank

Draw the triangle pattern using asterisks.

www.hackerrank.com

 

☑️  Draw The Triangle 2

[문제]

[문제 풀이]

내 코드

SET @num = 0;
SELECT REPEAT('* ', @num:=@num+1)
FROM information_schema.tables
LIMIT 20;

➡️ SET @ (사용자 정의 함수)

  • SET : 다양한 유형의 변수에 값을 할당해주는 함수
  • 사용자 변수는 세션내에서 로컬로 생성되기 때문에 세션내에서만 활용 가능 (=세션 종료시 사라짐)
  • 다양한 형태 값을(단일값 ~ 스칼라 서브쿼리) 저장할 수 있고, 그 값을 연산에 활용도 가능  
  • 변수 할당 연산자는  `=`  or `:=`  
-- 1. 변수 할당 : num 변수에 43 저장
SET @num = 43;

-- 2. 변수 할당 : total_tax 에 스칼라 서브쿼리 저장
SET @total_tax = (SELECT SUM(tax) FROM taxable_transactions);

-- 3. 변수 할당 : 연산자 활용
SELECT num := 43;

--4. 변수 사용 
SET @avg_tax = 100;
SELECT *
FROM taxable_transactions
WEHRE tax >= @avg_tax;

➡️ REPEAT ( 문자열 반복 함수)

  • REPEAT(str, count) : 문자열(str) , count 번 반복해주는 함수
SELECT REPEAT('MYSQL',2);

# 출력
-- MYSQLMYSQL

 

 

MySQL :: MySQL 8.4 Reference Manual :: 28.3.38 The INFORMATION_SCHEMA TABLES Table

28.3.38 The INFORMATION_SCHEMA TABLES Table The TABLES table provides information about tables in databases. Columns in TABLES that represent table statistics hold cached values. The information_schema_stats_expiry system variable defines the period of ti

dev.mysql.com

▲ INFORMATION_SCHEMA TABLES Table 

 

MySQL :: MySQL 8.4 Reference Manual :: 15.7.6.1 SET Syntax for Variable Assignment

15.7.6.1 SET Syntax for Variable Assignment SET variable = expr [, variable = expr] ... variable: { user_var_name | param_name | local_var_name | {GLOBAL | @@GLOBAL.} system_var_name | {PERSIST | @@PERSIST.} system_var_name | {PERSIST_ONLY | @@PERSIST_ONL

dev.mysql.com

 

▲ 사용자 정의 변수 로컬 함수

 

[SQL][해커랭크] Draw The Triangle 1 / SET @, REPEAT

https://www.hackerrank.com/challenges/draw-the-triangle-1/problem?isFullScreen=true Draw The Triangle 1 | HackerRankDraw the triangle pattern using asterisks.www.hackerrank.com 문제P(R) represents a pattern drawn by Julia in R rows. The following patte

geuljeok.tistory.com

▲ 문제풀이 참고

https://dev.mysql.com/doc/refman/8.4/en/repeat.html

 

MySQL :: MySQL 8.4 Reference Manual :: 15.6.5.6 REPEAT Statement

15.6.5.6 REPEAT Statement [begin_label:] REPEAT statement_list UNTIL search_condition END REPEAT [end_label] The statement list within a REPEAT statement is repeated until the search_condition expression is true. Thus, a REPEAT always enters the loop at l

dev.mysql.com

https://dev.mysql.com/doc/refman/8.4/en/string-functions.html

 

MySQL :: MySQL 8.4 Reference Manual :: 14.8 String Functions and Operators

14.8 String Functions and Operators Table 14.12 String Functions and Operators Name Description ASCII() Return numeric value of left-most character BIN() Return a string containing binary representation of a number BIT_LENGTH() Return length of argument

dev.mysql.com

 

▲ REPEAT 함수

'SQL' 카테고리의 다른 글

코테준비 | Top earners/Weather Observation Station 13~18(+해커랭크 SQL 모든 문제 해결 완료)  (0) 2025.02.18
코테준비 | 15 Days of Learning SQL (+해커랭크 고 난이도, where 절 연관 서브쿼리 활용)  (0) 2025.02.13
코테준비 | 해커랭크 interviews (다중 테이블 join)  (0) 2025.02.06
코테준비 | 해커랭크 SQL Project Planning / Placements (연속된 그룹 필터링/다중 JOIN)  (0) 2025.01.31
코테준비 | hackerrank - Challenges (다중컬럼 서브쿼리,CTE)  (0) 2025.01.23
'SQL' 카테고리의 다른 글
  • 코테준비 | Top earners/Weather Observation Station 13~18(+해커랭크 SQL 모든 문제 해결 완료)
  • 코테준비 | 15 Days of Learning SQL (+해커랭크 고 난이도, where 절 연관 서브쿼리 활용)
  • 코테준비 | 해커랭크 interviews (다중 테이블 join)
  • 코테준비 | 해커랭크 SQL Project Planning / Placements (연속된 그룹 필터링/다중 JOIN)
성장하는 쿠키의 로그 기록
성장하는 쿠키의 로그 기록
성장하는 쿠키의 모든 로그를 담습니다.
  • 성장하는 쿠키의 로그 기록
    쿠키 로그
    성장하는 쿠키의 로그 기록
  • 전체
    오늘
    어제
    • 분류 전체보기 (143)
      • TODAY I LEARNED (2)
      • 데이터 분석 (13)
      • SQL (49)
      • PYTHON (39)
      • 통계,검정,머신러닝 (22)
      • TABLEAU (5)
      • 내배캠 | 데이터분석 부트캠프 (12)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    내배캠
    머신러닝
    파이썬
    Python
    코딩테스트준비
    sql코딩테스트
    태블로
    pandas
    오블완
    코테준비
    해커랭크
    프로그래머스
    MySQL
    데이터분석
    데이터리안
    Wil
    티스토리챌린지
    데이터분석가
    SQL
    데이터분석프로젝트
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
성장하는 쿠키의 로그 기록
코테 준비 | Draw The Triangle 1/Draw The Triangle 2 (SET @ / REPEAT)
상단으로

티스토리툴바