Last active
March 10, 2017 14:10
-
-
Save npras/2748f0b64a0e1543d04af69505104dfd to your computer and use it in GitHub Desktop.
AF - Codility: Task2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(a) | |
total = a.size | |
lindex = a.size-1 | |
sorted = a.sort | |
min = total | |
combos = [] | |
return 0 if a == sorted | |
(2..total).each do |pair_size| | |
(0..lindex).each_cons(pair_size) { |range| combos << range } | |
end | |
combos.each do |range| | |
duped = a.dup | |
duped[range.first..range.last] = a[range.first..range.last].sort | |
if duped == sorted | |
min = (range.size < min ) ? range.size : min | |
return min if min == 2 | |
end | |
end | |
min | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(a) | |
total = a.size | |
lindex = a.size-1 | |
sorted = a.sort | |
min = total | |
return 0 if a == sorted | |
(2..total).each do |pair_size| | |
(0..lindex).each_cons(pair_size) do |range| | |
duped = a.dup | |
duped[range.first..range.last] = a[range.first..range.last].sort | |
return range.size if duped == sorted # preemptively return before trying larger index ranges. We only need the min | |
end | |
end | |
min | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment