using System; class BitArray { int[] bits; int length; public BitArray(int length) { if (length < 0) throw new ArgumentException(); bits = new int[((length - 1) >> 5) + 1]; this.length = length; } public int Length { get { return length; } } public bool this[int index] { get { if (index < 0 || index >= length) { throw new IndexOutOfRangeException(); } return (bits[index >> 5] & 1 << index) != 0; } set { if (index < 0 || index >= length) { throw new IndexOutOfRangeException(); } if (value) { bits[index >> 5] |= 1 << index; } else { bits[index >> 5] &= ~(1 << index); } } } }An instance of the BitArray class consumes substantially less memory than a corresponding bool[] (since each value of the former occupies only one bit instead of the latter's one byte), but it permits the same operations as a bool[]. The following CountPrimes class uses a BitArray and the classical "sieve" algorithm to compute the number of primes between 1 and a given maximum:
class CountPrimes { static int Count(int max) { BitArray flags = new BitArray(max + 1); int count = 1; for (int i = 2; i <= max; i++) { if (!flags[i]) { for (int j = i * 2; j <= max; j += i) flags[j] = true; count++; } } return count; } static void Main(string[] args) { int max = int.Parse(args[0]); int count = Count(max); Console.WriteLine("Found {0} primes between 1 and {1}", count, max); } }Note that the syntax for accessing elements of the BitArray is precisely the same as for a bool[]. end example] [Example: The following example shows a 26×10 grid class that has an indexer with two parameters. The first parameter is required to be an upper-or lowercase letter in the range A-Z, and the second is required to be an integer in the range 0-9.
using System; class Grid { const int NumRows = 26; const int NumCols = 10; int[,] cells = new int[NumRows, NumCols]; public int this[char c, int colm] { get { c = Char.ToUpper(c); if (c < 'A' || c > 'Z') { throw new ArgumentException(); } if (colm < 0 || colm >= NumCols) { throw new IndexOutOfRangeException(); } return cells[c - 'A', colm]; } set { c = Char.ToUpper(c); if (c < 'A' || c > 'Z') { throw new ArgumentException(); } if (colm < 0 || colm >= NumCols) { throw new IndexOutOfRangeException(); } cells[c - 'A', colm] = value; } } }end example]
| |
Jagger Software Ltd | |
Company # 4070126 | |
VAT # 762 5213 42 |