-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.go
More file actions
80 lines (69 loc) · 1.34 KB
/
array.go
File metadata and controls
80 lines (69 loc) · 1.34 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
package array
import (
"errors"
"fmt"
)
type Array struct {
data []int
length uint
}
func NewArray(capacity uint) *Array {
if capacity == 0 {
return nil
}
return &Array{
data: make([]int,capacity),
length: 0,
}
}
func (a *Array) Len() uint {
return a.length
}
func (a *Array) isIndexOutOfRange(index uint) bool {
if index > uint(cap(a.data)) {
return true
} else {
return false
}
}
func (a *Array) Find(index uint) (int,error) {
if a.isIndexOutOfRange(index) {
return 0, fmt.Errorf("out of index range")
}
return a.data[index],nil
}
func (a *Array) Insert(index uint,v int) error {
if a.Len() == uint(cap(a.data)) {
return errors.New("full array")
}
if index != a.length && a.isIndexOutOfRange(index) {
return errors.New("out of index range")
}
for i:= a.length;i > index;i-- {
a.data[i] = a.data[i-1]
}
a.data[index] = v
a.length++
return nil
}
func (a *Array) InsertToTail(v int) error {
return a.Insert(a.Len(), v)
}
func (a *Array) Delete(index uint) (int,error) {
if a.isIndexOutOfRange(index) {
return 0, errors.New("out of index range")
}
v := a.data[index]
for i := index;i < a.Len() - 1;i++ {
a.data[i] = a.data[i+1]
}
a.length--
return v,nil
}
func (a *Array) Print() {
var format string
for i := uint(0); i < a.Len(); i++ {
format += fmt.Sprintf("|%+v", a.data[i])
}
fmt.Println(format)
}