Thursday, 29 June 2017

Cracking the Coding Interview (add function without use of '+') - Attempt number 2


public class Adder2 
{

// full 1 bit Adder (Ci - Carry Input , a  parameter input, b parameter input, o is output , c (also an output) is carry flag used for the next bit addition (state))
/*
Ci  a  b    o    c
0   0  0    0    0
0   0  1    1    0
0   1  0    1    0
0   1  1    0    1
1   0  0    1    0
1   0  1    0    1
1   1  0    0    1
1   1  1 1    1
*/
static Integer [] sequentialBitIndexCheatSet = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30} ; // pre-ordered sequential bit positions starting from 0 to bit length of word - 1 


// n bit adder (depends on size of 'sequentialCheatSet')
static public int add(int a, int b) {

int [] output_logic  = {0,2,2,1,2,1,1,3} ;
int mask = 1 ;
int result = 0;
int carry_in = 0;
int carry_out ;
int output ;
int input_logic_index ;
int abit ;
int bbit ;
int bit_result ;

// This pre-sorted arrayList is purely here so we can skip using an 'add' instruction!

for(Integer bitNumber : sequentialBitIndexCheatSet) {

// 1 bit adder
abit = (1 & a) ;
bbit = (1 & b) ;

input_logic_index = (carry_in << 2) | (abit << 1) | (bbit << 0) ;

output = output_logic[input_logic_index] ;
carry_out = (output & 1) ;
bit_result = ((output & 2) >> 1) ;
carry_in = carry_out ;
result|=(bit_result<<bitNumber) ;
a>>>=1 ; b>>>=1 ;

}


return result  ; //| carry_out;
}

static public void main(String [] args) {
int failed = 0 ;
int tests = 0 ;
int numOfTests = 15 ; //(1<<bitLength) ;
int bitLength = sequentialBitIndexCheatSet.length - 1 ;
for (int i = 0 ; i <  numOfTests ; i++ ) {
for (int j = 0 ; j < numOfTests ; j++) {
tests++ ;
int fullResult = add(i,j) ;
int compare = i + j ;
if (compare != fullResult) {
System.out.println(" i, j " + i + "," + j + " full result = " + fullResult + "<->" + compare + "failed") ;
failed++ ;
}
}
}
System.out.println("Failure count " + failed  + " test count " + tests) ;
return ;
}


}









No comments:

Post a Comment