-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktracking.rb
More file actions
44 lines (35 loc) · 847 Bytes
/
backtracking.rb
File metadata and controls
44 lines (35 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Backtracking
# https://en.wikipedia.org/wiki/Backtracking
module Backtracking
def self.permutations(s, block = Proc.new)
n = s.length
a = s.split('')
permute(a, 0, n-1, block)
end
def self.permute(a, l, r, block = Proc.new)
if l == r
block.call a.join
else
(l..r).each do |i|
a[l], a[i] = a[i], a[l]
permute(a.clone, l+1, r, block)
a[l], a[i] = a[i], a[l]
end
end
end
def self.test(text = "abcd")
permutations(text) do |permutation|
puts permutation
end
end
end
def process_input(text)
Backtracking.permutations(text)
end
puts process_input(ARGV[0]) if __FILE__==$0
# usage
# $ irb
# > require './algorithms/backtracking.rb'
# > Backtracking.permutations("abcd") { |permutation| puts permutation }
# or
# ruby algorithms/backtracking.rb abcd