- 사용 라이브러리 :
h2
,spring web
,Lombok
,Thymleaf
,Jpa
package com.sparta.myselectshopbeta.naver.controller;
import com.sparta.myselectshopbeta.naver.dto.ItemDto;
import com.sparta.myselectshopbeta.naver.service.NaverApiService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class NaverApiController {
private final NaverApiService naverApiService;
@GetMapping("/search")
public List<ItemDto> searchItems(@RequestParam String query) {
return naverApiService.searchItems(query);
}
}
package com.sparta.myselectshopbeta.naver.service;
import com.sparta.myselectshopbeta.naver.dto.ItemDto;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class NaverApiService {
public List<ItemDto> searchItems(String query) {
RestTemplate rest = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("X-Naver-Client-Id", "ufC7iCHE1eRqXFSjFmTu");
headers.add("X-Naver-Client-Secret", "26mXWwGwvw");
String body = "";
HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
ResponseEntity<String> responseEntity = rest.exchange("https://openapi.naver.com/v1/search/shop.json?display=15&query=" + query , HttpMethod.GET, requestEntity, String.class);
HttpStatus httpStatus = responseEntity.getStatusCode();
int status = httpStatus.value();
log.info("NAVER API Status Code : " + status);
String response = responseEntity.getBody();
return fromJSONtoItems(response);
}
public List<ItemDto> fromJSONtoItems(String response) {
JSONObject rjson = new JSONObject(response);
JSONArray items = rjson.getJSONArray("items");
List<ItemDto> itemDtoList = new ArrayList<>();
for (int i=0; i<items.length(); i++) {
JSONObject itemJson = items.getJSONObject(i);
ItemDto itemDto = new ItemDto(itemJson);
itemDtoList.add(itemDto);
}
return itemDtoList;
}
}
RestTemplate
: Spring에서 지원하는 객체로 간편하게 Rest 방식 API를 호출할 수 있는 Spring 내장 클래스이다.HttpHeaders
: 찾아보진 않았지만 요청 시 Header에 추가할 값을 담아놓는 객체일 것 같다.HttpEntity
: HttpEntity클래스는 HTTP요청또는 응답에 해당하는 HttpHeader와 HttpBody를 포함하는 클래스다.
-> 아직 어떠한 객체가 어떤 상황에서 필요하며, 정확히 사용할 수는 없지만, naverApi의 규칙에 따른 url과 header 값에 부여 받은 id와 secret을 대입하여 받은 response를 Json타입으로 변환 하여 매핑 이름이 같은 DTO를 List<>형식으로 반환해주는 것 같다!!
-> 참고로 http://localhost:8080은 API권한 받을 때 넣어줘서 가능함..!
package com.sparta.myselectshopbeta.naver.dto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.json.JSONObject;
@Getter
@NoArgsConstructor
public class ItemDto {
private String title;
private String link;
private String image;
private int lprice;
public ItemDto(JSONObject itemJson) {
this.title = itemJson.getString("title");
this.link = itemJson.getString("link");
this.image = itemJson.getString("image");
this.lprice = itemJson.getInt("lprice");
}
}
- Maven Repository : https://mvnrepository.com/
quiz
에는 덧셈 뺄셈 수식이 들어있다.- 수식이 옳다면 O, 아니면 X를 순서대로 반환하는 배열을 리턴해라!
- 출력예시
quiz | result |
---|---|
["3 - 4 = -3", "5 + 6 = 11"] | ["X", "O"] |
["19 - 6 = 13", "5 + 66 = 71", "5 - 15 = 63", "3 - 1 = 2"] | ["O", "O", "X", "O"] |
class Solution {
public String[] solution(String[] quiz) {
String[] answer = new String[quiz.length];
for (int i = 0; i < quiz.length; i++) {
String[] split = quiz[i].trim().split(" ");
int cumulate = Integer.parseInt(split[0]);
for (int j = 1; j < split.length; j += 2) {
if (split[j].equals("+")) {
cumulate += Integer.parseInt(split[j + 1]);
} else {
cumulate -= Integer.parseInt(split[j + 1]);
}
}
answer[i] = cumulate == 0 ? "O" : "X";
}
return answer;
}
}
- 솔직히 혼자 다 풀지는 못했지만 연산자 사이에는 공백이 들어간다는 힌트로 잘라서 작업을 했다.
- 코드가 지저분해서 다른 사람의 코드를 보고 이해한 것을 바탕으로 작성했다.
- 지뢰는 2차원 배열
board
에 1로 표시,board
에는 지뢰가 매설 된 지역 1과 , 지뢰가 없는 지역 0 이 존재한다.- 지뢰가 매설된 지역의 지도
board
가 매개변수로 주어질 때, 안전한 지역의 칸 수를 return
- 출력예시
board | result |
---|---|
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]] | 16 |
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0]] | 13 |
[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]] | 0 |
class Solution {
//지뢰가 있는 지역 기준 좌우 대각선 전부 위험 지대로 판단한다
// 지뢰는 2차원 배열 board에 1로 표시되어있고, board에는 지뢰가 매설된 지역 1과 지뢰가 없는 지역0만 존재한다.
//지뢰가 매설되어 있는 지역의 지도 board가 매개변수로 주어질 때 안전한 지역의 칸수를 return
public int solution(int[][] board) {
int count = 0;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
if(board[i][j]==1){
if(i!=0 && board[i-1][j]!=1){
board[i-1][j]=2;
}
if(i!=board.length-1&&board[i+1][j]!=1){
board[i+1][j]=2;
}
if(j!=0&&board[i][j-1]!=1){
board[i][j-1]=2;
}
if(j!=board.length-1&&board[i][j+1]!=1){
board[i][j+1] = 2;
}
if(j!=0&&i!=0&&board[i-1][j-1]!=1){
board[i-1][j-1] = 2;
}
if(j!=board.length-1&&i!=0&&board[i-1][j+1]!=1){
board[i-1][j+1] = 2;
}
if(j!=0&&i!=0&&board[i-1][j-1]!=1){
board[i-1][j-1] = 2;
}
if(i!=board.length-1&&j!=0&&board[i+1][j-1]!=1){
board[i+1][j-1] = 2;
}
if(i!=board.length-1&&j!=0&&board[i+1][j-1]!=1){
board[i+1][j-1]=2;
}
if(i!=board.length-1&&j!=board.length-1&&board[i+1][j+1]!=1){
board[i+1][j+1] = 2;
}
}
}
}
for(int i = 0;i<board.length;i++){
for(int j=0;j<board.length;j++){
if(board[i][j]==0){
System.out.print(board[i][j]);
count++;
}
}
System.out.println();
}
return count;
}
}
- 문제 푸는데 시간이 오래 걸렸다....Level0인데..아직 많이 부족하다
- 이 문제는 솔직히 케이스를 하나씩 다 대입 해보면서 if조건을 추가했다.