As an input I have binary string String a = "100110". As output I need to have binary byte array byte[] b = {1,0,0,1,1,0}.
For now I'm using
for (int i=0; i<a.length; i++) {
b[i]= Byte.parseByte(a.substring(i, i+1));
}
But this approach is too slow. Can any one give a better suggestion? Thank you
You can do it without making objects for substrings, like this:
for (int i=0; i<a.length; i++) {
b[i]= a.charAt(i)=='1' ? (byte)1 : (byte)0;
}
The reason your approach is slower is that each call to substring produces a new String object, which becomes eligible for garbage collection as soon as parseByte is done with it.
Assuming the input is valid...
byte[] b = new byte[a.length()];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) (a.charAt(i) - '0');
}
Makes an int[] instead of byte[] but I hope for points for elegance:
int[] a = "100110"
// Turn it into a stream.
.chars()
// Make '0'/'1' into 0/1
.map(c -> c - '0')
// Roll it into an array.
.toArray();
Related
I have a List<List<Integer>> arr which is 2D_INTEGER_ARRAY. I need to convert this to 2D char[][] array. I tried with below code but it is giving compilation issue which is obvious but not able to figure out how can I do that?
public static int largestMatrix(List<List<Integer>> arr) {
char[][] matrix = new char[arr.size()][];
for (int i = 0; i < arr.size(); i++) {
List<Integer> row = arr.get(i);
// below line is giving error
matrix[i] = row.toArray(new char[row.size()]);
}
}
Error is:
[Java] The method toArray(T[]) in the type List<Integer> is not applicable for the arguments (char[])
Integer and char are separate types. If you want an integer represented as a digit, you need to convert it (casting will only give you the ASCII representation). Besides, you can't call toArray() with a primitive array. You'll have to iterate and convert manually:
matrix[i] = new char[row.size()];
for (int j = 0; j < row.size(); j++) {
matrix[i][j] = Character.forDigit(row.get(j), 10);
}
Basically you are trying to convert List<Integer> to char[] in this line:
matrix[i] = row.toArray(new char[row.size()]);
You can do so using this:
matrix[i] = row.stream()
.map(j -> Integer.toString(j))
.collect(Collectors.joining())
.toCharArray();
We can do it purely using java-8 streams as follows, I have taken a cue from Kartik's answer on the conversion of Stream of Integer to Stream of char[]:
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6), Arrays.asList(7,8,9));
char[][] chars = list.stream().map(l -> l.stream()
.map( i-> Integer.toString(i))
.collect(Collectors.joining())
.toCharArray())
.toArray(char[][]::new);
public byte[] d
In this byte array, each byte represents a digits, where d[0] is the least significant digit, and a[d.length-1] is the most significant digit. For example, 543210 is stored as {0,1,2,3,4,5}. The most significant digit can't be a zero;
In the real implementation, this array should be private.
Constructor Detail: AdditionOnlyInt
public AdditionOnlyInt(java.lang.String a)
This is a constructor that construct an AdditionOnlyInt with value presented by the input string. For example, if input a = "00012340", this constructor will set the byte array to have value {0,4,3,2,1}. Note that the leading zeros in the input string should not be stored.
Parameters:a - is a string such as "00012340"
I do not know how to do this constructor does anyone?
I know its very wrong but I tried this
public AdditionOnlyInt(String number) {
int counter = number.length();
number.replace("0","");
data = new byte[number.length()];
int i = 0;
while(i<number.length()) {
data[i] = (byte)number.charAt(counter);
i++;
counter--;
}
}
and I do know converting to byte gives you different values.
You're in luck: only a handful of modifications need to be made to your program. You weren't entirely wrong. :)
First, these three statements are giving you fits:
int counter = number.length();
number.replace("0","");
data = new byte[number.length()];
You get a counter, which is the unbiased String (that is, with zeroes), which will undoubtedly be smaller than the String, without zeroes. You'd also be creating the array with the size of the unbiased list.
Well...it would be if your second statement did something. String is immutable, so anything that's done to modify it would only generate a new String, leaving the old one unmodified. That's fixable by this:
number = number.replace("0", "");
...but in reality, given your input set, it should be fixed by this:
number = String.valueOf(Integer.parseInt(number));
This way, you keep internal zeroes.
Now assuming that your byte[] is actually called data and not d, there's one little issue we have to fix: numbers in terms of a byte are quite large (that is, the character for '7' is 0x37, which is 55).
So we need to bias it. Whatever our byte number is, we need to subtract '0' from it; that is, we need to subtract 48 from it, to give us our correct value. I'll show you what that looks like in a moment.
Now, for your loop:
int i = 0;
while(i<number.length()) {
data[i] = (byte)number.charAt(counter);
i++;
counter--;
}
I'm not sold on the necessity of counter, so let's get rid of it. Now we'll use i from now on. Essentially, what this means is that we have to move charAt from the end of the String to the front of the String, placing the values into the array as such. What that (mostly) looks like is this:
data[i] = (byte) (number.charAt(number.length() - 1 - i);
Pay close attention here - we have to subtract 1 from the length right off the bat, since we don't have a place on the String that's exactly equal to its maximum length. We then subtract i from that, so we get the effect of moving backwards on the String.
That is, for a string of length 10 without zeroes, if we start at i = 0, we get the character at 10 - 1 - 0 = 9, or the last character.
Remember what I said about biasing the result of that, though? After you've got the data, be sure to subtract '0' from it.
data[i] = (byte) (number.charAt(number.length() - 1 - i) - '0';
And really, that's all there is to it. You mostly got it, except the iteration and sanitization was a bit wonky.
public AdditionOnlyInt(String input)
{
//remove trailing 0s
int relevStart = 0;
while(input.charAt(relevStart) == '0')
{
relevStart++;
}
String relevantTerms = input.substring(relevStart);
//flip the remaining chars
int length = relevantTerms.length();
data = new byte[length];
for(int iter = 0; iter < length; iter++)
{
data[iter] = (byte) (relevantTerms.charAt(length - iter - 1) - '0');
}
}
Hope this helps.
Step 1: Check whether its a number by using Integer value = Integer.valueOf(args);
Step 2: convert the Integer into a byte array by calling byte array[] = value.toString().getBytes();
Step 3: the byte array contains the value in forward fashion, So swapping all the values in the array will make the digit reverse as user requested.
for (int i = 0, j = array.length - 1; i < array.length / 2; i++, j--) {
byte temp = array[i];
array[i] = array[j];
array[j] = temp;
}
find the complete program below:
public class AdditionOnlyInt {
public static void main(String[] args) {
// TODO Auto-generated method stub
new AdditionOnlyInt("01010120");
}
public AdditionOnlyInt(String args) {
try {
Integer value = Integer.valueOf(args);
byte array[] = value.toString().getBytes();
for (int i = 0, j = array.length - 1; i < array.length / 2; i++, j--) {
byte temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for (int i = 0; i < array.length; i++) {
System.out.print((char) array[i]);
}
} catch (Exception e) {
}
}
}
I'm trying to create a code that writes an array backwards and can only use an array, character, and an integer. So far I have this, but it isn't doing anything. I'm a beginner at java.
import javax.swing.JOptionPane;
public class TestingArraysUsingOneArray
{
public static void main(String args[])
{
{
String str = JOptionPane.showInputDialog("Enter any text that you want to reverse.");
char[] charArray = str.toCharArray();
char current;
int a = 0;
for (int i = 0; i>=str.length()%2; i++) {
current = str.charAt(a);
charArray[a] = str.charAt(str.length()-a);
charArray[str.length()-a] = current;
a++;
}
System.out.println(charArray);
}
}
}
The output I'm getting is hello when I enter in hello. What do I need to change to get this program to work?
Your don't need half the code. I would try to make it as simple as possible. Try this
String str = ...
for(int i = str.length() - 1; i >= 0; i--)
System.out.print(str.chatAt(i));
System.out.println();
If the assignment says you have to reverse an array of chars you can do this.
String str = ...
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length/2; i++) {
char ch = chars[i];
chars[i] = chars[chars.length - i - 1];
chars[chars.length - i - 1] = ch;
}
System.out.println(new String(chars));
As you can see this is needlessly complicated, so you would not do this. Another way you can do this if you don't want to use a loop is
String str = ...
System.out.println(new StringBuilder(str).reverse());
Well, for one thing, I think you want i<str.length()/2 - this will give you half the length. If you say i>=str.length()%2, you're getting the remainder when its length is divided by 2 - which is always either 1 or 0, and the loop continues as long as i is more than either 1 or 0. This should result in an infinite loop. Also, you don't need the variable a, as it is always equivalent to i. This, however, results in the string index being out of bounds sometimes, but I'll let you figure out how to solve that.
Your for loop is never entering because it should be i < str.length(), because at the moment when i is 0, the current check will immediately fail.
With that condition set, you need to change the two instances of str.length()-a to str.length()-a-1, because str.length-a when a is 0 will cause an StringIndexOutOfBoundException because the maximum index you can access is str.length-1.
Those are just corrections to the existing code. There's a better, more concise way of reversing the string suggested in another answer, which is the one you should accept.
What you want to do is replace the first character with the last and so on..
char[] charArray = str.toCharArray();
char current;
for (int i = 0; i < charArray.length / 2; i++) {
current = charArray[i];
charArray[i] = charArray[charArray.length - i - 1];
charArray[charArray.length - i - 1] = current;
}
The a int is completely redundant, and it would be a second int in your code - don't forget the variable in the for loop.
I'm taking care of some other methods and I don't know what to do with this one. I want to change the order of the string inside the array (not the order of the string*s*), but this isn't accepted. Any ideas?
public void invert() {
for(int i = 0; i < array.length; i++){
for(int j = 0, k = array[i].length() - 1; j < k; j++, k--){
char a = array[i].charAt(j);
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(k) = a; //AND HERE
}
}
}
EDIT: I'll leave here what I mean.
I have an array = {"Hello", "Goodbye"}
I want to change it to {"olleH", "eybdooG"}
Java string are immutable. You can't change them.
(But you can convert the string to a StringBuilder - http://docs.oracle.com/javase/tutorial/java/data/buffers.html - which is essentialy a mutable string, change the characters, and then convert the StrignBuilder back to String.)
Try this code (I haven't tested it, but I hope it works):
for(int i = 0; i < array.length; i++) {
StringBuilder b = new StringBuilder(array[i]);
for(int j = 0, k = b.length() - 1; j < k; j++, k--){
char a = b.charAt(j);
b.setCharAt(j, array[k].charAt(k));
b.setCharAt(k, a);
}
array[i] = b.toString();
}
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(a) returns a value not a variable. You are trying to assign a value to a value which doesn't make any sense.
java String is immutable. You can't change it.
Use StringBuilder which has setCharAt(int index,
char ch); function which is what you are probably wanting.
The most simple way is, to reverse letter with StringBuilder.reverse() method. Try,
for(String str : array){
System.out.println(new StringBuilder(str).reverse());
}
Just use this on every String in your array:
String reversed = new StringBuilder(stringFromArray).reverse().toString();
try doing new StringBuilder(array[i]).reverse().toString();
you would have to create a substring.
array[i]= array[i].substring(0,j) + array[k].charAt(k) + array[i].substring(j+1);
This would do the required edit i beleive
I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!