Java Code Challenge: Play the Stockmarket Solution
The solution to last week's Java Code Challenge in a surprisingly simple way.
Join the DZone community and get the full member experience.
Join For FreeAs always with these programming challenges I've been bowled over by the sheer variation in the solutions. For what sounds like a fairly simple challenge (finding the min/max pairing in a list of numbers) has produced a series of very interesting solutions.
A brief aside; it's possible to solve this challenge in a really stupid fashion. Most of the solutions have some form of double loop through the list- effectively, for each number in the list, finding it's corresponding max (if there is one), then comparing that list for the biggest difference. This is best demonstrated in this wonderfully succinct solution which I definitely think get's the prize for clarity from Grzegorz Ziemoński:
static Deal bestDeal(List<BigDecimal> stockPrices) {
return allPossibleDeals(stockPrices).stream().max(byGain()).get();
}
private static List<Deal> allPossibleDeals(List<BigDecimal> stockPrices) {
List<Deal> possibleDeals = new LinkedList<>();
for (int i = 0; i < (stockPrices.size() - SKIP_CLOSEST_OFFSET); ++i) {
for (int j = i + SKIP_CLOSEST_OFFSET; j < stockPrices.size(); ++j) {
possibleDeals.add(new Deal(stockPrices.get(i), stockPrices.get(j)));
}
}
return possibleDeals;
}
private static Comparator<Deal> byGain() {
return (d1, d2) -> d1.gain().compareTo(d2.gain());
}
This code effectively maps the list into a matrix of pairs; e.g. if you have the trades 1.0, 2.0, 3.0, 4.0, it will then produce a list of pairings 1.0/3.0, 1.0/4.0, 2.0/4.0 (he's used SKIP_CLOSEST_OFFSET to allow for the fact you cannot trade the tick afterwards). You can then zip through this list to find the max difference, and ergo the result.
However, it's possible to do this even simpler; Unfortunately the 2 challenges in the original question are woefully simple, which means you can in fact just loop through once as the data is nice enough that you can just reset your count if you find a new low value. It requires a bit more in the way of flags but results in a lot less looping.
public TradeResult bestTrades() {
double low = trades[0];
double high = trades[0];
boolean waitOneTickAfterTrading = true;
for (int i = 1; i < trades.length; i++) {
double trade = trades[i];
if(trade > high && !waitOneTickAfterTrading) {
high = trade;
}
waitOneTickAfterTrading = false;
if(trade < low) {
low = trade;
high = trade;
waitOneTickAfterTrading = true;
}
}
return new TradeResult(low, high);
}
I would argue that the fact that this is more efficient is fairly irrelevant- for a data set this small it doesn't matter. However if you had something like this in an interview then the complexity and speed of the algorithm would come up. No one else seems to have spotted that you can get both challenges to pass this way- I only discovered it as I build my code using TDD, which meant doing the simplest, dumbest thing to make the test pass.
I think a challenge this simple is still a great way of demonstrating the value of readable code for maintainability. The top solution use clear naming (stockPrices, possibleDeals, SKIP_CLOSEST_OFFSET) to make it as obvious to the reader of the code what is going on. If you take this other example from the comments you will see that, although it's functionally correct, it would be a nightmare to understand what was going on after returning to it a few weeks later out of context.
public static void main(String [] args) {
ArrayList<Trade> trades = new ArrayList<Trade>();
for (int i = 0; i < args.length - 2; ++i) {
double buy = Double.parseDouble(args[i]);
for (int j = i + 2; j < args.length; ++j) {
double sell = Double.parseDouble(args[j]);
trades.add(new Trade(buy, sell));
}
}
Optional<Trade> best = trades.stream().collect(
Collectors.maxBy(
(t1, t2) -> Double.valueOf(t1.sell - t1.buy).compareTo(Double.valueOf(t2.sell - t2.buy))
)
);
System.out.println(best.get());
System.exit(0);
}
A small thing which I think is nicely highlighted by this challenge is the Java 8 functional code which allows the easy transformation of collections, specifically in this case from a String of trades into an array or List. What before would've taken a for loop and some manual code can be done nice and cleanly in a "one liner":
List<Double> prices = Stream.of(ticks.split(" "))
.map(Double::parseDouble)
.collect(Collectors.toList());
Well done to everyone who completed the challenge. Remember to aim for terse, uncomplicated, easy to understand code!
Opinions expressed by DZone contributors are their own.
Comments