Monday, May 23, 2011

Bits for your bits

Maximum Mininum without branching

int x;  // we want to find the minimum of x and y
int y;   
int r;  // the result goes here 
r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)

Determining if an integer is a power of 2

unsigned int v; // we want to see if v is a power of 2
bool f;         // the result goes here 
f = (v & (v - 1)) == 0;

Counting Bits


Counting bits set, Brian Kernighan's way

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}
Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.

Counting bits set in 14, 24, or 32-bit words using 64-bit instructions

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v

// option 1, for at most 14-bit values in v:
c = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;

// option 2, for at most 24-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) 
     % 0x1f;

// option 3, for at most 32-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 
     0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15.

The best method for counting bits in a 32-bit integer v is the following:

v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count

The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn't use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0x1010101 and shifting right 24 bits.

A generalization of the best bit counting method to integers of bit-widths upto 128 (parameterized by type T) is this:
v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count
Sources
http://graphics.stanford.edu/~seander/bithacks.html

Friday, December 4, 2009

Eliminating the last one from binary number

Provided the Number is not zero Then
// representing number in some format  
//A contains the bits before the last one & B is after last one
//small c after variable represent Compliments of that number like N & Nc
Num=A1B
//Some Property -N=Nc+1  Nc is compliment of N
(-Num) =(A1B)c+1=Ac0Bc+1=Ac1B //{ 0Bc since Bc is all bit 1 adding 1 will give 1B}

Num= A1B
-Num=Ac1B
//if we Ac&A will be zero and B&B will be zero too.. so , so remaining will be the last one
(Num&(-Num))   //leave last single '1' 
Try this on you PC..

Python in 5 minute

Python, an interpreted, interactive, object-oriented, extensible programming language
with automatic memory tracking well use of python is "Google" every application.. expecting new programming language Go will be something like Python with other good features of other programming language

now let's talk about programming part..

for writing executing and writing program
you can download interpreter from Download
or net beans plugin for python from: Download
you don't have to declare what your object type is but yes before using it you have to give reference to object type if necessary

eg..
list/array you can declare in this way.:
a=[]
#map you can declare in this way.:
a={}
#set you can declare in this way
a=set()
#change in python and other programming language:

&& = and
true = True
false = False
|| = or
if() = "if():"
else if = "elif():"
while() = "while():"
foreach () =  for():
// = #
/* --- */ = """ ------- """   
#above can be use as multiline string also

Python uses whitespace indentation, rather than curly braces or keywords, to delimit blocks #eg:
a=2
if( a>0):
   print "HELLO WORLD"
   print "You are in If Loop"
print "You are now running normal"
out/put;
Hello World
you are in if loop
you are now running normal
Assigning variable in one line
a,b=0,1
will assign a=0 and b=1

#one funny program :
a,b=0,1
while b<1000:
    print b
   a,b=b,a+b
Guess the o/p of this program
it will print the Fibonacci series..
#checking presence of key,data ,in list or map
if a in b:
  do something
#########################################
#writing a function 
def  function_name(variable1,variable2...)
       return some variable

continue and break are same as other language
#traversing list
#creating a new list from original list
a=['my' 'name' 'is','rajesh','patidar']
a[:]  # this is will create a copy of a
a[2:4] # will create a new list form index 2 to index 3
a[2:] # will create a new list from index 2  to up to last
a[:2] #will create a list from starting up to index 1
a[:-2] # will create a new list leaving last two item of list
a[::-1] # reverse the list
############################################
Module in Python
it is same as header file in c++ and package in java
but it track module through file name
//hello.py
def sayHello(name):
       print "You are welcome MR: "+name

#myprg.py
import hello
sayHello("Rajesh Patidar")

Thursday, February 26, 2009

Basic Template Use in C++ for Dummies

Hi ...gyues.. if you don't now wat is template in c++ then here is some intresting thing for you...
and may be you will be loving it...., template & it's libarary is the feature of c++ which makes things easier... to solve and when u become familier with it you will loving Programming....
before you try it on your compiler... Turbo C dones't give any feature of template so you better to try this on GNU g++ you don't have it then don't worry here is the link. to download ...Download mingw gnu compiler
.................................
and you wish to write your code more easy and perfect way the here you can download codeblock Ide......
k...let start
let just make a function which will compare which one is max and which one is min
then...
//one munction for comparing the string as well as for interger you can use same for double and float...also...
#include<iostream >
using namespace std;
template < typename T > inline int Min(T a, T b) { return (b < a); }
int main()
{
cout <<Min(i,j)<<endl;
cout<<Min("hello","may")<<endl;
return 0;
}
hope you got the got...
use can use same thing in class formate also
template < class T > Hello
{
T t1;
void getT(t1 t)
{
//do you code according to the things t
}
};
now while creating the object use this formate
Hello < int > h;
Hello<double > h1;
Hello<string> h2;
so it will assign..the t accordingly...

now let come to the Libarary Part
vector
vector is the very good,it is something like dynamic array,you can insert,delete,element in the array without definning size and taking any counter for no of item in array, it will take care of all the things....eg:
vector<int > t;
t.push_back(2);
t.push_back(20);
t.push_back(14);
now t.size() will give you the size of the array
eg the current t.size()=3 //t contain tree element only
t.begin() will give pointer to first element ,and t.end() will give the pointer to the last element
and let letter on you wan't to sort the array then
u can use...
sort(t.begin(),t.end());
which will sort the element of array..
reverse(t.begin(),t.end());
to excess ith element in vector you can use directly like array t[i] ( will return the value of ith element in the vector)
Note:before using the above sort, reverse function you should include "#include<algorithm>" and "#include <vector>"

Wednesday, February 4, 2009

Rikshawala @IIT

one of my friend gone to iitkgp for coucelling and he ask the Rikshawala to take him to the iit
Rikshawala asked:-"Where Did u Wan't to Go"
Friend :- "IIT"
and it was the greatest and Funiest Joke the Riksawala Replied
Rikshawala:-"IIT ka name suna nahi ki Muuh Utha kar Chal diye"
can u imagine the face of the my friend who have tried a lot to get into IIT's and he got this JOKE

Bitwise Tricks

if you wan't to use your brain applying some algorithm and u can wash your brain .....here are some link.....
TopCoder Algorithm Tutorial
Google CodeJam

Algorithm tutorials are avaiable on The Link... Algorithm Link on Topcoder
Some of the Binary Tricks
n=(1011101110) base 2

for i->n , i>0 i=(i&(i-1))

print (i) in binary formate...

gause what this will print...
k.... if u have find out then ok...otherwise....just see the how the value of i will change....
i=1011101110
i=1011101100
i=1011101000

i=1011100000

i=1011000000
i=1010000000

i=1000000000
i=0000000000



//next trick...
you can change the value of the two varaible in bitwise
//eq swap a,b
a=a^b

b=a^b

a=a^b

this code look...somthing rediculous, but it will do the work....
//choosing subset problem using bitwise
u can use simple use this loop to get the subset of a n element set
for(int i=0;i (1<(1<<n); i++)
{

for(int j=0;j<n ; j++)
{
if(i&(1<<j))

cout << j
}
cout << endl;
}