Cartesian 0.2.1 → 0.2.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. data/lib/URL desafio.txt +1 -0
  2. data/lib/cartesian.rb +44 -4
  3. metadata +3 -2
@@ -0,0 +1 @@
1
+ http://www.ic.unicamp.br/~vignatti/desafio2.html
data/lib/cartesian.rb CHANGED
@@ -43,11 +43,19 @@ module Cartesian
43
43
  #
44
44
  # [1,2].cartesian %w(A B) #=> [[1, "A"], [1, "B"], [2, "A"], [2, "B"]]
45
45
  #
46
- def Cartesian.product(first, second)
46
+ # optional parameter {:flatten => true}
47
+ #
48
+ def Cartesian.product(first, second, params={})
49
+ params[:flatten] ||= true
50
+
47
51
  result = []
48
52
  first.each do |a|
49
53
  second.each do |b|
50
- result << [a, b]
54
+ if params[:flatten] == true
55
+ result << [a, b].flatten
56
+ else
57
+ result << [a, b]
58
+ end
51
59
  end
52
60
  end
53
61
  result
@@ -55,8 +63,8 @@ module Cartesian
55
63
 
56
64
  # Cartesian.product for mixin.
57
65
  #
58
- def cartesian(other)
59
- Cartesian.product(self, other)
66
+ def cartesian(other, params={})
67
+ Cartesian.product(self, other, params)
60
68
  end
61
69
 
62
70
  # Behaves as product, except for the elements are joined.
@@ -106,6 +114,38 @@ module Cartesian
106
114
  def x(other)
107
115
  CartesianIterator.new(self, other)
108
116
  end
117
+
118
+ # Concise way of iterating multi-dimensionally
119
+ # over the same array or range.
120
+ #
121
+ # For instance,
122
+ #
123
+ # for x,y,z in [0,1]**3
124
+ # puts [x, y, z].join(',')
125
+ # end
126
+ #
127
+ # produces the following output
128
+ #
129
+ # 0,0,0
130
+ # 0,0,1
131
+ # 0,1,0
132
+ # 0,1,1
133
+ # 1,0,0
134
+ # 1,0,1
135
+ # 1,1,0
136
+ # 1,1,1
137
+ #
138
+ # It also works with Range objects.
139
+ #
140
+ def **(fixnum)
141
+ return self if fixnum <= 1
142
+ iter = CartesianIterator.new(self, self)
143
+ (fixnum-2).times do
144
+ iter.x(self)
145
+ end
146
+ iter
147
+ end
148
+ alias :power! :**
109
149
  end
110
150
 
111
151
  class Array
metadata CHANGED
@@ -3,8 +3,8 @@ rubygems_version: 0.9.0
3
3
  specification_version: 1
4
4
  name: Cartesian
5
5
  version: !ruby/object:Gem::Version
6
- version: 0.2.1
7
- date: 2007-01-07 00:00:00 -03:00
6
+ version: 0.2.3
7
+ date: 2007-01-13 00:00:00 -03:00
8
8
  summary: The Cartesian module provide methods for the calculation of the cartesian producted between two enumberable objects. It can also be easily mixed in into any enumberable class, i.e. any class with Enumerable module mixed in.
9
9
  require_paths:
10
10
  - lib
@@ -33,6 +33,7 @@ files:
33
33
  - tests/tc_cartesian.rb
34
34
  - lib/cartesian.rb
35
35
  - lib/cartesian_iterator.rb
36
+ - lib/URL desafio.txt
36
37
  test_files:
37
38
  - tests/tc_cartesian.rb
38
39
  rdoc_options: []