Skip to content

Instantly share code, notes, and snippets.

@icio
Last active January 16, 2016 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save icio/74b2498e9f42a1d1c530 to your computer and use it in GitHub Desktop.
Save icio/74b2498e9f42a1d1c530 to your computer and use it in GitHub Desktop.
Jawa Pockets

As you cruise along the vast expanses of Tatooine desert, your X-34 landspeeder begins to splutter and stutter, before drifting slowly to a halt. A brief scan of the horizon reveals few features you can aim for in search of rescue.

Miraculously, a troop of Jawas appear out of nowhere -- presumably masked by the heat waves engulfing all who dare make this journey. The Jawas, being the scavengers they are, can be identified by the clattering of their many belongings. You strike up a conversation with one of the shorter ones, who is willing to trade some supplies you can use to fix your vehicle in exchange for some help with their counting.

Each Jawa's cloak contains many pockets. Many of those pockets (which aren't nearly as wet as an Otter's) contain pockets themselves, which themselves may contain pockets, and so-forth. The Jawas need your help to determine how many items they own altogether.

The pockets are represented as an array of the number of items within the pocket, and pockets which contain other pockets are themselves an array of counts of items in the nested pockets.

For example:

# Two pockets of 5 items, one pocket of 4 items, and one pocket with
# additional pockets containing 6, 4, and 3 items:
[5, 4, [6, 4, 3], 5]

# One pocket containing one pocket containing one pocket containing one item:
[[[1]]]

# Two pockets of 5 items, one pocket of 4 items, and one pocket with
# additional pockets containing 3 and 6 items with another nested in there
# containing 1, 2, and 3 items.
[5, 4, [6, 3, [1, 2, 3]], 5]

Write a function to count the total number of items for any given array of pockets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment