Skip to content

Commit

Permalink
exercises(zebra-puzzle): example: replace tuple with object
Browse files Browse the repository at this point in the history
  • Loading branch information
ee7 committed Nov 2, 2024
1 parent 9ee5299 commit 5134928
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions exercises/practice/zebra-puzzle/.meta/example.nim
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ type
Hobby = enum
Dancing, Painting, Reading, Football, Chess

House = tuple[color: Color, nationality: Nationality, pet: Pet, drink: Drink, hobby: Hobby]
House = object
color: Color
nationality: Nationality
pet: Pet
drink: Drink
hobby: Hobby

Solution = array[5, House]

Expand All @@ -28,6 +33,9 @@ iterator permutations[T]: array[5, T] =
while term.nextPermutation():
yield term

func init(T: typedesc[House], color: Color, nationality: Nationality, pet: Pet, drink: Drink, hobby: Hobby): T =
T(color: color, nationality: nationality, pet: pet, drink: drink, hobby: hobby)

func solve: Solution =
result = default(Solution)
for colors in permutations[Color]():
Expand All @@ -50,7 +58,7 @@ func solve: Solution =
if abs(hobby.find(Reading) - pets.find(Fox)) != 1: continue
if abs(hobby.find(Painting) - pets.find(Horse)) != 1: continue
for i in result.low..result.high:
result[i] = (colors[i], nationalities[i], pets[i], drinks[i], hobby[i])
result[i] = House.init(colors[i], nationalities[i], pets[i], drinks[i], hobby[i])
return result

# Calculate solution at compile time.
Expand Down

0 comments on commit 5134928

Please sign in to comment.