/
HighPeak.java
70 lines (58 loc) · 1.89 KB
/
HighPeak.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package high_peak;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
class Item {
String name;
int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
public String toString() {
return this.name + ": " + this.price;
}
}
public class Main {
public static void main(String[] args) throws Exception {
// Passing Input file
FileInputStream fis = new FileInputStream("D://Eclipse_Wokspaces/Class Workspace/interview_programs/src/high_peak/input.txt");
Scanner sc = new Scanner(fis);
int number_of_employees = Integer.parseInt(sc.nextLine().split(": ")[1]);
sc.nextLine();
sc.nextLine();
sc.nextLine();
ArrayList<Item> goodies_items = new ArrayList<Item>();
while (sc.hasNextLine()) {
String current[] = sc.nextLine().split(": ");
goodies_items.add(new Item(current[0], Integer.parseInt(current[1])));
}
sc.close();
Collections.sort(goodies_items, new Comparator<Item>() {
public int compare(Item a, Item b) {
return a.price - b.price;
}
});
int min_diff = goodies_items.get(goodies_items.size() - 1).price;
int min_index = 0;
for (int i = 0; i < goodies_items.size() - number_of_employees + 1; i++) {
int diff = goodies_items.get(number_of_employees + i - 1).price - goodies_items.get(i).price;
// Difference between goodie with highest and lowest price
if (diff <= min_diff) {
min_diff = diff;
min_index = i;
}
}
FileWriter fw = new FileWriter("output.txt");
fw.write("The goodies selected for distribution are:\n\n");
for (int i = min_index; i < min_index + number_of_employees; i++) {
fw.write(goodies_items.get(i).toString() + "\n");
}
fw.write("\nAnd the difference between the chosen goodie with highest price and the lowest price is "
+ min_diff);
fw.close();
}
}