laboratory/experiments/go/shuffle-elements/shuffle.go

73 lines
1.7 KiB
Go
Raw Normal View History

2024-01-23 20:51:52 +00:00
package main
type shuffleDirection int
const (
left shuffleDirection = iota
right
)
// shuffleFuncOne creates a new list where an element in one position is repositioned
// to the index of another element. All affected elements then shuffleFuncOne one place to the left
2024-01-23 20:51:52 +00:00
// or right depending on the direction of the move.
func shuffleFuncOne(list []any, oldPos, newPos int) []any {
2024-01-23 20:51:52 +00:00
var direction shuffleDirection
if newPos < oldPos {
direction = right
} else {
direction = left
}
newList := make([]any, len(list))
for i := range list {
switch {
case (direction == right) && (i < newPos || i > oldPos):
newList[i] = list[i]
case (direction == right) && (i == oldPos):
newList[newPos] = list[i]
case (direction == right):
newList[i+1] = list[i]
case (direction == left) && (i < oldPos || i > newPos):
newList[i] = list[i]
case (direction == left) && (i == oldPos):
newList[newPos] = list[i]
case (direction == left):
newList[i-1] = list[i]
}
}
return newList
}
// shuffleFuncTwo produces the same output as shuffleFuncOne using a slightly different method.
// The original slice is copied into a new slice and the element is immediately placed in the new
// position. The for loop then only focuses on the elements in range between the two positions and
// are shuffled left or right as required.
func shuffleFuncTwo(list []any, oldPos, newPos int) []any {
newList := make([]any, len(list))
copy(newList, list)
newList[newPos] = list[oldPos]
if newPos < oldPos {
for i := newPos; i <= oldPos; i++ {
if i != oldPos {
newList[i+1] = list[i]
}
}
return newList
}
for i := oldPos; i <= newPos; i++ {
if i != oldPos {
newList[i-1] = list[i]
}
}
return newList
}