fbinnzhivko

05.00 Wave Bits

Apr 15th, 2016
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. using System;
  2. public class WaveBits
  3. {
  4.     public static void Main()
  5.     {
  6.         ulong number = ulong.Parse(Console.ReadLine());
  7.  
  8.         int bestSequenceLength = 0;
  9.         int bestSequenceStartIndex = 0;
  10.         int currentSequenceLength = 1;
  11.  
  12.         // ends at 61, because the following boolean expressions will eventually check bits @62 and @63
  13.         for (int i = 0; i <= 61; i++)
  14.         {
  15.             bool isFirstBitUp = ((number >> i) & 1) == 1;
  16.             bool isSecondBitDown = ((number >> i + 1) & 1) == 0;
  17.             bool isThirdBitUp = ((number >> i + 2) & 1) == 1;
  18.  
  19.             bool isWaveTriple = isFirstBitUp && isSecondBitDown && isThirdBitUp;
  20.  
  21.             if (isWaveTriple)
  22.             {
  23.                 // our sequence always starts from 1, so we only need to increment by 2
  24.                 // for example 1 + 2 + 2 is the length of 10101
  25.                 currentSequenceLength += 2;
  26.  
  27.                 if (currentSequenceLength > bestSequenceLength)
  28.                 {
  29.                     bestSequenceStartIndex = i + 2;
  30.                     bestSequenceLength = currentSequenceLength;
  31.                 }
  32.  
  33.                 // skip the zero in the middle of the triple and test the next three bits
  34.                 i++;
  35.             }
  36.             else
  37.             {
  38.                 // the current sequence has ended, so start over
  39.                 currentSequenceLength = 1;
  40.             }
  41.         }
  42.  
  43.         int bestSequenceEndIndex = bestSequenceStartIndex - bestSequenceLength + 1;
  44.         ulong outputNumber = 0UL;
  45.  
  46.         for (int i = 63; i >= 0; i--)
  47.         {
  48.             bool inShouldBeDeletedRange = i <= bestSequenceStartIndex && i >= bestSequenceEndIndex;
  49.             if (inShouldBeDeletedRange)
  50.             {
  51.                 outputNumber >>= 1;
  52.             }
  53.             else
  54.             {
  55.                 ulong currentBit = number & (1UL << i);
  56.                 outputNumber |= currentBit;
  57.             }
  58.         }
  59.  
  60.         if (bestSequenceLength == 0)
  61.         {
  62.             Console.WriteLine("No waves found!");
  63.         }
  64.         else
  65.         {
  66.             Console.WriteLine(outputNumber);
  67.         }
  68.     }
  69. }
Add Comment
Please, Sign In to add comment