-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path014_rotate_array.sio
More file actions
102 lines (92 loc) · 2.58 KB
/
014_rotate_array.sio
File metadata and controls
102 lines (92 loc) · 2.58 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//@ run-pass
// HumanEval 014: Rotate Array
//
// Rotate an integer array to the right by k positions.
// Uses the reverse-three-times algorithm: reverse all, reverse first k,
// reverse remaining n-k. Uses struct wrapper for &! mutation.
struct Buf { data: [i64; 256] }
fn reverse_range(buf: &!Buf, lo: i64, hi: i64) with Mut, Panic {
var l = lo
var h = hi
while l < h {
let tmp = buf.data[l]
buf.data[l] = buf.data[h]
buf.data[h] = tmp
l = l + 1
h = h - 1
}
}
fn rotate_right(buf: &!Buf, n: i64, k: i64) with Mut, Panic, Div {
if n <= 1 { return }
let shift = k % n
if shift == 0 { return }
reverse_range(buf, 0, n - 1)
reverse_range(buf, 0, shift - 1)
reverse_range(buf, shift, n - 1)
}
fn main() -> i64 with IO, Mut, Panic, Div {
// Test 1: [1,2,3,4,5] rotated by 2 -> [4,5,1,2,3]
var b1 = Buf { data: [0; 256] }
b1.data[0] = 1
b1.data[1] = 2
b1.data[2] = 3
b1.data[3] = 4
b1.data[4] = 5
rotate_right(&!b1, 5, 2)
assert(b1.data[0] == 4)
assert(b1.data[1] == 5)
assert(b1.data[2] == 1)
assert(b1.data[3] == 2)
assert(b1.data[4] == 3)
// Test 2: [1,2,3,4,5,6,7] rotated by 3 -> [5,6,7,1,2,3,4]
var b2 = Buf { data: [0; 256] }
b2.data[0] = 1
b2.data[1] = 2
b2.data[2] = 3
b2.data[3] = 4
b2.data[4] = 5
b2.data[5] = 6
b2.data[6] = 7
rotate_right(&!b2, 7, 3)
assert(b2.data[0] == 5)
assert(b2.data[1] == 6)
assert(b2.data[2] == 7)
assert(b2.data[3] == 1)
assert(b2.data[4] == 2)
assert(b2.data[5] == 3)
assert(b2.data[6] == 4)
// Test 3: rotate by 0 (no change)
var b3 = Buf { data: [0; 256] }
b3.data[0] = 10
b3.data[1] = 20
b3.data[2] = 30
rotate_right(&!b3, 3, 0)
assert(b3.data[0] == 10)
assert(b3.data[1] == 20)
assert(b3.data[2] == 30)
// Test 4: rotate by n (full rotation = no change)
var b4 = Buf { data: [0; 256] }
b4.data[0] = 10
b4.data[1] = 20
b4.data[2] = 30
rotate_right(&!b4, 3, 3)
assert(b4.data[0] == 10)
assert(b4.data[1] == 20)
assert(b4.data[2] == 30)
// Test 5: rotate by more than n ([1,2,3] rotated by 5 = rotated by 2)
var b5 = Buf { data: [0; 256] }
b5.data[0] = 1
b5.data[1] = 2
b5.data[2] = 3
rotate_right(&!b5, 3, 5)
assert(b5.data[0] == 2)
assert(b5.data[1] == 3)
assert(b5.data[2] == 1)
// Test 6: single element
var b6 = Buf { data: [0; 256] }
b6.data[0] = 99
rotate_right(&!b6, 1, 7)
assert(b6.data[0] == 99)
println("014_rotate_array: ALL TESTS PASSED")
0
}