Last active
October 24, 2023 14:23
-
-
Save skatenerd/7ee4ab2b529d4ef0b6d2af5046910447 to your computer and use it in GitHub Desktop.
embolden substrings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def indices(s,t) | |
# indices('abcHellodefHello', 'Hello') | |
# => [3,11] | |
found = s.index(t) | |
if found | |
offset = 1 + found | |
return [found] + indices(s[offset..], t).map {|e| e + offset} | |
else | |
return [] | |
end | |
end | |
def insert_at_indices(t, todo) | |
# insert_at_indices('abcDEFghi', [[3, '____'], [6, '~~~~~~']]) | |
# => "abc____DEF~~~~~~ghi" | |
if todo.empty? | |
return t | |
end | |
first_instruction, *rest_instructions = todo.sort_by(&:first) | |
idx, value = first_instruction | |
t[...idx] + value + insert_at_indices(t[idx..], rest_instructions.map { |instruction_idx, instruction_value| [instruction_idx-idx, instruction_value] }) | |
end | |
def embolden(candidate, targets) | |
# "abc<b>DEF</b>ghi<b>DEF</b>jkl<b>MNO_" | |
# => "abc<b>DEF</b>ghi<b>DEF</b>jkl<b>MNO</b>" | |
bold_ranges = targets.flat_map { |t| indices(candidate,t).map { |e| e...(e+t.length) }} | |
bold_index_set = bold_ranges.flat_map(&:to_a).to_set | |
down = (0..candidate.length).select { |e| !bold_index_set.include?(e) && bold_index_set.include?(e-1) } | |
up = (0...candidate.length).select { |e| bold_index_set.include?(e) && !bold_index_set.include?(e-1) } | |
instructions = up.map { |e| [e,'<b>'] } + down.map { |e| [e, '</b>'] } | |
too_long_answer = insert_at_indices("#{candidate}_", instructions) | |
too_long_answer[...-1] | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment