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
Newsletter
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

  • How You Clear Your HTML5 Canvas Matters
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale
  • How to Format Articles for DZone
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 26, 16 · Opinion
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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