Ad
How To Split A String Into Consecutive Substrings Of Length At Most 3 In All Possible Ways?
I am trying to take a string, between length 1 and 10, and output all possible ways of breaking up the string into consecutive substrings that are of sizes 1, 2, or 3. For example:
Input: 123456
Slice the integer into individual characters, then proceed through to find combinations. The code would return all of the following arrays.
[1, 2, 3, 4, 5, 6]
[12, 3, 4, 5, 6]
[1, 23, 4, 5, 6]
[1, 2, 34, 5, 6]
[1, 2, 3, 45, 6]
[1, 2, 3, 4, 56]
[12, 34, 5, 6]
[12, 3, 45, 6]
[12, 3, 4, 56]
[1, 23, 45, 6]
[1, 2, 34, 56]
[1, 23, 4, 56]
[12, 34, 56]
[123, 4, 5, 6]
[1, 234, 5, 6]
[1, 2, 345, 6]
[1, 2, 3, 456]
[123, 456]
[1, 23, 456]
[1, 234, 56]
[12, 345, 6]
[12, 3, 456]
[123, 4, 56]
[123, 45, 6]
I'm trying to do this in ruby. Thanks!
Ad
Answer
Here's a working function. May be not optimal as I didn't spend much time on it.
str = "1234567890"
def f(s, n)
return [[]] if s.empty?
(1..[n, s.length].min).map{|c| f(s[c..-1], n).map{|a| [s[0, c]] + a}}.inject(&:+)
end
puts f(str, 3).collect{|l| l * "\t"}
EDIT: Made it a bit shorter and the length is now passed as second parameter to function for flexibility.
Ad
source: stackoverflow.com
Related Questions
- → Trigger a click with jQuery using link_to of rails 4
- → Adding html data attribute to simple_forms input
- → How to remove parameters from the root URL if it does I18n
- → passing parameters to rails back end from an ajax call
- → Blocking ?page= in robots.txt
- → react js and rails Updating state on a component with active record relationship
- → Kaminari How to process routes as javascript
- → State not passed into prop
- → Cannot read property 'modalIsOpen' of undefined
- → Objects not valid issue
- → How can I add a featured image from a blog post to my homepage on shopify
- → Need "add to cart" button price to update with correct amount depending on what checkbox is checked
- → GET /admin/webhooks.json returns an empty array
Ad