Skip to content

Instantly share code, notes, and snippets.

@shtakai
Created May 13, 2016 01:11
Show Gist options
  • Save shtakai/8503800c214da43af9daa04b6bd51a21 to your computer and use it in GitHub Desktop.
Save shtakai/8503800c214da43af9daa04b6bd51a21 to your computer and use it in GitHub Desktop.
ex [1,2,3,4] -> [2,1,4,3]
require 'pp'
def dual (a)
return [] if !a.any?
return [a[0]] if a.size == 1
head = [a[1], a[0]]
tail = a[2..a.size]
(head << dual(tail)).compact.flatten
end
(0..10).to_a.each{ |n|
arr = (0..n).to_a
pp "#{arr} -> #{dual arr}"
}
pp "#{[]} -> #{dual []}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment