I have an integer like:
0x10000010
I would like to know if a particular bit is 1 or 0. For example, something like:
int number = 0x10000010;
for (int i = 0; i < 8; i++) {
if (ith bit == 1) {
System.out.println("bit " + i + " is 1.");
} else {
System.out.println("bit " + i + " is 0.");
}
}
---- output ----
bit 0 is 1
bit 1 is 0
bit 2 is 0
bit 3 is 0
bit 4 is 0
bit 5 is 0
bit 6 is 1
bit 7 is 0
I've forgotten how to do this, and what this type of operation is called,
Thanks
number & (1 << i) will be 0 if the bit wasn't set, non-zero if it was.
Similar to dty's answer
int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++) {
if((number >> i) & 1 != 0)
System.out.println("bit " + i + " is 1.");
else
System.out.println("bit " + i + " is 0.");
}
or
int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++)
System.out.println("bit " + i + " is " + ((number >> i) & 1));
Related
In how many ways, can you pay N dollar with 1 dollar, 2 dollar & 5 dollar denominations, in such a way that
the number of 1 dollar coins are always greater than that of 2 dollar coins and number of 2 dollar coins are always greater than that of 5 dollar coins.
Note: At least one coin should be given from each denomination.
Constraints 1 <= N <= 100
I tried something like this, but am not able to get how to check the constraints
private static void numberOfWays(int number) {
int one = 0, two = 0;
int five = (number - 4) / 5;
if (((number - 5 * five) % 2) == 0)
{
one = 2;
}
else
{
one = 1;
}
two = (number - 5 * five - one) / 2;
System.out.println (one + two + five);
System.out.println (five);
System.out.println (two);
System.out.println (one);}
You could try something like this:
IntStream.rangeClosed(1, 100).forEach(target -> {
final int max1 = (target + 1 - 1) / 1;
final int max2 = (target + 2 - 1) / 2;
final int max5 = (target + 5 - 1) / 5;
IntStream .rangeClosed( 1, max5).forEach(count5 -> {
IntStream .rangeClosed(count5 + 1, max2).forEach(count2 -> {
IntStream.rangeClosed(count2 + 1, max1).forEach(count1 -> {
final int sum = count5*5 + count2*2 + count1*1;
if (sum == target) {
System.out.println("Target.: " + target + " -> " + count5 + "*5$ " + count2 + "*2$ " + count1 + "*1$");
}
});
});
});
System.out.println();
});
...but, as others have pointed out, your constraints make a solution for some amounts impossible.
Here's a variation of this theme, giving a solution for all N...
IntStream.rangeClosed(1, 100).forEach(target -> {
final int max1 = (target + 1 - 1) / 1;
final int max2 = (target + 2 - 1) / 2;
final int max5 = (target + 5 - 1) / 5;
for (int count1= max1; count1 > 0; count1--) {
for (int count2=Math.min(max2, count1 - 1); count2 > 0; count2--) {
for (int count5=Math.min(max5, count2 - 1); count5 > 0; count5--) {
final int sum = count5*5 + count2*2 + count1*1;
if (sum == target) {
System.out.println("Target..............: " + target + " -> " + count5 + "*5$ " + count2 + "*2$ " + count1 + "*1$");
return; // Note.: solution found, exit from Consumer, NOT Method!
}
}
}
}
/*
* Fallback 1: at least one of each denomination...
*/
for (int count1=max1; count1 > 0; count1--) {
for (int count2=max2; count2 > 0; count2--) {
for (int count5=max5; count5 > 0; count5--) {
final int sum = count5*5 + count2*2 + count1*1;
if (sum == target) {
System.out.println("Target (fallback 1).: " + target + " -> " + count5 + "*5$ " + count2 + "*2$ " + count1 + "*1$");
return; // Note.: solution found, exit from Consumer, NOT Method!
}
}
}
}
/*
* Fallback 2: "anything goes"...
*/
for (int count1=max1; count1 >= 0; count1--) {
for (int count2=max2; count2 >= 0; count2--) {
for (int count5=max5; count5 >= 0; count5--) {
final int sum = count5*5 + count2*2 + count1*1;
if (sum == target) {
System.out.println("Target (fallback 2).: " + target + " -> " + count5 + "*5$ " + count2 + "*2$ " + count1 + "*1$");
return; // Note.: solution found, exit from Consumer, NOT Method!
}
}
}
}
System.out.println("Target..............: " + target + " NO Solution possible!");
});
The constraints are interesting.
"At least one coin should be given from each denomination" means that there are no solutions for N < 7.
"The number of 1 dollar coins are always greater than that of 2 dollar coins and number of 2 dollar coins are always greater than that of 5 dollar coins" means that numFives = 1, numTwos = 2, and numOnes = 3 to start, so there are no solutions for N < 12.
This satisfies both constraints.
Knowing that, how do you plan to attack it? Brute force?
It sounds like a variation on the knapsack problem. Maybe you can read about that.
I think simplex method and dynamic programming with constraints is your best bet.
I'm trying non-recursive Merge Sort with 2 Arrays, But it doesn't work when given array's size is not 2^n.
It works fine when the given array's size is 2^n.
For example, given array which's size is not 2^n : 7 2 9 11 4 3 8 6 1 10
As step is 1, sort result is :
2 7 9 11 3 4 6 8 1 10
And now it will sort with 4 items, 4 items, 2 items.
But it doesn't work.
so I checked the console, and it seems like, the problem is
while(leftStart <= leftLast && rightStart <= rightLast).
As I catched, when checking 2 7 9 11 and 3 4 6 8 to sort, the leftStart is going to higher than leftLast, 2 < 7 (leftStart++), 2 < 9 (leftStart++) so leftStart > leftLast, the while loop is broken ).
It should check for the others, because it could be L1.get(leftStart) > L1.get(rightStart)
But I don't know how to solve this problem..
Thank you for your help.
public statid void main(String[] args){
ArrayList<Integer> l = new ArrayList<>();
l.add(7);
l.add(2);
l.add(9);
l.add(11);
l.add(4);
l.add(3);
l.add(8);
l.add(6);
l.add(1);
l.add(10);
sort(l);
}
public static void sort(ArrayList l) {
L1 = null;
L2 = null;
step = 1;
L1 = l;
L2 = new ArrayList<>();
for(int i = 0; i < L1.size(); i++)
L2.add(null);
int tSize = l.size();
while(step <= l.size() ) {
for(int i = 0; i < tSize; i += this.step*2) {
int leftStart = i;
int leftLast = (leftStart + this.step)-1;
if(leftLast >= tSize-1)
continue;
int rightStart = i + this.step;
int rightLast = (rightStart + this.step)-1;
if(rightStart >= tSize)
rightStart = tSize - 1;
int idx = i;
// System.out.println("step : " + step + " || idx : " + idx + " || leftStart : " + leftStart + " || rightStart : " + rightStart);
// System.out.println("step : " + step + " || idx : " + idx + " || leftEnd : " + leftLast + " || rightEnd : " + rightLast);
// System.out.println();
while(leftStart <= leftLast && rightStart <= rightLast) {
System.out.println("leftStart : " + leftStart + " || rightStart : " + rightStart + " || idx : " + idx);
Object a = L1.get(leftStart);
Object b = L1.get(rightStart);
if(comp.compare ( a, b ) < 0 ) {
L2.set(idx++, L1.get(leftStart++));
L2.set(idx, L1.get(rightStart));
}else {
System.out.println("idx :::: " + idx);
L2.set(idx++, L1.get(rightStart++));
L2.set(idx, L1.get(leftStart));
}
}
}
for(int i = 0; i < L1.size(); i++) {
L1.set(i, L2.get(i));
}
System.out.println("============================");
for(int j = 0; j < L1.size(); j++) {
System.out.print(L1.get(j) + " ");
}
System.out.println("\n============================");
step *= 2;
}
}
The result:
1 2 3 4 6 7 8 9 8 10
If an array has an odd number of items, then splitting it will result in one subarray will have one more item than the other.
[2,7,9,11,3,4,6,8,1,10]
/ \
[2,7,9,11,3] [4,6,8,1,10]
/ \ / \
[2,7,9] [11,3] [4,6,8] [1,10]
/ \ / \
[2,7] [9] [4,6] [8]
Both recursive and non-recursive merge sort have the same time complexity of O(nlog(n)).
The iterative version doesn't use recursion to split the array. Rather, it uses nested loops.
How can I invert the last bit in an int?
int a = 11;
System.out.print(a + " " + Integer.toBinaryString(a)) //11 1011
int b = invertLastBit(a);
System.out.print(b + " " + Integer.toBinaryString(b)); //10 1010
I wrote this:
static int invertLastBit(int i)
{
String s = Integer.toBinaryString(i);
if (s.charAt(s.length()-1) == '0'){
s = s.substring(0,s.length() - 1);
s = s+"1";
}else if (s.charAt(s.length()-1) == '1') {
s = s.substring(0, s.length() - 1);
s = s + "0";
}
return Integer.parseInt(s, 2);
}
But how should I rewrite invertLastBit() ?
You can use bitwise XOR :
int x = 5; // 101
x = x ^ 1; // 100
Using your original example :
int a = 11;
System.out.println (a + " " + Integer.toBinaryString(a)); //11 1011
int b = a^1;
System.out.println (b + " " + Integer.toBinaryString(b)); //10 1010
You don't even have to worry about converting to binary.
If the number if odd, the last bit has to be one, thus, subtract 1 from the number.
Otherwise, if the number is even, the last bit has to be 0, add 1 to the number.
That's all.
static int invertLastBit(int i){
if(i % 2 != 0) { //thanks harold
return i - 1;
} else {
return i + 1;
}
}
It is not difficult to reason about why this works.
I am writing a Sudoku solver in java and wonder how to assign the value in a string to a 2d array by using charAt or something else?
for example, this is the printboard looks like:
1 2 3 4 5 6 7 8 9
+-----------+-----------+-----------+
A | 0 0 0 | 0 0 5 | 0 9 0 |
B | 1 4 0 | 0 0 0 | 6 7 0 |
C | 0 8 0 | 0 0 2 | 4 5 1 |
+-----------+-----------+-----------+
D | 0 6 3 | 0 7 0 | 0 1 0 |
E | 9 0 0 | 0 0 0 | 0 0 3 |
F | 0 1 0 | 0 9 0 | 5 2 0 |
+-----------+-----------+-----------+
G | 0 0 7 | 2 0 0 | 0 8 0 |
H | 0 2 6 | 0 0 0 | 0 3 5 |
I | 0 0 0 | 4 0 9 | 0 6 0 |
+-----------+-----------+-----------+
and this is the way I am using to assign values to the printboard so far:
public void printBoard() {
System.out.print(" ");
for (int j = 0; j < 3; j++)
System.out.print(" " + (j+1));
System.out.print(" ");
for (int j = 3; j < 6; j++)
System.out.print(" " + (j+1));
System.out.print(" ");
for (int j = 6; j < 9; j++)
System.out.print(" " + (j+1));
System.out.print(" ");
System.out.println();
System.out.print(" +-----------+-----------+-----------+\n");
char row_letter = 'A';
for (int i = 0; i < 3; i++) {
System.out.print(row_letter + " |");
row_letter++;
System.out.print(" " + board[i][0] +
" " + board[i][1] +
" " + board[i][2] + " |" +
" " + board[i][3] +
" " + board[i][4] +
" " + board[i][5] + " |" +
" " + board[i][6] +
" " + board[i][7] +
" " + board[i][8] + " |");
System.out.println("");
}
System.out.print(" +-----------+-----------+-----------+\n");
for (int i = 3; i < 6; i++) {
System.out.print(row_letter + " |");
row_letter++;
System.out.print(" " + board[i][0] +
" " + board[i][1] +
" " + board[i][2] + " |" +
" " + board[i][3] +
" " + board[i][4] +
" " + board[i][5] + " |" +
" " + board[i][6] +
" " + board[i][7] +
" " + board[i][8] + " |");
System.out.println("");
}
System.out.print(" +-----------+-----------+-----------+\n");
for (int i = 6; i < 9; i++) {
System.out.print(row_letter + " |");
row_letter++;
System.out.print(" " + board[i][0] +
" " + board[i][1] +
" " + board[i][2] + " |" +
" " + board[i][3] +
" " + board[i][4] +
" " + board[i][5] + " |" +
" " + board[i][6] +
" " + board[i][7] +
" " + board[i][8] + " |");
System.out.println("");
}
System.out.print(" +-----------+-----------+-----------+\n");
}
public static void main(String[] args) {
int[][] board = new int[9][9];
board[0][3] = 1;
board[0][5] = 5;
board[1][0] = 1;
board[1][1] = 4;
board[1][6] = 6;
board[1][7] = 7;
board[2][1] = 8;
board[2][5] = 2;
board[2][6] = 4;
board[3][1] = 6;
board[3][2] = 3;
board[3][4] = 7;
board[3][7] = 1;
board[4][0] = 9;
board[4][8] = 3;
board[5][1] = 1;
board[5][4] = 9;
board[5][6] = 5;
board[5][7] = 2;
board[6][2] = 7;
board[6][3] = 2;
board[6][7] = 8;
board[7][1] = 2;
board[7][2] = 6;
board[7][7] = 3;
board[7][8] = 5;
board[8][3] = 4;
board[8][5] = 9;
I want to know how can I use a 81 digit string like:"000005090140000670080002451063070010900000003007200080026000035000409060"
to assign values to printboard in certain position, 0 represents unsolved.
To strictly answer the question, the formula
81 / 9 * row + col
will give you the character position in the string that represents the board position that you want, as long as you use zero indexed rows and columns.
So something like
public String GetBoardValue(int row, int col)
{
return boardString.CharAt(81 / 9 * row + col);
}
Be careful though, code like this is very fragile and prone to break. The numbers 81 and 9 used here only work when the string is exactly 81 characters long. 'Magic numbers' in programming are bad.
As markus has mentioned you need to think about what you are trying to achieve here. A pure string representation of the board in this manner has no intrinsic value or meaning. At least the 2D array is a data representation that more closely matches the Sudoku game board. However creating your own object to encapsulate the board data and provide accessors specific to the Sudoku board would be a much better way to go. It would give the data meaning and be much easier to work with. The goal of programming is to write code that makes sense so that someone else reading your code understands it and can work with it. Because in many cases that person will be you a couple of months down the track when you haven't looked at this code for a while. If it takes you time to read the code just to understand what you meant, then there are better ways to write it.
I'm trying to read the output of this code, but it simply just doesn't make sense to me.
Even after learning that a loop without braces only loops through the first line, the output still makes no sense, at all. Some numbers do, but others just don't.
My code:
int n = 8;
int i = 1;
int j = 1;
j = n + 2;
System.out.println (n + " " + i + " " + j );
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
System.out.println (n + " " + i + " " + j );
And it outputs:
8 1 10
4 2 10
4 4 10
2 2 11
1 2 13
I get the 8-1-10
and the 4-2-10
but anything after that, I'm stumped, I don't get how the computer calculates the rest.
Would someone mind going through the rest of the output with me, step by step?
Thank's in advance.
No braces means that the loop affects only the next statement that follows the loop.
So
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
is equivalent to
for (i = 2; i <= n; i = i+2)
{
System.out.println (n + " " + i + " " + j );
}
Usually, indentation is used in those cases to make the code more comprehensible, like this:
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
EDIT: Now, this is the actual answer to the question. It all depends on the different iterations the loop does and how do the variables get incremented.
int n = 8;
int i = 1;
int j = 1;
j = n + 2; //This means that j takes the value 10.
System.out.println (n + " " + i + " " + j ); // 8 1 10 So far, so good.
Now, on with the iteration:
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
For the first iteration, we have n=8 i=1 j=10, so since n > 0 is true the loop takes place.
n = n / 2; //n = 4
Then, the for (note that it just assigns the value 2 to i):
for (i = 2; i <= 4; i = i+2) //Since n = 4
Since n = 4, the only values that i can take are 2 and 4, then the prints are:
4 2 10
4 4 10
After that, j is incremented by one, making it j = 11. The condition for the while is met again because n = 4. n = n/2 makes n take the value 2, so it enters the while again. Let's take a look at the for again:
for (i = 2; i <= 2; i = i+2) //Since n = 2
This time, the only value that i can take is 2 (note that the value of i is reset again to 2 while starting the iteration), and that's the print you get.
2 2 11
Before iterating again, j++ makes j have the value 12.
On the final iteration, n = n/2 results in n = 1 since n is an int but this is done inside the while, so it enters again. Now that n = 1 the loop looks like this:
for (i = 2; i <= 1; i = i+2) //Since n = 1
i is set to 2 and the condition for the for is not met (2 <= 1 is false). Then there is no print this time, yet j is incremented to 13 at the end of the while.
In the next iteration you have n = 1, that means that the while's condition is not met so the iteration breaks. Finally you have n = 1, i = 2 and j = 13. That's the last print you get.
You start the while loop with n = 8, i = 1 and j = 10.
start while: (n=8 > 1) is true
n = 4
i = 2 (i <= 4, so do for loop, then change i to i+2=4)
print 4,2,10
i = 4 (i <= 4, so do for loop again, then i = i+2 = 6
print 4,4,10
i = 6 (i <= 4 is false, so exit for)
j++ so j becomes 11
next while:
n = n/2 = 2
i = 2 (i <= 2, so do for loop, then change i to i+2=4)
print 2,2,11
i = 4 (i <= 2 is false, so exit for)
j++ -> j = 12
next while:
n = n/2 = 1
i = 2 (i <= 1 is false, so exit loop)
j++ -> j = 13
exit while.
Final print= n = 1, i = 2 (value assigned in last for loop, loop doesn't get executed so i doesnt get incremented by 2), and j = 13
Hope this helps :)