-
-
Save andersonmo/614023e814dd0e80436bbf0c91c53516 to your computer and use it in GitHub Desktop.
import java.io.*; | |
import java.util.*; | |
import java.text.*; | |
import java.math.*; | |
import java.util.regex.*; | |
import java.net.*; | |
import com.google.gson.*; | |
//------ My code ----------- | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import java.time.DayOfWeek; | |
import java.time.LocalDate; | |
import java.time.Month; | |
import java.time.format.DateTimeFormatter; | |
import java.time.temporal.TemporalAdjusters; | |
public class Solution { | |
/* | |
* Complete the function below. | |
*/ | |
class Result { | |
int page; | |
int per_page; | |
int total; | |
int total_pages; | |
List<Data> data; | |
} | |
class Data { | |
String date; | |
float open; | |
float close; | |
float high; | |
float low; | |
} | |
static void openAndClosePrices(String firstDate, String lastDate, String weekDay) { | |
LocalDate startDay = LocalDate.of(2000, Month.JANUARY, 5); | |
LocalDate endDay = LocalDate.of(2014, Month.JANUARY, 1); | |
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("d-MMMM-yyyy", Locale.ENGLISH); | |
// | |
try{ | |
LocalDate date01 = LocalDate.parse(firstDate, timeFormat); | |
LocalDate date02 = LocalDate.parse(lastDate, timeFormat); | |
LocalDate tempDate; | |
String[] contWeekDays = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}; | |
if (date01.isBefore(startDay)) { | |
date01 = startDay;} | |
if (date02.isAfter(endDay)) { | |
date02 = endDay;} | |
if(!Arrays.asList(contWeekDays).contains(weekDay)){ | |
System.out.println("Out of parameters."); | |
} else{ | |
do { | |
tempDate = date01.with(TemporalAdjusters.nextOrSame(DayOfWeek.valueOf(weekDay.toUpperCase()))); | |
URL dataEntry = new URL("https://jsonmock.hackerrank.com/api/stocks/?date="+timeFormat.format(tempDate)); | |
InputStreamReader reader = new InputStreamReader(dataEntry.openStream()); | |
Result result = new Gson().fromJson(reader, Result.class); | |
if ( result.total == 0){ | |
date01 = tempDate.plusWeeks(1); | |
}else { | |
for (Data datas : result.data) { | |
System.out.println(datas.date + " " + datas.open + " " + datas.close); | |
date01 = tempDate.plusWeeks(1); | |
} | |
} | |
}while (date01.isBefore(date02)); | |
} | |
} catch (Exception ex){} | |
} | |
//---- End of my code ---- | |
public static void main(String[] args){ | |
Scanner in = new Scanner(System.in); | |
String _firstDate; | |
try { | |
_firstDate = in.nextLine(); | |
} catch (Exception e) { | |
_firstDate = null; | |
} | |
String _lastDate; | |
try { | |
_lastDate = in.nextLine(); | |
} catch (Exception e) { | |
_lastDate = null; | |
} | |
String _weekDay; | |
try { | |
_weekDay = in.nextLine(); | |
} catch (Exception e) { | |
_weekDay = null; | |
} | |
openAndClosePrices(_firstDate, _lastDate, _weekDay); | |
} | |
} |
String[] contWeekDays = {"Monday","Tuesday","Wednesday","Thursday","Fryday","Saturday","Sunday"};
It should be "Friday", as per the question. Your solution had some partial failures, do not know why.
Can you please point out failures in my sol. It passed 4/10 with partial failure in 1.
My Solution:
`
import com.google.gson.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
enum Week {
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
class StockPrice {
private int page;
private int per_page;
private int total;
private int total_pages;
private List data;
public StockPrice() {
}
public StockPrice(int page, int per_page, int total, int total_pages, List<Data> data) {
this.page = page;
this.per_page = per_page;
this.total = total;
this.total_pages = total_pages;
this.data = data;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPer_page() {
return per_page;
}
public void setPer_page(int per_page) {
this.per_page = per_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal_pages() {
return total_pages;
}
public void setTotal_pages(int total_pages) {
this.total_pages = total_pages;
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
}
class Data {
private Date date;
private float open;
private float high;
private float low;
private float close;
public Data() {
}
public Data(Date date, float open, float high, float low, float close) {
this.date = date;
this.open = open;
this.high = high;
this.low = low;
this.close = close;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public float getOpen() {
return open;
}
public void setOpen(float open) {
this.open = open;
}
public float getHigh() {
return high;
}
public void setHigh(float high) {
this.high = high;
}
public float getLow() {
return low;
}
public void setLow(float low) {
this.low = low;
}
public float getClose() {
return close;
}
public void setClose(float close) {
this.close = close;
}
}
class DateDeserializer implements JsonDeserializer {
final SimpleDateFormat sdf = new SimpleDateFormat("d-MMMMM-yyyy");
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Date date = null;
try {
date = sdf.parse(json.getAsJsonPrimitive().getAsString());
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
public class Solution {
private static final String urlString = "https://jsonmock.hackerrank.com/api/stocks";
private static final SimpleDateFormat sdf = new SimpleDateFormat("d-MMMMM-yyyy");
private static final DecimalFormat decimalFormat = new DecimalFormat("0.##");
static void openAndClosePrices(String firstDate, String lastDate, String weekDay) {
BufferedReader reader = null;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
Gson gson = gsonBuilder.create();
try {
Date from = sdf.parse(firstDate);
Date to = sdf.parse(lastDate);
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
StockPrice stockPrice = gson.fromJson(buffer.toString(), StockPrice.class);
List<Data> dataList = stockPrice.getData();
dataList.stream().filter(data -> {
if (data.getDate().compareTo(from) >= 0 && data.getDate().compareTo(to) <= 0)
return true;
return false;
}).filter(data -> data.getDate().getDay() == Week.valueOf(weekDay).ordinal()).forEach(data -> {
System.out.println(String.format("%s %s %s", sdf.format(data.getDate()),
decimalFormat.format(data.getOpen()), decimalFormat.format(data.getClose())));
});
} catch (MalformedURLException e) {
`
String[] contWeekDays = {"Monday","Tuesday","Wednesday","Thursday","Fryday","Saturday","Sunday"};
It should be "Friday", as per the question. Your solution had some partial failures, do not know why.
Can you please point out failures in my sol. It passed 4/10 with partial failure in 1.
@ashutosh049 thanks for see it type mistake.
About your code, have you imported the gson library to you project prior to run it?
In case of negative answer, get it here: https://search.maven.org/remotecontent?filepath=com/google/code/gson/gson/2.8.5/gson-2.8.5.jar
yes, there is no problem with the library but with the logic
yes, there is no problem with the library but with the logic
@ashutosh049 I will try to figure you logic problem on this. As soon as possible I will answer you back with a solution.
https://jsonmock.hackerrank.com/api/stocks/?key=value: This query returns all results where the searched key has an exact matching value.
Shit! I misunderstood this line, didn't know that we can pass the date query param here. Bad luck :(
Write a program to retrieve and report various stock information for given days.
Query for the stock information using one of the following queries:
Each of the queries returns a JSON response with the following five fields:
page: The current page number.
per_page: The maximum number of results per page.
total: The total number of response.
total_pages: The total number of pages which must be queried to get all the results.
data: An array of JSON objects that contains the stock information. The JSON contains the following five fields, which could be used as the key to query:
To solve this challenge, complete the function openAndClosePrices, which has three string parameters: firstDate, lastDate, and weekDay. Query for the stock open and close prices on each date when the weekday is weekDay if the stock information is available. The stock information on each date should be printed on a new line that contains the three space separated values that describe the date, the open price, and the close price respectively. The order of the dates in the output does not matter.
Function Description
Complete the openAndClosePrices function in the editor below. It must perform the operations described above and print the required information. There is no return value expected.
openAndClosePrices has the following parameters:
-firstDate: a date string in the format described above
-lastDate: a date string in the format described above
-weekday: a string that represents the day of week to query
Constraints
weekday will be one of the following: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Sample Input For Custom Testing
1-January-2000 22-February-2000 Monday
Sample Output