Skip to content

Instantly share code, notes, and snippets.

@jollyjoester
Created January 28, 2022 06:51
Show Gist options
  • Save jollyjoester/7f64049bdaa6eb0611b29a0115469986 to your computer and use it in GitHub Desktop.
Save jollyjoester/7f64049bdaa6eb0611b29a0115469986 to your computer and use it in GitHub Desktop.
What is the 100th word in the permutation of "GAKKOU" in Swift
import Algorithms
let word = ("GAKKOU".permutations().uniqued().map { String($0) }.sorted(by: <)[99])
print(word)
@uhooi
Copy link

uhooi commented Jan 28, 2022

Algorithms を使わないで実装してみました!

import Foundation

private func permutations<T>(of values: [T]) -> [[T]] {
  if values.count <= 1 {
    return [values]
  }
  var results: [[T]] = []
  for i in values.indices {
    let baseValue = values[i]
    var excludingBaseValue = values
    excludingBaseValue.remove(at: i)
    results += permutations(of: excludingBaseValue).map { [baseValue] + $0 }
  }
  return results
}

print(Array(Set(permutations(of: Array("GAKKOU")))).lazy.map { String($0) } .sorted()[99])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment