Skip to content

Instantly share code, notes, and snippets.

@tbilous
Created July 12, 2019 05:56
Show Gist options
  • Save tbilous/d6abcc0e2acdb263f468983946aab5ef to your computer and use it in GitHub Desktop.
Save tbilous/d6abcc0e2acdb263f468983946aab5ef to your computer and use it in GitHub Desktop.
Part 1 Task2 (Ver.2)
#!/usr/bin/env ruby
# example: ruby task_p1_t2_v2.rb 'To be or not to be -that is the question' 5
require 'ostruct'
v1, v2 = ARGV
input_str = v1
n = v2.to_i
input_words = input_str.split(/\s+/)
first_word = input_words.shift
initial_state = OpenStruct.new(
out: [],
current_line_len: 0,
buffer: [first_word],
last_seen: first_word
)
res = input_words.each_with_object(initial_state) do |current_word, state|
current_word_len = current_word.length
if current_word_len > n
chunks = current_word.chars.each_slice(n).to_a.map(&:join)
current_word = chunks.pop
state.out.push(state.buffer.join(' '))
state.out += chunks
state.buffer = [current_word]
state.current_line_len = current_word.length
elsif state.current_line_len + current_word_len + state.buffer.count <= n
state.current_line_len += current_word_len
state.buffer.push(current_word)
else
state.out.push(state.buffer.join(' '))
state.buffer = [current_word]
state.current_line_len = current_word.length
end
state.last_seen = current_word
puts state
end
puts res.out.push(res.last_seen).join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment