Skip to content

Commit 75ba248

Browse files
committed
Optimization: merge SMoves on the same axis (#6)
1 parent 0883b2e commit 75ba248

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

src/Optimizations.hs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,13 @@ splitLMove [] = []
2020
splitLMove ((LMove a b):Wait:cmds) =
2121
(SMove (fromShortLinDiff a)) : (SMove (fromShortLinDiff b)) : cmds
2222
splitLMove (cmd:cmds) = cmd : (splitLMove cmds)
23+
24+
-- | Turns [SMove a, SMove b] into [SMove x] if a and b are on the same axis
25+
-- and can be combined.
26+
mergeSMoves :: [Command] -> [Command]
27+
mergeSMoves [] = []
28+
mergeSMoves (m1@(SMove (LongLinDiff a1 d1)):m2@(SMove (LongLinDiff a2 d2)):cmds)
29+
| (a1 /= a2) || (d1 + d2 < -15) || (d1 + d2 > 15)
30+
= m1 : (mergeSMoves (m2:cmds))
31+
| otherwise = (SMove (LongLinDiff a1 (d1 + d2))) : cmds
32+
mergeSMoves (cmd:cmds) = cmd : (mergeSMoves cmds)

test/TestOptimizations.hs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ import Optimizations
77
import Trace
88

99
optimizations :: TestTree
10-
optimizations = testGroup "Optimizations" [testSplitLMove]
10+
optimizations = testGroup "Optimizations"
11+
[ testSplitLMove
12+
, testMergeSMoves
13+
]
1114

1215
testSplitLMove :: TestTree
1316
testSplitLMove = testGroup "splitLMove"
@@ -32,3 +35,40 @@ testSplitLMove = testGroup "splitLMove"
3235
splitLMove [LMove a b, Wait, LMove a b, Wait]
3336
@?= [SMove a', SMove b', LMove a b, Wait]
3437
]
38+
39+
testMergeSMoves :: TestTree
40+
testMergeSMoves = testGroup "mergeSMoves"
41+
[ testCase "Empty input" $ mergeSMoves [] @?= []
42+
43+
, testCase "SMoves on different axis" $
44+
let
45+
m1 = SMove (LongLinDiff X 13)
46+
m2 = SMove (LongLinDiff Y (-11))
47+
in mergeSMoves [m1, m2] @?= [m1, m2]
48+
49+
, testCase "Long SMoves can't be combined" $
50+
let
51+
m1 = SMove (LongLinDiff X 13)
52+
m2 = SMove (LongLinDiff X 11)
53+
in mergeSMoves [m1, m2] @?= [m1, m2]
54+
55+
, testCase "Unoptimal input.1" $
56+
let
57+
m1 = SMove (LongLinDiff X 4)
58+
m2 = SMove (LongLinDiff X 3)
59+
result = SMove (LongLinDiff X 7)
60+
in mergeSMoves [m1, m2] @?= [result]
61+
, testCase "Unoptimal input.2" $
62+
let
63+
m1 = SMove (LongLinDiff Z (-11))
64+
m2 = SMove (LongLinDiff Z (-4))
65+
result = SMove (LongLinDiff Z (-15))
66+
in mergeSMoves [m1, m2] @?= [result]
67+
68+
, testCase "Only first occurrence is optimized" $
69+
let
70+
m1 = SMove (LongLinDiff X 4)
71+
m2 = SMove (LongLinDiff X 3)
72+
combined = SMove (LongLinDiff X 7)
73+
in mergeSMoves [m1, m2, m1, m2] @?= [combined, m1, m2]
74+
]

0 commit comments

Comments
 (0)