Use extra functions and stop using downcase array.
This commit is contained in:
		
							parent
							
								
									a24b176417
								
							
						
					
					
						commit
						24c93c7a63
					
				
							
								
								
									
										22
									
								
								common.cr
									
									
									
									
									
								
							
							
						
						
									
										22
									
								
								common.cr
									
									
									
									
									
								
							@ -20,3 +20,25 @@ class Rectangle
 | 
			
		||||
    end
 | 
			
		||||
  end
 | 
			
		||||
end
 | 
			
		||||
 | 
			
		||||
class String
 | 
			
		||||
  def select(&block)
 | 
			
		||||
    String.build do |s|
 | 
			
		||||
      each_char do |c|
 | 
			
		||||
        s << c if yield c
 | 
			
		||||
      end
 | 
			
		||||
    end
 | 
			
		||||
  end
 | 
			
		||||
 | 
			
		||||
  def select!(&block)
 | 
			
		||||
    i = 0
 | 
			
		||||
    s = size
 | 
			
		||||
    while i < s
 | 
			
		||||
      if yield [i]
 | 
			
		||||
        i += 1
 | 
			
		||||
      else
 | 
			
		||||
        s -= 1
 | 
			
		||||
      end
 | 
			
		||||
    end
 | 
			
		||||
  end
 | 
			
		||||
end
 | 
			
		||||
 | 
			
		||||
							
								
								
									
										7
									
								
								day5.cr
									
									
									
									
									
								
							
							
						
						
									
										7
									
								
								day5.cr
									
									
									
									
									
								
							@ -3,7 +3,6 @@ require "./common.cr"
 | 
			
		||||
lines = File.read("day5_input").split("\n")
 | 
			
		||||
 | 
			
		||||
def react(string)
 | 
			
		||||
  lower = string.downcase.chars
 | 
			
		||||
  string = string.chars
 | 
			
		||||
 | 
			
		||||
  changed = true
 | 
			
		||||
@ -13,11 +12,9 @@ def react(string)
 | 
			
		||||
    while i < string.size - 1
 | 
			
		||||
      next_i = i + 1
 | 
			
		||||
      if string[i] != string[next_i] &&
 | 
			
		||||
          lower[i] == lower[next_i]
 | 
			
		||||
          string[i].downcase == string[next_i].downcase
 | 
			
		||||
        string.delete_at i
 | 
			
		||||
        string.delete_at i
 | 
			
		||||
        lower.delete_at i
 | 
			
		||||
        lower.delete_at i
 | 
			
		||||
 | 
			
		||||
        i -= 1
 | 
			
		||||
        i = 0 if i < 0
 | 
			
		||||
@ -35,7 +32,7 @@ puts react(lines[0]).size
 | 
			
		||||
 | 
			
		||||
pairs = {} of Tuple(Char, Char) => Int32
 | 
			
		||||
('a'..'z').to_a.zip(('A'..'Z').to_a).each do |pair|
 | 
			
		||||
  new_string = lines[0].delete(pair[0]).delete(pair[1])
 | 
			
		||||
  new_string = lines[0].select { |c| c != pair[0] && c != pair[1] }
 | 
			
		||||
  pairs[pair] = react(new_string).size
 | 
			
		||||
end
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user