Does the calculation correct for bin to dec? - java

00101=5 digits, disregard two Zeros and calculate
0+(5-2-1)^2 = 4
4+(5-3-1)^2 = 5
5+(5-4-1)^2 = 5
final answer Is it Correct?
char[] charArray = binary.toCharArray();
double answer = 0;
for (double index = 0; index < charArray.length; index++)
{
if (charArray[(int)index] == '1')
{
answer = answer + Math.pow(2.0, (charArray.length - index - 1));
}
}

Use Integer.parseInt , that converts your String to int using base two:
int decimalValue = Integer.parseInt(c, 2);
Refer this:
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29
Your expected results are being calculated as if the binary string is read from right to left; however, your code is reading the binary string from left to right.
You can also try this:
char[] charArray = binary.toCharArray();
double answer = 0;
for (double index = charArray.length - 1; index >= 0; index--)
{
if (charArray[(int)index] == '1')
{
answer = answer + Math.pow(2.0, index);
}
}

Don't reinvent the Wheel. Use following simple code.
int dec=Integer.valueOf(binStr, 10);//Here 10 is base.

Related

How do i split a string every five characters using loops? [duplicate]

This question already has answers here:
Splitting a string at every n-th character
(10 answers)
Closed 2 years ago.
Suppose I have a string: "VJKUKUTGCNNAUVWRKF"
How can I use loops to make it into this instead
"VJKUK UTGCN NAUVW RKF" where there is a space every
five characters (notice the last part only has three characters).
Perhaps
String str = "VJKUKUTGCNNAUVWRKF";
StringBuilder sb = new StringBuilder();
for (int j = 1; j <= str.length(); j++) {
sb.append(str.charAt(j-1));
if (j % 5 == 0) {
sb.append(" ");
}
}
String str2 = sb.toString();
I don't think it's a perfectly optimized solution, but it is one way.
If you are using java8 or higher :
String original = "VJKUKUTGCNNAUVWRKF";
String modifided = Pattern.compile("(?<=\\G.{5})")
.splitAsStream(original)
.collect(Collectors.joining(" "));
If you want to use regex please refer this
Splitting a string at every n-th character
Code:
String s = "VJKUKUTGCNNAUVWRKF";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G.....)")));
You can use some variables to keep track of the index positions and use substring(startIndex, endIndex) to update the new string. We use StringBuilder to create the new String.
String first = "VJKUKUTGCNNAUVWRKF";
StringBuilder splittedString = new StringBuilder();
int length = first.length();
int index = 0;
while(length > 0){
int endIndex = index + 5;
if(length <= 5){
endIndex = index + length;
}
splittedString.append(first.substring(index, endIndex));
splittedString.append(" ");
length -= 5;
index += 5;
}
System.out.println(splittedString.toString().trim());
Use String.substring() and concatenate.
String s = "JJGDVKJGFGKKGRFJJF";
String result="";
for (int i=0;i<s.length;i+=5) {
if(!result.equals("") result+=" ";
result+=s.substring(i, Math.max(i+5, s.length));
}
I'm writing from my mobile. So it's difficult to make a good code. There may be a few mistakes to correct.
#Aharon already give you a good solution, but it could produce redundant " " when the String length is a multiple of 5.
This could fix the case and be a little more efficient and organized:
public static String split(String s, int size, String sep) {
if (s.length() <= size) {
return s;
}
final int expectedLength = s.length() + s.length() / size;
final StringBuilder sb = new StringBuilder(expectedLength);
sb.append(s, 0, size);
int counter = 2 * size;
while (counter <= s.length()) {
sb.append(sep).append(s, counter - size, counter);
counter += size;
}
if (counter - size < s.length()) {
sb.append(sep).append(s, counter - size, s.length());
}
return sb.toString();
}
So you can just call:
String s = "VJKUKKASDD";
String out = split(s, 5, " ");

Breaking up paragraphs into String tokens

I am able to break up paragraphs of text into substrings based upon nth given character limit. The conflict I have is that my algorithm is doing exactly this, and is breaking up words. This is where I am stuck. If the character limit occurs in the middle of a word, how can I back track to a space so that all my substrings have entire words?
This is the algorithm I am using
int arrayLength = 0;
arrayLength = (int) Math.ceil(((mText.length() / (double) charLimit)));
String[] result = new String[arrayLength];
int j = 0;
int lastIndex = result.length - 1;
for (int i = 0; i < lastIndex; i++) {
result[i] = mText.substring(j, j + charLimit);
j += charLimit;
}
result[lastIndex] = mText.substring(j);
I am setting the charLimit variable with any nth, integer value. And mText is string with a paragraph of text. Any suggestions on how I can improve this? Thank you in advance.
I am receiving good responses, just so you know what I did to figure out of I landed on a space or not, I used this while loop. I just do not know how to correct from this point.
while (!strTemp.substring(strTemp.length() - 1).equalsIgnoreCase(" ")) {
// somehow refine string before added to array
}
Not sure if I understood correctly what you wanted but an answer to my interpretation:
You could find the last space before your character limit with lastIndexOf and then check if you are close enough to your limit (for text without whitespace) i.e.:
int arrayLength = 0;
arrayLength = (int) Math.ceil(((mText.length() / (double) charLimit)));
String[] result = new String[arrayLength];
int j = 0;
int tolerance = 10;
int splitpoint;
int lastIndex = result.length - 1;
for (int i = 0; i < lastIndex; i++) {
splitpoint = mText.lastIndexOf(' ' ,j+charLimit);
splitpoint = splitpoint > j+charLimit-tolerance ? splitpoint:j+charLimit;
result[i] = mText.substring(j, splitpoint).trim();
j = splitpoint;
}
result[lastIndex] = mText.substring(j).trim();
this will search for the last space before charLimit (example value) and either split the string there if it is less then tolerance away or split at charLimit if it isn't.
Only problem with this solution is that the last Stringtoken can be longer than charLimit so you might need to adjust arrayLength and loop while (mText - j > charLimit)
Edit
running sample code:
public static void main(String[] args) {
String mText = "I am able to break up paragraphs of text into substrings based upon nth given character limit. The conflict I have is that my algorithm is doing exactly this, and is breaking up words. This is where I am stuck. If the character limit occurs in the middle of a word, how can I back track to a space so that all my substrings have entire words?";
int charLimit = 40;
int arrayLength = 0;
arrayLength = (int) Math.ceil(((mText.length() / (double) charLimit)));
String[] result = new String[arrayLength];
int j = 0;
int tolerance = 10;
int splitpoint;
int lastIndex = result.length - 1;
for (int i = 0; i < lastIndex; i++) {
splitpoint = mText.lastIndexOf(' ' ,j+charLimit);
splitpoint = splitpoint > j+charLimit-tolerance ? splitpoint:j+charLimit;
result[i] = mText.substring(j, splitpoint);
j = splitpoint;
}
result[lastIndex] = mText.substring(j);
for (int i = 0; i<arrayLength; i++) {
System.out.println(result[i]);
}
}
Output:
I am able to break up paragraphs of text
into substrings based upon nth given
character limit. The conflict I have is
that my algorithm is doing exactly
this, and is breaking up words. This is
where I am stuck. If the character
limit occurs in the middle of a word,
how can I back track to a space so that
all my substrings have entire words?
Additional Edit: added trim() as per suggestion by curiosu. It removes whitespace surroundig the string tokens.

Is there a difference in terms of algorithm efficiency between subtracting ASCII values and simply subtracting an integer?

I recently completed TopCoder algorithm contest single round match 618, and the problem was quite simple. Given a string consisting only of capital letters from A to Z, A = 1, B = 2, etc. and Z = 26. The objective was to return the string's total value using these values.
This was my algorithm:
public class WritingWords {
public int write(String word) {
int total = 0;
word = word.replaceAll("\\s+","");
for(int i = 0; i < word.length(); i++){
total += (int)word.charAt(i)-64;
}
return total;
}
}
I obtained a score of ~165/250.
This is the code of another user who got ~249/250:
public class WritingWords {
public int write(String word) {
int total = 0;
for(int i = 0; i < word.length(); i++){
total += word.charAt(i)-'A'+1;
}
return total;
}
}
To me, the two source codes look very similar, and I'm unsure as to why I might have gotten such a lower score. What might be the reason that the latter algorithm is so much more efficient than mine? Seems to me that they'd both run in O(n) time anyways.
Given a string consisting only of capital letters from A to Z, A = 1, B = 2, etc. and Z = 26.
Given that problem statement, this line
word = word.replaceAll("\\s+","");
is useless and iterates over the whole String value pointlessly.
Both total += (int)word.charAt(i)-64; and total += word.charAt(i)-'A'+1; would run pretty much equally fast. The problem is in this line here:
word = word.replaceAll("\\s+","");
This line (which is only in your code) is what slows down your program. As you can see in the other response, this line is unnecassary.
This
total += word.charAt(i) - 64;
is exactly the same as
total += (int) word.charAt(i) - 64;
which is the same as
total += word.charAt(i) - 'A' + 1;
If you want to speed up your program, don't use a regular expression
public int write(String word) {
int total = 0;
for(int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch >= 'A')
total += word.charAt(i) - 64;
}
return total;
}

How do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

What's wrong with my bit vector?

I am trying to create a bit vector backed by an int[].
So I have the following code:
public class BitVector {
int[] vector = new int[1 << 16];
public void setBit(int nextInt) {
nextInt = nextInt & 0xFFFF;
int pos = nextInt / 32;
int offset = nextInt % 32;
vector[pos] |= (1 << offset);
}
public int findClearedBit() {
for(int i = 0; i < vector.length; i++){
for(int j = 0; j < 8; j++){
if((vector[i] & (1 << j)) == 0)
return i * 32 + j;
}
}
return -1;
}
}
I know that perhaps I should have used byte[] instead etc but I was wondering why this way it does not work.
The idea is that I pass in int from a stream and keep the lower 16 bits and mark the corresponding bit as set. So when I iterate over the vector I will find the number (indicate by the lower 16 bits) missing.
But I get wrong result. So I believe my handing is wrong.
Any ideas?
Update:
I have a stream of 32-bit integers. As I read them in I try to mark a number missing by using the lower 16-bits and setting the bitvector (code posted).
I also try to find the upper 16 bits missing reading the stream a second time.
So while the missing number is: 231719592 = (1101110011111100001010101000) = (3535-49832)
When I read the stream I don't get 49832 as the missing lower bits but 65536
Update2:
public int findMissingInt(File f)throws Exception{
Scanner sc = new Scanner(f);
int SIZE = 1 << 16;
int[] occurences = new int[SIZE];
while(sc.hasNext()){
occurences[getIdx(sc.nextInt())]++;
}
int missingUpper = -1;
for(int i = 0; i < occurences.length; i++){
if(occurences[i] < SIZE){
System.out.println("Found upper bits:"+i);
missingUpper = i;
break;
}
}
if(missingUpper == -1){
return -1;
}
//Arrays.fill(occurences, 0); //I reused this. Bellow changed after answer of Peter de Rivaz
BitVector v = new BitVector(new int[1 << (16-5)]);
sc = new Scanner(f);
while(sc.hasNext()){
v.setBit(sc.nextInt());
}
int missingLower = v.findClearedBit();
System.out.println("Lower bits:"+missingLower);
return createNumber(missingUpper, missingLower);
}
private int createNumber(int missingUpper, int missingLower) {
int result = missingUpper;
result = result << 16;
return result | missingLower;
}
public int getIdx(int nextInt) {
return (nextInt >>> 16);
}
I get:
Missing number=231719592
Found upper bits:3535 //CORRECT
Lower bits:-1 //WRONG
Actual missing number=-1 //WRONG
I think there are two problems:
Your array has 65536 entries, but you store 32 bits in each entry, so you only need 65536/32 entries in it.
You store 32 bits in each int, but only check j from 0 to 7 when finding gaps
The first bug means that your program reports 65536 as a missing 16bit number.
The second bug means that your program does not spot the missing number.
i.e. change
int[] vector = new int[1 << 16];
to
int[] vector = new int[1 << (16-5)];
and change
for(int j = 0; j < 8; j++)
to
for(int j = 0; j < 32; j++)
EDIT
Judging from the comments, the question is actually how to find a missing number with limited RAM. The answer to this question can be found here on stackoverflow.
There is an additional bug in the higher level code.
During the second pass that populates the bitset, you should only include numbers that have the matching upper bits.
i.e. change
v.setBit(sc.nextInt());
to something like
int nx = sc.nextInt();
if (getIdx(nx)==missingUpper)
v.setBit(nx);

Categories