Created
July 9, 2020 22:22
-
-
Save escalonn/d1c9f2d7c5b97c81c5a57e67e7c5b763 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
class Solution { | |
/* provided template code above. discouraged from editing, so we're not expected | |
to need System.Threading.Tasks. */ | |
/* | |
* Complete the function below. | |
* https://jsonmock.hackerrank.com/api/countries/search?name= | |
*/ | |
static int getCountries(string s, int p) { | |
var count = 0; | |
var baseUrl = $"https://jsonmock.hackerrank.com/api/countries/search?name={s}"; | |
using (var httpClient = new HttpClient()) | |
{ | |
var json = httpClient.GetStringAsync(baseUrl).Result; | |
var obj = JObject.Parse(json); | |
var totalPages = (int)obj["total_pages"]; | |
count += obj["data"].Count(x => (long)x["population"] > p); | |
var countTasks = new List<System.Threading.Tasks.Task<int>>(); | |
for (var page = 2; page <= totalPages; page++) | |
{ | |
var url = $"{baseUrl}&page={page}"; | |
// i tried a few different combinations here. Task.Run doesn't make sense for I/O bound operations | |
// but it seemed to timeout less anyway (??) | |
countTasks.Add(System.Threading.Tasks.Task.Run(() => httpClient.GetStringAsync(url).ContinueWith(antecedent => | |
{ | |
var obj2 = JObject.Parse(antecedent.Result); | |
return obj2["data"].Count(x => (long)x["population"] > p); | |
}))); | |
} | |
foreach (var countTask in countTasks) | |
{ | |
count += countTask.Result; | |
} | |
} | |
return count; | |
} | |
/* provided template code below. discouraged from editing, so we're not expected | |
to make it an async function. */ | |
static void Main(String[] args) { | |
string fileName = System.Environment.GetEnvironmentVariable("OUTPUT_PATH"); | |
TextWriter tw = new StreamWriter(@fileName, true); | |
int res; | |
string _s; | |
_s = Console.ReadLine(); | |
int _p; | |
_p = Convert.ToInt32(Console.ReadLine()); | |
res = getCountries(_s, _p); | |
tw.WriteLine(res); | |
tw.Flush(); | |
tw.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment