Skip to content

Commit

Permalink
Merge 9fd043c into b8a3f20
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 26, 2019
2 parents b8a3f20 + 9fd043c commit 7f8c5c4
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,4 +393,5 @@ problems from
* [Day 398](https://github.com/vaskoz/dailycodingproblem-go/issues/799)
* [Day 399](https://github.com/vaskoz/dailycodingproblem-go/issues/801)
* [Day 400](https://github.com/vaskoz/dailycodingproblem-go/issues/803)
* [Day 401](https://github.com/vaskoz/dailycodingproblem-go/issues/805)

22 changes: 22 additions & 0 deletions day401/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package day401

// ApplyPermutation mutates the given input based on the
// permutation information in the 2nd argument.
// Runs in O(N) time and O(N/2) space.
// Correct input is the responsibility of the caller.
func ApplyPermutation(input []interface{}, permutation []int) {
if len(input) != len(permutation) {
panic("permutation length must match input length")
}

passed := make(map[int]interface{}, len(input))

for i, pos := range permutation {
if pos < i {
input[i] = passed[pos]
} else {
passed[i] = input[i]
input[i] = input[pos]
}
}
}
50 changes: 50 additions & 0 deletions day401/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package day401

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
input []interface{}
perm []int
expected []interface{}
}{
{
[]interface{}{"a", "b", "c"},
[]int{2, 1, 0},
[]interface{}{"c", "b", "a"},
},
}

func TestApplyPermutation(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
copied := append([]interface{}{}, tc.input...)
if ApplyPermutation(copied, tc.perm); !reflect.DeepEqual(copied, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, copied)
}
}
}

func TestApplyPermutationBadInput(t *testing.T) {
t.Parallel()

defer func() {
if err := recover(); err == nil {
t.Errorf("Expected a panic")
}
}()
ApplyPermutation([]interface{}{"a", "b", "c"}, []int{2, 1, 0, 3})
}

func BenchmarkApplyPermutation(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
copied := append([]interface{}{}, tc.input...)
ApplyPermutation(copied, tc.perm)
}
}
}

0 comments on commit 7f8c5c4

Please sign in to comment.