-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit-sum.zsh
83 lines (71 loc) · 1.78 KB
/
split-sum.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/zsh
splitSum() {
nums=("$@")
totalLeft=0
totalRight=0
left=1
right=$#
if [[ $right -lt 2 ]]; then
echo '" " " "'
return
fi
while [[ $right -ne $left ]]; do
if [[ "$totalLeft" -le "$totalRight" ]]; then
totalLeft=$(($totalLeft + ${nums[$left]}))
left=$(($left + 1))
else
totalRight=$(($totalRight + ${nums[$right]}))
right=$(($right - 1))
fi
done
# Check middle in the left group.
if [ $(($totalLeft + ${nums[$left]})) -eq $totalRight ]; then
leftArray=("${nums[@]:1:$left}")
rightArray=("${nums[@]:$right}")
echo "\"${leftArray[@]}\" \"${rightArray[@]}\""
return
fi
# Check middle in the right group.
if [[ $totalLeft -eq $(($totalRight + ${nums[$right]})) ]]; then
leftArray=("${nums[@]:1:$((left - 1))}")
rightArray=("${nums[@]:$((right - 1))}")
echo "\"${leftArray[@]}\" \"${rightArray[@]}\""
return
fi
echo '" " " "'
return
}
# Global so they aren't reallcoated on the stack each invocation.
cases=(" " \
"100" \
"99 99" \
"98 1 99" \
"99 1 98" \
"1 2 3 0" \
"1 2 3 5" \
"1 2 2 1 0" \
"10 11 12 16 17" \
"1 1 1 1 1 1 6" \
"6 1 1 1 1 1 1" \
)
# Test cases
testCases() {
toScreen=("$@")
for c in ${cases[@]}; do
if [[ -z "$toScreen" ]]; then
splitSum ${=c} > /dev/null
else
echo "zsh: \"$c\" -> $(splitSum ${=c})"
fi
done
}
testCases "true"
start_time=$(date +%s)
# zsh is so slow, do 100,000 then * 10
for ((i = 0; i < 100000; i++)); do
testCases
done
end_time=$(date +%s)
elapsed_time=$((end_time - start_time))
elapsed_time=$((elapsed_time * 10))
echo "zsh: $elapsed_time seconds"