Given a matrix m,a starting position p1 and a final point p2.
The objective is to compute how many ways there are to reach the final matrix (p2=1 and others=0). For this, every time you skip into a position you decrements by one.
you can only skip from one position to another by at most two positions, horizontal or vertical. For example:
m = p1=(3,1) p2=(2,3)
[0 0 0]
[1 0 4]
[2 0 4]
You can skip to the positions [(3,3),(2,1)]
When you skip from one position you decrement it by one and does it all again. Let’s skip to the first element of the list. Like this:
m=
[0 0 0]
[1 0 4]
[1 0 4]
Now you are in position (3,3) and you can skip to the positions [(3,1),(2,3)]
And doing it until the final matrix:
[0 0 0]
[0 0 0]
[1 0 0]
In this case the amount of different ways to get the final matrix is 20.
I’ve created the functions below:
import Data.List
type Pos = (Int,Int)
type Matrix = [[Int]]
moviments::Pos->[Pos]
moviments (i,j)= [(i+1,j),(i+2,j),(i-1,j),(i-2,j),(i,j+1),(i,j+2),(i,j-1),(i,j-2)]
decrementsPosition:: Pos->Matrix->Matrix
decrementsPosition(1,c) (m:ms) = (decrements c m):ms
decrementsPosition(l,c) (m:ms) = m:(decrementsPosition (l-1,c) ms)
decrements:: Int->[Int]->[Int]
decrements 1 (m:ms) = (m-1):ms
decrements n (m:ms) = m:(decrements (n-1) ms)
size:: Matrix->Pos
size m = (length m,length.head $ m)
finalMatrix::Pos->Pos->Matrix
finalMatrix (m,n) p = [[if (l,c)==p then 1 else 0 | c<-[1..n]]| l<-[1..m]]
possibleMov:: Pos->Matrix->[Pos]
possibleMov p mat = checks0 ([(a,b)|a<-(dim m),b<-(dim n)] `intersect` xs) mat
where xs = movements p
(m,n) = size mat
dim:: Int->[Int]
dim 1 = [1]
dim n = n:dim (n-1)
checks0::[Pos]->Matrix->[Pos]
checks0 [] m =[]
checks0 (p:ps) m = if ((takeValue m p) == 0) then checks0 ps m
else p:checks0 ps m
takeValue:: Matrix->Pos->Int
takeValue x (i,j)= (x!!(i-1))!!(j-1)
Any idea how do I create a function ways?
ways:: Pos->Pos->Matrix->Int
Explore the possible paths in parallel. From the starting position, make all possible moves. Each of the resulting configurations can be reached in exactly one way. Then, from each of the resulting configurations, make all possible moves. Add the counts of the new configurations that can be reached from several of the previous configurations. Repeat that step until there is only one nonzero element in the grid. Cull impossible paths early.
For the bookkeeping which configuration can be reached in how many ways from the initial configuration, the easiest way is to use a
Map. I chose to represent the grid as an (unboxed) array, sinceThe code: