杨辉三角
给定一个非负整数numRows,生成杨辉三角的前numRows行。
在杨辉三角中,每个数是它的左上方和右上方的数的和。
public List<List<Integer>> generate(int numRows){ List<List<Integer>> ret = new ArrayList<>(); List<Integer> row = new ArrayList<>(); row.add(1); ret.add(row); for (int i = 0; i < numRows; i++) { List<Integer> curRow = new ArrayList<>(); curRow.add(1); List<Integer> prevRow = ret.get(i-1); for (int j = 0; j < i; j++) { int x = prevRow.get(j)+prevRow.get(j-1); curRow.add(x); } curRow.add(1); ret.add(curRow); } return ret; }
洗牌算法
import java.util.ArrayList; import java.util.List; import java.util.Random; public class CardList { private static final String[] SUITS = {"♦","❤","♠","♣"}; public static List<Card> buyCards(){ List<Card> list = new ArrayList<>(); for (int i = 0; i < SUITS.length; i++) { for (int j = 0; j <= 13; j++) { Card card = new Card(SUITS[i],j); list.add(card); } } return list; } public static void shuffle(List<Card> list){ Random random = new Random(); for (int i = list.size()-1; i > 0; i++) { int index = random.nextInt(i); swap(list,i,index); } } private static void swap(List<Card> list,int i,int j){ Card tmp = list.get(i); list.set(i,list.get(i)); list.set(j,tmp); } public static void main(String[] args) { List<Card> list = buyCards(); System.out.println(list); shuffle(list); System.out.println(list); List<List<Card>> hand = new ArrayList<>(); List<Card> hand1 = new ArrayList<>(); List<Card> hand2 = new ArrayList<>(); List<Card> hand3 = new ArrayList<>(); hand.add(hand1); hand.add(hand2); hand.add(hand3); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { Card card = list.remove(0); hand.get(j).add(card); } } } }
public class Card { private String suit; private int rank; public Card(String suit, int rank) { this.suit = suit; this.rank = rank; } @Override public String toString() { return "Card{" + "suit='" + suit + '\'' + ", rank=" + rank + '}'; } public String getSuit() { return suit; } public void setSuit(String suit) { this.suit = suit; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } }