Difference between revisions of "99 questions/90 to 94"
DonStewart (talk  contribs) 
APapageorge (talk  contribs) 

(9 intermediate revisions by 4 users not shown)  
Line 4:  Line 4:  
If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields. 
If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields. 

−  
−  == Miscellaneous problems == 

== Problem 90 == 
== Problem 90 == 

Line 16:  Line 14:  
Example in Haskell: 
Example in Haskell: 

+  
−  <pre> 

+  <haskell> 

−  > length (queens 8) 

+  λ> length (queens 8) 

92 
92 

−  > head (queens 8) 
+  λ> head (queens 8) 
[1,5,8,6,3,7,2,4] 
[1,5,8,6,3,7,2,4] 

−  </pre> 

−  
−  Solution: 

−  The simplest solution is a composition of separate functions to generate the list of candidates and to test each candidate: 

−  <haskell> 

−  queens :: Int > [[Int]] 

−  queens n = filter test (generate n) 

−  where generate 0 = [[]] 

−  generate k = [q : qs  q < [1..n], qs < generate (k1)] 

−  test [] = True 

−  test (q:qs) = isSafe q qs && test qs 

−  isSafe try qs = not (try `elem` qs  sameDiag try qs) 

−  sameDiag try qs = any (\(colDist,q) > abs (try  q) == colDist) $ zip [1..] qs 

</haskell> 
</haskell> 

−  By definition/data representation no two queens can occupy the same column. 

−  <hask>try `elem` alreadySet</hask> checks for a queen in the same row, <hask>abs (try  q) == col</hask> checks for a queen in the same diagonal. 

+  [[99 questions/Solutions/90  Solutions]] 

−  This is easy to understand, but it's also quite slow, as it generates and tests N^N possible Nqueen configurations. 

+  
−  The key to speeding it up is to fuse the composition <hask>filter test . generate</hask> into a semantically equivalent function <hask>queens'</hask> that does the tests as early as possible. 

−  If a list already contains two queens in a line, there's no point in considering all the possible ways of adding more queens. 

−  Now that the recursive call incorporates testing, we avoid recomputing it by interchanging the two generators, and reverse each answer at the end to obtain the original order. 

−  This yields the following version, which is much faster: 

−  <haskell> 

−  queens :: Int > [[Int]] 

−  queens n = map reverse $ queens' n 

−  where queens' 0 = [[]] 

−  queens' k = [q:qs  qs < queens' (k1), q < [1..n], isSafe q qs] 

−  isSafe try qs = not (try `elem` qs  sameDiag try qs) 

−  sameDiag try qs = any (\(colDist,q) > abs (try  q) == colDist) $ zip [1..] qs 

−  </haskell> 

−  If you approach this problem with an imperative mindset, you might be tempted to use an accumulating parameter for the list of candidates. 

−  This would make the function harder to understand, and would not help much (if at all): the important thing here is the breadth of the search tree, not its depth. 

== Problem 91 == 
== Problem 91 == 

Line 67:  Line 38:  
Example in Haskell: 
Example in Haskell: 

+  
−  <pre> 

+  <haskell> 

−  Knights> head $ knightsTo 8 (1,1) 

+  λ> head $ knightsTo 8 (1,1) 

[(2,7),(3,5),(5,6),(4,8),(3,6),(4,4),(6,5),(4,6), 
[(2,7),(3,5),(5,6),(4,8),(3,6),(4,4),(6,5),(4,6), 

(5,4),(7,5),(6,3),(5,5),(4,3),(2,4),(1,6),(2,8), 
(5,4),(7,5),(6,3),(5,5),(4,3),(2,4),(1,6),(2,8), 

Line 77:  Line 49:  
(2,1),(1,3),(2,5),(1,7),(3,8),(5,7),(7,8),(8,6), 
(2,1),(1,3),(2,5),(1,7),(3,8),(5,7),(7,8),(8,6), 

(6,7),(8,8),(7,6),(8,4),(7,2),(5,1),(3,2),(1,1)] 
(6,7),(8,8),(7,6),(8,4),(7,2),(5,1),(3,2),(1,1)] 

−  +  λ> head $ closedKnights 8 

[(1,1),(3,2),(1,3),(2,1),(3,3),(5,4),(6,6),(4,5), 
[(1,1),(3,2),(1,3),(2,1),(3,3),(5,4),(6,6),(4,5), 

(2,6),(1,8),(3,7),(5,8),(4,6),(2,5),(4,4),(5,6), 
(2,6),(1,8),(3,7),(5,8),(4,6),(2,5),(4,4),(5,6), 

Line 86:  Line 58:  
(6,2),(8,1),(7,3),(5,2),(7,1),(8,3),(7,5),(8,7), 
(6,2),(8,1),(7,3),(5,2),(7,1),(8,3),(7,5),(8,7), 

(6,8),(4,7),(2,8),(1,6),(2,4),(1,2),(3,1),(2,3)] 
(6,8),(4,7),(2,8),(1,6),(2,4),(1,2),(3,1),(2,3)] 

−  </pre> 

−  
−  Solution: 

−  <haskell> 

−  module Knights where 

−  
−  import Data.List 

−  
−  type Square = (Int, Int) 

−  
−   Possible knight moves from a given square on an nxn board 

−  knightMoves :: Int > Square > [Square] 

−  knightMoves n (x, y) = filter (onBoard n) 

−  [(x+2, y+1), (x+2, y1), (x+1, y+2), (x+1, y2), 

−  (x1, y+2), (x1, y2), (x2, y+1), (x2, y1)] 

−  
−   Is the square within an nxn board? 

−  onBoard :: Int > Square > Bool 

−  onBoard n (x, y) = 1 <= x && x <= n && 1 <= y && y <= n 

−  
−   Knight's tours on an nxn board ending at the given square 

−  knightsTo :: Int > Square > [[Square]] 

−  knightsTo n finish = [pos:path  (pos, path) < tour (n*n)] 

−  where tour 1 = [(finish, [])] 

−  tour k = [(pos', pos:path)  

−  (pos, path) < tour (k1), 

−  pos' < sortImage (entrances path) 

−  (filter (`notElem` path) (knightMoves n pos))] 

−  entrances path pos = 

−  length (filter (`notElem` path) (knightMoves n pos)) 

−  
−   Closed knight's tours on an nxn board 

−  closedKnights :: Int > [[Square]] 

−  closedKnights n = [pos:path  (pos, path) < tour (n*n), pos == start] 

−  where tour 1 = [(finish, [])] 

−  tour k = [(pos', pos:path)  

−  (pos, path) < tour (k1), 

−  pos' < sortImage (entrances path) 

−  (filter (`notElem` path) (knightMoves n pos))] 

−  entrances path pos 

−   pos == start = 100  don't visit start until there are no others 

−   otherwise = length (filter (`notElem` path) (knightMoves n pos)) 

−  start = (1,1) 

−  finish = (2,3) 

−  
−   Sort by comparing the image of list elements under a function f. 

−   These images are saved to avoid recomputation. 

−  sortImage :: Ord b => (a > b) > [a] > [a] 

−  sortImage f xs = map snd (sortBy cmpFst [(f x, x)  x < xs]) 

−  where cmpFst x y = compare (fst x) (fst y) 

−  </haskell> 

−  This has a similar structure to the 8 Queens problem, except that we apply a heuristic invented by Warnsdorff: when considering next possible moves, we prefer squares with fewer open entrances. 

−  This speeds things up enormously, and finds the first solution to boards smaller than 76x76 without backtracking. 

−  
−  
−  Solution 2: 

−  
−  <haskell> 

−  knights :: Int > [[(Int,Int)]] 

−  knights n = loop (n*n) [[(1,1)]] 

−  where loop 1 = map reverse . id 

−  loop i = loop (i1) . concatMap nextMoves 

−  
−  nextMoves already@(x:xs) = [next:already  next < possible] 

−  where possible = filter (\x > on_board x && not (x `elem` already)) $ jumps x 

−  
−  jumps (x,y) = [(x+a, y+b)  (a,b) < [(1,2), (2,1), (2,1), (1,2), (1,2), (2,1), (2,1), (1,2)]] 

−  on_board (x,y) = (x >= 1) && (x <= n) && (y >= 1) && (y <= n) 

</haskell> 
</haskell> 

+  [[99 questions/Solutions/91  Solutions]] 

−  This is just the naive backtracking approach. I tried a speedup using Data.Map, but the code got too verbose to post. 

== Problem 92 == 
== Problem 92 == 

Line 162:  Line 66:  
(***) Von Koch's conjecture 
(***) Von Koch's conjecture 

−  Several years ago I met a mathematician who was intrigued by a problem 
+  Several years ago I met a mathematician who was intrigued by a problem whose solution he didn't know. His name was Von Koch, and I don't know whether the problem has been solved since. 
https://prof.ti.bfh.ch/hew1/informatik3/prolog/p99/p92a.gif 
https://prof.ti.bfh.ch/hew1/informatik3/prolog/p99/p92a.gif 

Line 175:  Line 79:  
Example in Haskell: 
Example in Haskell: 

−  <pre> 

−  > head $ vonKoch [(1,6),(2,6),(3,6),(4,6),(5,6),(5,7),(5,8),(8,9),(5,10),(10,11),(11,12),(11,13),(13,14)] 

−  [6,7,8,9,3,4,10,11,5,12,2,13,14,1] 

−  </pre> 

−  Solution: 

<haskell> 
<haskell> 

+  λ> head $ vonKoch [(1,6),(2,6),(3,6),(4,6),(5,6),(5,7),(5,8),(8,9),(5,10),(10,11),(11,12),(11,13),(13,14)] 

−  vonKoch edges = do 

+  [6,7,8,9,3,4,10,11,5,12,2,13,14,1] 

−  let n = length edges + 1 

−  nodes < permutations [1..n] 

−  let nodeArray = listArray (1,n) nodes 

−  let dists = sort $ map (\(x,y) > abs (nodeArray ! x  nodeArray ! y)) edges 

−  guard $ and $ zipWith (/=) dists (tail dists) 

−  return nodes 

</haskell> 
</haskell> 

+  [[99 questions/Solutions/92  Solutions]] 

−  This is a simple bruteforce solver. This function will permute all assignments of the different node numbers and will then verify that all of the edge differences are different. This code uses the List Monad. 

+  
== Problem 93 == 
== Problem 93 == 

Line 202:  Line 97:  
Example in Haskell: 
Example in Haskell: 

+  
−  <pre> 

+  <haskell> 

−  P93> putStr $ unlines $ puzzle [2,3,5,7,11] 

+  λ> mapM_ putStrLn $ puzzle [2,3,5,7,11] 

2 = 3(5+711) 
2 = 3(5+711) 

2 = 35(711) 
2 = 35(711) 

Line 214:  Line 110:  
2(35)+7 = 11 
2(35)+7 = 11 

23+5+7 = 11 
23+5+7 = 11 

−  </ 
+  </haskell> 
+  
The other two solutions alluded to in the problem description are dropped by the Haskell solution as trivial variants: 
The other two solutions alluded to in the problem description are dropped by the Haskell solution as trivial variants: 

+  
<pre> 
<pre> 

2 = 3(5+(711)) 
2 = 3(5+(711)) 

Line 221:  Line 119:  
</pre> 
</pre> 

+  [[99 questions/Solutions/93  Solutions]] 

−  Solution: 

−  <haskell> 

−  module P93 where 

−  import Control.Monad 

−  import Data.List 

−  import Data.Maybe 

−  
−  type Equation = (Expr, Expr) 

−  data Expr = Const Integer  Binary Expr Op Expr 

−  deriving (Eq, Show) 

−  data Op = Plus  Minus  Multiply  Divide 

−  deriving (Bounded, Eq, Enum, Show) 

−  type Value = Rational 

−  
−   toplevel function: all correct equations generated from the list of 

−   numbers, as pretty strings. 

−  puzzle :: [Integer] > [String] 

−  puzzle ns = map (flip showsEquation "") (equations ns) 

−  
−   generate all correct equations from the list of numbers 

−  equations :: [Integer] > [Equation] 

−  equations [] = error "empty list of numbers" 

−  equations [n] = error "only one number" 

−  equations ns = [(e1, e2)  

−  (ns1, ns2) < splits ns, 

−  (e1, v1) < exprs ns1, 

−  (e2, v2) < exprs ns2, 

−  v1 == v2] 

−  
−   generate all expressions from the numbers, except those containing 

−   a division by zero, or redundant rightassociativity. 

−  exprs :: [Integer] > [(Expr, Value)] 

−  exprs [n] = [(Const n, fromInteger n)] 

−  exprs ns = [(Binary e1 op e2, v)  (ns1, ns2) < splits ns, 

−  (e1, v1) < exprs ns1, 

−  (e2, v2) < exprs ns2, 

−  op < [minBound..maxBound], 

−  not (right_associative op e2), 

−  v < maybeToList (apply op v1 v2)] 

−  
−   splittings of a list into two nonempty lists 

−  splits :: [a] > [([a],[a])] 

−  splits xs = tail (init (zip (inits xs) (tails xs))) 

−  
−   applying an operator to arguments may fail (division by zero) 

−  apply :: Op > Value > Value > Maybe Value 

−  apply Plus x y = Just (x + y) 

−  apply Minus x y = Just (x  y) 

−  apply Multiply x y = Just (x * y) 

−  apply Divide x 0 = Nothing 

−  apply Divide x y = Just (x / y) 

−  
−   e1 op (e2 op' e3) == (e1 op e2) op' e3 

−  right_associative :: Op > Expr > Bool 

−  right_associative Plus (Binary _ Plus _) = True 

−  right_associative Plus (Binary _ Minus _) = True 

−  right_associative Multiply (Binary _ Multiply _) = True 

−  right_associative Multiply (Binary _ Divide _) = True 

−  right_associative _ _ = False 

−  
−   Printing of equations and expressions 

−  
−  showsEquation :: Equation > ShowS 

−  showsEquation (l, r) = showsExprPrec 0 l . showString " = " . showsExprPrec 0 r 

−  
−   all operations are left associative 

−  showsExprPrec :: Int > Expr > ShowS 

−  showsExprPrec _ (Const n) = shows n 

−  showsExprPrec p (Binary e1 op e2) = showParen (p > op_prec) $ 

−  showsExprPrec op_prec e1 . showString (opName op) . 

−  showsExprPrec (op_prec+1) e2 

−  where op_prec = precedence op 

−  
−  precedence :: Op > Int 

−  precedence Plus = 6 

−  precedence Minus = 6 

−  precedence Multiply = 7 

−  precedence Divide = 7 

−  
−  opName :: Op > String 

−  opName Plus = "+" 

−  opName Minus = "" 

−  opName Multiply = "*" 

−  opName Divide = "/" 

−  </haskell> 

−  Unlike the Prolog solution, I've eliminated solutions like 

−  <tt>"1+(2+3) = 6"</tt> as a trivial variant of <tt>"1+2+3 = 6"</tt> (cf the function <tt>right_associative</tt>). 

−  Apart from that, the Prolog solution is shorter because it uses builtin evaluation and printing of expressions. 

== Problem 94 == 
== Problem 94 == 

Line 319:  Line 130:  
[https://prof.ti.bfh.ch/hew1/informatik3/prolog/p99/p94.txt Sample results] 
[https://prof.ti.bfh.ch/hew1/informatik3/prolog/p99/p94.txt Sample results] 

+  Example in Haskell: 

−  Solution: 

<haskell> 
<haskell> 

+  λ> length $ regular 6 3 

−  <solution in haskell> 

+  2 

</haskell> 
</haskell> 

+  [[99 questions/Solutions/94  Solutions]] 

−  <description of implementation> 

[[Category:Tutorials]] 
[[Category:Tutorials]] 
Latest revision as of 00:05, 18 November 2022
This is part of NinetyNine Haskell Problems, based on NinetyNine Prolog Problems.
If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields.
Problem 90
(**) Eight queens problem
This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal.
Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generateandtest paradigm.
Example in Haskell:
λ> length (queens 8)
92
λ> head (queens 8)
[1,5,8,6,3,7,2,4]
Problem 91
(**) Knight's tour
Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? A set of solutions is given on the The_Knights_Tour page.
Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour).
There are two variants of this problem:
 find a tour ending at a particular square
 find a circular tour, ending a knight's jump from the start (clearly it doesn't matter where you start, so choose (1,1))
Example in Haskell:
λ> head $ knightsTo 8 (1,1)
[(2,7),(3,5),(5,6),(4,8),(3,6),(4,4),(6,5),(4,6),
(5,4),(7,5),(6,3),(5,5),(4,3),(2,4),(1,6),(2,8),
(4,7),(6,8),(8,7),(6,6),(4,5),(6,4),(5,2),(7,1),
(8,3),(6,2),(8,1),(7,3),(8,5),(7,7),(5,8),(3,7),
(1,8),(2,6),(3,4),(1,5),(2,3),(3,1),(1,2),(3,3),
(1,4),(2,2),(4,1),(5,3),(7,4),(8,2),(6,1),(4,2),
(2,1),(1,3),(2,5),(1,7),(3,8),(5,7),(7,8),(8,6),
(6,7),(8,8),(7,6),(8,4),(7,2),(5,1),(3,2),(1,1)]
λ> head $ closedKnights 8
[(1,1),(3,2),(1,3),(2,1),(3,3),(5,4),(6,6),(4,5),
(2,6),(1,8),(3,7),(5,8),(4,6),(2,5),(4,4),(5,6),
(6,4),(8,5),(7,7),(6,5),(5,3),(6,1),(4,2),(6,3),
(8,2),(7,4),(5,5),(3,4),(1,5),(2,7),(4,8),(3,6),
(1,7),(3,8),(5,7),(7,8),(8,6),(6,7),(8,8),(7,6),
(8,4),(7,2),(5,1),(4,3),(3,5),(1,4),(2,2),(4,1),
(6,2),(8,1),(7,3),(5,2),(7,1),(8,3),(7,5),(8,7),
(6,8),(4,7),(2,8),(1,6),(2,4),(1,2),(3,1),(2,3)]
Problem 92
(***) Von Koch's conjecture
Several years ago I met a mathematician who was intrigued by a problem whose solution he didn't know. His name was Von Koch, and I don't know whether the problem has been solved since.
Anyway the puzzle goes like this: Given a tree with N nodes (and hence N1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible.
For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution!
Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured below?
Example in Haskell:
λ> head $ vonKoch [(1,6),(2,6),(3,6),(4,6),(5,6),(5,7),(5,8),(8,9),(5,10),(10,11),(11,12),(11,13),(13,14)]
[6,7,8,9,3,4,10,11,5,12,2,13,14,1]
Problem 93
(***) An arithmetic puzzle
Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 23+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!).
Division should be interpreted as operating on rationals, and division by zero should be avoided.
Example in Haskell:
λ> mapM_ putStrLn $ puzzle [2,3,5,7,11]
2 = 3(5+711)
2 = 35(711)
2 = 3(5+7)+11
2 = 357+11
2 = (3*5+7)/11
2*(35) = 711
2(3(5+7)) = 11
2(357) = 11
2(35)+7 = 11
23+5+7 = 11
The other two solutions alluded to in the problem description are dropped by the Haskell solution as trivial variants:
2 = 3(5+(711)) 23+(5+7) = 11
Problem 94
(***) Generate Kregular simple graphs with N nodes
In a Kregular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (nonisomorphic!) 3regular graphs with 6 nodes are there?
Example in Haskell:
λ> length $ regular 6 3
2