Skip to content

Commit

Permalink
Merge pull request #61 from feverdreme/master
Browse files Browse the repository at this point in the history
updates to array's min and max
  • Loading branch information
Spu7Nix authored Aug 1, 2021
2 parents 3a6da29 + 45585f1 commit 684e822
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions spwn-lang/libraries/std/array.spwn
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,33 @@ $.assert(!arr2.is_empty())
max: #[desc("Gets the highest number in the array.") example("
arr = [3, 1, 4, 1]
$.assert(arr.max() == 4)

arr = ['abc', 'b', 'abdc']
$.assert(arr.max(key = (el: @string) => el.length) == 'abdc')
")]
(self, minval = -999999999999) {
let highest = minval
(self, key: @macro = (el) => el) {
let highest = self[0]

for el in self {
if el > highest {
if key(el) > key(highest) {
highest = el
}
}

return highest
},
min: #[desc("Gets the lowest number in the array.") example("
arr = [3, 1, 4, 1]
$.assert(arr.min() == 1)

arr = ['abc', 'b', 'abdc']
$.assert(arr.max(key = (el: @string) => el.length) == 'b')
")]
(self, max_val = 999999999999) {
let lowest = max_val
(self, key: @macro = (el) => el) {
let lowest = self[0]

for el in self {
if el < lowest {
if key(el) < key(lowest) {
lowest = el
}
}
Expand Down Expand Up @@ -182,12 +191,12 @@ $.assert(arr.sum() == 15)
},

_partition: #[desc("Private function needed for .sort()")]
(self, low: @number, high: @number, key: @macro = (a, b) => a <= b) {
(self, low: @number, high: @number, comp: @macro = (a, b) => a <= b) {
pivot = self[high]
let i = low - 1

for j in low..high {
if key(self[j], pivot) {
if comp(self[j], pivot) {
i += 1
self[i] <=> self[j]
}
Expand All @@ -210,7 +219,7 @@ arr = [5, 1, 5, 3, 2]
arr.sort(key = (a, b) => a > b)
$.assert(arr == [5, 5, 3, 2, 1])
")]
(self, begin: @number = 0, end: @number = -1, key: @macro = (a, b) => a <= b) {
(self, begin: @number = 0, end: @number = -1, comp: @macro = (a, b) => a <= b) {

// when end == -1, that means the end of the array, but comparing to -1 doesnt work so switch it back to legnth - 1
let new_end = end
Expand All @@ -222,10 +231,10 @@ $.assert(arr == [5, 5, 3, 2, 1])
// no type checking becuase theoretically this can sort anything if it hasthe right comparator
// if sort was overloaded we could have two seperate implementations
if begin < new_end {
let q = self._partition(low = begin, high = new_end, key = key)
let q = self._partition(low = begin, high = new_end, comp = comp)

self.sort(begin = begin, end = q-1, key = key)
self.sort(begin = q+1, end = new_end, key = key)
self.sort(begin = begin, end = q-1, comp = comp)
self.sort(begin = q+1, end = new_end, comp = comp)
}
},

Expand Down

0 comments on commit 684e822

Please sign in to comment.