일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 항해99
- redux-saga
- axios
- 테코테코
- Get
- useDispatch
- react-router
- json-server
- programmers
- react-redux
- createSlice
- maeil-mail
- 이코테
- 프로그래머스
- Algorithm
- 항해플러스
- SW
- C++
- sw expert academy
- 알고리즘
- JavaScript
- 매일메일
- redux
- redux-toolkit
- 자바
- react
- 코딩테스트합격자되기
- Python
- 리액트
- java
- Today
- Total
Binary Journey
[프로그래머스] 직사각형 별찍기 본문
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
** Java
Java로는 다음과 같이 작성하였다.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
System.out.printf("*");
}
System.out.println();
}
}
}
대략 1800명이 같은 풀이로 통과하였다.
다른 풀이 중 추천을 가장 많이 받은 풀이를 보면
import java.util.Scanner;
import java.util.stream.IntStream;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
StringBuilder sb = new StringBuilder();
IntStream.range(0, a).forEach(s -> sb.append("*"));
IntStream.range(0, b).forEach(s -> System.out.println(sb.toString()));
}
}
* StringBuilder
일반적으로 String 은 immutable(불변) 의 특성을 가지고 있어서 문자열을 인스턴스를 한 번 생성하고 나면 문자열 값을 변경하지 못한다.
따라서 편집이 필요할 경우 기존 값을 버리고 새로운 변수에 값을 할당해야 하는데 이 경우 능률성이 매우 낮아진다.
StringBuilder와 StringBuffer 는 이를 보완하기 위해 만들어진 클래스 중 하나라고 한다.
StringBuilder 생성 목적에 맞게 같은 인스턴스 안의 문자열에 필드 값을 추가하거나 변경이 가능하다고 한다.
String 클래스의 메소드는 물론 문자열 추가 혹은 변경을 위한 추가 메소드를 가지고 있다.
그 중 append() 는 문자열을 뒤로 추가해 나가는 메소드이다.
참고:
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
StringBuilder (Java Platform SE 7 )
Inserts the string into this character sequence. The characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by
docs.oracle.com
* IntStream
IntStream 의 경우 primitive Data인 int를 스트림으로 다루는 것을 가능케 한다고 한다.
IntStream.of(1, 2, 3, 4);
와
IntStream.range(1, 5);
는 똑같이 1, 2, 3, 4 에 대한 int 스트림을 생성한다.
반면
IntStream.of(1, 2, 3, 4, 5);
와
IntStream.rangeClose(1, 5);
는 1, 2, 3, 4, 5 에 대한 int 스트림을 생성한다.
range 와 rangeClose 를 잘 구별하자.
이렇게 생성된 값들은 stream 메소드들을 사용할 수 있다. iterator, anyMatch, noneMatch, filter 등이 가능하다.
참고:
https://blog.daum.net/oraclejava/15874666
[자바8강좌,int스트림]JAVA8, IntStream, of, range, rangeClosed, filter
[자바8강좌,int스트림]JAVA8, IntStream, of, range, rangeClosed, filter 자바8에 추가된 IntStream은 원시데이터형 int를 스트림으로 다룰수 있도록 해주는데 java.util.stream 패키지에는 스트림관련 API들이..
blog.daum.net
https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
IntStream (Java Platform SE 8 )
Returns an infinite sequential ordered IntStream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. The first element (position 0) in the IntStream will be the prov
docs.oracle.com
** Javascript
javascript 로도 풀어보았다.
(원래도 이랬는지 모르겠는데 저장되어있는 풀이가 이렇게 되어있다.)
process.stdin.setEncoding('utf8');
process.stdin.on('data', data => {
const n = data.split(" ");
const a = Number(n[0]), b = Number(n[1]);
for (var i = 0; i < b; i++) {
var answer = "";
for (var j = 0; j < a; j++) {
answer += "*";
}
console.log(answer);
}
});
위와 같이 작성하였다.
추천을 많이 받은 다른 사람의 풀이를 보면 신박한 것을 볼 수 있는데
process.stdin.setEncoding('utf8');
process.stdin.on('data', data => {
const n = data.split(" ");
const a = Number(n[0]), b = Number(n[1]);
const row = '*'.repeat(a)
for(let i =0; i < b; i++){
console.log(row)
}
});
repeat()이란 함수를 사용한 것이다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
String.prototype.repeat() - JavaScript | MDN
repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.
developer.mozilla.org
해설을 보면 python 에서 문자열 * 숫자 처럼 사용할 수 있다.
** Python
a, b = map(int, input().strip().split(' '))
for i in range(b):
print(a * "*")
문자열에 숫자를 곱하여 출력할 수 있는 파이썬의 특징상 이렇게도 쓸 수 있다.
(추천수가 가장 높은 풀이다.)
a, b = map(int, input().strip().split(' '))
answer = ('*'*a +'\n')*b
print(answer)
'프로그래머스 > level 1' 카테고리의 다른 글
[프로그래머스] 정수 제곱근 판별 (0) | 2021.07.22 |
---|---|
[프로그래머스] 숫자 문자열과 영단어 (0) | 2021.07.21 |
[프로그래머스] 문자열 내림차순으로 배치하기 (0) | 2021.07.21 |
[프로그래머스] 문자열 내 마음대로 정렬하기 (0) | 2021.07.21 |
[프로그래머스] x만큼 간격이 있는 n개의 숫자 (0) | 2021.07.20 |