O(nlogn) Algorithm - Find three evenly spaced ones within binary string

前端 未结 30 2946
刺人心
刺人心 2020-11-28 00:07

I had this question on an Algorithms test yesterday, and I can\'t figure out the answer. It is driving me absolutely crazy, because it was worth about 40 points. I figure

30条回答
  •  清酒与你
    2020-11-28 00:57

    A fun question, but once you realise that the actual pattern between two '1's does not matter, the algorithm becomes:

    • scan look for a '1'
    • starting from the next position scan for another '1' (to the end of the array minus the distance from the current first '1' or else the 3rd '1' would be out of bounds)
    • if at the position of the 2nd '1' plus the distance to the first 1' a third '1' is found, we have evenly spaces ones.

    In code, JTest fashion, (Note this code isn't written to be most efficient and I added some println's to see what happens.)

    import java.util.Random;
    
    import junit.framework.TestCase;
    
    public class AlgorithmTest extends TestCase {
    
     /**
      * Constructor for GetNumberTest.
      *
      * @param name The test's name.
      */
     public AlgorithmTest(String name) {
      super(name);
     }
    
     /**
      * @see TestCase#setUp()
      */
     protected void setUp() throws Exception {
      super.setUp();
     }
    
     /**
      * @see TestCase#tearDown()
      */
     protected void tearDown() throws Exception {
      super.tearDown();
     }
    
     /**
      * Tests the algorithm.
      */
     public void testEvenlySpacedOnes() {
    
      assertFalse(isEvenlySpaced(1));
      assertFalse(isEvenlySpaced(0x058003));
      assertTrue(isEvenlySpaced(0x07001));
      assertTrue(isEvenlySpaced(0x01007));
      assertTrue(isEvenlySpaced(0x101010));
    
      // some fun tests
      Random random = new Random();
    
      isEvenlySpaced(random.nextLong());
      isEvenlySpaced(random.nextLong());
      isEvenlySpaced(random.nextLong());
     }
    
     /**
      * @param testBits
      */
     private boolean isEvenlySpaced(long testBits) {
      String testString = Long.toBinaryString(testBits);
      char[] ones = testString.toCharArray();
      final char ONE = '1';
    
      for (int n = 0; n < ones.length - 1; n++) {
    
       if (ONE == ones[n]) {
        for (int m = n + 1; m < ones.length - m + n; m++) {
    
         if (ONE == ones[m] && ONE == ones[m + m - n]) {
          System.out.println(" IS evenly spaced: " + testBits + '=' + testString);
          System.out.println("               at: " + n + ", " + m + ", " + (m + m - n));
          return true;
         }
        }
       }
      }
    
      System.out.println("NOT evenly spaced: " + testBits + '=' + testString);
      return false;
     }
    }
    

提交回复
热议问题