Advertisement
Guest User

Untitled

a guest
Aug 27th, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. 3
  2. abcdde
  3. baccd
  4. eeabg
  5.  
  6. 2
  7.  
  8. public class GemCounter {
  9.  
  10. private static final int LETTERCOUNT = 26;
  11.  
  12. // Start with 1 bit set for each element/letter.
  13. private int gemsSoFar = (1 << LETTERCOUNT) - 1;
  14.  
  15. public GemCounter() {
  16. // default constructor. Does nothing.
  17. }
  18.  
  19. public void processRock(final String rock) {
  20. int gotElement = 0; // no bits are set.
  21. for (int i = 0; i < rock.length(); i++) {
  22. int element = rock.charAt(i) - 'a';
  23. if (element >= 0 && element < LETTERCOUNT) {
  24. // bitwise OR the bit that represents the element
  25. gotElement |= 1 << element;
  26. }
  27. }
  28. // only bits that were found in this rock
  29. // and also that have been seen before
  30. // will remain set.
  31. gemsSoFar = gemsSoFar & gotElement;
  32. }
  33.  
  34. public int getGemCount() {
  35. // count the number of bits that are still set.
  36. return Integer.bitCount(gemsSoFar);
  37. }
  38.  
  39. public static void main(String[] args) {
  40. String[] rocks = {"abcdde", "baccd", "eeabg"};
  41.  
  42. GemCounter gemcount = new GemCounter();
  43. for (String rock : rocks) {
  44. gemcount.processRock(rock);
  45. System.out.printf("Processed %s, got %d gems still%n", rock, gemcount.getGemCount());
  46. }
  47.  
  48. System.out.printf("%d rocks have %d gems%n", rocks.length, gemcount.getGemCount());
  49.  
  50. }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement