Advertisement
zvoulgaris

Animal Food Drill

Jan 12th, 2021
2,937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.66 KB | None | 0 0
  1. # Animal foods drill: https://programmingpraxis.com/2021/01/12/animal-txt
  2. # Requirement: a text file containing information about the dietary patterns of various animals
  3.  
  4. function ParseDataFile(fn::String = "animal.txt")
  5.     f = open(fn, "r")
  6.     lines = readlines(f)
  7.     close(f)
  8.     return lines
  9. end
  10.  
  11. function OutputResults(D::Array{String, 2})
  12.     animals = D[:,1]
  13.     foods = D[:,2]
  14.  
  15.     for food in unique(foods)
  16.         animals_for_given_food = unique(D[D[:,2] .== food ,1])
  17.         c = length(animals_for_given_food)
  18.         println("Food: ", uppercasefirst(food), " Animals who ate it: ", c)
  19.         println("=======")
  20.         for i = 1:c; println(animals_for_given_food[i]); end
  21.         println("")
  22.     end
  23. end
  24.  
  25. function main(fn::String = "animal.txt")
  26.     lines = ParseDataFile(fn)
  27.     n = length(lines)
  28.     animal = ""
  29.     D = Array{String}(undef, n, 2)
  30.     AnimalFound = false
  31.     FoundFood = false
  32.     c = 0
  33.  
  34.     for line in lines
  35.         if !isempty(line)
  36.             temp = split(line, " ")
  37.  
  38.             if AnimalFound
  39.                 NewCombo = true
  40.  
  41.                 for i = 1:c
  42.                     if D[i,1] == animal && D[i,2] == temp[end]; NewCombo = false; end
  43.                 end
  44.  
  45.                 if NewCombo
  46.                     c += 1
  47.                     D[c,:] .= animal, temp[end]
  48.                     FoundFood = true
  49.                 end
  50.             else
  51.                 animal = temp[end]
  52.                 AnimalFound = true
  53.             end
  54.         else
  55.             if FoundFood
  56.                 AnimalFound = false
  57.                 FoundFood = false
  58.             end
  59.         end
  60.     end
  61.  
  62.     OutputResults(D[1:c,:])
  63. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement