Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @(#)shopify.java
- *
- * shopify application
- *
- * @Atilla Saadat
- * @version 1.00 2016/1/19
- *
- * Library imported from JSON jar found here: http://central.maven.org/maven2/org/json/json/20151123/json-20151123.jar
- * Knapsack algorithm based on: https://cs.uwaterloo.ca/~mgrzes/code/mg/Knapsack.java
- */
- import java.util.*;
- import java.io.*;
- import java.net.URL;
- import java.nio.charset.Charset;
- import org.json.*;
- public class bench {
- //---------------------------------------------------------------------------------------------------
- // JSON Parse and read funtions
- private static String readAll(Reader rd) throws IOException {
- StringBuilder sb = new StringBuilder();
- int cp;
- while ((cp = rd.read()) != -1) {
- sb.append((char) cp);
- }
- return sb.toString();
- }
- public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
- InputStream is = new URL(url).openStream();
- try {
- BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
- String jsonText = readAll(rd);
- JSONObject json = new JSONObject(jsonText);
- return json;
- } finally {
- is.close();
- }
- }
- //---------------------------------------------------------------------------------------------------
- // Gets Price and Weights of Keyboard and Computer Variants
- public static double findKeyCompTotalPrice( String jsonLink) throws IOException, JSONException{
- JSONArray products = (readJsonFromUrl(jsonLink)).getJSONArray("products");
- for(int index = 0; index < products.length(); index++){
- String currentItem = products.getJSONObject(index).getString("product_type");
- if(currentItem.equals("Keyboard")||currentItem.equals("Computer")){ // Search for Keyboard or Computer
- int numOfVariants = products.getJSONObject(index).getJSONArray("variants").length();
- for(int variant = 0; variant < numOfVariants; variant++){
- priceList.add(Double.parseDouble(products.getJSONObject(index).getJSONArray("variants").getJSONObject(variant).getString("price")));
- weightList.add(products.getJSONObject(index).getJSONArray("variants").getJSONObject(variant).getInt("grams"));
- }
- }
- }
- // Return Price of all Keyboard and Computer Variants based of 1/0 Greedy Algorithm
- double x = 0;
- int y = 0;
- for(int i = 0; i < weightList.size();i++){
- x+=priceList.get(i);
- y+=weightList.get(i);;
- }
- return finalPrice(maxWeight,priceList,weightList);
- }
- //---------------------------------------------------------------------------------------------------
- public static void main(String[] args) throws IOException {
- String jsonLink = "http://resttest.bench.co/transactions/";
- //Based on above link, all items should be taken because: all Keyboard and Computer weights < 100kg
- System.out.println(findKeyCompTotalPrice(maxWeight,jsonLink));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement