Last active
August 29, 2015 14:27
-
-
Save Po-Jen/8de7af9e797038e18ae9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
simpleDealer()的邏輯很簡單,既然我已經知道要發牌給四個人,那就先產生四個空牌堆。 | |
然後,因為要發13張牌給每個人,那就用for迴圈跑13次,每次都發4張牌。 | |
最後再把四個牌堆都塞到decks裡面,就可以回傳結果了。 | |
*/ | |
function simpleDealer(deck) | |
{ | |
var deckOne = []; | |
var deckTwo = []; | |
var deckThree = []; | |
var deckFour = []; | |
for(var i=0; i<13; i++) | |
{ | |
deckOne.push(deck[4*i]); | |
deckTwo.push(deck[4*i+1]); | |
deckThree.push(deck[4*i+2]); | |
deckFour.push(deck[4*i+3]); | |
} | |
var decks=[]; | |
decks.push(deckOne); | |
decks.push(deckTwo); | |
decks.push(deckThree); | |
decks.push(deckFour); | |
return decks; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
simpleDealer()看起來有點笨,因為必須用var deckOne = [];這種方式手動產生四個牌堆 | |
最後還得把四個牌堆都再塞進decks。 | |
所以我們可以嘗試把這一點改善一下,變成更簡潔的simpleDealerTwo() | |
*/ | |
function simpleDealerTwo(deck) | |
{ | |
var decks = []; | |
for (var init = 0; init < 4; init++) | |
decks.push([]); | |
for(var i=0; i<13; i++) | |
for(var person=0; person<4; person++) | |
decks[person].push(deck[4*i+person]); | |
return decks; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
simplleDealerTwo()還是有一個重大缺點,就是for迴圈執行的次數都是我們寫在程式碼內指定的, | |
如果一直都是發牌給4個人,當然沒有問題。 | |
但如果今天你希望你的function可以發牌給不同人數的人,又不希望更改程式碼, | |
那就必須把"人數"跟"每個人應拿牌數"自動算出,而非手動指定4跟13。 | |
不過,因為你寫function的時候並不知道使用這個函式發牌的人會發給幾個人, | |
所以最好的方法,就是讓使用者可以在呼叫function的時候,自己指定numOfPeople, | |
使用者也會為你的貼心感到窩心。 | |
修改過後的結果就是simpleDealerThree()。 | |
*/ | |
function simpleDealerThree(deck, numOfPeople) | |
{ | |
var decks = []; | |
for (var init = 0; init < numOfPeople; init++) | |
decks.push([]); | |
var cardOfEach = deck.length / numOfPeople; //deck.length是52,除以人數就知道每人可以拿幾張 | |
for(var i=0; i<cardOfEach; i++) | |
for(var person=0; person<numOfPeople; person++) | |
decks[person].push(deck[numOfPeople*i+person]); | |
return decks; | |
} |
在寫程式碼的時候可以用 ``` 上下夾住 會自己 highlight
Cool!謝啦!
應該 上面的 ``` 旁邊加上 js 就會有 js highlight
帥!XD
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
執行:
https://jsbin.com/vasipevuji/edit?js,console