[ 프로그래머스 ]
- 삼각형의 완성조건(2)
: for, while에서 벗어나지 못하기.. stream 어케 하는 것임★
import java.util.Arrays;
class Solution {
public int solution(int[] sides) {
Arrays.sort(sides);
int small = sides[0];
int large = sides[1];
int x=1;
int answer = 0;
while(true){
if(x<=large && large<x+small) answer++;
else if(x>large && x<large+small) answer++;
else if(x>large && x>=large+small) break;
x++;
}
return answer;
}
}
- 외계어 사전
: 스트림으로 풀어서 뿌듯함,, 🌷
먼저 길이로 필터링하고, split() 메서드로 각 요소를 배열로 쪼갠 다음,
리스트로 변환해서 containsAll() 메서드로 모든 요소를 포함하는 것만 다시 필터링하여, 남은 사이즈가 있는지로 리턴값 확인.
삼항연산자도 활용해서 코드 길이 줄였다.
import java.util.*;
import java.util.stream.*;
import java.util.Arrays;
class Solution {
public int solution(String[] spell, String[] dic) {
List<String[]> dicList = Arrays.stream(dic)
.filter(i->i.length()==spell.length)
.map(i->i.split(""))
.filter(a->Arrays.asList(a).containsAll(Arrays.asList(spell)))
.collect(Collectors.toList());
return dicList.size()>0?1:2;
}
}
- 평균 구하기
: 스트림은 역시 잘만 쓰면 편하다.
그런데 import 경로 외우는 거 너무 헷갈림,, 메서드랑 임포트 경로 검색 없이 어떻게 코테봄..?
import java.util.stream.IntStream;
class Solution {
public double solution(int[] arr) {
return IntStream.of(arr).average().getAsDouble();
}
}
- 자릿수 더하기
: 다른 사람들 풀이 보니까, 나머지(%) 이용해서 타입 변환 없이 푸는 게 훨씬 효율적인 코드인 것 같음.
import java.util.*;
public class Solution {
public int solution(int n) {
String str = String.valueOf(n);
int sum = 0;
for(int i=0; i<str.length(); i++){
sum += str.charAt(i)-'0';
}
return sum;
}
}