arraylist.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright (c) 2015, Emir Pasic. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package arraylist implements the array list.
  5. //
  6. // Structure is not thread safe.
  7. //
  8. // Reference: https://en.wikipedia.org/wiki/List_%28abstract_data_type%29
  9. package arraylist
  10. import (
  11. "fmt"
  12. "github.com/emirpasic/gods/lists"
  13. "github.com/emirpasic/gods/utils"
  14. "strings"
  15. )
  16. func assertListImplementation() {
  17. var _ lists.List = (*List)(nil)
  18. }
  19. // List holds the elements in a slice
  20. type List struct {
  21. elements []interface{}
  22. size int
  23. }
  24. const (
  25. growthFactor = float32(2.0) // growth by 100%
  26. shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink)
  27. )
  28. // New instantiates a new empty list
  29. func New() *List {
  30. return &List{}
  31. }
  32. // Add appends a value at the end of the list
  33. func (list *List) Add(values ...interface{}) {
  34. list.growBy(len(values))
  35. for _, value := range values {
  36. list.elements[list.size] = value
  37. list.size++
  38. }
  39. }
  40. // Get returns the element at index.
  41. // Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false.
  42. func (list *List) Get(index int) (interface{}, bool) {
  43. if !list.withinRange(index) {
  44. return nil, false
  45. }
  46. return list.elements[index], true
  47. }
  48. // Remove removes one or more elements from the list with the supplied indices.
  49. func (list *List) Remove(index int) {
  50. if !list.withinRange(index) {
  51. return
  52. }
  53. list.elements[index] = nil // cleanup reference
  54. copy(list.elements[index:], list.elements[index+1:list.size]) // shift to the left by one (slow operation, need ways to optimize this)
  55. list.size--
  56. list.shrink()
  57. }
  58. // Contains checks if elements (one or more) are present in the set.
  59. // All elements have to be present in the set for the method to return true.
  60. // Performance time complexity of n^2.
  61. // Returns true if no arguments are passed at all, i.e. set is always super-set of empty set.
  62. func (list *List) Contains(values ...interface{}) bool {
  63. for _, searchValue := range values {
  64. found := false
  65. for _, element := range list.elements {
  66. if element == searchValue {
  67. found = true
  68. break
  69. }
  70. }
  71. if !found {
  72. return false
  73. }
  74. }
  75. return true
  76. }
  77. // Values returns all elements in the list.
  78. func (list *List) Values() []interface{} {
  79. newElements := make([]interface{}, list.size, list.size)
  80. copy(newElements, list.elements[:list.size])
  81. return newElements
  82. }
  83. // Empty returns true if list does not contain any elements.
  84. func (list *List) Empty() bool {
  85. return list.size == 0
  86. }
  87. // Size returns number of elements within the list.
  88. func (list *List) Size() int {
  89. return list.size
  90. }
  91. // Clear removes all elements from the list.
  92. func (list *List) Clear() {
  93. list.size = 0
  94. list.elements = []interface{}{}
  95. }
  96. // Sort sorts values (in-place) using.
  97. func (list *List) Sort(comparator utils.Comparator) {
  98. if len(list.elements) < 2 {
  99. return
  100. }
  101. utils.Sort(list.elements[:list.size], comparator)
  102. }
  103. // Swap swaps the two values at the specified positions.
  104. func (list *List) Swap(i, j int) {
  105. if list.withinRange(i) && list.withinRange(j) {
  106. list.elements[i], list.elements[j] = list.elements[j], list.elements[i]
  107. }
  108. }
  109. // Insert inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
  110. // Does not do anything if position is negative or bigger than list's size
  111. // Note: position equal to list's size is valid, i.e. append.
  112. func (list *List) Insert(index int, values ...interface{}) {
  113. if !list.withinRange(index) {
  114. // Append
  115. if index == list.size {
  116. list.Add(values...)
  117. }
  118. return
  119. }
  120. l := len(values)
  121. list.growBy(l)
  122. list.size += l
  123. // Shift old to right
  124. for i := list.size - 1; i >= index+l; i-- {
  125. list.elements[i] = list.elements[i-l]
  126. }
  127. // Insert new
  128. for i, value := range values {
  129. list.elements[index+i] = value
  130. }
  131. }
  132. // String returns a string representation of container
  133. func (list *List) String() string {
  134. str := "ArrayList\n"
  135. values := []string{}
  136. for _, value := range list.elements[:list.size] {
  137. values = append(values, fmt.Sprintf("%v", value))
  138. }
  139. str += strings.Join(values, ", ")
  140. return str
  141. }
  142. // Check that the index is within bounds of the list
  143. func (list *List) withinRange(index int) bool {
  144. return index >= 0 && index < list.size
  145. }
  146. func (list *List) resize(cap int) {
  147. newElements := make([]interface{}, cap, cap)
  148. copy(newElements, list.elements)
  149. list.elements = newElements
  150. }
  151. // Expand the array if necessary, i.e. capacity will be reached if we add n elements
  152. func (list *List) growBy(n int) {
  153. // When capacity is reached, grow by a factor of growthFactor and add number of elements
  154. currentCapacity := cap(list.elements)
  155. if list.size+n >= currentCapacity {
  156. newCapacity := int(growthFactor * float32(currentCapacity+n))
  157. list.resize(newCapacity)
  158. }
  159. }
  160. // Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity
  161. func (list *List) shrink() {
  162. if shrinkFactor == 0.0 {
  163. return
  164. }
  165. // Shrink when size is at shrinkFactor * capacity
  166. currentCapacity := cap(list.elements)
  167. if list.size <= int(float32(currentCapacity)*shrinkFactor) {
  168. list.resize(list.size)
  169. }
  170. }