A lot of programming problems can be solved simply using the correct datastructures. In the process of learning Julia we review some data structures in Julia to solve some problems. The following is a solution to project euler problem 17.
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
All we do here is have a dictionary to map the numbers to their english equivalent. After defining the a few base numbers in the dictionary we can build strings for every other number. The spaces are removed from the words simply because the problem description says not to count the spaces.
The standard data structures available in Julia are quite nice. This example is a problem that can be solved quite easily with a map. This example was chosen because coming from R there is no equivalent data structure. The closest data structures are environments and lists in R. However, for a lot of uses environments and lists don’t quite act in the same way as a dictionary or map.
Using a list to build a map from integers to strings it looks like it unnecessarily fills in all the values inbetween 1 and 5 with NAs. So if I have gaps in the domain of my map the list will automatically fill them in.
I could try to do the same thing with environments:
The problem with environments is that you cannot index with integers. To map integers to strings the best you can do is cast integers to strings and map strings to strings.