What does 'if((mask | u)==u)' mean? - c++

This is the recurrence relation of maximum sum subset problem.
The complete code is:
if ((mask | u) == u)
dp[u] = max(max(0, dp[u ^ mask] + array[I], dp[u]);
What does exactly mean the following if-statement?
if((mask | u) == u)
Thank you in advance!

It means: “Are all bits of mask in u”.
So if there is a bit in mask not in u this test returns false.
For instance with mask=0b001 and u=0b011 it returns true. But with mask=0b101 and u=0b011 it returns false because the third bit of mask is not set in u.

Binary OR for binary values A, B evaluates as (1) if either A = 1 or B = 1. These bitwise operations extend to strings of binary digits. In C/C++, that's most commonly expressed as integral types.
OR | A = 0 | A = 1 |
-----------------------
B = 0 | (0) | (1) |
-----------------------
B = 1 | (1) | (1) |
-----------------------
(forgive the ASCII art - more concise illustrations and links are here)
mask = {m(n - 1), m(n - 2), .., m(1), m(0)} : (n) binary digits (bits) m(i)
u = {u(n - 1), u(n - 2), .., u(1), u(0)} : (n) binary digits (bits) u(i)
Let's consider (m(i) | u(i)) == u(i) for: i = {0, .., n - 1} ; should any of these bit-wise comparisons be false, then the expression ((mask | u) == u) evaluates as false.
From the OR table we can conclude that the expression is false if and only if m(i) = 1 and u(i) = 0. That is: m(i) | u(i) == (1) OR (0) == (1) which does not equal u(i) == 0
A more concise way of expressing the issue is that if mask has a bit at a position (i) set to (1), and u has a bit at the same position cleared to (0), then (mask | u) cannot equal u.

Related

What does a bitwise AND do with no value infront of it?

I am using Verilog. Say you have the term:
& A
or
~& A
What does this do? Does it just compare it to an all empty array?
It performs a bitwise operation on all bits of the operand
e.g.:
//let x = 4’b1010
&x //equivalent to 1 & 0 & 1 & 0. Results in 1’b0
|x //equivalent to 1 | 0 | 1 | 0. Results in 1’b1
^x //equivalent to 1 ^ 0 ^ 1 ^ 0. Results in 1’b0
More about verilog operators: https://web.engr.oregonstate.edu/~traylor/ece474/beamer_lectures/verilog_operators.pdf

Generate dummies in Stata vs. in R

Stata
r, u, s are dummies. I'm wondering if the following line is also generating dummy n, if r or u or s ==1, but just omit ==1 after r, u, s?
generate byte n = r | u | s
R
Does it make a difference when we generate byte and variable in R or it's the same in R?
This answer addresses Stata questions only.
In Stata if r u s are all 0, 1 variables then r | u | s is also 0, 1 and will be 1 if any of those is 1 and 0 if and only if all are 0. So, it is equivalent to max(r, u, s).
But watch out if r u s are 0, 1 or missing, then r | u | s will also be 1 if any of those is missing. But max(r, u, s) will be missing only if all of those are missing.
If missings are present, then you could use
* 1
gen n = r | u | s if !missing(r, u, s)
The result will be 1 if any argument r u s is 1, 0 if all arguments are 0, and missing if any argument is missing.
* 2
gen n = (r == 1) | (u == 1) | (s == 1)
The result will be 1 if any argument is 1 and 0 otherwise. "Otherwise" is anything from all 0s to all missings.
* 3
gen n = inlist(1, r, u, s)
#3 is equivalent to #2.
In all cases, specifying byte is good practice to save on storage, but not material otherwise.

Decide(in Haskell) if a number is or not a palindrome without using lists

I need to check in Haskell if a four digit number is a palindrome, the problem is that I can't use lists, and in spite of having a fixed digit number, I should use recursion. I have been think on the problem and I couldn't get a solution using recursion. The closest that I could get was this:
pldrm :: Integer -> Bool
pldrm x
|x > 9999 = False
|x > 999 = (div x 1000 == mod x 10) && (mod (div x 100) 10) == div (mod x 100) 10
|otherwise = False
Do you have any idea? thanks
How about just checking if a number is equal to its reversal?
palindrome :: Integer -> Bool
palindrome x = reversal x == x
reversal :: Integral a => a -> a
reversal = go 0
where go a 0 = a
go a b = let (q,r) = b `quotRem` 10 in go (a*10 + r) q
This lets negative numbers like -121 be palindromes, which is easy to check for if you don't want that to be true.
nonNegativePalindrome x = x >= 0 && palindrome x
reversal gives us the integer with digits in reverse order of our input (ignoring the infinite leading zeroes implicit in 12 == ...000012).
reversal works by peeling off the digits from the bottom (using quotRem, which is a lot like divMod) and putting them together in reverse order (via muliplication and adding).
reversal 12345
= go 0 12345
= go 5 1234
= go 54 123
= go 543 12
= go 5432 1
= go 54321 0
= 54321
It's worth noting that n == reversal $ reversal n only if n is zero or has a non-zero 1s digit. (reversal (reversal 1200) == 12), but that integers in the range of reversal are all invertible: reversal x == reversal (reversal (reversal x)) forall x.
More thorough explanation of how to reach this solution in this blog post.
Ok, this is indeed a bit tricky and more math than Haskell so let's look at a possible solution (assuming a decimal system).
The idea is to use div and mod to get at the highest and lowest digit of a number.
Remember that you can write
(q,r) = n `divMod` m
to get numbers q and r so that q * m + r = n with 0 <= r < q. For m = 10 this
will conveniently get (for positive n):
in q all but the last digits
in r the last digit
remark: I had this wrong for some time - I hope it's correct now - the edge cases are really tricky.
palindrome :: Integer -> Bool
palindrome n = palin n (digits n)
where
palin x dgts
| x < 0 = False
| x == 0 = True
| x < 10 = dgts == 1
| otherwise = q == x `mod` 10 && palin inner (dgts-2)
where
inner = r `div` 10
(q,r) = x `divMod` size
size = 10^(dgts-1)
digits :: Integer -> Integer
digits x
| x < 10 = 1
| otherwise = 1 + digits (x `div` 10)
Obvious I did not know the size of your problem so digits will look for the number of digits:
digits 5445 = 4
digits 123 = 3
...
The edge cases are these:
| x < 0 = False
| x == 0 = True
| x < 10 = digits == 1
Obvious negative numbers should not be palindromes
if all digits are 0 then it's an palindrome
one-digit numbers are palindromes if indeed we are looking only at length 1 (this had me bad, as the inner of stuff like 1011 is a one digit nubmer 1)
The rest is based on this observations:
x div 10^(digits-1) = the highest digit (5445 div 1000 = 5)
x mod 10^(digits-1) = all but the highest digit (5445 mod 1000 = 445)
x mod 10 = the lowest digit (5445 mod 10 = 5)
number div 10 = remove the lowest digit (5445 div 10 = 544)
just to be safe let's test it using Quickcheck:
Let's use Quickcheck to test it (should be a nice example :D )
module Palindrome where
import Test.QuickCheck
main :: IO ()
main = do
checkIt palindrome
palindrome :: Integer -> Bool
palindrome n = palin n (digits n)
where
palin x dgts
| x < 0 = False
| x == 0 = True
| x < 10 = dgts == 1
| otherwise = q == x `mod` 10 && palin inner (dgts-2)
where
inner = r `div` 10
(q,r) = x `divMod` size
size = 10^(dgts-1)
digits :: Integer -> Integer
digits x
| x < 10 = 1
| otherwise = 1 + digits (x `div` 10)
checkIt :: (Integer -> Bool) -> IO ()
checkIt p =
quickCheckWith more (\n -> n < 0 || p n == (reverse (show n) == show n))
where more = stdArgs { maxSuccess = 10000, maxSize = 999999 }
seems ok:
runghc Palindrom.hs
+++ OK, passed 10000 tests.
If only four digit numbers considered, you can recursively subtract 1001 to check if first and last digits are equal and then subtract 0110 to check if middle digits are equal.
pldrm :: Int -> Bool
pldrm x
| x > 1000 = pldrm (x - 1001)
| x > 100 = pldrm (x - 110)
| otherwise = x == 0
Please note that this function will give incorrect results for numbers outside of [1000,9999] range.
It is a pity that you cannot use lists. Here is cumbersome solution based on arithmetic operations (works only for four-digit numbers):
pldrm :: Int -> Bool -- no need for Integer if you work only with four
-- digit numbers
pldrm x = (div x 1000 == mod x 10) && (div y 10 == mod y 10)
where y = rem x 1000 `quot` 10 -- extracts two inner digits
> pldrm 3113
True
> pldrm 3111
False
isPolindrom :: Integer -> Bool
isPolindrom n = if let i = read (reverse (show n)) :: Integer in i==n then True else False

How to implement arithmetic right shift from logical shift?

I need to implement a 32-bit arithmetic right shift from logical shifts, and, or, xor and normal integer arithmetic operations.
I read somewhere the following is supposed to work:
(x>>N)|(((1<<N)-1)<<(32-N))
x is the integer that will be shifted and N is the amount of bits to shift.
This works for negative (msb is 1) numbers but not for positive numbers (msb is 0).
Does anyone know an efficient algorithm that always produces the right result?
You can use this
(x >> N) | (-(x < 0) << (32 - N))
If x is negative then -(x < 0) returns -1, which have a bit pattern of all 1s, assuming 2's complement. -1 << (32 - N) will make a value which has all 1s in the top N bits and 0s in the remaining part. If x is non-negative then the latter part will always be zero, and the result will be the same as a logical shift. Alternatively it can be modified to
(x >> N) | ~(((x < 0) << (32 - N)) - 1)
Note that it won't work for N <= 0 or N >= 32 (since shifting more than the width of type invokes UB) so you should treat those cases specifically if needed
If you're not allowed to use comparison then you can change x < 0 to (unsigned)x >> 31 and get the below equivalent ways
(x >> N) | (-((unsigned)x >> 31) << (32 - N))
(x >> N) | ((~0*(unsigned)x >> 31) << (32 - N))
(x >> N) | ~((((unsigned)x >> 31) << (32 - N)) - 1)
LSR 1:
+---+---+---+---
| | | | ...
+---+---+---+---
\ \ \ \
\ \ \
\ \ \
+---+---+---+---
| 0 | | | ...
+---+---+---+---
ASR 1:
+---+---+---+---
| | | | ...
+---+---+---+---
|\ \ \ \
| \ \ \
| \ \ \
+---+---+---+---
| | | | ...
+---+---+---+---
An ASR consists of an LSR plus an OR.
So you want to replicate bit31 N times. The efficient solution is probably an efficient implementation of
( bit31 ? 0xFFFFFFFF : 0x00000000 ) << ( 32 - N ) )
I've come up with
LSL(SUB(LSR(NOT(X), 31), 1), SUB(32, N))
The whole thing
OR(LSL(SUB(LSR(NOT(X), 31), 1), SUB(32, N)), LSR(X, N))
That doesn't seem very efficient.

what this "if(k.c[3] & c)" part of code doing?

#include<stdio.h>
#include<iostream.h>
main()
{
unsigned char c,i;
union temp
{
float f;
char c[4];
} k;
cin>>k.f;
c=128;
for(i=0;i<8;i++)
{
if(k.c[3] & c) cout<<'1';
else cout<<'0';
c=c>>1;
}
c=128;
cout<<'\n';
for(i=0;i<8;i++)
{
if(k.c[2] & c) cout<<'1';
else cout<<'0';
c=c>>1;
}
return 0;
}
if(k.c[2] & c)
That is called bitwise AND.
Illustration of bitwise AND
//illustration : mathematics of bitwise AND
a = 10110101 (binary representation)
b = 10011010 (binary representation)
c = a & b
= 10110101 & 10011010
= 10010000 (binary representation)
= 128 + 16 (decimal)
= 144 (decimal)
Bitwise AND uses this truth table:
X | Y | R = X & Y
---------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
See these tutorials on bitwise AND:
Bitwise Operators in C and C++: A Tutorial
Bitwise AND operator &
A bitwise operation (AND in this case) perform a bit by bit operation between the 2 operands.
For example the & :
11010010 &
11000110 =
11000010
Bitwise Operation in your code
c = 128 therefore the binary representation is
c = 10000000
a & c will and every ith but if c with evert ith bit of a. Because c only has 1 in the MSB position (pos 7), so a & c will be non-zero if a has a 1 in its position 7 bit, if a has a 0 in pos bit, then a & c will be zero. This logic is used in the if block above. The if block is entered depending upon if the MSB (position 7 bit) of the byte is 1 or not.
Suppose a = ? ? ? ? ? ? ? ? where a ? is either 0 or 1
Then
a = ? ? ? ? ? ? ? ?
AND & & & & & & & &
c = 1 0 0 0 0 0 0 0
---------------
? 0 0 0 0 0 0 0
As 0 & ? = 0. So if the bit position 7 is 0 then answer is 0 is bit position 7 is 1 then answer is 1.
In each iteration c is shifted left one position, so the 1 in the c propagates left wise. So in each iteration masking with the other variable you are able to know if there is a 1 or a 0 at that position of the variable.
Use in your code
You have
union temp
{
float f;
char c[4];
} k;
Inside the union the float and the char c[4] share the same memory location (as the property of union).
Now, sizeof (f) = 4bytes) You assign k.f = 5345341 or whatever . When you access the array k.arr[0] it will access the 0th byte of the float f, when you do k.arr[1] it access the 1st byte of the float f . The array is not empty as both the float and the array points the same memory location but access differently. This is actually a mechanism to access the 4 bytes of float bytewise.
NOTE THAT k.arr[0] may address the last byte instead of 1st byte (as told above), this depends on the byte ordering of storage in memory (See little endian and big endian byte ordering for this)
Union k
+--------+--------+--------+--------+ --+
| arr[0] | arr[1] | arr[2] | arr[3] | |
+--------+--------+--------+--------+ |---> Shares same location (in little endian)
| float f | |
+-----------------------------------+ --+
Or the byte ordering could be reversed
Union k
+--------+--------+--------+--------+ --+
| arr[3] | arr[2] | arr[1] | arr[0] | |
+--------+--------+--------+--------+ |---> Shares same location (in big endian)
| float f | |
+-----------------------------------+ --+
Your code loops on this and shifts the c which propagates the only 1 in the c from bit 7 to bit 0 in one step at a time in each location, and the bitwise anding checks actually every bit position of the bytes of the float variable f, and prints a 1 if it is 1 else 0.
If you print all the 4 bytes of the float, then you can see the IEEE 754 representation.
c has single bit in it set. 128 is 10000000 in binary. if(k.c[2] & c) checks if that bit is set in k.c[2] as well. Then the bit in c is shifted around to check for other bits.
As result the program is made to display the binary representation of float it seems.