ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Ruby] Nested loops _ String
    coding for food 2022. 8. 2. 13:08
    # Nested Loops 
    
    arr = ["a", "b", "c", "d"]
    
    # below we iterate through all possible w/duplicates
    
    arr.each do |ele1|
      arr.each do |ele2|
        puts ele1 + ele2
      end
    end
    -----------------------------
    #=>
    aa
    ab
    ac
    ad
    ba
    bb
    bc
    bd
    ca
    cb
    cc
    cd
    da
    db
    dc
    dd
    # below we iterate through only unique pairs
    
    arr.each_with_index do |ele1, idx1|
      arr.each_with_index do |ele2, idx2|
        if idx2 > idx1
          puts ele1 + ele2
          puts idx1.to_s + "  " + idx2.to_s
          puts "------"
        end
      end
    end
    
    # if idx2 is greater than idx1, then idx2 is never referring to what idx1 referred to previously.
    # Right, basically idx2 is always going to a new element and never trying to touch what idx1 already touched previously.
    -----------------------------------------
    #=>
    ab
    0  1
    ------
    ac
    0  2
    ------
    ad
    0  3
    ------
    bc
    1  2
    ------
    bd
    1  3
    ------
    cd
    2  3
    ------

     

Designed by Tistory.