int OR operation - java

Can someone explain why the following program printing output as 7
public class Test{
public static void main(String []args){
int i =1;
int j =2;
int k= 5;
System.out.println(i|j|k);
}
}
I would like to know how the OR operation happens in java int.

That is the bitwise-OR operator in Java. Last 8 bits for simplicity:
1 = 00000001
2 = 00000010
5 = 00000101
============
7 = 00000111 // 1 where the corresponding bit is set in any of the above numbers

These values have the bit values:
1 -> 0001
2 -> 0010
5 -> 0101
when you bitwise-OR them yogether you get:
0111
which is 7

Related

How can I print the number of combination and not the actual combination? Java

I'd like to print the number of combination and not the actual combination of bits. How can I code that? I'm looking forward for some solution. Thank you!
The Task:
Write a program that accepts a number. This number corresponds to the number of bits to be taken into account. The program should then display on the screen how many binary combinations there are that do not consist of two adjacent 1s. For example, given a 3-bit number, there are 5 out of 8 possible combinations.
import java.util.Scanner;
public class BinaryS {
public static String toString(char[] a) {
String string = new String(a);
return string;
}
static void generate(int k, char[] ch, int n) {
if (n == k) {
for (int i = 0; i < ch.length; i++) {}
System.out.print(toString(ch) + " ");
return;
}
// If the first Character is
//Zero then adding**
if (ch[n - 1] == '0') {
ch[n] = '0';
generate(k, ch, n + 1);
ch[n] = '1';
generate(k, ch, n + 1);
}
// If the Character is One
// then add Zero to next**
if (ch[n - 1] == '1') {
ch[n] = '0';
// Calling Recursively for the
// next value of Array
generate(k, ch, n + 1);
}
}
static void fun(int k) {
if (k <= 0) {
return;
}
char[] ch = new char[k];
// Initializing first character to Zero
ch[0] = '0';
// Generating Strings starting with Zero--
generate(k, ch, 1);
// Initialized first Character to one--
ch[0] = '1';
generate(k, ch, 1);
}
public static void main(String args[]) {
System.out.print("Number: ");
Scanner scanner = new Scanner(System.in);
int k = scanner.nextInt();
//Calling function fun with argument k
fun(k);
}
}
The program actually works fine , my only problem is I would like to print the number of combinations and not the actual combination. For example for the input 3 we get 000 001 010 100 101 which is 5.
Unfortunately, your code has some problems. For one you have an empty forloop in the generate method. However, I can help you get the count by doing it a different way and printing the results. Forgetting about the loop that goes from 2 to 20, here is what is going on. And this may not be most efficient way of finding the matches but for short runs it exposes the counts as a recognizable pattern (which could also be determined by mathematical analysis).
first, create an IntPredicate that checks for adjacent one bits by masking the lower order two bits.
Generate an IntStream from 0 to 2n where n is the number of bits.
then using aforementioned predicate with a filter count every value that does not contain two adjacent 1 bits.
IntPredicate NoAdjacentOneBits = (n)-> {
while (n > 0) {
if ((n & 3) == 3) {
return false;
}
n>>=1;
}
return true;
};
for (int n = 1; n <= 20; n++) {
long count = IntStream.range(0, (int) Math.pow(2, n))
.filter(NoAdjacentOneBits).count();
System.out.println("For n = " + n + " -> " + count);
}
prints (with annotated comments on first three lines)
For n = 1 -> 2 // not printed but would be 0 and 1
For n = 2 -> 3 // 00, 01, 10
For n = 3 -> 5 // 000, 001, 010, 100, 101
For n = 4 -> 8
For n = 5 -> 13
For n = 6 -> 21
For n = 7 -> 34
For n = 8 -> 55
For n = 9 -> 89
For n = 10 -> 144
For n = 11 -> 233
For n = 12 -> 377
For n = 13 -> 610
For n = 14 -> 987
For n = 15 -> 1597
For n = 16 -> 2584
For n = 17 -> 4181
For n = 18 -> 6765
For n = 19 -> 10946
For n = 20 -> 17711
The counts are directly related to the nth term of the Fibonacci Series that starts with 2 3 5 8 . . .
So you really don't even need to inspect the values for adjacent bits. Just compute the related term of the series.

Pack 3 ints into short

I am trying to pack 3 ints into short and then get the values back; I am using a test code with the following values:
160, 71, 50
But when I try to unpack the values, ​​x & z are wrong, I get 15, 71, 50 (please, note 15 when 160 is expected).
Why is this? thanks. My code is
public static void main(String[] args) {
int[] testValue = new int[]{160, 71, 50};
short packed = pack(testValue[0], testValue[1], testValue[2]);
int[] output = unpack(packed);
System.out.println(output[0]);
System.out.println(output[1]);
System.out.println(output[2]);
}
public static short pack(int x, int y, int z) {
return (short) (x << 12 | z << 8 | y);
}
public static int[] unpack(short packed) {
int x = packed >> 12 & 0xF;
int y = packed & 0xFF;
int z = packed >> 8 & 0xF;
return new int[]{x, y, z};
}
Well, it's impossible; let's see why. We have 3 values to pack 160, 71, 50:
160 == 10100000 (binary), 8 bits long
71 == 1000111 (binary), 7 bits long
50 == 110010 (binary), 6 bits long
Please, note, that
160 is 8 bits long
71 is 7 bits long
50 is 6 bits long
------------------
21 bits for all 3 numbers
we need at least 21 bits (8 + 7 + 6) to store all three numbers when char as well as short is 16 bit value only.
You don't have enough bits in a 16 bit short to pack those three values.
Here is a breakdown of your bits:
160 << 12 = 0x0AA000
50 << 8 = 0x003200
71 << 0 = 0x000047
ORing these together results in:
0xA3247
Which can be stored in 3 bytes not two.
When casting to a short you end up with
0x3247
You could fit three values in the short if you could store each number in 5 bits individually.
Each number ranging from 0 - 31 for unsigned values. With only one value being able to take up 6 bits. This would yield 5 + 5 + 6 = 16 bits.

Folding paper strip and generate numbers while unfolding

I have an assignment question that I am struggling with and need some direction to solve.
Suppose i have a strip of paper and i fold it from the center such that the left half goes behind the right half. Then i number the folded peices in sequence i get the numbers when i unfold as follows.
1 : 2
If i fold twice i get the numbers when unfolded as follows
1 : 4 : 3 : 2
if I fold thrice i get as follows
1 8 5 4 3 6 7 2
I want to generate the array of numbers when I fold it n times. so if i fold it for example 25 times i will get 2^25 numbers in similar sequence.
These are the observations i made
the first and last numbers are always 1 and 2.
the middle two numbers are always 4 and 3
the number at index 1 is largest number and number at second last location is second largest number.
It looks like a preorder traversal of binary search tree but I dont know how that helps.
I tried to construct binary tree from the preorder and then convert it to inorder assuming that I can reverse this process to get the same series and I was wrong about it.
EDIT : For searching an element in this generated array I can do a sequential search which will be O(n) efficient. But I realise there has to be a much faster way to search for a number in this series.
I cannot do binary search because this is not sorted and there are over a billion numbers when 25+ foldings are done.
What kind of search tactics can i use to find a number and its index?
This was one of the reasons I wanted to convert it into a binary search tree which will have log(n) search efficiency.
EDIT 2: I tried the table folding algorithm as suggested by one of the answers and it is not memory efficient. I cannot store over a billion numbers in my memory so there has to be a way to find a numbers index without actually creating the array of numbers.
1st fold: 1 2
2nd fold: 1 4 3 2
3rd fold: 1 8 5 4 3 6 7 2
4th fold: 1 16 9 8 5 12 13 4 3 14 11 6 7 10 15 2
Generate table (with example to 4th fold)
Imagine you have a nth fold paper and then unfold it.
Generate a table with size ( column = 1, row = 2^n ) and fill the column from down to up with values in ascending order
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
Resize the table to size (column = org. column*2, row = org. row / 2) recursively by sticking top x row to bottom x row from back to front
8 9
7 10
6 11
5 12
4 13
3 14
2 15
1 16
4 13 12 5
3 14 11 6
2 15 10 7
1 16 9 8
2 15 10 7 6 11 14 3
1 16 9 8 5 12 13 4
1 16 9 8 5 12 13 4 3 14 11 6 7 10 15 2
Read the final 1 row table from front to end as result
1 16 9 8 5 12 13 4 3 14 11 6 7 10 15 2
The remaining work to you is to prove this work and then code it (I only test up to n=4 because I am lazy)
You can calculate the number of a fold without having to calculate the whole sequence by using bit-reversal (which reverses the binary representation of a number, so that e.g. 0001 becomes 1000).
These are the sequences you get with bit reversal:
1 bit: 0 1
2 bits: 0 2 1 3
3 bits: 0 4 2 6 1 5 3 7
4 bits: 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15
And these are the paper-folding sequences (counting from 0):
1 fold: 0 1
2 folds: 0 3 2 1
3 folds: 0 7 4 3 2 5 6 1
4 folds: 0 15 8 7 4 11 12 3 2 13 10 5 6 9 14 1
If you split the paper-folding sequences into even and odd numbers, you get:
0
1
0 2
3 1
0 4 2 6
7 3 5 1
0 8 4 12 2 10 6 14
15 7 11 3 13 5 9 1
You'll see that the paper-folding sequences are the same as the bit-reversal sequences, but with the first half (even numbers) interlaced with the reverse of the second half (odd numbers).
You'll also notice that each pair of adjacent even/odd numbers adds up to 2n-1 (where n is the number of folds), which means they are each other's inverse, and you can calculate one from the other using a bit-wise NOT.
So, to get the paper-folding number of fold x (counting from 0) of a strip folded n times:
divide x by 2, perform bitwise NOT if x was odd, then bit-reverse (using n digits)
Example (folding 4 times):
fold x/2 binary inverted bit-reversed from 1
0 0 0000 0000 0 1
1 0 0000 1111 1111 15 16
2 1 0001 1000 8 9
3 1 0001 1110 0111 7 8
4 2 0010 0100 4 5
5 2 0010 1101 1011 11 12
6 3 0011 1100 12 13
7 3 0011 1100 0011 3 4
8 4 0100 0010 2 3
9 4 0100 1011 1101 13 14
10 5 0101 1010 10 11
11 5 0101 1010 0101 5 6
12 6 0110 0110 6 7
13 6 0110 1001 1001 9 10
14 7 0111 1110 14 15
15 7 0111 1000 0001 1 2
Example: billionth fold: (folding 30 times)
fold: 1,000,000,000
counting from 0: 999,999,999 (x is odd)
x/2: 499,999,999
binary: 011101110011010110010011111111 (30 digits)
bitwise NOT: 100010001100101001101100000000 (because x was odd)
bit-reversed: 000000001101100101001100010001
decimal: 3,560,209
counting from 1: 3,560,210
I don't speak Java, but something like this should do the trick:
public static long foldIndex(int n, long x) { // counting from zero
return Long.reverse((x & 1) == 0 ? x >>> 1 : ~(x >>> 1)) >>> (Long.SIZE - n);
}
Here'a an algorithm to find what index a number will be at after the
unfolding.
It keeps track of the coordinates of where your search number is moving to based on the folds. For example, if you are interested in 3 folds (n=3, numFolds) and you want to know where the number 7 will be (searchNumber), the algorithm runs as follows:
Initial State:
8
7
6
5
4
3
2
1
The 7 is at [1,7] - column 1, row 7
Now, when we fold the top half down:
4 5
3 6
2 7
1 8
The 7 is at [2, 1] - column 2, row 2
When we do the next fold the 7 does not move (hence the if (row > half) logic)
2 7 6 3
1 8 5 4
On the last fold:
1 8 5 4 3 6 7 2
The 7 is at [7, 1] - column 7, row 1 and the code will return 7.
public static long getIndexOfAfterFold (long numFolds, long searchNumber)
{
long total = (long) Math.pow(2, numFolds);
long [] coordsOfSearchNumber = new long [] {1, searchNumber};
int iterations = 0;
while (iterations < numFolds)
{
long half = total / 2;
long row = coordsOfSearchNumber[1];
// we are folding down
if (row > half)
{
long newRow = (total - row) + 1;
long col = coordsOfSearchNumber[0];
long newFoldThickness = (long) Math.pow(2, iterations + 1);
long newCol = newFoldThickness - (col - 1);
coordsOfSearchNumber[0] = newCol;
coordsOfSearchNumber[1] = newRow;
}
total = total / 2;
iterations++;
}
return coordsOfSearchNumber[0];
}
EDIT: Converted the above code to use long instead on int.
Notes:
It runs in O(n) time where n is the number of folds.
Usage: System.out.println(getIndexOfAfterFold(4, 13));
This code will give the list of all numbers after the folding
Note: This is based on the answer supplied by #hk6279 (the table folding algorithm)
public static void unFold (int numFolds)
{
int total = (int) Math.pow(2, numFolds);
List<ArrayList<Integer>> table = new ArrayList<ArrayList<Integer>> (total);
// populate the single column table
for (int i = 0; i < total; i++)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i + 1);
table.add(list);
}
int iterations = 0;
while (iterations < numFolds)
{
int half = table.size() / 2;
// place the fold back on itself
for (int i = 0; i < half; i++)
{
ArrayList<Integer> list = table.get(i);
ArrayList<Integer> foldList = table.get(table.size() - (i + 1));
// reverse the fold
Collections.reverse(foldList);
// add the fold to front
list.addAll(foldList);
}
// remove the part we folded
table.subList(half, table.size()).clear();
iterations++;
}
System.out.println(table);
}
This is what n=5 looks like:
1, 32, 17, 16, 9, 24, 25, 8, 5, 28, 21, 12, 13, 20, 29, 4, 3, 30, 19, 14, 11, 22, 27, 6, 7, 26, 23, 10, 15, 18, 31, 2
I don't know Java, but this should be easy to port and works for arbitrary numbers of folds. Idea's about the same as m69's, so I won't explain the logic myself.
#include <iostream>
size_t reverse(size_t n, int bits)
{
size_t result = 0;
size_t msb_value = 1 << (bits - 1);
while (n)
{
if (n & 1) result |= msb_value;
msb_value >>= 1;
n >>= 1;
}
return result;
}
struct Fold_Sequence
{
Fold_Sequence(size_t folds) : folds_(folds), max_(1 << folds) { }
size_t operator[](size_t i) const
{
size_t x = reverse((i / 2) % max_, folds_);
return i & 1 ? (max_ - x - 1) : x;
}
size_t folds_, max_, i = 0;
};
int main()
{
const size_t folds = 4;
const unsigned num_parts = 1 << folds;
Fold_Sequence seq{folds};
for (unsigned j = 0; j < num_parts; ++j)
std::cout << seq[j] + 1 << '\n';
}
I liked the elegance of hk6279's solution too, so I implemented it (also in C++, and I was too lazy to use a multidimensional array/vector<vector<>> and have to resize things carefully all the time, so it's inefficiently implemented using a map keyed on x,y coordinates):
#include <iostream>
#include <map>
#define DBG(X) do { std::cout << X << '\n'; } while (false)
typedef std::pair<size_t, size_t> Coord;
struct matrix : std::map<Coord, size_t>
{
matrix(size_t n)
: y_size_(n)
{
for (size_t i = 0; i < n; ++i)
(*this)[{0, i}] = i; // bottom left is 0,0; 0,1 is above
}
void fold()
{
size_t x_size_ = x_size();
for (size_t y = y_size_ / 2; y < y_size_; ++y)
for (size_t x = 0; x < x_size_; ++x)
move(x, y, x_size_ * 2 - x - 1, y_size_ - y - 1);
y_size_ /= 2;
}
void move(size_t from_x, size_t from_y, size_t to_x, size_t to_y)
{
DBG("move(" << from_x << ',' << from_y << " -> " << to_x << ',' << to_y
<< ") value " << ((*this)[{from_x, from_y}]));
(*this)[{to_x, to_y}] = (*this)[{from_x, from_y}];
erase({from_x, from_y});
}
size_t operator()(size_t x, size_t y) const
{
auto it = find({x, y});
if (it != end()) return it->second;
std::cerr << "m(" << x << ',' << y << ") doesn't exist\n";
exit(1);
}
size_t x_size() const { return size() / y_size_; }
size_t y_size() const { return y_size_; }
size_t y_size_;
};
std::ostream& operator<<(std::ostream& os, const matrix& m)
{
for (size_t y = m.y_size_ - 1; y <= m.y_size_; --y)
{
for (size_t x = 0; x < m.x_size(); ++x)
os << m(x, y) << ' ';
os << '\n';
}
return os;
}
int main()
{
const size_t n = 4;
matrix m(1 << n);
for (int i = 0; i < n; ++i)
{
m.fold();
std::cout << i+1 << " folds ==> " << m.x_size() << 'x' << m.y_size()
<< " matrix:\n" << m << '\n';
}
}

Can someone please explain this bitwise program to me?

public class UpCase {
public static void main(String[] args) {
int t;
byte val;
val = 123;
for (t = 128; t > 0; t = t / 2) {
System.out.println(t);
if ((val & t) != 0) System.out.println(" 1");
else System.out.println(" 0");
}
}
}
In particular, I am not sure why we are using val=123? I understand that this program will print out 123 in binary but why is that the case? How does this work? I do understand however, the principles of the & operator and how you can turn on and off bits but I am not sure how it works in this particular example?
This program will print out the binary digits of the number in val from MSB to LSB by comparing it to each power of 2:
123 : 01111011 &
128 : 10000000 =
00000000
00000000 != 0 => false, print 0
123 : 01111011 &
64 : 01000000 =
01000000
01000000 != 0 => true, print 1
123 : 01111011 &
32 : 00100000 =
00100000
00100000 != 0 => true, print 1
// repeat for 2^4-2^1...
123 : 01111011 &
1 : 00000001 =
00000001
00000001 != 0 => true, print 1
Very simple:
It just checks if the value (123 in this case) using the bitwise operator &. The result of that is 1 or 0, this process is repeated for the following value 0.5t etc until t=0, resulting in the binary string for this value 123.

Unexpected output for int type

Learning JAVA, i was trying to test the upper limit of while loop which goes on incrementing an int.Please see the program below :
public class Test {
public static int a(){
int a = 10;
while(a > 9 )
++a;
return a;
}
public static void main(String[] argc) {
Test t = new Test();
int k = t.a();
System.out.println("k = "+(1 * k));
}
}
I am aware that 32 bits range is from -2,147,483,648 to 2,147,483,647, so on the basis of that, i was expecting output as 2,147,483,647 but instead i am getting :
k = -2147483648
I even tried
System.out.println("k = "+(1 * k/2));
but still output is :
k = -1073741824
Question :
Why is solution negative when it should be positive?
You are incrementing your a int by 1 until it reaches 1 + Integer.MAX_VALUE, which shifts its value to -2147483648 == Integer.MIN_VALUE.
Here's your loop commented:
// "infinite" loop as a is assigned value 10
while(a > 9)
// when a reaches Integer.MAX_VALUE, it is still incremented by 1
++a;
// loop condition now false, as value for a has shifted to -2147483648
return a;
What is happening is called integer overflow.
Maximum 32-bit integer value in binary is:
0111 1111 1111 1111 1111 1111 1111 1111
When you add 1 to this number you get:
1000 0000 0000 0000 0000 0000 0000 0000
This is the twos compliment, or -2,147,483,648. Since any negative number is less than 9, the while loop exits.
You increment the value until it reaches the positive limit and it becomes all bits but the sign bit becomes 1.
0x7FFFFFFF = 01111111 11111111 11111111 11111111
This is binary representation of 2147483647, which is INT_MAX. When you increment it by one once again, it becomes
0x80000000 = 10000000 00000000 00000000 00000000
which is equal to INT_MIN, -2147483648.
Now,
2147483647 is greater than 9 so your loop continues. One more increment and oops, suddenly it is -2147483648 which is smaller than 9. This is the point where your loop condition fails.
If we look at Oracle docs on int values We can find out that:
The operators that work on the int primitive value do not indicate overflow or underflow
The results are specified by the language and independent of the JVM version as folows:
Integer.MAX_VALUE + 1 is the same as Integer.MIN_VALUE
Integer.MIN_VALUE - 1 is the same as Integer.MAX_VALUE

Categories