I have used JAVA to create a linked list of 30 nodes. Each node is assigned a random Boolean value when instantiated.
I want each node assigned its own random boolean method/function/rule that takes three Boolean arguments and returns the result:
boolean assignedBolMethod(boolean a, boolean b, boolean c) {
boolean answer = conduct assigned ruled
return answer;
}
I understand there are 256 such rules to chose from (2^2^3); how could I generate all 256 possible rules without typing them out manually?
Let's say '0' when we mean false and '1' when we mean true, because that makes this a lot easier to read:
There are 8 different possible inputs (000, 001, 010, 011, 100, 101, 110, and 111), and for each input, there are 2 possible answers: 0 or 1.
Let's define a 'rule' as follows: We always list all the inputs in that exact order, and then we list the rule's answer to each input in terms of a 1 or a 0. Thus, 00001111 is the rule that says '000 = 0', '001 = 0, 010 = 0, 011 = 0, 100 = 1, ', etcetera - in other words, the rule is: return a;, if you were to put it in code.
It is then obvious that there are indeed 256 rules (2 ^ 8), and you can represent each rule as a single byte, as bytes consist of 8 bits. Every existing byte represents one rule. Thus 'a rule' and 'a byte' are completely interchangeable, thus, this boils down to: How do I generate an arbitrary byte.
And that's easy:
Random r = new Random(); // do this once someplace
byte rule = r.nextByte();
Alternatively if you want an ordered list of every possible rule:
byte[] rules = new byte[256];
for (int i = 0; i < rules.length; i++) rules[i] = (byte) i;
But this array is mostly meaningless; it effectively maps '100' to '100' - not very useful. There is no actual need to have a 'list' of all possible rules: Java already ships with it: byte - that is a data type that exactly matches. Thus, if you have some code and you want 'rule 100' to be applied, all you need to write is byte rule = 100; - no need for a list.
Given a byte that represents a rule, plus those 3 inputs, how do you determine the answer the rule indicates is correct?
Well, first you need to collapse those 3 booleans you have into which one of the 8 bits in your byte represents the answer.
int bitPos = (a ? 1 : 0) + (b ? 2 : 0) + (c ? 4 : 0);
This gives you the position of the bit (a number between 0 and 7) that determines the answer.
Then, given a bit position and a byte:
boolean answer = ((rule >> bitpos) & 1) != 0;
Breaking that down:
a >> b will take the bitstring of a (let's say it's rule 00110111), and shift it to the right by b spots. So if we want the bit at bitpos=2 (so, the third bit), 0b00110111 >> 2 is 0b00001101. This means the bit we are interested in is now at the very end.
a & b will take the bitstring of a, and the bitstring of b, and checks for all positions where both a and b have a 1. Then, it returns a new number represented by setting each bit to 1 where both a and b have a one. Therefore, a & 1 has the effect of zeroing out all bits, except the lowest bit (1 = 00000001 - all bits unset except the lowest bit). It gets rid of all bits, except the bit we care about.
!= 0 then just checks if that bit was set or not.
Related
I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the gray code sequence is not mentioned.
I searched on various forums but couldn't get the right answer. It would be great if you can provide a solution for this.
My attempt to the problem - Convert two integers to binary and add the digits in both the numbers separately and find the difference between the sum of the digits in two numbers. If the difference is one then they are gray code neighbors.
But I feel this wont work for all cases. Any help is highly appreciated. Thanks a lot in advance!!!
Actually, several of the other answers seem wrong: it's true that two binary reflected Gray code neighbours differ by only one bit (I assume that by « the » Gray code sequence, you mean the original binary reflected Gray code sequence as described by Frank Gray). However, that does not mean that two Gray codes differing by one bit are neighbours (a => b does not mean that b => a). For example, the Gray codes 1000 and 1010 differ by only one bit but are not neighbours (1000 and 1010 are respectively 15 and 12 in decimal).
If you want to know whether two Gray codes a and b are neighbours, you have to check whether previous(a) = b OR next(a) = b. For a given Gray code, you get one neighbour by flipping the rightmost bit and the other neighbour bit by flipping the bit at the left of the rightmost set bit. For the Gray code 1010, the neighbours are 1011 and 1110 (1000 is not one of them).
Whether you get the previous or the next neighbour by flipping one of these bits actually depends on the parity of the Gray code. However, since we want both neighbours, we don't have to check for parity. The following pseudo-code should tell you whether two Gray codes are neighbours (using C-like bitwise operations):
function are_gray_neighbours(a: gray, b: gray) -> boolean
return b = a ^ 1 OR
b = a ^ ((a & -a) << 1)
end
Bit trick above: a & -a isolates the rigthmost set bit in a number. We shift that bit by one position to the left to get the bit we need to flip.
Assumptions:
Inputs a and b are grey code sequences in binary reflected gray code.
i.e a's and b's bit encoding is binary gray code representations.
#convert from greycode bits into regular binary bits
def gTob(num): #num is binary graycode
mask = num >> 1
while mask!=0:
num = num^mask
mask >>= 1
return num; #num is converted
#check if a and b are consecutive gray code encodings
def areGrayNeighbors(a,b):
return abs(gTob(a) - gTob(b)) == 1
Few Test cases:
areGrayNeighbors(9,11) --> True (since (1001, 1011) differ in only one
bit and are consecutive numbers in decimal representation)
areGrayNeighbors(9,10) --> False
areGrayNeighbors(14,10) --> True
References:
method gTob() used above is from rodrigo in this post The neighbors in Gray code
public int checkConsecutive2(int b1, int b2){
int x = (b1 ^ b2);
if((x & (x - 1)) !=0){
return 0;
}else{
return 1;
}
}
If two numbers are in gray code sequence, they differ by one binary digit. i.e the exclusive OR on the two numbers returns a power of 2. So, find XOR and check if the result is a power of two.
This solution works well for the all the test cases written by CodeKaichu above. I would love to know if it fails in any cases.
public boolean grayCheck(int x, int y) {
int z = x^y;
return (z&z-1)==0;
}
An obvious answer, but it works.
Convert each gray code into its respective Binary form, subtract the two. If you answer is a binary equivalent of +1 or -1 then the two gray codes are adjacent.
This seems like an over kill, but when you're siting in an interview and don't know the correct method, this works. Also to optimize, one can check the single bit difference filter, so we don't waste time converting and subtracting numbers that we know for sure aren't adjacent.
If you just want to check if the input numbers differ by just one bit:
public boolean checkIfDifferByOneBit(int a, int b){
int diff = 0;
while(a > 0 && b > 0){
if(a & 1 != b & 1)
diff++;
a = a >> 1;
b = b >> 1;
}
if (a > 0 || b > 0) // a correction in the solution provided by David Jones
return diff == 0 // In the case when a or b become zero before the other
return diff == 1;
}
You can check if two numbers differ by one bit or not as follows. In this method, difference in the length of binary numbers are taken care of. Eg, the output for 11 (1011) and 3 (11) will be returned as true.
Also, this does not solve the second criteria for Gray code adjacency. But if you only want to check if the numbers differ by one bit, the code below will help.
class Graycode{
public static boolean graycheck(int one, int two){
int differences = 0;
while (one > 0 || two > 0){
// Checking if the rightmost bit is same
if ((one & 1) != (two & 1)){
differences++;
}
one >>= 1;
two >>= 1;
}
return differences == 1;
}
public static void main(String[] args){
int one = Integer.parseInt(args[0]);
int two = Integer.parseInt(args[1]);
System.out.println(graycheck(one,two));
}
}
If two numbers are in gray code sequence, they differ by one binary digit. i.e the exclusive OR on the two numbers returns a power of 2. So, find XOR and check if the result is a power of two.
python 3.8
a=int(input())
b=int(input())
x=a^b
if((x and (not(x & (x - 1))) )):
print("True")
else:
print("False")
I've had to solve this question in an interview as well. One of the conditions for the two values to be a gray code sequence is that their values only differ by 1 bit. Here is a solution to this problem:
def isGrayCode(num1, num2):
differences = 0
while (num1 > 0 or num2 > 0):
if ((num1 & 1) != (num2 & 1)):
differences++
num1 >>= 1
num2 >>= 1
return differences == 1
Googling around for a while to find subsets of a String, i read wikipedia and it mentions that
.....For the whole power set of S we get:
{ } = 000 (Binary) = 0 (Decimal)
{x} = 100 = 4
{y} = 010 = 2
{z} = 001 = 1
{x, y} = 110 = 6
{x, z} = 101 = 5
{y, z} = 011 = 3
{x, y, z} = 111 = 7
Is there a possible way to implement this through program and avoid recursive algorithm which uses string length?
What i understood so far is that, for a String of length n, we can run from 0 to 2^n - 1 and print characters for on bits.
What i couldn't get is how to map those on bits with the corresponding characters in the most optimized manner
PS : checked thread but couldnt understood this and c++ : Power set generated by bits
The idea is that a power set of a set of size n has exactly 2^n elements, exactly the same number as there are different binary numbers of length at most n.
Now all you have to do is create a mapping between the two and you don't need a recursive algorithm. Fortunately with binary numbers you have a real intuitive and natural mapping in that you just add a character at position j in the string to a subset if your loop variable has bit j set which you can easily do with getBit() I wrote there (you can inline it but for you I made a separate function for better readability).
P.S. As requested, more detailed explanation on the mapping:
If you have a recursive algorithm, your flow is given by how you traverse your data structure in the recursive calls. It is as such a very intuitive and natural way of solving many problems.
If you want to solve such a problem without recursion for whatever reason, for instance to use less time and memory, you have the difficult task of making this traversal explicit.
As we use a loop with a loop variable which assumes a certain set of values, we need to make sure to map each value of the loop variable, e.g. 42, to one element, in our case a subset of s, in a way that we have a bijective mapping, that is, we map to each subset exactly once. Because we have a set the order does not matter, so we just need whatever mapping that satisfies these requirements.
Now we look at a binary number, e.g. 42 = 32+8+2 and as such in binary with the position above:
543210
101010
We can thus map 42 to a subset as follows using the positions:
order the elements of the set s in any way you like but consistently (always the same in one program execution), we can in our case use the order in the string
add an element e_j if and only if the bit at position j is set (equal to 1).
As each number has at least one digit different from any other, we always get different subsets, and thus our mapping is injective (different input -> different output).
Our mapping is also valid, as the binary numbers we chose have at most the length equal to the size of our set so the bit positions can always be assigned to an element in the set. Combined with the fact that our set of inputs is chosen to have the same size (2^n) as the size of a power set, we can follow that it is in fact bijective.
import java.util.HashSet;
import java.util.Set;
public class PowerSet
{
static boolean getBit(int i, int pos) {return (i&1<<pos)>0;}
static Set<Set<Character>> powerSet(String s)
{
Set<Set<Character>> pow = new HashSet<>();
for(int i=0;i<(2<<s.length());i++)
{
Set<Character> subSet = new HashSet<>();
for(int j=0;j<s.length();j++)
{
if(getBit(i,j)) {subSet.add(s.charAt(j));}
}
pow.add(subSet);
}
return pow;
}
public static void main(String[] args)
{System.out.println(powerSet("xyz"));}
}
Here is easy way to do it (pseudo code) :-
for(int i=0;i<2^n;i++) {
char subset[];
int k = i;
int c = 0;
while(k>0) {
if(k%2==1) {
subset.add(string[c]);
}
k = k/2;
c++;
}
print subset;
}
Explanation :- The code divides number by 2 and calculates remainder which is used to convert number to binary form. Then as you know only selects index in string which has 1 at that bit number.
I have a long that corresponds to an assembly language instruction.
Here's the problem; the first field is Opcode. It can be either 1 or 2 digits. So for example in 120602, 12 is the opcode. In 10602, 1 is the opcode.
I want to extract each individual field; where opcode is the first 1-2 numbers on the left, 1 to the right of that is op1mode, 1 to the right of that is op1gpr, 1 to the right of that is op2mode, and finally, the last part is op2gpr.
Ideally, I want to assign each to its own variable for later use, or separate them in an array.
I was thinking that this can be achievable using bitwise operations; namely masks and shifts.
How would one split the number with just bitwise operations?
Bitwise/bitshifts won't do you any good unless the fields are combined in a base 2 representation. As shown, your digits are base 10. On the other hand, you can use integer division and modulo for the numbers you've shown.
120602 / 10000 = 12
120602 % 10000 = 602
These basically correspond to the following types of operations for binary digits:
0x1D71A >>> 12 = 0x1D
0x1D71A & 0xFFF = 0x71A
An easy way to do that (but without bit manipulation), is to define an array containing five integers, and then to fill it which the digits of your number. You will have to begin from the end of the number, it is easier.
An example in Java:
long number = 120602;
int[] op = new int[5];
for(int i = 0; i < 4; ++i) {
op[i] = (int) (number % 10);
number /= 10;
}
op[4] = (int) number;
And here:
op[0] is op2gpr
op[1] is op2mode
op[2] is op1gpr
op[3] is op1mode
op[4] is opcode
I have a byte array i.e from byte[0] to byte[2]. I want to first split byte[0] into 8 bits. Then bytes[1] and finally bytes[2]. By splitting I mean that if byte[0]=12345678 then i want to split as variable A=8,Variable B=7, variable C=6,Variable D=5,........ Variable H=0. How to split the byte and store the bits into variables? I want to do this in JAVA
well the bitwise operations seem to be almost what you're talking about.
a byte is composed of 8 bits, and so it goes in the rage of 0 to 255.
written in binary that's 00000000 to 11111111.
Bitwise operations are those that basically use masks to get out as much info as possible out of a byte.
Say for instance you have your 1101 0011 byte (space added for visibility only) = 211 (decimal). You can split that into 2 "variables" b1 and b2 of half a byte each. they'll thus cover the range of 0 to 15.
How you do this is by defining some masks. A mask to get your first half-a-byte-value would be 0000 1111.
You take your value of 11010011 apply the bitwise and (& ) operator to it.
So saying byte b = 211; byte mask1=15; OR byte b=0x11010011; byte mask1=0x00001111;
you then have your variable byte b1=b & mask1;
Thus applying that operation would result in b1=00000011 = 3;
With a mask byte mask2=0x11110000; applying the same operation on b, you'd get byte b2=mask2 & b = 0x11010000;
Now of course that leaves the number b2 possibly too large for you. All you have to do if you want to grab the value 0x1101 is to right shift it. Thus b2>>=4;
You can have your masks in any form, but it's usual to have them in decimal as the powers of 2 (so that you can take any bit out of your byte) or decide what range you want on your variables and make the mask "larger" like 0x00000011, or ox00001100. Those 2 masks would respectively get you 2 values from a byte, each value ranging from 0 to 3, values that you can fit 4 inside a byte.
for more info, chek out the relevant wiki.
Sorry, the values were a little off (since byte seems to go from -128 to 127, but the idea is the same.
Second edit (never used bitwise operations myself lol)... the "0x" notation is for hexadecimals. So you'll actually have to calculate for yourself what 01001111 actually means... pretty sucky :| but it's gonna do the trick.
boolean a = (theByte & 0x1) != 0;
boolean b = (theByte & 0x2) != 0;
boolean c = (theByte & 0x4) != 0;
boolean d = (theByte & 0x8) != 0;
boolean e = (theByte & 0x10) != 0;
boolean f = (theByte & 0x20) != 0;
boolean g = (theByte & 0x40) != 0;
boolean h = (theByte & 0x80) != 0;
This question was asked in my interview.
random(0,1) is a function that generates integers 0 and 1 randomly.
Using this function how would you design a function that takes two integers a,b as input and generates random integers including a and b.
I have No idea how to solve this.
We can do this easily by bit logic (E,g, a=4 b=10)
Calculate difference b-a (for given e.g. 6)
Now calculate ceil(log(b-a+1)(Base 2)) i.e. no of bits required to represent all numbers b/w a and b
now call random(0,1) for each bit. (for given example range will be b/w 000 - 111)
do step 3 till the number(say num) is b/w 000 to 110(inclusive) i.e. we need only 7 levels since b-a+1 is 7.So there are 7 possible states a,a+1,a+2,... a+6 which is b.
return num + a.
I hate this kind of interview Question because there are some
answer fulfilling it but the interviewer will be pretty mad if you use them. For example,
Call random,
if you obtain 0, output a
if you obtain 1, output b
A more sophisticate answer, and probably what the interviewer wants is
init(a,b){
c = Max(a,b)
d = log2(c) //so we know how much bits we need to cover both a and b
}
Random(){
int r = 0;
for(int i = 0; i< d; i++)
r = (r<<1)| Random01();
return r;
}
You can generate random strings of 0 and 1 by successively calling the sub function.
So we have randomBit() returning 0 or 1 independently, uniformly at random and we want a function random(a, b) that returns a value in the range [a,b] uniformly at random. Let's actually make that the range [a, b) because half-open ranges are easier to work with and equivalent. In fact, it is easy to see that we can just consider the case where a == 0 (and b > 0), i.e. we just want to generate a random integer in the range [0, b).
Let's start with the simple answer suggested elsewhere. (Forgive me for using c++ syntax, the concept is the same in Java)
int random2n(int n) {
int ret = n ? randomBit() + (random2n(n - 1) << 1) : 0;
}
int random(int b) {
int n = ceil(log2(b)), v;
while ((v = random2n(n)) >= b);
return v;
}
That is-- it is easy to generate a value in the range [0, 2^n) given randomBit(). So to get a value in [0, b), we repeatedly generate something in the range [0, 2^ceil(log2(b))] until we get something in the correct range. It is rather trivial to show that this selects from the range [0, b) uniformly at random.
As stated before, the worst case expected number of calls to randomBit() for this is (1 + 1/2 + 1/4 + ...) ceil(log2(b)) = 2 ceil(log2(b)). Most of those calls are a waste, we really only need log2(n) bits of entropy and so we should try to get as close to that as possible. Even a clever implementation of this that calculates the high bits early and bails out as soon as it exits the wanted range has the same expected number of calls to randomBit() in the worst case.
We can devise a more efficient (in terms of calls to randomBit()) method quite easily. Let's say we want to generate a number in the range [0, b). With a single call to randomBit(), we should be able to approximately cut our target range in half. In fact, if b is even, we can do that. If b is odd, we will have a (very) small chance that we have to "re-roll". Consider the function:
int random(int b) {
if (b < 2) return 0;
int mid = (b + 1) / 2, ret = b;
while (ret == b) {
ret = (randomBit() ? mid : 0) + random(mid);
}
return ret;
}
This function essentially uses each random bit to select between two halves of the wanted range and then recursively generates a value in that half. While the function is fairly simple, the analysis of it is a bit more complex. By induction one can prove that this generates a value in the range [0, b) uniformly at random. Also, it can be shown that, in the worst case, this is expected to require ceil(log2(b)) + 2 calls to randomBit(). When randomBit() is slow, as may be the case for a true random generator, this is expected to waste only a constant number of calls rather than a linear amount as in the first solution.
function randomBetween(int a, int b){
int x = b-a;//assuming a is smaller than b
float rand = random();
return a+Math.ceil(rand*x);
}