Array that alphabetizes and alternates between all caps

后端 未结 5 990
面向向阳花
面向向阳花 2020-12-22 10:44

I need to get the user to input five words, which I believe I have. Then the program needs to spit the words in alphabetical order with every other word being in all-caps, s

相关标签:
5条回答
  • 2020-12-22 10:49

    I'd use:

    user_input = %w(the quick red fox jumped)
    uc_flag = true
    output = []
    user_input.sort.each { |w| 
      output << if uc_flag
                  w.upcase
                else
                  w.downcase
                end
      uc_flag = !uc_flag
    }
    output # => ["FOX", "jumped", "QUICK", "red", "THE"]
    

    It's old-school but is extremely fast as it only makes one pass through the array.

    It can be written a bit more tersely using:

    output << (uc_flag ? w.upcase : w.downcase)
    

    but ternary statements are generally considered to be undesirable.

    If the user is allowed to enter mixed-case words, use:

    sort_by(&:downcase) 
    

    instead of sort.

    0 讨论(0)
  • 2020-12-22 10:51

    Just out of curiosity:

    arr = %w(orange apple lemon melon lime)
    a1, a2 = arr.sort.partition.with_index { |_, i| i.even? }
    a1.map(&:downcase).zip(a2.map &:upcase).flatten.compact
    
    0 讨论(0)
  • 2020-12-22 10:52

    with_index can help you with the every other word problem:

    words = %w(hello world this is test)
    # => ["hello", "world", "this", "is", "test"]
    words.map(&:downcase).sort.map.with_index {|word, index| index.odd? ? word : word.upcase}
    # => ["HELLO", "is", "TEST", "this", "WORLD"]
    
    0 讨论(0)
  • 2020-12-22 11:10

    Here are two ways that don't use indices.

    arr = %w|the quicK brown dog jumpEd over the lazy fox|
      #=> ["the", "quicK", "brown", "dog", "jumpEd", "over", "the", "lazy", "fox"]
    

    Note:

    arr.sort
      #=> ["brown", "dog", "fox", "jumpEd", "lazy", "over", "quicK", "the", "the"] 
    

    #1

    e = [:UC, :LC].cycle
    arr.sort.map { |w| (e.next == :UC) ? w.upcase : w.downcase }
      # => ["BROWN", "dog", "FOX", "jumped", "LAZY", "over", "QUICK", "the", "THE"]
    

    #2

    arr.sort.each_slice(2).flat_map { |u,v| v ? [u.upcase, v.downcase] : [u.upcase] }
      # => ["BROWN", "dog", "FOX", "jumped", "LAZY", "over", "QUICK", "the", "THE"]  
    
    0 讨论(0)
  • 2020-12-22 11:15

    If I understand well (but the question is not so clear) you want to sort and then put one word out of two in uppercase and the other in lowercase:

    words.sort.each_with_index.map{|w,i| i.odd? ? w.upcase : w.downcase }
    

    Test:

    words=%w( orange banana apple melon)
    

    Result:

    ["APPLE", "banana", "MELON", "orange"]
    
    0 讨论(0)
提交回复
热议问题