Reorder Slice By Permutation Indices

Reorder items by an index permutation after validating length and uniqueness, so bad indices fail before any element is moved.

GoData Integrity

Code

gosnippet
34 lines
package main

import "fmt"

// reorder returns items arranged by perm: out[i] = items[perm[i]].
func reorder[T any](items []T, perm []int) ([]T, error) {
	if len(perm) != len(items) {
		return nil, fmt.Errorf("perm length %d != items %d", len(perm), len(items))
	}
	seen := make([]bool, len(perm))
	for _, p := range perm {
		if p < 0 || p >= len(items) || seen[p] {
			return nil, fmt.Errorf("perm index %d out of range or repeated", p)
		}
		seen[p] = true
	}
	out := make([]T, len(perm))
	for i, p := range perm {
		out[i] = items[p]
	}
	return out, nil
}

func main() {
	steps := []string{"plan", "build", "test", "ship"}

	// reversal by index: ship, test, build, plan
	out, err := reorder(steps, []int{3, 2, 1, 0})
	fmt.Println(out, err)

	// repeated index is rejected before any reorder happens
	_, err = reorder(steps, []int{0, 0, 1, 2})
	fmt.Println("bad perm:", err)
}

Under the hood — Reorder Slice By Permutation Indices

Under the hood: the function main.

One loop does the cycling here: for _, p := range perm.

Points of care

  • The API surface is all built-in, which leaves no supply chain to vet.

Using it

The declaration that sets the shape: func main()

The demo output is labeled (bad perm:); each label names the call that printed it.

Key statements

return nil, fmt.Errorf("perm index %d out of range or repeated", p)
return nil, fmt.Errorf("perm length %d != items %d", len(perm), len(items))
for i, p := range perm {
	out[i] = items[p]
}

Interactive Tools for This Topic

FAQ

What does Reorder Slice By Permutation Indices print when run?
Execute the whole file; each printed line is prefixed with a label like `bad perm:`.