How do you iterate over a 2d array in increments a

2019-07-06 22:34发布

I'm trying to grab two subarrays at a time within an array - any ideas on how to do this?

example:

deck = [[2,spades],[3,hearts],[6,diamonds],[10,clubs],[8,hearts],[9,clubs]]

Is there any way to grab two cards at a time with a loop, so the index would increase every time and go from [0..1] then [1..0] and so on to grab two cards at a time.

I'd like to put:

player 1 cards: [2,spades],[3,hearts]

player 2 cards: [6,diamonds],[10,clubs]

3条回答
我只想做你的唯一
2楼-- · 2019-07-06 22:50

My recommendation would just be to pass the deck array in to a method and return an array with [player1, player2, deck]. If you're just drawing from the "top" of the deck, you can just use shift to take the first element out of the array.

The Long Solution

deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]

def drawTwo(arr)
  if arr.count >= 4
    player_one = [deck.shift, deck.shift]
    player_two = [deck.shift, deck.shift]
    return [player_one, player_two, deck]
  else
    return "Not enough cards in deck, please provide a new deck"
  end
end

round = drawTwo(deck)
player_one = round[0]
player_two = round[1]
deck = round[2]

puts "Player one: #{player_one}"
puts "Player two: #{player_two}"
puts "Deck: #{deck}"

I tried to be pretty detailed and not obfuscate this code much so it should read pretty explanatory.

You could make it a bit shorter by rewriting it like this, I just wanted it to be understandable what was happening:

The Condensed Solution

deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]

def drawTwo(arr)
  arr.count >= 4 ? [[arr.shift, arr.shift], [arr.shift, arr.shift]] : raise "Not enough cards..."
end

player_one, player_two = drawTwo(deck)

puts "Player one: #{player_one}"
puts "Player two: #{player_two}"
puts "Deck: #{deck}"

Be sure to include a deck.shuffle when you first generate the deck.

Also, I don't know what you're using to generate the deck, but since I was having fun with it:

Generating A Shuffled Deck

def newShuffledDeck
    ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
    suits = ["hearts", "spades", "clubs", "diamonds"]
    deck = ranks.product(suits)
    deck.shuffle
end
查看更多
太酷不给撩
3楼-- · 2019-07-06 22:53

Try this

hands = array.each_slice(hand_size).take(player_count)

hands.each_with_index do |hand, n|
  puts "player #{n + 1} cards are: #{hand}"
end

How does this work?

  • each_slice(n) cuts the array into pieces of length n
  • take(n) takes the first n pieces
查看更多
孤傲高冷的网名
4楼-- · 2019-07-06 22:56

You could use Enumerable::each_slice

deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]

deck.each_slice(2) do |el|
  puts el
end
查看更多
登录 后发表回答