Skip to content

Instantly share code, notes, and snippets.

@Arkham
Last active November 24, 2023 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arkham/fec786e6ce4239197fa377eecee1e407 to your computer and use it in GitHub Desktop.
Save Arkham/fec786e6ce4239197fa377eecee1e407 to your computer and use it in GitHub Desktop.
a functional altermative
# generate 100 random integers and store them in a file
STORE = "numbers.txt"
unless File.exists?(STORE)
File.write(STORE, 100.times.map { Random.rand(10) }.join("\n"))
end
numbers = File.read(STORE).split("\n").map { |n| n.to_i }
puts numbers
# numbers.each_with_index do |num, index|
# puts "#{index}: #{"#" * num}"
# end
# 91: ######
# 92: ######
# 91-92: ######
# keep track of a previous number
# if current number is same as previous number, do nothing
# otherwise, print summary of previous group
# previous_num = nil
# previous_index = nil
# numbers.each_with_index do |num, index|
# if previous_num
# next if num == previous_num
# if previous_index == index - 1
# puts "#{previous_index}: #{"#" * previous_num}"
# else
# puts "#{previous_index}-#{index-1}: #{"#" * previous_num}"
# end
# end
# previous_num = num
# previous_index = index
# end
# total = numbers.length
# if previous_index == total - 1
# puts "#{previous_index}: #{"#" * previous_num}"
# else
# puts "#{previous_index}-#{total-1}: #{"#" * previous_num}"
# end
# initial = {
# last_num: nil,
# result: []
# }
# grouped = numbers.each_with_index.each_with_object(initial) do |pair, state|
# num, _ = pair
# if state[:last_num] == num
# state[:result].last.push(pair)
# else
# state[:result].push([pair])
# end
# state[:last_num] = num
# end[:result]
# grouped.each do |group|
# if group.length == 1
# num, index = group.last
# puts "#{index}: #{"#" * num}"
# else
# num, first_idx = group.first
# _, last_idx = group.last
# puts "#{first_idx}-#{last_idx}: #{"#" * num}"
# end
# end
numbers.each_with_index.slice_when do |prev, curr|
prev.first != curr.first
end.each do |group|
case group
in [[num, index]]
puts "#{index}: #{"#" * num}"
in [[num, first_idx], *, [_, last_idx]]
puts "#{first_idx}-#{last_idx}: #{"#" * num}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment