Is there a better(Faster) way to split a binary string into an Array?
My code That loops and substring every 8 characters in one element.
binary = my binary string(Huge) : "1010101011111000001111100001110110101010101"
int index = 0;
while (index < binary.length()) {
int num = binaryToInteger(binary.substring(index, Math.min(index + 8,binary.length())));
l.add( num);
temp = temp+ String.valueOf(num);
index += 8;
}
What I am trying to do is to split my binary string into pieces of 8 characters 10101010 and then get the int value of the 8 characters and will store that in arraylist witch in this case was l
My code is working but is very time consuming.. Is there a faster way of getting this done?
It's easy using regex:
binary.split("(?<=\\G.{8})");
However, it creates an array of strings. I don't get your will of creating an array of integers, since binary strings don't fit into this type (they can start with "0" and they can be really long).
I think there are mutiple options using Regex, substring, split etc available in java or Google Guavas - Splitter.fixedLength().
Splitter.fixedLength(8).split("1010101011111000001111100001110110101010101");
This Split a string, at every nth position clearly explain the performance of various functions.
It would probably faster using toCharArray:
Long time = System.currentTimeMillis();
List<Integer> l = new ArrayList<>();
int index = 0;
String binary =
"1010101011111000001111100001110110101";
char[] binaryChars = binary.toCharArray();
while (index < binaryChars.length) {
int num = 0;
for (int offset = 0; offset < Math.min(8, binary.length() - index); offset++) {
int bo = index + offset;
if (binaryChars[bo] == '1') {
num += Math.pow(2, offset + 1);
}
}
l.add(num);
index += 8;
}
System.out.println(System.currentTimeMillis() - time);
Since you want to split into groups of eight bits, I guess, you want to decode bytes rather than ints. This is easier than you might think:
String binary = "1010101011111000001111100001110110101010101";
byte[] result=new BigInteger(binary, 2).toByteArray();
Maybe you can try making a for-each loop to go through each character in the string, combine them into 8-bit values and convert into bytes. I don't know if that will be faster, just a suggestion.
for (char c : binary.toCharArray() ) { do stuff }
Related
I have an array of integer 1s and 0s (possibly need to get converted to byte type?). I have used [an online ASCII to binary generator][1] to get the equivalent binary of this 6 digit letter sequence:
abcdef should equal 011000010110001001100011011001000110010101100110 in binary.
My array is set up as int[] curCheckArr = new int[48]; and my string is basically just using a StringBuilder to build the same ints as strings, and calling toString() - so I have access to the code as a string or an array.
I have tried a few different methods, all of which crash the browser, including:
StringBuilder curCheckAlphaSB = new StringBuilder(); // Some place to store the chars
Arrays.stream( // Create a Stream
curCheckString.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
).forEach(s -> // Go through each 8-char-section...
curCheckAlphaSB.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);
String curAlpha = curCheckAlphaSB.toString();
and
String curAlpha = "";
for (int b = 0; b < curCheckString.length()/8; b++) {
int a = Integer.parseInt(curAlpha.substring(8*b,(b+1)*8),2);
curAlpha += (char)(a);
}
How can I most efficiently convert these 48 1s and 0s to a six digit alpha character sequence?
Assuming each character is represented by precisely one byte you can iterate over the input with Integer.parseInt() (because byte value in the input is potentially unsigned):
String input = "011000010110001001100011011001000110010101100110";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i += 8) {
int c = Integer.parseInt(input.substring(i, i + 8), 2);
sb.append((char) c);
}
System.out.println(sb); // abcdef
Using a regex is probably the slowest part of these. Using a pre-compiled regex would help, but substring is faster. Not creating any Strings except the result would be faster. e.g. use StringBuilder instead of += for String.
I am trying to make a program that, depending on an int called length, adds a certain number of 9s to a variable called nines. For example, if length is 4 then I want nines to equal 9999. If length is 7, I want nines to equal 9999999. The value of length needs to correspond to the number of nines in nines. Is this possible, and if so, how?
Yes, it is possible: observe that your target number is ten to the power of Length, minus one:
int res = Math.pow(10, length) - 1;
You could do this:
StringBuilder sb = new StringBuilder();
while (length-- > 0) {
sb.append('9');
]
nines = sb.toString();
Or, if nines is an int:
nines = 0;
while (length-- > 0) {
nines = 10 * nines + 9;
}
The simplest way:
String nines = "";
for(int i = 0; i < length; i++) {
nines += "9";
}
return Integer.parseInt(nines);
You can do this by creating a String with the correct number of numerical characters, then parse it into an int. Something like this...
String bigNumber = "";
for (int i=0;i<length;i++){
bigNumber += "9";
}
int intNumber = Integer.parseInt(bigNumber);
However, note that there are limits to the size of the int. I would recommend that you...
Perhaps try using something that can hold larger numbers, such as long (realising that long still has a limit, but its a higher limit than int).
Provide error checking - if there are too many characters or the number is too big, show an error to the user, rather than crashing your application.
Since we're at it...
char[] nineChars = new char[length];
Arrays.fill(nineChars, '9');
String nines = new String(nineChars);
If you're not opposed to including another library, you could use Apache Commons Lang StringUtils.repeat http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html#repeat(char, int)
String nines = StringUtils.repeat('9',length);
I've got a char array called encoded which has a series of char values. I want to insert 3 chars into the middle of the array and keep the remaining chars by pushing them to the next spaces. Is this possible?
Portion of the code I've used as follows just inserts and replaces the next two chars too.
encoded = new char[20];
encoded = encodeArray.toCharArray();
for (int x = 0; x < encoded.length; x++) {
if (encoded[x] == a) {
encoded[x] = amp;
} if (encoded[x] == und) {
for (int y = 0; y < 3; y++) {
encoded[x+y] = tilde;
}
}
}
Any direction would be greatly appreciated.
Several points.
First, Java's arrays a relatively low-level data structures. They don't support insertion, etc. And they don't dynamically grow.
In your case, you can manually shift the characters by n, but that is loss-less only if the original array had extra n slots of capacity.
For manipulating character arrays, look at java.lang.StringBuilder
Finally, since we are talking Java, there are certain Unicode codepoints that require two Java chars. One of the many reasons to use higher level operations when manipulating character sequences.
You should push your remaining chars right 3 places(if overflow then you will loose the 3 chars from end) as below:
if (encoded[x] == und) {
//move the chars 3 places right first
for (int z = encoded.length-4; z > x; z--) {
encoded[z+3] = encoded[z];
}
//then fill the 3 places as you want
for (int y = 0; y < 3 && x+y < encoded.length; y++) {
encoded[x+y] = tilde;
}
}
If you want to increase the length of your char array by 3 (to retail all old characters) then you need to redefine a a char array of size as encoded.length+3 and copy the element using System.arraycopy(Object src,int srcPos, Object dest, int destPos, int length) and then insert the three characters in between.
Using a String instead of a charArray will allow you to use replaceAll.
I'm trying some online problems. I programmed how to solve the greatest palindrome product of 2 two-digit numbers. For example 91*99=9009. I managed to do it by using the recursive function but I wonder how can i do it using arrays like this one?
product[0]=9;
product[1]=0;
product[2]=0;
product[3]=9;
or if the computed product is 969;
product[0]=9;
product[1]=6;
product[2]=9;
Then I will output it starting from the last index to the first index then test if its equal to the original number.
EDIT:
My question is, how can i store the computed product to an array?
There's no reason to solve that Project Euler problem using arrays. But if you're fixated on it, then there is a simple algorithm to convert an array of digits into a number. Just do this:
int number = 0;
int number_2 = 0;
//going forwards:
for (int i = 0; i < array.length; i++)
{
number = number * 10 + array[i];
}
//going backwards:
for (int i = array.length - 1; i >= 0; i--)
{
number_2 = number_2 * 10 + array[i];
}
if (number == number_2)
{
//you have a palindrome
}
It's not the most efficient method, I know (#Nandkumar's is faster), but it's really really simple, that's what I was aiming for.
Create a new String from the integer product.
I won't writ you code, because it looks like an assignment, but I'll give you a hint.
Convert the int into a string first.
Characters in a string are very much like arrays, so it'll be easy to convert the string into an array.
To convert the number into an array you can try this...
Char [] product = String.valueOf("969").toCharArray();
Provide your product to String.valueOf(int), it will be converted to string and then convert it into array using String.toCharArray() like
boolean palindrome = true;
int product = 9009; // or any calculated number
char str[] = String.valueOf(product).toCharArray();
for(int i=0,j=str.length-1; i!=j ;i++,j--) {
if(str[i] == str[j]){
continue;
} else {
palindrome = false;
break;
}
}
I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.
Here's what I have tried.
//Directly converting from char to int
//(returns different values like 49 instead of 1?)
//I also tried converting to an array of char, which worked,
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.
for (int count = 0; count <=15; count++)
{
intArray[count] = UserInput.charAt(count);
}
//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""
int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
intArray[count]= (varX / varY * 10);
}
Any idea what I should do?
how about this:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.
Here is a solution:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.
Some tips:
I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
I changed "count" to "i". Another convention...