Reputation: 527
Given an array of prices (such as 341.95) how would I go about finding the 50 cheapest prices?
The trick is some of the prices in the array could match and the list of 50 should be unique prices. For example if there are 6 prices in there for 123.45 I only want one in my final list of 50. There can't be any duplicates.
I was thinking that the best way would be to take that array and suck it into a second array, filtering out any matching numbers but that's easier said than done.
Upvotes: 0
Views: 85
Reputation: 5883
If you have an array of Double objects, you can use the Groovy JDK's toUnique
, sort
, and take
methods to find the lowest 50 prices.
// generate some random prices
def r = new Random()
Double[] allPrices = (0..100).collect { (r.nextDouble() * 100).trunc(2) }
Double[] lowestPrices = allPrices.toUnique().sort().take(50)
Hat tip to @cfrick for the suggestion to use take
instead of the range and Math.min syntax.
Upvotes: 0
Reputation: 3892
Here is the groovier solution to your problem
//priceArray is your input array
def firstFiftyPrices = priceArray.unique().sort().take(50)
Upvotes: 1
Reputation: 527
Based on everyones input I came up with this and it appears to work. lowestPrices is my list of prices, thanks everyone!
Object[] st = lowestPrices.toArray();
for (Object s : st) {
if (lowestPrices.indexOf(s) != lowestPrices.lastIndexOf(s)) {
lowestPrices.remove(lowestPrices.lastIndexOf(s));
}
}
System.out.println("Distinct List " + lowestPrices)
Upvotes: 0
Reputation: 41213
Using Java 8 streams:
int[] lowestPrices = Arrays.stream(prices)
.sorted()
.distinct()
.limit(50)
.toArray();
Note that I've used int[]
even though you used "123.45" as an example. Using floating point for monetary values is a terrible idea, so represent $123.45 as 12345 cents.
Upvotes: 2
Reputation: 681
Iterate through the array, add each item to a TreeSet
, and then return a list of the first 50 elements.
Upvotes: 0
Reputation: 35011
Optimal in place solution is
Upvotes: 1