📄 4.6.txt
字号:
Listing 4.6 Performing a Binary Search on an Array of Integers
using System;
using System.Collections;
namespace _12_BinarySearch
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int[] lottoNumbers = new int[3];
// generate the random numbers
GenerateNumbers( lottoNumbers );
// start the game
PlayGame( lottoNumbers );
}
static void GenerateNumbers( int[] numbers )
{
// initialize random number generator with current ticks
Random rand = new Random((int)DateTime.Now.Ticks);
// fill array with random numbers from 1 to 10
for( int i = 0; i < numbers.GetUpperBound(0)+1; i++ )
{
numbers[i] = rand.Next( 1, 10 );
}
// sort the final array
Array.Sort( numbers );
}
static void PlayGame( int[] numbers )
{
int[] playerNumbers = new int[3];
char[] space = {‘ ‘};
string input;
int matches = 0;
// get user input and quit if ‘q’ is entered
Console.Write( “Enter 3 digits between 1 and 10 (q to quit): “ );
input = Console.ReadLine();
while( input.Length != 1 || Char.ToUpper( input[0] ) != ‘Q’ )
{
// split the input into a string array
string[] temp = input.Split( space, 3 );
// make sure 3 numbers were entered
if( temp.Length < 3 )
{
Console.WriteLine( “You did not enter 3 digits.” );
Console.Write( “Enter 3 digits between 1 and 10 “ +
“(q to quit): “ );
input = Console.ReadLine();
continue;
}
// convert string values and place into integer array
for ( int i = 0; i < 3; i ++ )
playerNumbers[i] = Int32.Parse( temp[i] );
// count how many matches occured
matches = NumMatches( playerNumbers, numbers );
if( matches == 3)
{
Console.WriteLine( “You won!” );
return;
}
else
{
Console.WriteLine( “You have {0} matches. Try again.”,
matches );
}
Console.Write( “Enter 3 digits between 1 and 10 “ +
“(q to quit): “ );
input = Console.ReadLine();
}
}
static int NumMatches( int[] playerNumbers, int[] numbers )
{
int matches = 0;
// arraylist to hold current numbers to compare
ArrayList al = new ArrayList( numbers );
foreach( int number in playerNumbers )
{
// search for current user number in arraylist
int result = al.BinarySearch( number );
if( result >= 0 )
{
// since matched, remove it so it isn’t counted again
al.RemoveAt( result );
matches++;
}
}
return matches;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -