Generate sequences of adjecent subsets (from a list of lists) [closed]
Вопрос
I have an matrix (array of arrays) in the form
[1, 2, 3, 4]
[12, 23, 34]
[123, 234]
[1234]
And want to produce sequences of this matrix that is following each other and is (converted to a string) in the same length as the array at index 0 (top-most). So i.e. the result of this would be
[1, 2, 3, 4]
[12, 3, 4]
[1, 23, 4]
[1, 2, 34]
[12, 34]
[123, 4]
[1, 234]
[1234]
The thing I want to achive is to get all parts of a string that can be directly connected to each other and splitted i sub arrays (as shown in the example).
The implementation language is irrelevant but preferably in i.e. Python, java, ruby, C#, clojure, Psudo code, or other language at a fairly high level.
Решение
I improved the code from my previous one.
a = ["1", "2", "3", "4"]
['', '.'].repeated_permutation(a.length - 1).map{|b| a.zip(b).join.split('.')}
will give you:
[
["1234"],
["123", "4"],
["12", "34"],
["12", "3", "4"],
["1", "234"],
["1", "23", "4"],
["1", "2", "34"],
["1", "2", "3", "4"]
]
Другие советы
Here's a Python version (edited to be more concise; thanks to FMc's suggestions):
def consecutive_slice(arr):
yield arr
mx = len(arr) + 1
for size in xrange(2, mx):
for i in xrange(mx - size):
yield(arr[:i] + [''.join(arr[i:i+size])] + arr[i+size:])
Usage example:
>>> for seq in consecutive_slice(['1', '2', '3', '4']):
... print(seq)
...
['1', '2', '3', '4']
['12', '3', '4']
['1', '23', '4']
['1', '2', '34']
['123', '4']
['1', '234']
['1234']
def adj(ar)
result = [ar]
2.upto ar.size do |j|
0.upto ar.size-j do |i|
result << [*ar[0, i], ar[i,j].join.to_i, *ar[i+j..-1]]
end
end
result
end
Test
a = [*1..5]
adj a
# [[1, 2, 3, 4, 5],
# [12, 3, 4, 5],
# [1, 23, 4, 5],
# [1, 2, 34, 5],
# [1, 2, 3, 45],
# [123, 4, 5],
# [1, 234, 5],
# [1, 2, 345],
# [1234, 5],
# [1, 2345],
# [12345]]
EDIT
If you want it work with Ruby 1.8.7 (upper is 1.9+)
def adj(ar)
result = [ar]
2.upto ar.size do |j|
0.upto ar.size-j do |i|
result << [ar[0, i], ar[i,j].join.to_i, ar[i+j..-1]].flatten
end
end
result
end
a = (1..5).to_a
adj a
#=> same result
Oh, Here is a cool functional (is it?) one-line solution:
a = [1,2,3,4]
result = [array]
2.upto(a.size){ |s| a.each_cons(s).with_index{ |g, i| result << [*(a-g)[0, i], g.join.to_i, *(a-g)[i..-1]] } }
result
# [[1, 2, 3, 4],
# [12, 3, 4],
# [1, 23, 4],
# [1, 2, 34],
# [123, 4],
# [1, 234],
# [1234]]
(Ruby version) I believe that this works in the general case for your matrix. I converted to strings so the sort would work out nicely. Edited to include ['12', '34'] in the generated sequence.
m = [['1', '2', '3', '4'], ['12', '23', '34'], ['123', '234'], ['1234']]
m0 = m.first.join
seq = m.map do |row|
( 1..row.size ).map { |e| row.combination( e ).to_a }.flatten( 1 ).map do |a|
m0.include?( str = a.join ) ? ( m0.delete( str ).chars.to_a + a ).sort : nil
end.compact.uniq
end.flatten 1