Skip to content

Commit 3f604e9

Browse files
committed
Solve 'Change two-dimensional array' kata
1 parent 9110b10 commit 3f604e9

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/Matrix.hs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
module Matrix (matrix) where
2+
3+
-- https://www.codewars.com/kata/581214d54624a8232100005f/train/haskell
4+
5+
matrix :: [[Int]] -> [[Int]]
6+
matrix arr = changeDiags 0 arr
7+
8+
changeDiags :: Int -> [[Int]] -> [[Int]]
9+
changeDiags _ [] = []
10+
changeDiags i (x : xs) = (changeRow i x :) . changeDiags (i + 1) $ xs
11+
12+
changeRow :: Int -> [Int] -> [Int]
13+
changeRow index xs
14+
| xs !! index < 0 = replace index 0 xs
15+
| otherwise = replace index 1 xs
16+
17+
replace :: Int -> a -> [a] -> [a]
18+
replace pos x xs = (take pos xs ++) . (x :) . drop (pos + 1) $ xs

test/MatrixSpec.hs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
module MatrixSpec where
2+
3+
import Matrix (matrix)
4+
import Test.Hspec
5+
6+
spec :: Spec
7+
spec = do
8+
describe "Fixed Tests" $ do
9+
mapM_
10+
fixedTest
11+
[ ( [ [-1, 4, -5, -9, 3],
12+
[6, -4, -7, 4, -5],
13+
[3, 5, 4, -9, -1],
14+
[1, 5, -7, -8, -9],
15+
[-3, 2, 1, -5, 6]
16+
],
17+
[ [0, 4, -5, -9, 3],
18+
[6, 0, -7, 4, -5],
19+
[3, 5, 1, -9, -1],
20+
[1, 5, -7, 0, -9],
21+
[-3, 2, 1, -5, 1]
22+
]
23+
),
24+
( [ [-1, 4, -5, -9, 3],
25+
[6, 8, -7, 4, -5],
26+
[3, 5, 1, -9, -1],
27+
[1, 5, -7, 15, -9],
28+
[-3, 2, 1, -5, -6]
29+
],
30+
[ [0, 4, -5, -9, 3],
31+
[6, 1, -7, 4, -5],
32+
[3, 5, 1, -9, -1],
33+
[1, 5, -7, 1, -9],
34+
[-3, 2, 1, -5, 0]
35+
]
36+
),
37+
( [ [-1, 4, -5, -9, 3, 8],
38+
[6, 8, -7, 4, -5, -1],
39+
[3, 5, 1, -9, -1, 6],
40+
[1, 5, -7, 15, -9, 3],
41+
[-3, 2, 1, -5, -6, 0],
42+
[8, 2, 0, -2, 4, -5]
43+
],
44+
[ [0, 4, -5, -9, 3, 8],
45+
[6, 1, -7, 4, -5, -1],
46+
[3, 5, 1, -9, -1, 6],
47+
[1, 5, -7, 1, -9, 3],
48+
[-3, 2, 1, -5, 0, 0],
49+
[8, 2, 0, -2, 4, 0]
50+
]
51+
),
52+
( [ [1, 1, -5, 5],
53+
[2, -4, 11, 2],
54+
[3, 1, -1, 4],
55+
[2, -6, 8, 10]
56+
],
57+
[ [1, 1, -5, 5],
58+
[2, 0, 11, 2],
59+
[3, 1, 0, 4],
60+
[2, -6, 8, 1]
61+
]
62+
)
63+
]
64+
65+
fixedTest :: ([[Int]], [[Int]]) -> SpecWith ()
66+
fixedTest (inp, ans) = it ("matrix " ++ show inp) $ matrix inp `shouldBe` ans

0 commit comments

Comments
 (0)