I'm trying to reach following sequences of 1 and 0 for a three input system:
000
001
010
...
...
My current code didn't make it :-
for (int i = 0; i < possibleCombinations; i++) {
for (j = 0 ; j < 3; j++) {
if (j < 2 ){
k = j;
}
System.out.print(k + " ");
}
System.out.println();
}
How i can reach above result?
One line:
for (int i = 0; i < 8; i++) {
System.out.println(((i>>2)%2)+""+((i>>1)%2)+""+(i%2));
}
You can generalize this for n-channels of course.
int numChannels=3;
for (int i = 0; i < 2<<numChannels; i++) {
for(int j=numChannels-1; j>=0;j--){
System.out.print((i>>j)%2);
}
System.out.println();
}
Think it about using the periodicity of the occurence of zeroes and ones (first channel has pattern 00001111.., second 0011.., third 01..).
You can use bitmasks for this:
void generateCombinations(int n) {
for(int i = 0; i < (1 << n); i++) {
for(int j = n - 1; j >= 0; j--) {
if((i & (1 << j)) != 0) {
System.out.print(1);
} else {
System.out.print(0);
}
}
System.out.println();
}
}
So for n = 3 you will have 2 ^ n = 8 combinations. That's why the first for is 1 << n, this is the same as 2 ^ n.
For every number you check whether it's bits and print them.
(i & (1 << j)) != 0 - this checks if a bit is 1 or 0 on position j.
We have these situations:
n=2; -> 00,01,10,11
n=3;->000,001,010,011,100,101,110,111.
....
The algorithm is to just enumerate all numbers till 2^n - 1 in binary. For instance , n=2 :
0 in binary will be 00
1 in binary will be 01
2 in binary will be 10
3 in binary will be 11
For converting one integer number to binary string, you should use Integer.toBinaryString method.
Code:
static String print_binary(int n)
{
String binaryString=Integer.toBinaryString(n);
String additional=new String(new char[n-binaryString.length()]).replace("\0", "0");
if(binaryString.length() < n)
binaryString+=additional;
return binaryString;
}
static void Main(String args[]){
int possibleCombinations = 1<<LENGTH, i;
for(i = 0; i< possibleCombinations; i++)
System.out.println(print_binary(i));
}
Related
Update : My question is why do we need BigInteger in Java. Why can't we solve the question directly on the pseudocode as it workis in every other language.
This is the pseudocode for generating subsequences of a Array.
int[] arr = {1,2,3} ;
int opsize = 2^size_of_array ;
for (int counter = 1; counter < opsize; counter++)
{
for (int j = 0; j < n; j++)
{
if (counter & (1<<j))
print(arr[j] + " ");
}
print new line ;
}
It is working for every language except Java. In every other language the output is
1
2
1 2
3
1 3
2 3
1 2 3
In Java, the code is
class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
int[] arr = {1,2,3};
int n = arr.length ; ;
int res = (int) Math.pow(2,n);
for(int i = 1 ; i < res ; i++)
{
for(int j = 0 ; j < n ; j++)
if ((i & (1<<j)) == 1 )
System.out.print(arr[j] + " ");
System.out.println();
}
}
}
In Java, the output for the same code is
1
1
1
1
In Java, we need BigInteger to solve the same question
int opsize = (int)Math.pow(2, n);
for (int counter = 1; counter < opsize; counter++)
{
for (int j = 0; j < n; j++)
{
if (BigInteger.valueOf(counter).testBit(j))
System.out.print(arr[j]+" ");
}
System.out.println();
}
This is the offending line of code:
if ((i & (1<<j)) == 1 )
This is not the same as if (counter & (1<<j)) in C - in C, an integer is equivalent to a "true" condition if its value is not zero.
To correct this, you should write:
if ((i & (1<<j)) != 0)
After that change, the output is what you expected it to be.
EDIT: I read the question a bit wrong.
The code without BigInteger has a problem:
if ((i & (1<<j)) == 1 )
In the bitshift, you shift by j. This is only true if j = 0 and i has the first bit set.
Suppose we have:
i=5
j=2
Then we do the bitshift an have following binary representations:
i = 0101
j = 0100
After AND operation we have:
0100
Which obviously does not satisfy the condition.
If you change it to:
if ((i & (1<<j)) > 0 )
It works, because the answer is > 0 if the specific bit defined by 1 << j is set.
EDIT: Removed the original answer which did not answer the question.
Your condition is bad:
(i & (1<<j)) == 1
It should be
(i & (1<<j)) != 0
An exemple, for i=6=0b0110and j=1=0b0001:
1<<j == 2 == 0b0010
i & (1<<j) == 0b0110 & 0b0010 == 0b0010 == 2
The below code prints all subsets, but I need of size greater than or equal to 2.
public static void printSubsets(char set[])
{
int n = set.length;
for (int i = 0; i < (1<<n); i++)
{
System.out.print("{ ");
for (int j = 0; j < n; j++)
if ((i & (1 << j)) >0 )
System.out.print(set[j] + " ");
System.out.println("}");
}
}
A subset of size 0 corresponds to i == 0. To eliminate the empty subset start at i = 1.
A subset of size 1 corresponds to i having exactly one bit set; or, equivalently, when it is a power of 2. A positive number i is a power of two if (i & (i - 1)) == 0.
for (int i = 1; i < (1<<n); i++) {
if ((i & (i - 1)) == 0) {
continue;
}
System.out.print("{ ");
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
System.out.print(set[j] + " ");
}
}
System.out.println("}");
}
Alternatively, you could keep your original loop and simply insert this check:
if (Integer.bitCount(i) < 2) {
continue;
}
It's not as clever or efficient, but it is nice and readable.
I am trying to create a program insert two possible operations (* and +) in between inputed numbers and keep track of the total. The program simply reads from left to right so therefor do not apply BEDMAS
For instance if I inputed: 1 2 3
The output would be 1 + 2 + 3 -> Sum = 6
Or output would be 1 + 2 * 3 -> Sum = 9
Or output would be 1 * 2 + 3 -> Sum = 5
Etc
I am having difficulty because my program continues to try to numbers.remove() from an empty ArrayList(numbers).
public static void calculate(ArrayList<Integer> numbers, int target){
ArrayList<Integer> temp_array = new ArrayList<Integer>(numbers);
int sum = 0;
int n = (numbers.size() - 1);
System.out.println("This is where we calcutale L");
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
char[] charArray = new char[n];
while(charArrayCount < Math.pow(2,n)){
for (int j = 0; j < chars.length; j++) {
charArray[j] = chars[j] == '0' ? '+' : '*';
}
for(char c : charArray){
int current = numbers.get(0);
if (c == '+'){
sum = sum + current;
}
numbers.remove(0);
System.out.println(sum);
}
numbers = temp_array;
sum = 0;
}
}
}
I am supposed to get this series
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
NOTE:The spaces mentioned have to be present it should have the exact same output as i have mentioned
I tried this:
class pattern_19
{
static void main()
{
int i,j;
int s=1;
System.out.println(s);
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
s=s*11;
}
System.out.println(s);
s=1;
}
}
}
MY OUTPUT:
11
121
1331
14641
161051
1771561
This did not work any help will be appreciated
Your code would not compile because your main method was not defined correctly. This is one thing but not the main reason why you were getting an unexpected output.
Your s variable represent one integer on each line.
What you'll have to do from there is split your int and print each one of the digits seperately.
Here is a correction, I used an enhanced loop and a charArray to print the digits seperately but there are other ways to achieve this of course (using a loop and integer division works also or modify the way you find s).
Solution
public static void main(String[] args) {
int i, j;
int s = 1;
System.out.println(s + " ");
for (i = 1; i <= 6; i++) {
for (j = 1; j <= i; j++) {
s = s * 11;
}
for (char c : String.valueOf(s).toCharArray()) System.out.print(c + " ");
System.out.println();
s = 1;
}
}
PS : Multiplying by 11 wont work when you'll need numbers with a length of 2. I'll edit my answer right now.
Here is the algorithm solution
public static void main(String[] args) {
int rows = 6;
int[][] triangle = new int[rows][rows];
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) {
if (j == 0) triangle[i - 1][j] = 1;
else triangle[i - 1][j] = triangle[i - 2][j - 1] + triangle[i - 2][j];
System.out.print(triangle[i - 1][j] + " ");
}
System.out.println();
}
}
I finally also got an alternative to do the same here it goes
public class PascalTriangle {
public static void main() {
int rows = 6;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Now this one is working properly .
int j = 0;
for (int i = 1; i < 4; i++)
{
if ((columnIndex + i) > 6 || this.isWinningCondition(columnIndex, i, j, colSlot, isRed))
{
break;
}
else
{
pieces++;
}
}
for (int i = -1; i > -4; i--)
{
if ((columnIndex + i) < 0 || this.isWinningCondition(columnIndex, i, j, colSlot, isRed))
{
break;
}
else
{
pieces++;
}
}
Basically, it is apart of a Connect4 program that searches for three in a row on the left and right side of a specific column (in this case, it is searching for horizontal wins), hence the incrementing (for the right side) and the decrementing (for the left side) for loops. Is there a way I can combine these for loops into one, so I don't have to repeat myself?
If your MaxValue ( 4 )is always the same for both for loop, you can always do :
for( int i = 1; i < 4; ++i)
{
//verify i version 1
int i2 = i * -1;
// verify i2 version 2
}
Try the mixed for loop.
for(int i = 0, j = 4; i <= 4 && j >=0; i ++, j --)
{
System.out.println(i + " " + j);
}
Output:
0 4
1 3
2 2
3 1
4 0