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

42 lines
993 B
Go

package main
type shuffleDirection int
const (
left shuffleDirection = iota
right
)
// shuffle creates a new list where an element in one position is repositioned
// to the index of another element. All affected elements then shuffle one place to the left
// or right depending on the direction of the move.
func shuffle(list []any, oldPos, newPos int) []any {
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
}