Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 3
- abcdde
- baccd
- eeabg
- 2
- public class GemCounter {
- private static final int LETTERCOUNT = 26;
- // Start with 1 bit set for each element/letter.
- private int gemsSoFar = (1 << LETTERCOUNT) - 1;
- public GemCounter() {
- // default constructor. Does nothing.
- }
- public void processRock(final String rock) {
- int gotElement = 0; // no bits are set.
- for (int i = 0; i < rock.length(); i++) {
- int element = rock.charAt(i) - 'a';
- if (element >= 0 && element < LETTERCOUNT) {
- // bitwise OR the bit that represents the element
- gotElement |= 1 << element;
- }
- }
- // only bits that were found in this rock
- // and also that have been seen before
- // will remain set.
- gemsSoFar = gemsSoFar & gotElement;
- }
- public int getGemCount() {
- // count the number of bits that are still set.
- return Integer.bitCount(gemsSoFar);
- }
- public static void main(String[] args) {
- String[] rocks = {"abcdde", "baccd", "eeabg"};
- GemCounter gemcount = new GemCounter();
- for (String rock : rocks) {
- gemcount.processRock(rock);
- System.out.printf("Processed %s, got %d gems still%n", rock, gemcount.getGemCount());
- }
- System.out.printf("%d rocks have %d gems%n", rocks.length, gemcount.getGemCount());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement