你如何以增量迭代2d数组并用ruby增加增量? [英] How do you iterate over a 2d array in increments and increase the increment with ruby?
问题描述
我试图在阵列中一次抓取两个子阵列 - 有关如何执行此操作的任何想法吗?
I'm trying to grab two subarrays at a time within an array - any ideas on how to do this?
示例:
deck = [[2,spades],[3,hearts],[6,diamonds],[10,clubs],[8,hearts],[9,clubs]]
有没有办法一次抓住两张卡片,所以索引每次都会增加,然后从[0..1]再到[1..0],依此类推,一次抓两张牌。
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.
我想把:
玩家1卡: [2,黑桃],[3,心灵]
玩家2卡: [6,钻石],[10,俱乐部]
推荐答案
我的建议只是将deck数组传递给方法并返回一个数组与[player1,player2,deck]。如果您只是从套牌的顶部绘制,您可以使用 shift
从阵列中取出第一个元素。
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.
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:
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}"
确保第一次包含 deck.shuffle
生成牌组。
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:
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
这篇关于你如何以增量迭代2d数组并用ruby增加增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!