How to Write an Readable and Understandable Bitwise Operator Formula? - c++11

I am Learning the bitwise operator from a course downloaded from udemy but It is very confusing.
They teach by this example which is very confusing to read and understand, is there a course or example which will teach bitwise operator in simple way? and also what is the use of bitwise operator? is it important to take headache from it or not?
The example:
#include <iostream>
using namespace std;
main()
{
/*
Operator Symbol Form Operation
left shift << x << y all bits in x shifted left y bits
right shift >> x >> y all bits in x shifted right y bits
bitwise NOT ~ ~x all bits in x flipped
bitwise AND & x & y each bit in x AND each bit in y
bitwise OR | x | y each bit in x OR each bit in y
bitwise XOR ^ x ^ y each bit in x XOR each bit in y
0
1
0101 0110
for example 126
1 * 10 ^ 2 + 2 * 10 ^ 1 + 6 * 10 ^ 0 = ?
1 * 10 ^ 2 = 100
2 * 10 ^ 1 = 20
6 * 10 ^ 0 = 6 why? because write 10 about 0 times = 0
we have the answer 126
1 2 6
3 2 1 // this is the position of 126. it's in -1 formula we can use
3-1=2
2-1=1
1-1=0
1 2 6 = 1 * 10 ^ 2 + 2 * 10 ^ 1 + 6 * 10 ^ 0
1 0 1 0 = 1 * 2 + 0 * 2 + 1 * 2 + 0 * 2
1 0 1 0 = 1 * 2 ^ 3 + 0 * 2 ^ 2 + 1 * 2 ^ 1 + 0 * 2 ^ 0 = 10
1 * 2 ^ 3 = 8
0 * 2 ^ 2 = 0
1 * 2 ^ 1 = 2
0 * 2 ^ 0 = 0
8 + 0 + 2 + 0 = 10
// Decimal notation for 1 0 1 0 is 10
1 0 1 1 0 0 = 0*0^0 + 0*0^1 + 1*2^2 + 1*2^3 + 0*0^4 + 1*2^5 = 44
0*0^0 = 0
0*0^1 = 0
1*2^2 = 4
1*2^3 = 8
0*0^4 = 0
1*2^5 = 32
0+0+4+8+0+32 = 44
*/
cout << (10 >> 1) << endl;
}

Related

For loop variables get changed in Fortran

I am using the finite element method and separating a unit isosceles triangle into triangles with six nodes. While calculating coordinates of the nodes I noticed that the variables in the for loop get messed up for some reason and I cannot figure out why. Here is my code:
PROGRAM triangle
IMPLICIT NONE
INTEGER, PARAMETER :: stepSize = 4
INTEGER, PARAMETER :: numberOfNodes = ((2*stepSize - 1) * (2*stepSize)) / 2
INTEGER :: i, j, counter
REAL, DIMENSION(2, numberOfNodes) :: nodeCoordinates
counter = 0
DO j = 1, 2*stepSize - 1
DO i = 1, 2*stepSize - 1 - counter
nodeCoordinates(1, i + (j-1)*(2*stepSize - 1)) = ((REAL(i-1)) / REAL(2*stepSize - 2))
nodeCoordinates(2, i + (j-1)*(2*stepSize - 1)) = ((REAL(j-1)) / REAL(2*stepSize - 2))
END DO
counter = counter + 1
END DO
END PROGRAM triangle
When I print the variable j in the inner for loop, the following is shown:
1
1
1
1
1
1
1
2
2
2
2
2
2
3
3
3
3
3
4
4
4
4
0
0
0
1
1
2

Find the all possible multiples( size of n ) of a positive integer k

Input 1 :
64
Output:( size of 3 )
1 x 1 x 64 =64
1 x 2 x 32 =64
1 x 4 x 16 =64
1 x 8 x 8 =64
2 x 2 x 16 =64
2 x 4 x 8 =64
4 x 4 x 4 =64
Input 2 :
6
Output:( size of 2 )
1 x 6 =6
2 x 3 =6
I tried Using Complete Binary Tree but I didn't get all possible Combination
.
Here is :
64
32 2
16 2 2 1
8 2 1 2 1 2 1 1
If Your trace level by level elements only some combinations are available
64 x 1 X 1
32 X 2 X 1
16 x 2 x 2
8 x 2 x 2 x 2( limit > 3 )
Question is I need all possible combinations
You can use recursion method. Consider the following PHP code (I guess you can convert for the idea to each language you need):
function comb($num, $cnt, $prefix, $minDiv) {
if ($cnt == 0)
{
if ($num == 1)
return rtrim($prefix,",");
else return false;
}
$arrs = array();
for ($i=$minDiv; $i <= $num; $i++) {
if ($num % $i == 0) { // if num modulo i equal 0
$ans = comb($num/$i, $cnt-1, $prefix . $i . ",", $i );
if ($ans) // if valid combination add it
$arrs[] = $ans;
}
}
return $arrs;
}
$ans = comb(64,3, "",1);
echo "ANSWER:\n";
echo print_r($ans);
This code will generate the following answer for comb(6,2, "", 1):
1,6
2,3

Count the frequency of matrix values including 0

I have a vector
A = [ 1 1 1 2 2 3 6 8 9 9 ]
I would like to write a loop that counts the frequencies of values in my vector within a range I choose, this would include values that have 0 frequencies
For example, if I chose the range of 1:9 my results would be
3 2 1 0 0 1 0 1 2
If I picked 1:11 the result would be
3 2 1 0 0 1 0 1 2 0 0
Is this possible? Also ideally I would have to do this for giant matrices and vectors, so the fasted way to calculate this would be appreciated.
Here's an alternative suggestion to histcounts, which appears to be ~8x faster on Matlab 2015b:
A = [ 1 1 1 2 2 3 6 8 9 9 ];
maxRange = 11;
N = accumarray(A(:), 1, [maxRange,1])';
N =
3 2 1 0 0 1 0 1 2 0 0
Comparing the speed:
K>> tic; for i = 1:100000, N1 = accumarray(A(:), 1, [maxRange,1])'; end; toc;
Elapsed time is 0.537597 seconds.
K>> tic; for i = 1:100000, N2 = histcounts(A,1:maxRange+1); end; toc;
Elapsed time is 4.333394 seconds.
K>> isequal(N1, N2)
ans =
1
As per the loop request, here's a looped version, which should not be too slow since the latest engine overhaul:
A = [ 1 1 1 2 2 3 6 8 9 9 ];
maxRange = 11; %// your range
output = zeros(1,maxRange); %// initialise output
for ii = 1:maxRange
tmp = A==ii; %// temporary storage
output(ii) = sum(tmp(:)); %// find the number of occurences
end
which would result in
output =
3 2 1 0 0 1 0 1 2 0 0
Faster and not-looping would be #beaker's suggestion to use histcounts:
[N,edges] = histcounts(A,1:maxRange+1);
N =
3 2 1 0 0 1 0 1 2 0
where the +1 makes sure the last entry is included as well.
Assuming the input A to be a sorted array and the range starts from 1 and goes until some value greater than or equal to the largest element in A, here's an approach using diff and find -
%// Inputs
A = [2 4 4 4 8 9 11 11 11 12]; %// Modified for variety
maxN = 13;
idx = [0 find(diff(A)>0) numel(A)]+1;
out = zeros(1,maxN); %// OR for better performance : out(maxN) = 0;
out(A(idx(1:end-1))) = diff(idx);
Output -
out =
0 1 0 3 0 0 0 1 1 0 3 1 0
This can be done very easily with bsxfun.
Let the data be
A = [ 1 1 1 2 2 3 6 8 9 9 ]; %// data
B = 1:9; %// possible values
Then
result = sum(bsxfun(#eq, A(:), B(:).'), 1);
gives
result =
3 2 1 0 0 1 0 1 2

Comparing Two Matrices in MATLAB which shows how much they are matched

Please assume A is a matrix of 4 x 4 which has:
A = 1 0 1 0
1 0 1 0
1 1 1 0
1 1 0 0
And B is a reference matrix (4 x 4) which is:
B = 1 0 1 0
1 0 1 0
1 0 1 0
1 1 1 0
Now, if A would be compared to B which is the reference matrix, by matching these two matrices, almost all of members are equal except A(4,3) and A(3,2). However, since B is the reference matrix and A is comparing to that, only differences of those members are matter which are 1 in B. In this particular example, A(4,3) is only matter, not A(3,2), Means:
>> C = B ~= A;
ans =
0 0 0 0
0 0 0 0
0 1 0 0
0 0 1 0
A(4,3) ~= B(4,3)
Finally, we are looking for a piece of code which can show how many percentage of ones in A are equal to their equivalent members at B. In this case the difference is:
(8 / 9) * 100 = 88.89 % are matched.
Please bear in mind that speed is also important here. Therefore, quicker solution are more appreciated. Thanks.
For getting only the different entries where there is a 1 in B, just add an & to it, so you'll only get these entries. To get the percentage, take the sum where A and B are 1. Then divide it by the sum of 1 in B (or the sum of 1in A -> see the note below).
A = [1 0 1 0;
1 0 1 0;
1 1 1 0;
1 1 0 0];
B = [1 0 1 0;
1 0 1 0;
1 0 1 0;
1 1 1 0];
C = (B ~= A) & B
p = sum(B(:) & A(:)) / sum(B(:)) * 100
This is the result:
C =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
p =
88.8889
Edit / Note: In the OP's question it's not 100% clear if he wants the percentage in relation to the sum of ones in A or B. I assumed that it is a percentage of the reference-matrix, which is B. Therefore I divide by sum(B(:)). In case you need it in reference to the ones in A, just change the last line to:
p = sum(B(:) & A(:)) / sum(A(:)) * 100
If I got it right, what you want to know is where B == 1 and A == 0.
Try this:
>> C = B & ~A
C =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
To get the percentage, you could try this:
>> 100 * sum(A(:) & B(:)) / sum(A(:))
ans =
88.8889
You can use matrix-multiplication, which must be pretty efficient as listed next.
To get the percentage value with respect to A -
percentage_wrtA = A(:).'*B(:)/sum(A(:)) * 100;
To get the percentage value with respect to B -
percentage_wrtB = A(:).'*B(:)/sum(B(:)) * 100;
Runtime tests
Here's some quick runtime tests to compare matrix-multiplication against summation of elements with (:) and ANDing -
>> M = 6000; %// Datasize
>> A = randi([0,1],M,M);
>> B = randi([0,1],M,M);
>> tic,sum(B(:) & A(:));toc
Elapsed time is 0.500149 seconds.
>> tic,A(:).'*B(:);toc
Elapsed time is 0.126881 seconds.
Try:
sum(sum(A & B))./sum(sum(A))
Output:
ans =
0.8889

Total probability of a given answer of a given number of additions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm doing C++, and I want to find out the simplest way to find the total probability of a given answer of a given number of additions.
For example, the given answer is 5, and the given number of additions is 4 (x+x+x+x). The total probability that I want to find is 4:
1) 1 + 1 + 1 + 2 = 5
2) 1 + 1 + 2 + 1 = 5
3) 1 + 2 + 1 + 1 = 5
4) 2 + 1 + 1 + 1 = 5
Another example, the given answer is 6, and the given number of additions is 4 (x+x+x+x). The total probability is 10:
1) 1 + 1 + 1 + 3 = 6
2) 1 + 1 + 3 + 1 = 6
3) 1 + 3 + 1 + 1 = 6
4) 3 + 1 + 1 + 1 = 6
5) 1 + 1 + 2 + 2 = 6
6) 1 + 2 + 2 + 1 = 6
7) 2 + 2 + 1 + 1 = 6
8) 2 + 1 + 1 + 2 = 6
9) 2 + 1 + 2 + 1 = 6
10) 1 + 2 + 1 + 2 = 6
I have absolutely no idea where to start
Here's a start for you.
Have a look at this table
1 2 3 4 5
+------------------
1 | 1 0 0 0 0
2 | 1 1 0 0 0
3 | 1 2 1 0 0
4 | 1 3 3 1 0
5 | 1 4 6 4 1
The number of summands is increasing from left to right, the total increases in rows, so e.g. there are 3 ways to sum 3 integers (greater than 0) for a total of 4 (namely 1+1+2, 1+2+1, 2+1+1).
With 4 additions and a result Y, if all numbers will be positive and nonzero and small enough (<100) you can easily at least bruteforce this... just cycle trough all numbers with 4x for cycles and if they sum up to Y increment number of permutations. Disadvantage is the complexity O(N^4) which will be very slow.
#include <iostream>
using namespace std;
int main()
{
int y = 6;
int perm = 0;
for(int a = 1; a < y; a++)
for(int b = 1; b < y; b++)
for(int c = 1; c < y; c++)
for(int d = 1; d < y; d++)
{
if((a+b+c+d)==y)
{
cout << a << " + " << b << " + " << c << " + " << d << " = " << y << endl;
perm++;
}
}
cout << "number of permutations: " << perm << endl;
}
This is not probability what you are trying to find, it's number of comibnations.
Looking at your examples, I assume that the number of numbers you are adding is fixed (i.e. 4), so every number is greater or equal to 1. We can do simple math here then - let's substract this number from both sides of the equation:
Original: 1) 1 + 1 + 1 + 2 = 5
Result of substracting: 1) 0 + 0 + 0 + 1 = 1
When the substraction is done, your problem is the combination with repetition problem.
The formulas you can find in the link I provided are quite simple. The problem can be solved using following code:
#include <iostream>
unsigned factorial(int n)
{
if (n == 1) return 1;
return n * factorial(n-1);
}
unsigned combinationsWithRepetition(int n, int k)
{
return factorial(n + k - 1) / (factorial(k) * factorial(n - 1));
}
unsigned yourProblem(unsigned numberOfNumbers, unsigned result)
{
return combinationsWithRepetition(numberOfNumbers, result - numberOfNumbers);
}
int main()
{
std::cout << yourProblem(4, 5) << std::endl;
std::cout << yourProblem(4, 6) << std::endl;
return 0;
}
Also, you can check this code out in online compiler.
Note that this code covers only the problem solving and could be improved if you choose to use it (i.e. it is not protected against invalid values).

Resources