Skip to the content

The sailboat's heading

Problem

The sailboat came back to port with its logbook full of headings: each time the helmsman corrected course, he wrote down where the bow was pointing, in degrees from 0 to 359. The owner wants to know how much the helm turned over the whole voyage.

Write a function that takes the list of headings, in order, and returns the sum of the turns between each heading and the next, as a whole number. Each turn goes the shorter way: from 350 to 10 is 20 degrees through north, not 340. With [90, 120, 350, 20]: 30 + 130 + 30 = 190.

A turn is never more than 180; if it's exactly 180, it counts as 180. If two headings in a row are the same, that turn is 0. With one heading or none there were no turns: you return 0.

Examples

  • Turns that don't cross north

    [90, 120, 100] → 50

  • Crossing north

    [350, 10] → 20

  • A half turn and back

    [0, 180, 0] → 360

  • A single heading

    [45] → 0

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def total_turn(headings):
    pass

JavaScript

function totalTurn(headings) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →