JavaScript Bit Manipulation to C++ Bit Manipulation - c++

The following Pseudo and JavaScript code is a extract from the implementation of a algorithm , i want to convert it to C++ .
Pseudo Code :
for b from 0 to 2|R| do
for i from 0 to |R| do
if BIT-AT(b, i) = 1 then // b’s bit at index i
JavaScript Code :
for (var b = 0; b < Math.pow(2, orders[r].length); b++) // use b's bits for directions
{
for (var i = 0; i < orders[r].length; i++)
{
if (((b >> i) & 1) == 1) { // is b's bit at index i on?
I don't understand what is happening in the last line of this code , What Should be the C++ code for the above given JavaScript code . So far what i have written is :
for (int b = 0; b < pow(2, orders.at(r).size()); b++)
{
for (int i = 0; i < orders.at(r).size(); i++)
{
if (((b >> i) & 1) == 1)***//This line is not doing what it is supposed to do according to pseudo code***
The last line is giving me segmentation fault .
--
Edit:I apologize the problem was somewhere else , This code works fine .

(((b >> i) & 1) == 1)
| |
| |
| bitwise AND between the result of the shift and number 1.
|
shift b by i bits to the right
After that the result is compared with the number 1.
So if, for example, b is 8, and i is 2, it will do the following:
shift 8 (which is 00001000) by 2 bits to the right. The result will be 00000100.
apply the bitwise AND: 00000100 BITWISE_AND 00000001, the result will be 0.
Compare it with 1. Since 0 =/= 1, you will not enter that last if.
As for the logic behind this, the code ((b >> i) & 1) == 1) returns true if the bit number i of the b variable is 1, and false otherwise.
And I believe that c++ code will be the same, with the exception that we don't have Math class in c++, and you'll have to replace vars with the corresponding types.

>> is the right shift operator, i.e. take the left operand and move its bit n positions to the right (defined by the right operand).
So essentially, 1 << 5 would move 1 to 100000.
In your example (b >> i) & 1 == 1 will check whether the i-th bit is set (1) due to the logical and (&).
As for your code, you can use it (almost) directly in C or C++. Math.pow() would become pow() inside math.h, but (in this case) you could simply use the left shift operator:
for (int b = 0; b < (1 << orders[r].length); ++b) // added the brackets to make it easier to read
for (int i = 0; i < orders[r].length; ++i)
if (((b >> i) & 1) == 1) {
// ...
}
1 << orders[r].length will essentially be the same as pow(2, orders[r].length), but without any function call.

Related

Add a bit in the middle of any two bits

In a binary representation of a number is there a simpler way than this
long half(long patten, bool exclusive) {
if (patten == 0) {
return 1;
}
long newPatten = 0;
for (int p = 0; p < MAX_STEPS; p++) {
long check = 1 << p;
if ((check & patten) > 0) {
int end = (p + MAX_STEPS) - 1;
for (int to = p+1; to <= end; to++) {
long checkTo = 1 << (to % MAX_STEPS);
if ( (checkTo & patten) > 0 || to == end ) {
int distance = to - p;
long fullShift = (int)round( ((float)p) + ((float)distance)/2 );
long shift = fullShift % MAX_STEPS;
long toAdd = 1 << shift;
newPatten = newPatten | toAdd;
break;
}
}
}
}
return exclusive ? patten ^ newPatten : patten | newPatten;
}
To add a bit in the middle of any two other bits with wrapping around and rounding to one side when there is an even number of positions between?
E.g.
010001 to
110101
Or
1001 to
1101
Update: These bits aren't coming from anywhere else, such as another number, just want a new True bit to be in the middle of any other two True bits, so if there was a 101, then the middle would be the 0 and the result would be 111. Or if we started with 10001, then the middle would be the center 0 and the result would be 10101.
When i say wrapping i also mean adding bits as if the bit array was a circle so if we had 00100010 representing the positions with letters:
00100010
hgfedcba
So we have True bits at b and f we would put a middle bit between b and f going left to right at d but also going right to left, wrapping around and putting it at h resulting in:
10101010
hgfedcba
I understand this isn't a usual problem.
Are there known tricks to do things like this without loops?

How to store output of very large Fibonacci number?

I am making a program for nth Fibonacci number. I made the following program using recursion and memoization.
The main problem is that the value of n can go up to 10000 which means that the Fibonacci number of 10000 would be more than 2000 digit long.
With a little bit of googling, I found that i could use arrays and store every digit of the solution in an element of the array but I am still not able to figure out how to implement this approach with my program.
#include<iostream>
using namespace std;
long long int memo[101000];
long long int n;
long long int fib(long long int n)
{
if(n==1 || n==2)
return 1;
if(memo[n]!=0)
return memo[n];
return memo[n] = fib(n-1) + fib(n-2);
}
int main()
{
cin>>n;
long long int ans = fib(n);
cout<<ans;
}
How do I implement that approach or if there is another method that can be used to achieve such large values?
One thing that I think should be pointed out is there's other ways to implement fib that are much easier for something like C++ to compute
consider the following pseudo code
function fib (n) {
let a = 0, b = 1, _;
while (n > 0) {
_ = a;
a = b;
b = b + _;
n = n - 1;
}
return a;
}
This doesn't require memoisation and you don't have to be concerned about blowing up your stack with too many recursive calls. Recursion is a really powerful looping construct but it's one of those fubu things that's best left to langs like Lisp, Scheme, Kotlin, Lua (and a few others) that support it so elegantly.
That's not to say tail call elimination is impossible in C++, but unless you're doing something to optimise/compile for it explicitly, I'm doubtful that whatever compiler you're using would support it by default.
As for computing the exceptionally large numbers, you'll have to either get creative doing adding The Hard Way or rely upon an arbitrary precision arithmetic library like GMP. I'm sure there's other libs for this too.
Adding The Hard Way™
Remember how you used to add big numbers when you were a little tater tot, fresh off the aluminum foil?
5-year-old math
1259601512351095520986368
+ 50695640938240596831104
---------------------------
?
Well you gotta add each column, right to left. And when a column overflows into the double digits, remember to carry that 1 over to the next column.
... <-001
1259601512351095520986368
+ 50695640938240596831104
---------------------------
... <-472
The 10,000th fibonacci number is thousands of digits long, so there's no way that's going to fit in any integer C++ provides out of the box. So without relying upon a library, you could use a string or an array of single-digit numbers. To output the final number, you'll have to convert it to a string tho.
(woflram alpha: fibonacci 10000)
Doing it this way, you'll perform a couple million single-digit additions; it might take a while, but it should be a breeze for any modern computer to handle. Time to get to work !
Here's an example in of a Bignum module in JavaScript
const Bignum =
{ fromInt: (n = 0) =>
n < 10
? [ n ]
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
, fromString: (s = "0") =>
Array.from (s, Number) .reverse ()
, toString: (b) =>
b .reverse () .join ("")
, add: (b1, b2) =>
{
const len = Math.max (b1.length, b2.length)
let answer = []
let carry = 0
for (let i = 0; i < len; i = i + 1) {
const x = b1[i] || 0
const y = b2[i] || 0
const sum = x + y + carry
answer.push (sum % 10)
carry = sum / 10 >> 0
}
if (carry > 0) answer.push (carry)
return answer
}
}
We can verify that the Wolfram Alpha answer above is correct
const { fromInt, toString, add } =
Bignum
const bigfib = (n = 0) =>
{
let a = fromInt (0)
let b = fromInt (1)
let _
while (n > 0) {
_ = a
a = b
b = add (b, _)
n = n - 1
}
return toString (a)
}
bigfib (10000)
// "336447 ... 366875"
Expand the program below to run it in your browser
const Bignum =
{ fromInt: (n = 0) =>
n < 10
? [ n ]
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
, fromString: (s = "0") =>
Array.from (s) .reverse ()
, toString: (b) =>
b .reverse () .join ("")
, add: (b1, b2) =>
{
const len = Math.max (b1.length, b2.length)
let answer = []
let carry = 0
for (let i = 0; i < len; i = i + 1) {
const x = b1[i] || 0
const y = b2[i] || 0
const sum = x + y + carry
answer.push (sum % 10)
carry = sum / 10 >> 0
}
if (carry > 0) answer.push (carry)
return answer
}
}
const { fromInt, toString, add } =
Bignum
const bigfib = (n = 0) =>
{
let a = fromInt (0)
let b = fromInt (1)
let _
while (n > 0) {
_ = a
a = b
b = add (b, _)
n = n - 1
}
return toString (a)
}
console.log (bigfib (10000))
Try not to use recursion for a simple problem like fibonacci. And if you'll only use it once, don't use an array to store all results. An array of 2 elements containing the 2 previous fibonacci numbers will be enough. In each step, you then only have to sum up those 2 numbers. How can you save 2 consecutive fibonacci numbers? Well, you know that when you have 2 consecutive integers one is even and one is odd. So you can use that property to know where to get/place a fibonacci number: for fib(i), if i is even (i%2 is 0) place it in the first element of the array (index 0), else (i%2 is then 1) place it in the second element(index 1). Why can you just place it there? Well when you're calculating fib(i), the value that is on the place fib(i) should go is fib(i-2) (because (i-2)%2 is the same as i%2). But you won't need fib(i-2) any more: fib(i+1) only needs fib(i-1)(that's still in the array) and fib(i)(that just got inserted in the array).
So you could replace the recursion calls with a for loop like this:
int fibonacci(int n){
if( n <= 0){
return 0;
}
int previous[] = {0, 1}; // start with fib(0) and fib(1)
for(int i = 2; i <= n; ++i){
// modulo can be implemented with bit operations(much faster): i % 2 = i & 1
previous[i&1] += previous[(i-1)&1]; //shorter way to say: previous[i&1] = previous[i&1] + previous[(i-1)&1]
}
//Result is in previous[n&1]
return previous[n&1];
}
Recursion is actually discommanded while programming because of the time(function calls) and ressources(stack) it consumes. So each time you use recursion, try to replace it with a loop and a stack with simple pop/push operations if needed to save the "current position" (in c++ one can use a vector). In the case of the fibonacci, the stack isn't even needed but if you are iterating over a tree datastructure for example you'll need a stack (depends on the implementation though). As I was looking for my solution, I saw #naomik provided a solution with the while loop. That one is fine too, but I prefer the array with the modulo operation (a bit shorter).
Now concerning the problem of the size long long int has, it can be solved by using external libraries that implement operations for big numbers (like the GMP library or Boost.multiprecision). But you could also create your own version of a BigInteger-like class from Java and implement the basic operations like the one I have. I've only implemented the addition in my example (try to implement the others they are quite similar).
The main idea is simple, a BigInt represents a big decimal number by cutting its little endian representation into pieces (I'll explain why little endian at the end). The length of those pieces depends on the base you choose. If you want to work with decimal representations, it will only work if your base is a power of 10: if you choose 10 as base each piece will represent one digit, if you choose 100 (= 10^2) as base each piece will represent two consecutive digits starting from the end(see little endian), if you choose 1000 as base (10^3) each piece will represent three consecutive digits, ... and so on. Let's say that you have base 100, 12765 will then be [65, 27, 1], 1789 will be [89, 17], 505 will be [5, 5] (= [05,5]), ... with base 1000: 12765 would be [765, 12], 1789 would be [789, 1], 505 would be [505]. It's not the most efficient, but it is the most intuitive (I think ...)
The addition is then a bit like the addition on paper we learned at school:
begin with the lowest piece of the BigInt
add it with the corresponding piece of the other one
the lowest piece of that sum(= the sum modulus the base) becomes the corresponding piece of the final result
the "bigger" pieces of that sum will be added ("carried") to the sum of the following pieces
go to step 2 with next piece
if no piece left, add the carry and the remaining bigger pieces of the other BigInt (if it has pieces left)
For example:
9542 + 1097855 = [42, 95] + [55, 78, 09, 1]
lowest piece = 42 and 55 --> 42 + 55 = 97 = [97]
---> lowest piece of result = 97 (no carry, carry = 0)
2nd piece = 95 and 78 --> (95+78) + 0 = 173 = [73, 1]
---> 2nd piece of final result = 73
---> remaining: [1] = 1 = carry (will be added to sum of following pieces)
no piece left in first `BigInt`!
--> add carry ( [1] ) and remaining pieces from second `BigInt`( [9, 1] ) to final result
--> first additional piece: 9 + 1 = 10 = [10] (no carry)
--> second additional piece: 1 + 0 = 1 = [1] (no carry)
==> 9542 + 1 097 855 = [42, 95] + [55, 78, 09, 1] = [97, 73, 10, 1] = 1 107 397
Here is a demo where I used the class above to calculate the fibonacci of 10000 (result is too big to copy here)
Good luck!
PS: Why little endian? For the ease of the implementation: it allows to use push_back when adding digits and iteration while implementing the operations will start from the first piece instead of the last piece in the array.

How can I account for a decimal using the modulus operator

The project I am working on needs to find some way of verifying that a variable after the modulus operation is either number != 0, number > 0, or number < (0 < x < 1). I have the first two understood, however employing the mod operator to accomplish the third is difficult.
Essentially what I am looking to do is to be able to catch a value similar to something like this:
a) 2 % 6
b) flag it and store the fact that .333 is less than 1 in a variable (bool)
c) perform a follow up action on the basis that the variable returned a value less than 1.
I have a feeling that the mod operator cannot perform this by itself. I'm looking for a way to utilize its ability to find remainders in order to produce a result.
edit: Here is some context. Obveously the below code will not give me what I want.
if (((inGameTotalCoins-1) % (maxPerTurn+1)) < 0){
computerTakenCoins = (inGameTotalCoins - 1);
inGameTotalCoins = 1;
The quotient is 0(2/6) with the fractional part discarded.The fractional part is .3333 ... So you are basically talking about the fractional part of the quotient , not the modulus value. Modulus can be calculated as follows :
(a / b) * b + (a % b) = a
(2 / 6) * 6 + (2 % 6) = 2
0 * 6 + (2 % 7) = 2
(2 % 6) = 2
*6 goes into 2 zero times with 2 left over.
How about this:-
int number1 = 2;
int number2 = 6;
float number3 = static_cast<float>(number1) / static_cast<float>(number2);
bool isfraction = number3 > 0 && number3 < 1;
if(isfraction){
std :: cout << "true\n" << number3;
}
else{
std :: cout << "false" << number3;
}
number != 0 includes number > 0 and number < (0 x < 1). And number > 0 includes number < (0 x < 1). Generally we do not classify so. For example, people classify number > 0, number == 0 and number < 0.
If you do the modulous operation, you get remainder. Remainder's definition is not one thing. You can see it at https://en.m.wikipedia.org/wiki/Remainder

Move number away from n in C++

I am looking for a simple way to increment/decrement a number away from n, without using if statements, or creating a function. Here is an example:
Increment x from 9 to 10, n is 6
Decrement x from 3 to 2, n is 6
An obvious way to do this is with if statements, but that seems like too much code in my opinion. Here is a function that I could imagine using:
x += 1 * GetSign(6, 9) //GetSign(A, B) returns 1 or -1 depending on what would
Be necessary to move farther away from 6. The made up function above would look something like:
int GetSign(A, B)
{
if( A < B) return -1;
else return 1;
}
You can use the ternary operator:
int A = 6;
int B = 9;
x += (A < B) ? (-1) : (1);

Long Hand Multiplication In C++

I am trying to implement Long Hand Multiplication method for 8 bit binary numbers stored in two arrays BeforeDecimal1 and BeforeDecimal2. The problem is I always get the wrong result. I tried to figure out the issue but couldn't do it. Here is the code:
This is a much more refined code then previous one. It is giving me result but the result is not correct.
int i=0,carry=0;
while(true)
{
if(BeforeDecimal2[i]!=0)
for(int j=7;j>=0;j--)
{
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside first, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside second, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside third, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==0)
{
cout<<"Inside fourth, j= "<<j<<endl;
carry=0;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==0)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=0;
}
}
for(int h=7;h>=0;h--)
{
if(h==0)
{
BeforeDecimal1[0]=0; // that is inserting zeros from the right
}
else
{
BeforeDecimal1[h]=BeforeDecimal1[h-1];
BeforeDecimal1[h-1]=0;
}
}
if(i==3)
break;
i++;
}
Regards
Maybe it would be easiest to back up and start with 8-bit binary numbers stored as 8-bit binary numbers. Much like when we do decimal multiplication, we start with a number of digits. We take the values of multiplying by those individual digits, and add them together to get the final result. The difference (or one obvious difference) is this since we're working in binary, all our digits represent powers of two, so we can get each intermediate result by simply bit shifting the input.
Since it's binary, we have only two possibilities for each digit: if it's a 0, then we need to add 0 times the other number shifted left the appropriate number of places. Obviously, 0 time whatever is still 0, so we simply do nothing in this case. The other possibility is that we have a 1, in which case we add 1 times the other number shifted left the appropriate number of places.
For example, let's consider something like 17 x 5, or (in binary) 10001 x 101.
10001
101
------
10001
+ 1000100
--------
= 1010101
Converting that to something more recognizable, we get 0x55, or 85d.
In code, that process comes out fairly short and simple. Start with a result of 0. Check whether the least significant bit in one operand is set. If so, add the other operand to the result. Shift the one operand right a bit and the other left a bit, and repeat until the operand you're shifting to the right equals 0:
unsigned short mul(unsigned char input1, unsigned char input2) {
unsigned short result = 0;
while (input2 != 0) {
if (input2 & 1)
result += input1;
input1 <<= 1;
input2 >>= 1;
}
return result;
}
If you want to deal with signed numbers, it's generally easiest to figure up the sign of the result separately, and do the multiplication on the absolute values.
You have problem in following lines of code
if(reverse==0)
{
totalReverse=totalReverse-1;
reverse=totalReverse;
}
after some iterations of the inner for loop (index j based) the values of reverse goes should goes to negative and when reverse less than 3 then there should be exception thrown.
Are you running this code without exception handling?
to me this smells like shift and add. is there a requirement that you may use operations simulating logical gates only?
for your full adder you have 3 inputs s(s[j]), b(BeforeDecimal1[j]), c(carry), and two outputs ns(new s[j]), nc (new carry)
the table looks like this
s b c ns nc
0 0 0 0 0 handled in v5 clause 4
0 0 1 1 0 handled in v5 clause 3
0 1 0 1 0 handled in v6 clause 5
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1 handled in v5 clause 2
1 1 0 0 1 handled in v5 clause 1
1 1 1 1 1
your code covers only 4 (now 5) of these 8 clauses
to avoid the ugly if-else-if rake i recommend to use temporary result variables (carry and s still valid in the next if clause)
when you analyze the table you could also do (pseudo bool notation)
nc = s && b || s && c || b && c;
ns = s XOR b XOR c; // there is no XOR in C++: axb = a&&!b || !a&&b
arithmetic notation
nc = (s + b + c) / 2;
ns = (s + b + c) % 2;
// [...]
for(int j=7;j>=0;j--)
{
// start changed code
const int sum = s[j] + BeforeDecimal1[j] + carry;
s[j]=sum % 2;
carry=sum / 2;
// end changed code
}
// [...]
here is a nice simulation of your problem Sequential Multiplication
Unless your requirement precisely states otherwise, which isn't clear from your question or any of your comments so far, it is not necessary to process arrays of bits. Arrays of bytes are much more efficient in both space and time.
You don't need this exhaustive explosion of cases either. The only special case is where either operand is zero, i.e. a[i]|b[i] == 0, when
result[i] = carry;
carry = 0;
All other cases can be handled by:
result[i] = a[i]*b[i]+carry;
carry = (result[i] >>> 8) & 1;
result[i] &= 0xff;
I don't see much point in the names BeforeDecimal1 and BeforeDecimal2 either.