Collections與應用(PowerPoint2003 ppt 檔, 609KB)

集合
(Collections)
鄭士康
國立台灣大學
電機工程學系/電信工程研究所/
資訊網路與多媒體研究所
1
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
2
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
3
Collections, Enumerator,
Enumerable
•
•
•
•
列串List
動態列串Linked List, 動態加入與刪除, 排序
堆疊
Comparer
4
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
5
UsingList.Program.cs (1/11)
/*
* 示範List的使用
* 1/3/2009
*/
using System;
using System.Collections.Generic;
namespace UsingList
{
public enum Suit
{
CLUB = 0,
DIAMOND = 1,
HEART = 2,
SPADE = 3
}
6
UsingList.Program.cs (2/11)
public struct Card : IComparable<Card>
{
public Suit suit;
public int rank;
public Card(Suit suit, int rank)
{
this.suit = suit;
this.rank = rank;
}
public string Name()
{
string result = null;
7
UsingList.Program.cs (3/11)
switch (suit) {
case Suit.CLUB:
result = "c" +
break;
case Suit.DIAMOND:
result = "d" +
break;
case Suit.HEART:
result = "h" +
break;
case Suit.SPADE:
result = "s" +
break;
default:
break;
}
rank.ToString();
rank.ToString();
rank.ToString();
rank.ToString();
8
UsingList.Program.cs (4/11)
return result;
}
public void Dump()
{
string[] ranks = {
"A", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"J", "Q", "K" };
switch (suit) {
case Suit.CLUB:
Console.Write("c" + ranks[rank - 1]);
break;
case Suit.DIAMOND:
Console.Write("d" + ranks[rank - 1]);
break;
9
UsingList.Program.cs (5/11)
case Suit.HEART:
Console.Write("h" + ranks[rank - 1]);
break;
case Suit.SPADE:
Console.Write("s" + ranks[rank - 1]);
break;
default:
break;
}
}
public int CompareTo(Card c)
{
int result = 0;
10
UsingList.Program.cs (6/11)
if (this.suit < c.suit) {
result = -1;
} else if (this.suit > c.suit) {
result = 1;
} else {
if (this.rank < c.rank) {
result = -1;
} else if (this.rank > c.rank) {
result = 1;
} else {
result = 0;
}
}
return result;
}
}
11
UsingList.Program.cs (7/11)
public class CardComparer : IComparer<Card>
{
public int Compare(Card cx, Card cy)
{
return cx.CompareTo(cy);
}
}
class Program
{
static void Main(string[] args)
{
List<Card> hand = new List<Card>();
WriteList(hand);
12
UsingList.Program.cs (8/11)
Console.WriteLine(
"加入c2, sJ, hQ, hA, d7, c7");
hand.Add(new Card(Suit.CLUB, 2));
hand.Add(new Card(Suit.SPADE, 11));
hand.Add(new Card(Suit.HEART, 12));
hand.Add(new Card(Suit.SPADE, 1));
hand.Add(new Card(Suit.DIAMOND, 7));
hand.Add(new Card(Suit.CLUB, 7));
WriteList(hand);
Console.WriteLine("位置1插入d9");
hand.Insert(1,new Card(Suit.DIAMOND, 9));
WriteList(hand);
Console.WriteLine("移走位置2的牌卡");
hand.Remove(hand[2]);
WriteList(hand);
13
UsingList.Program.cs (9/11)
Console.WriteLine("移走位置3的牌卡");
hand.RemoveAt(3);
WriteList(hand);
Console.WriteLine("反轉排列順序");
hand.Reverse();
WriteList(hand);
Console.WriteLine("重新由小而大排序");
hand.Sort();
WriteList(hand);
int idx;
Card d7 = new Card(Suit.DIAMOND, 7);
Console.WriteLine("搜尋d7");
if (hand.Contains(d7)) {
idx = hand.BinarySearch(d7);
Console.WriteLine(
"於位置{0}找到d7",idx);
}
14
UsingList.Program.cs (10/11)
else {
Console.WriteLine("沒有找到d7");
}
Console.WriteLine("搜尋c10");
idx = hand.BinarySearch(
new Card(Suit.CLUB, 10), new CardComparer());
if (idx >= 0) {
Console.WriteLine(
"於位置{0}找到c10", idx);
}
else {
Console.WriteLine("沒有找到c10");
}
Console.WriteLine();
}
15
UsingList.Program.cs (11/11)
static void WriteList(List<Card> lc)
{
foreach( Card c in lc )
{
c.Dump();
Console.Write("\t");
}
Console.WriteLine(
"容量=" + lc.Capacity +
"; 牌數=" + lc.Count);
}
}
}
16
練習
• 撰寫類別Square,模擬邊長為整數a的正
方形。注意繼承IComparable介面,定義
CompareTo函式,以便比較不同正方形之
大小。
• 撰寫測試程式,建立正方形的List,嘗試
加入或刪除其中元素,反轉排列,重新排
序,以foreach取出所有元素,尋找某一
元素。
17
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
18
堆疊(Stack)
• Push
• Pop
• Peek
top
19
TestStack.Program.cs (1/12)
/*
* 示範Stack的使用
* 1/3/2009
*/
using System;
using System.Collections.Generic;
namespace TestStack
{
public enum Suit
{
CLUB = 0,
DIAMOND = 1,
HEART = 2,
SPADE = 3
}
20
TestStack.Program.cs (2/12)
public struct Card
{
public Suit suit;
public int rank;
public Card(Suit suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public string Name() {
string result = null;
21
TestStack.Program.cs (3/12)
switch (suit) {
case Suit.CLUB:
result = "c" +
break;
case Suit.DIAMOND:
result = "d" +
break;
case Suit.HEART:
result = "h" +
break;
case Suit.SPADE:
result = "s" +
break;
default:
break;
}
rank.ToString();
rank.ToString();
rank.ToString();
rank.ToString();
22
TestStack.Program.cs (4/12)
return result;
}
public void Dump()
{
string[] ranks = {
"A", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"J", "Q", "K" };
switch (suit)
{
case Suit.CLUB:
Console.Write("c" + ranks[rank - 1]);
break;
23
TestStack.Program.cs (5/12)
case Suit.DIAMOND:
Console.Write("d" + ranks[rank - 1]);
break;
case Suit.HEART:
Console.Write("h" + ranks[rank - 1]);
break;
case Suit.SPADE:
Console.Write("s" + ranks[rank - 1]);
break;
default:
break;
}
}
}
24
TestStack.Program.cs (6/12)
public class Deck
{
private Stack<Card> cardStack =
new Stack<Card>();
public Deck()
{
Random rand = new Random();
PrepareDeck(rand);
}
public Deck(int seed)
{
Random rand = new Random(seed);
PrepareDeck(rand);
}
25
TestStack.Program.cs (7/12)
// Reference: ArrayAndFileIO.ppt, p. 39
private void PrepareDeck(Random rand)
{
int i;
bool[] used = new bool[52];
for (i = 0; i < 52; ++i)
{
used[i] = false;
}
int pos;
// position in the table given in reference
int s;
Suit suit;
26
TestStack.Program.cs (8/12)
for (i = 0; i < 52; ++i) {
pos = rand.Next() % 52;
// search for un-used position
while (used[pos]) {
++pos;
pos = pos % 52;
}
s = pos / 13;
switch (s)
{
case 0:
suit = Suit.CLUB;
break;
case 1:
suit = Suit.DIAMOND;
break;
27
TestStack.Program.cs (9/12)
case 2:
suit = Suit.HEART;
break;
case 3:
suit = Suit.SPADE;
break;
default:
suit = Suit.CLUB;
break;
}
int rank = pos % 13 + 1;
used[pos] = true;
cardStack.Push(new Card(suit, rank));
}
}
28
TestStack.Program.cs (10/12)
public Deck(Card[] cards)
{
int nCards = cards.Length;
this.cardStack = new Stack<Card>();
int i;
for (i = 0; i < nCards; ++i)
{
cardStack.Push(cards[i]);
}
}
public Card DealACard()
{
return cardStack.Pop();
}
29
TestStack.Program.cs (11/12)
public bool HasMoreCard()
{
bool empty = false;
try
{
cardStack.Peek();
}
catch (Exception)
{
empty = true;
}
return !empty;
}
}
30
TestStack.Program.cs (12/12)
class Program {
static void Main(string[] args) {
Deck deck = new Deck();
int i;
Card card;
for (i = 0; i < 53; ++i) {
if (deck.HasMoreCard()) {
card = deck.DealACard();
card.Dump();
Console.Write("\t");
if ((i + 1) % 10 == 0)
Console.WriteLine();
}
}
}
}
}
31
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
32
BlackJack_0_1GC.MainForm.cs(1/11)
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace BlackJack_0_1GC
{
//***********************************
public struct PlayerInfo
{
public string name;
public Status status;
33
BlackJack_0_1GC.MainForm.cs(2/11)
public int totalPoints;
public List<Card> cards;
}
//***********************************
public partial class MainForm : Form
{
//*******************************
private Game game;
private PlayerInfo playerInfo;
private PlayerInfo dealerInfo;
private Image image;
private Graphics graphics;
private bool inGame = false;
//*******************************
34
BlackJack_0_1GC.MainForm.cs(3/11)
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender,
EventArgs e)
{
//************************************
game.ProcessPlayerRun(out playerInfo);
ShowInfo();
CheckBlackJackOrBurst(playerInfo);
CheckBlackJackOrBurst(dealerInfo);
//*************************************
}
35
BlackJack_0_1GC.MainForm.cs(4/11)
//*****************************************
private void ShowInfo()
{
int i;
string fileName;
graphics = CreateGraphics();
for (i = 0; i < playerInfo.cards.Count;
++i)
{
fileName = "..\\PlayingCards\\" +
playerInfo.cards[i].Name() + ".jpg";
image = Image.FromFile(fileName);
graphics.DrawImage(image,
5 + 100 * i, 220, 85, 150);
}
36
BlackJack_0_1GC.MainForm.cs(5/11)
for (i = 0; i < dealerInfo.cards.Count;
++i) {
fileName = "..\\PlayingCards\\" +
dealerInfo.cards[i].Name() + ".jpg";
image = Image.FromFile(fileName);
graphics.DrawImage(image,
5 + 100 * i, 5, 85, 150);
}
label1.Text =
dealerInfo.totalPoints.ToString();
label2.Text =
playerInfo.totalPoints.ToString();
label11.Text = dealerInfo.name;
label12.Text = playerInfo.name;
}
//******************************************
37
BlackJack_0_1GC.MainForm.cs(6/11)
private void button3_Click(object sender,
EventArgs e)
{
//**************************************
// "開始"按鈕
inGame = true;
game = new Game();
game.InitPlay(out playerInfo,
out dealerInfo);
ShowInfo();
CheckBlackJackOrBurst(playerInfo);
CheckBlackJackOrBurst(dealerInfo);
button3.Enabled = false;
button4.Enabled = true;
//***************************************
}
38
BlackJack_0_1GC.MainForm.cs(7/11)
private void button2_Click(object sender,
EventArgs e)
{
//**************************************
// "停"按鈕
game.ProcessDealerRun(out dealerInfo);
ShowInfo();
CheckBlackJackOrBurst(playerInfo);
CheckBlackJackOrBurst(dealerInfo);
if (playerInfo.status == Status.PASS &&
dealerInfo.status == Status.PASS)
{
39
BlackJack_0_1GC.MainForm.cs(8/11)
if (dealerInfo.totalPoints >=
playerInfo.totalPoints)
{
MessageBox.Show(dealerInfo.name
+ "勝" + playerInfo.name);
}
else
{
MessageBox.Show(playerInfo.name
+ "勝" + dealerInfo.name);
}
}
//**************************************
}
40
BlackJack_0_1GC.MainForm.cs(9/11)
private void CheckBlackJackOrBurst(
PlayerInfo info)
{
if (info.status == Status.BLACK_JACK)
{
MessageBox.Show(info.name +
" 二十一點");
}
if (info.status == Status.BURST)
{
MessageBox.Show(info.name + " 爆!!!");
}
}
41
BlackJack_0_1GC.MainForm.cs(10/11)
private void button4_Click(object sender,
EventArgs e)
{
//**************************************
// "清除"按鈕
inGame = false;
Invalidate();
label1.Text = "0";
label2.Text = "0";
button4.Enabled = false;
button3.Enabled = true;
//**************************************
}
42
BlackJack_0_1GC.MainForm.cs(11/11)
//****************************************
protected override void OnPaint(
PaintEventArgs e) {
base.OnPaint(e);
if (inGame)
{
ShowInfo();
}
}
private void MainForm_Load(object sender,
EventArgs e)
{}
//*****************************************
}
}
43
BlackJack_0_1GC.Game.cs (1/6)
/*
* 二十一點遊戲, GUI and Collections 版本
* 1/11/2009
*/
using System;
namespace BlackJack_0_1GC
{
class Game
{
const int N_PLAYERS = 2;
Deck deck;
Player[] players = new Player[N_PLAYERS];
public Game()
{
44
BlackJack_0_1GC.Game.cs (2/6)
players[0] = new Player("Jeng");
players[N_PLAYERS - 1] = new Dealer();
deck = new Deck();
}
public void InitPlay(out PlayerInfo
playerInfo, out PlayerInfo dealerInfo)
{
int i;
// 第一輪發牌
for (i = 0; i < N_PLAYERS; ++i)
{
players[i].SaveACard(
deck.DealACard());
}
45
BlackJack_0_1GC.Game.cs (3/6)
// 第二輪發牌
for (i = 0; i < N_PLAYERS; ++i)
{
players[i].SaveACard(
deck.DealACard());
}
playerInfo.name = players[0].Name;
playerInfo.status =
players[0].GetStatus();
playerInfo.totalPoints =
players[0].GetTotalPoints();
playerInfo.cards =
players[0].DumpCards();
dealerInfo.name =
players[N_PLAYERS - 1].Name;
46
BlackJack_0_1GC.Game.cs (4/6)
dealerInfo.status =
players[N_PLAYERS - 1].GetStatus();
dealerInfo.totalPoints =
players[N_PLAYERS - 1].GetTotalPoints();
dealerInfo.cards =
players[N_PLAYERS - 1].DumpCards();
}
public void ProcessPlayerRun(out
PlayerInfo playerInfo)
{
players[0].SaveACard(deck.DealACard());
playerInfo.name = players[0].Name;
playerInfo.status =
players[0].GetStatus();
47
BlackJack_0_1GC.Game.cs (5/6)
playerInfo.totalPoints =
players[0].GetTotalPoints();
playerInfo.cards =
players[0].DumpCards();
}
public void ProcessDealerRun(out
PlayerInfo dealerInfo)
{
while (
players[N_PLAYERS - 1].WantOneMoreCard())
{
players[N_PLAYERS - 1].SaveACard(
deck.DealACard());
}
48
BlackJack_0_1GC.Game.cs (6/6)
dealerInfo.name =
players[N_PLAYERS - 1].Name;
dealerInfo.status =
players[N_PLAYERS - 1].GetStatus();
dealerInfo.totalPoints =
players[N_PLAYERS - 1].GetTotalPoints();
dealerInfo.cards =
players[N_PLAYERS - 1].DumpCards();
}
}
}
49
BlackJack_0_1GC.Player.cs (1/7)
/*
* 模擬玩家, GUI與Collections版本
* 1/11/2009
*/
using System;
using System.Collections.Generic;
namespace BlackJack_0_1GC
{
class Player
{
private List<Card> hand = new List<Card>();
private Status status;
private int totalPoints;
private string name;
50
BlackJack_0_1GC.Player.cs (2/7)
public Player() {
name = "無名氏";
}
public Player(string name)
{
this.name = name;
}
public string Name
{
get { return name; }
}
public void SaveACard(Card card)
{
hand.Add(card);
SetStatus();
}
51
BlackJack_0_1GC.Player.cs (3/7)
public Status GetStatus() {
return status;
}
public int GetTotalPoints()
{
return totalPoints;
}
public List<Card> DumpCards()
{
return hand;
}
virtual public bool WantOneMoreCard()
{
return true; // to be changed for dealer
}
52
BlackJack_0_1GC.Player.cs (4/7)
private void SetStatus()
{
int points;
int sum = 0;
foreach (Card card in hand)
{
points = Points(card.rank);
sum += points;
}
status = JudgeStatus(sum);
totalPoints = sum;
bool isWithAce = false;
if (status == Status.PASS)
{
53
BlackJack_0_1GC.Player.cs (5/7)
// check if with Aces
foreach (Card card in hand) {
points = Points(card.rank);
if (points == 1) {
isWithAce = true;
break;
}
}
if (isWithAce)
{
sum += 10;
if (sum == 21)
{
status = Status.BLACK_JACK;
}
54
BlackJack_0_1GC.Player.cs (6/7)
if (sum <= 21)
{
totalPoints = sum;
}
}
}
}
private int Points(int rank)
{
int points = rank;
if (rank > 10) points = 10;
return points;
}
55
BlackJack_0_1GC.Player.cs (7/7)
private Status JudgeStatus(int sum) {
Status status;
if (sum == 21) {
status = Status.BLACK_JACK;
}
else if (sum > 21) {
status = Status.BURST;
}
else {
status = Status.PASS;
}
return status;
}
}
}
56
BlackJack_0_1GC.Dealer.cs
/*
* 模擬莊家代表
* 10/10/2008
*/
using System;
namespace BlackJack_0_1GC {
class Dealer : Player {
public Dealer() : base("莊家") {
}
override public bool WantOneMoreCard() {
return (base.GetTotalPoints() < 17);
}
}
}
57
BlackJack_0_1GC.Deck.cs (1/6)
/*
* 模擬牌疊--使用堆疊
* 1/11/2009
*/
using System;
using System.Collections.Generic;
namespace BlackJack_0_1GC
{
public class Deck
{
private Stack<Card> cardStack =
new Stack<Card>();
public Deck() {
Random rand = new Random();
PrepareDeck(rand);
}
58
BlackJack_0_1GC.Deck.cs (2/6)
public Deck(int seed)
{
Random rand = new Random(seed);
PrepareDeck(rand);
}
// Reference: ArrayAndFileIO.ppt, p. 39
private void PrepareDeck(Random rand)
{
int i;
bool[] used = new bool[52];
for (i = 0; i < 52; ++i)
{
used[i] = false;
}
59
BlackJack_0_1GC.Deck.cs (3/6)
int pos;
// position in the table given in reference
int s;
Suit suit;
for (i = 0; i < 52; ++i)
{
pos = rand.Next() % 52;
// search for un-used position
while (used[pos])
{
++pos;
pos = pos % 52;
}
s = pos / 13;
60
BlackJack_0_1GC.Deck.cs (4/6)
switch (s) {
case 0:
suit =
break;
case 1:
suit =
break;
case 2:
suit =
break;
case 3:
suit =
break;
default:
suit =
break;
}
Suit.CLUB;
Suit.DIAMOND;
Suit.HEART;
Suit.SPADE;
Suit.CLUB;
61
BlackJack_0_1GC.Deck.cs (5/6)
int rank = pos % 13 + 1;
used[pos] = true;
cardStack.Push(new Card(suit, rank));
}
}
public Deck(Card[] cards)
{
int nCards = cards.Length;
this.cardStack = new Stack<Card>();
int i;
for (i = 0; i < nCards; ++i)
{
cardStack.Push(cards[i]);
}
}
62
BlackJack_0_1GC.Deck.cs (6/6)
public Card DealACard() {
return cardStack.Pop();
}
public bool HasMoreCard() {
bool empty = false;
try {
cardStack.Peek();
}
catch (Exception)
{
empty = true;
}
return !empty;
}
}
}
63
BlackJack_0_1G.Card.cs (1/5)
/*
* 模擬一張撲克牌
* 12/5/2008
*/
using System;
namespace BlackJack_0_1GC
{
public enum Suit {
CLUB = 0,
DIAMOND = 1,
HEART = 2,
SPADE = 3
}
64
BlackJack_0_1G.Card.cs (2/5)
public struct Card
{
public Suit suit;
public int rank;
public Card(Suit suit, int rank)
{
this.suit = suit;
this.rank = rank;
}
public string Name()
{
string result = null;
switch (suit) {
case Suit.CLUB:
result = "c" + rank.ToString();
break;
65
BlackJack_0_1G.Card.cs (3/5)
case Suit.DIAMOND:
result = "d" + rank.ToString();
break;
case Suit.HEART:
result = "h" + rank.ToString();
break;
case Suit.SPADE:
result = "s" + rank.ToString();
break;
default:
break;
}
return result;
}
66
BlackJack_0_1G.Card.cs (4/5)
public void Dump() {
string[] ranks = {
"A", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"J", "Q", "K" };
switch (suit)
{
case Suit.CLUB:
Console.Write("c" + ranks[rank - 1]);
break;
case Suit.DIAMOND:
Console.Write("d" + ranks[rank - 1]);
break;
case Suit.HEART:
Console.Write("h" + ranks[rank - 1]);
break;
67
BlackJack_0_1G.Card.cs (5/5)
case Suit.SPADE:
Console.Write("s" + ranks[rank - 1]);
break;
default:
break;
}
}
}
}
68
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
69
UsingRecursion.Program (1/3)
/*
* 利用階乘說明遞迴函式的用法
* 1/18/2009
*/
using System;
using System.Diagnostics;
namespace UsingRecursion
{
class Program
{
static void Main(string[] args)
{
int factorialNonRecursive =
FactorialNonRecursive(10);
int factorialRecursive =
FactorialRecursive(10);
70
UsingRecursion.Program (2/3)
Debug.Assert(
factorialNonRecursive == 3628800 &&
factorialRecursive == 3628800);
}
/*
* 不用遞迴計算階乘
* 3/17/2007
*/
static int FactorialNonRecursive(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
71
UsingRecursion.Program (3/3)
/*
* 利用遞迴計算階乘
* 3/17/2007
*/
static int FactorialRecursive(int n)
{
if (n == 1 || n == 0) return 1;
int result =
n * FactorialRecursive(n - 1);
return result;
}
}
}
72
遞迴的觀念
73
練習
• 以遞迴形式計算Fibonacci數列
Fn  Fn 1  Fn 2
F1  F0  1
74
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
75
二分搜尋法 (Binary Search)
Alice
Bob
Carol
David
Elaine
Fred
George
Harry
Irene
John
Kelly
Larry
Mary
Nancy
Oliver
Harry
Irene
John
Kelly
Larry
Mary
Nancy
Oliver
Irene
John
Kelly
76
二分搜尋法虛擬碼
*J. G. Brookshear, Computer Science – An Overview, 8th edition,
Addison-Wesley, 2005
77
類別 NameList
78
BinarySearch.Program.cs
using System;
using System.Diagnostics;
namespace BinarySearch
{
class Program
{
static void Main(string[] args)
{
Debug.Assert(
BinarySearchTest.Test1_OK());
}
}
}
79
BinarySearch.BinarySearchTest.cs (1/3)
using System;
namespace BinarySearch
{
class BinarySearchTest
{
public static bool Test1_OK()
{
string[] list = new string[5];
list[0] = "Abe";
list[1] = "Bob";
list[2] = "Carol";
list[3] = "David";
list[4] = "Eve";
NameList nameList = new NameList( list );
int index1;
80
BinarySearch.BinarySearchTest.cs (2/3)
bool success1 =
0, 4, out
int index2;
bool success2 =
0, 4, out
int index3;
bool success3 =
0, 4, out
int index4;
bool success4 =
0, 4, out
int index5;
bool success5 =
0, 4, out
nameList.Search("Carol",
index1);
nameList.Search("Bob",
index2);
nameList.Search("Abe",
index3);
nameList.Search("David",
index4);
nameList.Search("Eve",
index5);
81
BinarySearch.BinarySearchTest.cs (3/3)
int index6;
bool fail1 = !nameList.Search("Mary",
0, 4, out index6);
int index7;
bool fail2 = !nameList.Search("Aaron",
0, 4, out index7);
int index8;
bool fail3 = !nameList.Search("Brown",
0, 4, out index8);
return (success1 && (index1 == 2) &&
success2 && (index2 == 1) &&
success3 && (index3 == 0) &&
success4 && (index4 == 3) &&
success5 && (index5 == 4) &&
fail1 && fail2 && fail3
); } } }
82
BinarySearch.NameList.cs (1/3)
/*
* 排序好的名單類別
* 1/18/2009
*/
using System;
namespace BinarySearch
{
class NameList
{
string[] list; // 儲存之名單
public NameList(string[] list)
{
this.list = list;
}
83
BinarySearch.NameList.cs (2/3)
/*
* 檢查字串target是否在list之中
* 3/20/2007
*/
public bool Search(string target,//搜尋之字串
int low,
// 檢查註標之下限
int high,
// 檢查註標之上限
out int index // 最後檢查的註標
)
{
index = (low + high) / 2;
if (low > high ) return false;
int result =
target.CompareTo(list[index]);
84
BinarySearch.NameList.cs (3/3)
if (result == 0) {
return true;
}
else if (result < 0) {
high = index - 1;
return Search(
target, low, high, out index);
}
else {
low = index + 1;
return Search(
target, low, high, out index);
}
}
}
}
85
綱要
1.
2.
3.
4.
5.
6.
7.
Collections與泛型概說
List類別
堆疊Stack類別
二十一點模擬程式0.1GC版
*遞迴函式
*二分搜尋法
Dictionary類別
86
Dictionary, DictionaryEntry,
Keys, Values
key
趙大
錢二
孫三
李四
周五
吳六
value
(02)77777777
(02)56565656
(039)333444
(04)666789
(02)78978922
(02)74774755
87
UsingDictionary.Program.cs
using System;
using System.Diagnostics;
namespace UsingDictionary
{
class Program
{
static void Main(string[] args)
{
Debug.Assert(DictionaryTest.Test1_OK());
}
}
}
88
UsingDictionary.DictionaryTest.cs (1/2)
using System;
using System.Collections.Generic;
namespace UsingDictionary
{
class DictionaryTest
{
public static bool Test1_OK()
{
Dictionary<string, string> phoneBook =
new Dictionary<string, string>();
phoneBook.Add("趙大", "(02)77777777");
phoneBook.Add("錢二", "(02)56565656");
phoneBook.Add("孫三", "(03)9333444");
phoneBook.Add("李四", "(04)6667899");
phoneBook.Add("周五", "(02)78978922");
phoneBook.Add("吳六", "(02)74774755");
89
UsingDictionary.DictionaryTest.cs (2/2)
bool success1 =
(phoneBook["孫三"] == "(03)9333444");
bool success2 = phoneBook.ContainsKey
"周五");
phoneBook.Remove("錢二");
phoneBook["李四"] = "(04)1234567";
bool success3 =
phoneBook.ContainsValue("(04)1234567");
bool fail1 =
!phoneBook.ContainsValue("(02)56565656");
return (success1 && success2 && success3
&& fail1);
}
}
}
90
練習
• 利用Dictionary,製作成績表
gradeTable,以學號為key,0~100之整
數為value
• 寫測試程式加入、取得、刪除、修改成績,
並列印結果
91