DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Kotlin Code Style: Best Practices for Former Java Developers
  • Java Code Review Solution
  • Leverage Lambdas for Cleaner Code
  • Getting Started With JMS-ActiveMQ: Explained in a Simple Way

Trending

  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  • A Walk-Through of the DZone Article Editor
  • How to Write for DZone Publications: Trend Reports and Refcards
  • Docker Hardened Images Are Free Now — Here's What You Still Need to Build
  1. DZone
  2. Coding
  3. Java
  4. Java Code Challenge: Play the Stockmarket Solution

Java Code Challenge: Play the Stockmarket Solution

The solution to last week's Java Code Challenge in a surprisingly simple way.

By 
Sam Atkinson user avatar
Sam Atkinson
·
Jul. 26, 16 · Opinion
Likes (4)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

As 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!  

code style Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Kotlin Code Style: Best Practices for Former Java Developers
  • Java Code Review Solution
  • Leverage Lambdas for Cleaner Code
  • Getting Started With JMS-ActiveMQ: Explained in a Simple Way

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook