Hacker Rank Price Check Solution
import java.io.*;
import java.util.*;
import java.util.stream.*;
class Result {
/*
* Complete the 'priceCheck' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING_ARRAY products
* 2. FLOAT_ARRAY productPrices
* 3. STRING_ARRAY productSold
* 4. FLOAT_ARRAY soldPrice
*/
public static int priceCheck(List<String> products, List<Float> productPrices, List<String> productSold, List<Float> soldPrice) {
// A map to store product names and their corresponding prices
Map<String, Float> priceMap = new HashMap<>();
// Populate the map with products and their prices
for (int i = 0; i < products.size(); i++) {
priceMap.put(products.get(i), productPrices.get(i));
}
// Count the number of price mismatches
int mismatches = 0;
for (int i = 0; i < productSold.size(); i++) {
String soldProduct = productSold.get(i);
float recordedPrice = soldPrice.get(i);
// Check if the sold price is different from the actual product price
if (priceMap.containsKey(soldProduct) && !priceMap.get(soldProduct).equals(recordedPrice)) {
mismatches++;
}
}
return mismatches;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int productsCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> products = IntStream.range(0, productsCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(Collectors.toList());
int productPricesCount = Integer.parseInt(bufferedReader.readLine().trim());
List<Float> productPrices = IntStream.range(0, productPricesCount).mapToObj(i -> {
try {
return bufferedReader.readLine().replaceAll("\\s+$", "");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).map(String::trim)
.map(Float::parseFloat)
.collect(Collectors.toList());
int productSoldCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> productSold = IntStream.range(0, productSoldCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(Collectors.toList());
int soldPriceCount = Integer.parseInt(bufferedReader.readLine().trim());
List<Float> soldPrice = IntStream.range(0, soldPriceCount).mapToObj(i -> {
try {
return bufferedReader.readLine().replaceAll("\\s+$", "");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).map(String::trim)
.map(Float::parseFloat)
.collect(Collectors.toList());
int result = Result.priceCheck(products, productPrices, productSold, soldPrice);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Comments
Post a Comment