what I am trying to put all possible 256 binary bit sequences into a string array. In order to do that, I have created 8 for loops to have all the possible cases. Here's what I've tried so far.
static String[] BitSequences() {
int[] result = new int[256];
for (int a = 0; a < 256; a++) {
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
result[a] = ; //this part is a problem
}
}
}
}
}
}
}
}
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
This method is supposed to return a string array that contains all the possible cases. However, I don't know how to insert these value by making for-loops using int values. It is easy to print it out:
'
System.out.println(i+j+k+.....+p)
'
any help would be appreciated!
Consider using the built in conversion method for binary strings:
static String[] BitSequences() {
String[] result = new String[256];
for (int a = 0; a < 256; a++) {
result[a] = Integer.toBinaryString(a);
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
An 8-bit, two's complement integer ranges from -128 to 127. To represent that range, we can use IntStream#rangeClosed.
From this answer, we can utilize BigInteger to left-pad the binary String (generated by Integer#toBinaryString) with 0s if its length is less than 8 (denoting that the value is positive).
Otherwise, the value represents a negative number, and its respective binary string will have a length greater than 8, which must be truncated to 8 characters using String#substring.
Finally, the Stream<String> can be collected to a String[] using Stream#toArray.
public static String[] generateBitSequences() {
return IntStream.rangeClosed(-128, 127)
.mapToObj(Integer::toBinaryString)
.map(BigInteger::new)
.map(b -> String.format("%08d", b)) // Left pad positive values with 0s.
.map(s -> s.substring(s.length() - 8)) // Remove leading 1s from negative values.
.toArray(String[]::new);
}
Output:
[10000000, 10000001, ..., 01111110, 01111111]
Related
I'm using an one-dimensional byte array to store blob data on an sqlite database.
I'm looking for a fast and clean way of converting two-dimensional boolean arrays (boolean [][]) to one-dimensional byte arrays (byte[]) and then back.
I can use any external libraries and temporary arrays.
The only idea I've had is to encode the 2D array into a 1D string array as outer array indexes separated from the value by a dash or other unique sign, then converted into bytes (as that would eliminate the dimensional incompatibility), but that does not seem optimal.
Are there any good, clean ways of doing this operation?
Thanks in advance.
It seems that you need some kind of coding/decoding declaration in your code. So if I were you I would make something like this.
Given:
N-dimensional array [i] [j] [k] ... [n];
Binary number with the length equals to the number of dimensions (N);
Imagine having the 2D array:
1 2
1 [true] [true]
2 [false] [false]
One dimension could be coded from left to right or from right to left. For instance I'll take right to left.
The result array should be like
[0b01] [0b01]
The code:
class Encoder {
private static final byte START_MASK = 0b01;
public byte[] code(boolean[][] arr) {
int length = arr.length;
byte[] result = new byte[length];
for (int i = 0; i < length; i++) {
byte mask = START_MASK;
for (int j = 0; j < length; j++) {
result[i] = (byte) (result[i] | (arr[j][i] ? mask : 0));
mask = (byte) (mask << 2);
}
}
return result;
}
public boolean[][] decode(byte[] arr) {
int length = arr.length;
boolean[][] result = new boolean[length][length];
for (int i = 0; i < length; i++) {
byte mask = START_MASK;
for (int j = 0; j < length; j++) {
result[j][i] = (mask & arr[i]) == mask;
mask = (byte) (mask << 2);
}
}
return result;
}
}
After some thinking I discovered that it is simpler to encode to string instead of trying to encode to bytes. This is supported by SQLite and thus achieves my goal. Here's the code i used to do it. It also supports varying sizes of sub-arrays. I'm not certain about exceeding maximum string length though.
public static String Bool2DToString(boolean[][] arr){
String result = "";
for(int i = 0; i < arr.length; i++){
if(i > 0){result += ":";}
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j]){
result += "1";
} else {
result += "0";
}
}
}
return result;
}
public static boolean[][] StringToBool2D(String str){
String[] splitstr = str.split(":");
boolean[][] result = new boolean[splitstr.length][splitstr[0].length()];
for(int i = 0; i < splitstr.length; i++){
char[] a = splitstr[i].toCharArray();
for(int j = 0; j < a.length; j++){
if(a[j] == '1'){
result[i][j] = true;
} else {
result[i][j] = false;
}
}
}
return result;
}
I wanted to multiply the number based on its String length.
For example
String s = "153";
So, here the length of the above string is 3. So i wanted to multiply each number in the string 3 times (which is the actual length of the string)
Something like below
Here the length is 3
Something like this 1*1*1+5*5*5+3*3*3
Can anyone please help me in that?
This is what I have tried:
int number = 153;
String originalNumber = number+"";
char[] ch = originalNumber.toCharArray();
int length = originalNumber.length();
for (int i = 0; i < ch.length; i++) {
char c = ch[i];
for (int j = 0; j < ch.length; j++) {
// I'm stuck here
}
}
So you have to take each digit and take it to the power of the length of your string, then add all those results up.
You could do the following:
String s = "153";
int result = 0;
for (char n : s.toCharArray())
if (Character.isDigit(n))
result += Math.pow(Character.getNumericValue(n), s.length());
System.out.println(result);
It prints:
153
I added a safety check to see if the char is actually a digit (if (Character.isDigit(n))).
Classic solution : You need to turn each char, in an int then use use power to the length and sum all :
int res = 0;
for (int i = 0; i < ch.length; i++) {
int newNb = (int) Math.pow(Character.digit(ch[i], 10), ch.length);
res += newNb;
}
for-each loop solution
for (char c : ch) {
int newNb = (int) Math.pow(c - '0', ch.length);
res += newNb;
}
To turn a char c to its corresponding int value you can do :
int a = Character.getNumericValue(c);
int a = Character.digit(c, 10);
int a = c - '0';
You could simply iterate over each digit of the given string and calculate it's power. It is better to use str.charAt(i) instead of str.toCharArray() to not create additional char[].
public static int multiplyNumberLength(String str) {
int res = 0;
for (int i = 0; i < str.length(); i++)
if (Character.isDigit(str.charAt(i)))
res += Math.pow(str.charAt(i) - '0', str.length());
return res;
}
To turn a character back into a digit:
char c = ch[i];
int digit = c - '0';
int product = 1;
then for your inner loop multiply the digit into the product.
I have the following two-dimensional int array:
int[][] array = new int[128][128];
This two-dimensional array contains only zeros and ones. I want to read each line and make a byte[] (byte array) out of its contents. For instance, let's say that the first line is: 0101111000111...101, consisting of 128 numbers. I want this line to be a byte[] of 128 bits (which means 16 bytes).
What's the most efficient way to transform each line into a byte array? Bear in mind that maintaining the size is important. Since each lines consists of 128 "bits" the byte array should have a size of 16 bytes (128/8).
One way I've thought on how to do this is to make each line into a BigInteger and then convert it into byte array but unfortunately I can't produce the proper results. I've also tried some of the other options available to StackOverflow to no avail. For instance this solution produces an output of 512 and I don't understand why.
For the above reason I don't consider this post a duplicate since the various asks and answers don't take in mind the size of the byte array and its correlation to the int array.
Here's code for a 1D array. You just repeatedly do that for the outer array of a 2D array.
int[] bits = {0,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1};
assert bits.length % 8 == 0;
byte[] bytes = new byte[bits.length / 8];
for (int i = 0; i < bytes.length; i++) {
int b = 0;
for (int j = 0; j < 8; j++)
b = (b << 1) + bits[i * 8 + j];
bytes[i] = (byte)b;
}
for (int i = 0; i < bytes.length; i++)
System.out.printf("%02x ", bytes[i]); // prints: 5e 3d
System.out.println();
This is the more common Most Significant Bit First.
Answer by #AndrewWilliamson shows an algorithm for Least Significant Bit First.
Since you know that the array will always be a multiple of 8, then you can safely convert from binary to bytes with bit manipulations.
public byte getByte(int[][] array, int x, int y) {
byte result = 0;
for (int bit = 0; bit < 8; bit++)
result += (byte)(array[x][y + bit] * (1 << bit));
return result;
}
Alternatively, as #Andreas pointed out, Most Significant Bit normally comes first. Just change the for-loop to this:
result += (byte)(array[x][y + bit] * (128 >> bit));
The approach that you linked to converts the ints to bytes by simply considering the four individual bytes that an int consists of.
What you need is a method that sets individual bits in the resulting bytes. This can be done by checking whether each of the 128 values in the input array is 0 or 1, and setting the corresponding bit in the output array acoordingly. This can be done with each row independently.
Here is an MCVE that shows the conversion process and prints and compares the results:
import java.util.Random;
public class IntArrayToByteArray2D
{
public static void main(String[] args)
{
int sizeX = 128;
int sizeY = 128;
int input[][] = new int[sizeX][sizeY];
Random random = new Random(0);
for (int x=0; x<sizeX; x++)
{
for (int y=0; y<sizeY; y++)
{
boolean b = random.nextBoolean();
input[x][y] = b ? 1 : 0;
}
}
System.out.println("Input: ");
String inputString = createString(input);
System.out.println(inputString);
byte output[][] = convert(input);
String outputString = createString(output);
System.out.println(outputString);
System.out.println(inputString.equals(outputString));
}
private static byte[][] convert(int input[][])
{
byte output[][] = new byte[input.length][];
for (int i=0; i<input.length; i++)
{
output[i] = convert(input[i]);
}
return output;
}
private static byte[] convert(int input[])
{
// Check whether input.length is divisible by 8, if desired
byte output[] = new byte[input.length >> 3];
for (int i=0; i<output.length; i++)
{
for (int j=0; j<8; j++)
{
if (input[(i<<3)+j] != 0)
{
output[i] |= (1 << j);
}
}
}
return output;
}
private static String createString(int array[][])
{
StringBuilder sb = new StringBuilder();
for (int x=0; x<array.length; x++)
{
for (int y=0; y<array[x].length; y++)
{
sb.append(array[x][y]);
}
sb.append("\n");
}
return sb.toString();
}
private static String createString(byte array[][])
{
StringBuilder sb = new StringBuilder();
for (int x=0; x<array.length; x++)
{
for (int y=0; y<array[x].length; y++)
{
for (int b=0; b<8; b++)
{
if ((array[x][y] & (1<<b)) == 0)
{
sb.append("0");
}
else
{
sb.append("1");
}
}
}
sb.append("\n");
}
return sb.toString();
}
}
This Question is part of ongoing Competition , I have solved the 75% of this Question Data Set but the 25% is giving me TLE. I am asking why it's is giving TLE an i am sure my complexity is O(n*n)Question:
String S consisting of N lowercase English alphabets. We has prepared a list L consisting of all non empty substrings of the string S.
Now he asks you Q questions. To ith question, you need to count the number of ways to choose exactly Ki equal strings from the list L
For Example:
String = ababa
L = {"a", "b", "a", "b", "a", "ab", "ba", "ab", "ba", "aba", "bab", "aba", "abab", "baba", "ababa"}.
k1 = 2: There are seven ways to choose two equal strings ("a", "a"), ("a", "a"), ("a", "a"), ("b", "b"), ("ab", "ab"), ("ba", "ba"), ("aba", "aba").
k2 = 1: We can choose any string from L (15 ways).
k3 = 3: There is one way to choose three equal strings - ("a", "a", "a").
k4 = 4: There are no four equal strings in L .
Question LINK
My approach
I am making a TRIE of IT and Calculating The and Array F[i] where F[i] represent the number of times i equal String Occur.
My TRIE:
static class Batman{
int value;
Batman[] next = new Batman[26];
public Batman(int value){
this.value = value;
}
}
MY Insert Function
public static void Insert(String S,int[] F , int start){
Batman temp = Root;
for(int i=start;i<S.length();i++){
int index = S.charAt(i)-'a';
if(temp.next[index]==null){
temp.next[index] = new Batman(1);
F[1]+=1;
}else{
temp.next[index].value+=1;
int xx = temp.next[index].value;
F[xx-1]-=1;
F[xx]+=1;
// Calculating The Frequency of I equal Strings
}
temp = temp.next[index];
}
}
MY MAIN FUNCTION
public static void main(String args[] ) throws java.lang.Exception {
Root = new Batman(0);
int n = in.nextInt();
int Q = in.nextInt();
String S = in.next();
int[] F = new int[n+1];
for(int i=0;i<n;i++)
Insert(S,F,i);
long[] ans = new long[n+1];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
ans[i]+= F[j]*C[j][i]; // C[n][k] is the Binomial Coffecient
ans[i]%=mod;
}
}
while(Q>0){
Q--;
int cc = in.nextInt();
long o =0;
if(cc<=n) o=ans[cc];
System.out.println(o+" "+S.length());
}
}
Why My appraoch is giving TLE as time Complexity is O(N*N) ans the length of String is N<=5000. Please Help me Working CODE
One reason this program get TLE (keep in mind that time constraint is 1 sec):
Each time you create a Batman object, it will create an array with length [26], and it is equivalence to adding a loop with n = 26.
So, you time complexity is 26*5000*5000 = 650000000 = 6.5*10^8 operations, theoretically, it can still fit into time limit if CPU speed is 10^9 operations per sec, but also keep in mind that there are some heavy calculation stuffs after this, so, this should be the reason.
To solve this problem, I used Z-algorithm and get accepted: Link
The actual code is quite complex, so the idea is, you have a table count[i][j], which is the number of substring that matched substring (i, j). Using Z-algorithm, you can have a time complexity of O(n^2).
For each string s:
int n = in.nextInt();
int q = in.nextInt();
String s = in.next();
int[][] cur = new int[n][];
int[][] count = new int[n][n];
int[] length = new int[n];
for (int i = 0; i < n; i++) {
cur[i] = Z(s.substring(i).toCharArray());//Applying Z algorithm
for (int j = 1; j < cur[i].length; j++) {
if (cur[i][j] > length[j + i]) {
for (int k = i + length[j + i]; k < i + cur[i][j]; k++) {
count[i][k]++;
}
length[j + i] = cur[i][j];
}
}
}
int[] F = new int[n + 1];
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
int v = count[i][j] + (length[i] < (j - i + 1) ? 1 : 0);
F[v]++;
}
}
Z-algorithm method:
public static int[] Z(char[] s) {
int[] z = new int[s.length];
int n = s.length;
int L = 0, R = 0;
for (int i = 1; i < n; i++) {
if (i > R) {
L = R = i;
while (R < n && s[R - L] == s[R])
R++;
z[i] = R - L;
R--;
} else {
int k = i - L;
if (z[k] < R - i + 1) {
z[i] = z[k];
} else {
L = i;
while (R < n && s[R - L] == s[R])
R++;
z[i] = R - L;
R--;
}
}
}
return z;
}
Actual code: http://ideone.com/5GYWeS
Explanation:
First, we have an array length, with length[i] is the longest substring that matched with the string start from index i
For each index i, after calculate the Z function, we see that, if cur[i][j] > length[j + i], which means, there exists one substring longer than previous substring matched at index j + i, and we havent counted them in our result, so we need to count them.
So, even there are 3 nested for loop, but each substring is only counted once, which make this whole time complexity is O(n ^2)
for (int j = 1; j < cur[i].length; j++) {
if (cur[i][j] > length[j + i]) {
for (int k = i + length[j + i]; k < i + cur[i][j]; k++) {
count[i][k]++;
}
length[j + i] = cur[i][j];
}
}
For below loop, we notice that, if there is a matched for substring (i,j), length[i] >= length of substring (i,j), but if there is no matched, we need to add 1 to count substring (i,j), as this substring is unique.
for(int j = i; j < n; j++){
int v = count[i][j] + (length[i] < (j - i + 1) ? 1 : 0);
F[v]++;
}
I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
The output should look like this:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
Thanks for looking.
No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}
Just print the for variables (i...p) without accessing this obscure empty array.
Well, if it's OK to use some built-in classes, you can do this in the following way:
for (int i=0; i<256; i++){
System.out.println(Integer.toBinaryString(i));
}
And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):
for (int i=0;i<256;i++){
int mask = 256;
while (mask > 0){
if ((mask & i) == 0){
System.out.print("0");
} else {
System.out.print("1");
}
mask = mask >> 1;
}
System.out.println();
}
Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:
public static void printBin()
{
for (int i = 0; i < 256; i++) {
int binary = decToBin(i, "");
// pad to give length of 8
System.out.println(String.format("%08d", binary));
}
}
public static int decToBin(int dec, String bin)
{
int quot = dec / 2;
int remainder = dec % 2;
if (quot == 0)
return Integer.parseInt("" + remainder + bin);
return decToBin(quot, "" + remainder + bin);
}
Heres another way of generating all the values using bit operations
public static void main(String[] args) {
int numBits = 8;
int val = 0;
int[] values = new int[]{0,1};
values[0] = 0;
values[1] = 1;
for (int i = 1; i < numBits; i++) {
int[] moreValues = new int[values.length * 2];
int start = (int)Math.pow(2, i);
for (int j = 0; j < values.length; j++) {
moreValues[j * 2] = values[j] << 1;
moreValues[j * 2 + 1] = values[j] << 1 | 1;
}
values = moreValues;
}
//print the values
for (int value: values) {
System.out.println(Integer.toBinaryString(value));
}
}
And another way, using bit operations and recursion
private static void generateNumbers(int number, int numBits, int currentBit) {
if (numBits == currentBit) {
Integer.toBinaryString(number);
return;
}
currentBit++;
generateNumbers(number << 1, numBits, currentBit);
generateNumbers(number << 1 | 1, numBits, currentBit);
}
public static void generateNumbers(int numBits) {
generateNumbers(0, 8, 1);
generateNumbers(1, 8, 1);
}
public static void main(String[] args) {
generateNumbers(8);
}
package org.cross.topology;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//System.out.println("sushil");
int digits=3;//Provide number of digits for which you want combinations of 0 and 1
int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
String current_char="0";
int startindex=0,lastindex;
ArrayList<String> al=new ArrayList<String>(combinations);
for(int k=0;k<combinations;k++)
{
al.add("");
}
for(int i=1;i<=digits;i++)
{
noof0and1=noof0and1/2;
while(temp!=combinations)
{
temp=temp+noof0and1;
secondloopcounter++;
}
lastindex=noof0and1;
startindex=0;
for(int s=0;s<secondloopcounter;s++)
{
for(int j=startindex;j<lastindex;j++)
{
String temps=al.get(j)+current_char;
al.remove(j);
al.add(j, temps);
}
if(current_char.equals("0"))
{
current_char="1";
}
else
{
current_char="0";
}
startindex=lastindex;
lastindex=lastindex+noof0and1;
}
temp=0;
secondloopcounter=0;
}
for(int l=0;l<al.size();l++)
{
System.out.println(al.get(l));
}
}
}
Below is the solution using Recursion as an approach in java
public class NumberOfBinaryPatterns {
static int[] bitArray = new int[]{0,1};
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int numberOfBits=4; // It can be any value based on the requirement, In this case we can put this as 8
drawBinaryPattern(numberOfBits,"");
}
private static void drawBinaryPattern(int n,String seed)
{
if(n==0){
System.out.println(seed);
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
drawBinaryPattern(n-1,temp);
}
}
}
Do in php , very easy
Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.
for($c=1;$c<=pow(2,8);$c++)
{
$bin_str=base_convert($c,10,2); //converting combination number into binary string
$len_str=strlen($bin_str); // Length of string obtained
for($i=1;$i<=8-$len_str;$i++)
$bin_str="0".$bin_str; // adding as many 0 as required to complete in byte format
echo "<br>".$bin_str; //Displaying binary values in byte structure
}