Skip to content

Commit

Permalink
Optimized loops
Browse files Browse the repository at this point in the history
  • Loading branch information
loz committed Dec 3, 2012
1 parent 223bfb7 commit 1cb0c91
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
47 changes: 34 additions & 13 deletions Arigeom/lib/arigeom.rb
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env ruby

class Arigeom
def permutations(set)
options = []
Expand All @@ -21,30 +23,49 @@ def arithmetic_change(set)
end

def find_geometric(set)
options = permutations(set)
changes = options.map { |o| {set: o, change: geometric_change(o)} }
sets = changes.select {|o| o[:change].uniq.length == 1 }
sets = sets.map { |o| o[:set] }
sets.last
combination_select(set) do |combi|
geometric_change(combi)
end.last
end

def find_arithmetic(set)
options = permutations(set)
changes = options.map { |o| {set: o, change: arithmetic_change(o)} }
sets = changes.select {|o| o[:change].uniq.length == 1 }
sets = sets.map { |o| o[:set] }
sets.last
combination_select(set) do |combi|
arithmetic_change(combi)
end.last
end

private

def combination_select(set, &block)
selected = []
(2..set.length).each do |size|
set.combination(size).each do |s|
changes = yield s
if changes.uniq.size == 1
selected << s
end
end
end
selected
end

def differ(set, &block)
options = set.dup
last = options.shift
options.map do |s|
last = set.first
set[1..-1].map do |s|
change = yield(s, last)
last = s
change
end
end
end

if __FILE__ == $0
finder = Arigeom.new
tests = readline.chomp.to_i
tests.times do
_ = readline
set = readline.split(' ').map &:to_i
puts finder.find_arithmetic(set).join(" ")
puts finder.find_geometric(set).join(" ")
end
end
9 changes: 9 additions & 0 deletions Arigeom/testfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
4
6
2 4 5 8 11 16
5
1 2 3 4 5
8
1 3 9 10 19 27 28 81
6
1 4 7 10 13 25

0 comments on commit 1cb0c91

Please sign in to comment.