Skip to content

Instantly share code, notes, and snippets.

@Sharrp
Last active August 29, 2015 14:14
Show Gist options
  • Save Sharrp/84a7862c04531fc2e5a6 to your computer and use it in GitHub Desktop.
Save Sharrp/84a7862c04531fc2e5a6 to your computer and use it in GitHub Desktop.
Next number with the same digits
// Find the first number greater than given, made up with the same digits
// 0 - lowest digit in input array of digits
func nextNumber(digits: [Int]) -> [Int]
{
var next = digits
for i in 1..<next.count
{
if next[i] < next[i-1] // First descending order
{
// Find the first greater than next[i]
var replaceIndex = i-1
for j in 0..<i-1
{
if next[j] > next[i]
{
replaceIndex = j
break
}
}
swap(&next[i], &next[replaceIndex])
// Reverse order of remaining digits
var left = i-1
var right = 0
while left > right
{
swap(&next[left--], &next[right++])
}
break
}
}
return next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment