Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AF - Codility: Task2
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
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