HackerRank RestAPI 문제

정상민·2023년 11월 1일

HackerRank Certify에 있는 Rest API(Intermediate) 문제 풀이

구글링 없이 풀 수 있는걸까?

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;


import java.net.*;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
class Result {

    /*
     * Complete the 'getNumDraws' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER year as parameter.
     */
    public static int numDraws(int year) throws Exception {
        String DrawCntByYearUrl = String.format(MATCH_URL+"?year=%d", year, URLEncoder.encode("UTF-8"));
        
        
        return getNumDraws(DrawCntByYearUrl, year, 0, 1);
    }
    private static int getNumDraws(String Url, int year, int totalNumDraws, int page) throws Exception {
        String response = getResponsePerPage(Url, page);
        
        JsonObject jsonResponse = new Gson().fromJson(response, JsonObject.class);
        int totalPages = jsonResponse.get("total_pages").getAsInt();
        JsonArray data = jsonResponse.getAsJsonArray("data");
        for (JsonElement e : data) {
            int team1goals = e.getAsJsonObject().get("team1goals").getAsInt();
            int team2goals = e.getAsJsonObject().get("team2goals").getAsInt();
            if(team1goals == team2goals) totalNumDraws++;
        }
        // System.out.println(String.format(" totalNumDraws: %s and page: %d", totalNumDraws, page));
        return totalPages==page? totalNumDraws : getNumDraws(Url, year, totalNumDraws, page+1);
    }
    
    
    
    private static final String MATCH_URL = "https://jsonmock.hackerrank.com/api/football_matches";
    private static final String COMPETITION_URL = "https://jsonmock.hackerrank.com/api/football_competition";
    
    public static int drawMatches(int year) throws Exception{
        
        int maxGoal = 10;
        int totalMatch=0;
        
        for(int goal=0; goal<=maxGoal; goal++) {
            totalMatch += getDrawMatchbyGoals(MATCH_URL+"?year="+year, goal);
        }
        
        return totalMatch;
    }
    
    private static int getDrawMatchbyGoals(String url, int goal) throws Exception{
        
        String endpoint = String.format(url+"&team1goals=%d&team2goals=%d",goal,goal);
        String response = getResponsePerPage(endpoint, 1);
        
        JsonObject res = new Gson().fromJson(response, JsonObject.class);
        return res.get("total").getAsInt();
    }
    public static int totalGoals(String team, int year) throws Exception {
        
        String team1Url = String.format(MATCH_URL+"?year=%d&team1=%s", year, URLEncoder.encode(team,"UTF-8"));
        String team2Url = String.format(MATCH_URL+"?year=%d&team2=%s", year, URLEncoder.encode(team,"UTF-8"));
        
        return getTeamGoals(team1Url,"team1", 1,0) + getTeamGoals(team2Url,"team2", 1,0);
    }

    private static int getTeamGoals(String teamUrl, String teamtype, int page, int totalGoals) throws Exception {
        
        String response = getResponsePerPage(teamUrl, page);
        
        JsonObject jsonResponse = new Gson().fromJson(response, JsonObject.class);
        int totalPages = jsonResponse.get("total_pages").getAsInt();
        JsonArray data = jsonResponse.getAsJsonArray("data");
        for (JsonElement e : data) {
            totalGoals += e.getAsJsonObject().get(teamtype+"goals").getAsInt();        
        }
        
        return totalPages==page? totalGoals : getTeamGoals(teamUrl, teamtype, page+1, totalGoals);
    }

    private static String getResponsePerPage(String endpoint, int page) throws MalformedURLException, IOException, ProtocolException {
        
        // System.out.println(String.format(" URL: %s and page: %d", endpoint, page));
        
        URL url = new URL(endpoint+"&page="+page);
        HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
        con.setRequestMethod("GET");
        con.addRequestProperty("Content-Type", "application/json");
        
        int status = con.getResponseCode();
        if(status<200 || status>=300) {
            throw new IOException("Error in reading data with status:"+status);
        }
        
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response;
        StringBuilder sb = new StringBuilder();
        while((response = br.readLine())!=null) {
            sb.append(response);
        }
        
        br.close();
        con.disconnect();
        
        return sb.toString();
    }
}
public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

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

        int result = Result.drawMatches(year);

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

        bufferedReader.close();
        bufferedWriter.close();
    }
}
profile
안녕하세요! 개인 공부를 꾸준히 기록하는 공간입니다.

0개의 댓글