Skip to content

Instantly share code, notes, and snippets.

@dgageot
Created February 1, 2018 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgageot/3bc11338ca2e17fc2a8b6a0025e3184a to your computer and use it in GitHub Desktop.
Save dgageot/3bc11338ca2e17fc2a8b6a0025e3184a to your computer and use it in GitHub Desktop.
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package main
import "fmt"
func main() {
fmt.Println(permutationAtIndex([]string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 999999))
}
func permutationAtIndex(digits []string, index int) []string {
var result []string
length := len(digits)
for i := 0; i < length; i++ {
permutationCountForTheOtherDigits := fact(length - i - 1)
choice := index / permutationCountForTheOtherDigits
index = index % permutationCountForTheOtherDigits
result = append(result, digits[choice])
digits = removeDigitAt(digits, choice)
}
return result
}
func fact(n int) int {
f := 1
for i := 2; i <= n; i++ {
f *= i
}
return f
}
func removeDigitAt(digits []string, index int) []string {
return append(digits[0:index], digits[index+1:]...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment