Guest User

BitShooter

a guest
Dec 29th, 2014
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. using System;
  2.  
  3. class BitShooter
  4. {
  5.     static void Main()
  6.     {
  7.         //parse bit field integer
  8.         ulong bitField = ulong.Parse(Console.ReadLine());
  9.  
  10.         //read the three commands
  11.         for (int i = 0; i < 3; i++)
  12.         {
  13.             string input = Console.ReadLine();
  14.             int[] shot = SplitString(input);
  15.             int shotCenter = shot[0];
  16.             int shotSize = shot[1];
  17.             //key part of the solution is the shot mask!
  18.             ulong mask = (ulong)Math.Pow(2, shotSize) - 1;
  19.             //shift right
  20.             if (shotCenter < shotSize / 2)
  21.             {
  22.                 mask = ~(mask >> ((shotSize / 2) - shotCenter));
  23.             }
  24.             //shift left
  25.             else
  26.             {
  27.                 mask = ~(mask << (shotCenter - (shotSize / 2)));
  28.             }
  29.             //shoot the bits with the mask
  30.             bitField &= mask;
  31.         }
  32.         //split the bit field in two parts
  33.         ulong BitFieldLeft = bitField >> 32;
  34.         ulong BitFieldRight = (bitField << 32) >> 32;
  35.         //display result
  36.         Console.WriteLine("left: {0}", CountOneBits(BitFieldLeft));
  37.         Console.WriteLine("right: {0}", CountOneBits(BitFieldRight));
  38.  
  39.     }
  40.     public static int[] SplitString(string input)
  41.     {
  42.         string[] array = input.Split(' ');
  43.         int[] numbers = new int[array.Length];
  44.         for (int i = 0; i < numbers.Length; i++)
  45.         {
  46.             numbers[i] = int.Parse(array[i]);
  47.         }
  48.         return numbers;
  49.     }
  50.     public static int CountOneBits(ulong number)
  51.     {
  52.         int count = 0;
  53.         while (number > 0)
  54.         {
  55.             if (number % 2 == 1)
  56.             {
  57.                 count++;
  58.             }
  59.             number /= 2;
  60.         }
  61.         return count;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment