Posted By

jaircazarin on 11/08/08


Tagged

c optimization


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

jaircazarin
umang_nine
khouser


Boolean Matrix


 / Published in: C#
 

Define a two-dimensional boolean array. Minimize the memory allocated. Write a function to set a value to an element of this array.

  1. sing System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace BooleanMatrix {
  7. class BooleanMatrix {
  8. private const int BITSPERWORD = 32;
  9. private const int SHIFT = 5;
  10. private const int MASK = 0x1F;
  11. private int width;
  12. private int height;
  13. private int length;
  14. private int[] bitset;
  15.  
  16. public BooleanMatrix(int width, int height)
  17. {
  18. this.width = width;
  19. this.height = height;
  20. this.length = width * height;
  21. bitset = new int[1 + this.length / BITSPERWORD];
  22. }
  23.  
  24. public void Set(int x, int y) {
  25. int index = getIndex(x, y);
  26. bitset[index >> SHIFT] |= (1 << (index & MASK));
  27. }
  28.  
  29. public void Clear(int x, int y) {
  30. int index = getIndex(x, y);
  31. bitset[index >> SHIFT] &= ~(1 << (index & MASK));
  32. }
  33.  
  34. public int Test(int x, int y) {
  35. int index = getIndex(x, y);
  36. return bitset[index >> SHIFT] & (1 << (index & MASK));
  37. }
  38.  
  39. private int getIndex(int x, int y) {
  40. return x * this.width + y;
  41. }
  42.  
  43. public int Height {
  44. get { return height; }
  45. }
  46.  
  47. public int Width {
  48. get { return width; }
  49. }
  50. }
  51. }

Report this snippet  

You need to login to post a comment.