Animal.txt
January 12, 2021
Today’s task is from a beginning programmer, who starts with an input file called animal.txt:
There once was a Dog
Wednesday he ate Apples
Thursday he ate Apples
Friday he ate Apples
Saturday he ate carrots
There once was a Bear
Tuesday he ate carrots
Wednesday he ate carrots
Thursday he ate chicken
He wants to create this output:
Food: Apples Animals who ate it: 1
=======
Dog
Food: Carrots Animals who ate it: 2
========
Bear
Dog
Food: Chicken Animals who ate it: 1
========
Bear
He gave a complicated awk solution that didn’t work; it produced duplicate lines of output in those cases
where the same animal ate the same food on multiple days.
Your task is to write a program to produces the desired transformation form input to output. When
you are finished, you are welcome to read or run a suggested solution, or to post your own solution or
discuss the exercise in the comments below.
A cute little exercise. I hope it’s not counted as cheating if I tackle it using Julia (1.5.2): https://pastebin.com/UDbyNBhQ
I really had no idea that bears ate carrots!
Here’s a solution in Python.
Example usage:
Python
import re
inFile = open(‘animal.txt’)
dt = dict()
l = set()
f = ”
for line in inFile:
if re.match(“There once was a”, line):
if f:
dt[f] = l
f = line.split()[-1].capitalize()
l = set()
elif re.search(“he ate”, line):
s = line.split()[-1].capitalize()
l.add(s)
dt[f] = l
dtr = dict() #reverse dict
for k, v in dt.items():
for iv in v:
if iv in dtr:
dtr[iv].add(k)
else:
dtr[iv] = set([k])
for val in dtr:
print(‘\nFood: {} Animals who ate it: {}’.format(val, len(dtr[val])))
print(‘=======’)
for i in dtr[val]:
print(i)
ouch (
https://pastebin.com/yh2iQweK
Here’s an AWK version. The food names are capitalized, and the output sorted, to match the example.
Here’s a solution in Haskell using the cool Parsec module in the standard library. I noticed the capitalisation of animals and foods was inconsistent in the example input but I’m just ignoring that. Also it’s not quite obvious how to format code in these comments, so this might look terrible.
(and then I saw the “HOWTO: Posting Source Code” link right at the top of the page. On the plus side, it seems that the “code” tag suffices in place of “sourcecode” and the “lang” property can be omitted for unsupported languages like Haskell)
Here a solution in Java:
package codekatas;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.TreeSet;
public class AnimalFood {
}
Here a solution in Java: