I am trying to get my Binary to Decimal method to calculate properly. I have to use the multiply and/or divide methods in the "bToD" method. I can't figure out how to get it return the answer correct. It should only be returning "5", but instead it is returning 45. I need to fix this method in order to continue the remaining Hexadecimal to Binary and Octal to Binary methods.
package numType;
import java.util.Scanner;
public class numType{
public static String multiply2(String n) { //return 2*n
String r = "";
int c = 0;
for (int i = n.length()-1; i >= 0; i--) {
int p = (n.charAt(i)-'0')*2+c;
c = p/10;
r = p%10+r;
}
if (c > 0)
r = c+r;
return r;
}
public static String divide2(String n) { //return n/2
String r = "";
int b = 0;
int i = 0;
if (n.charAt(0) < '2') {
b = 1;
i = 1;
}
for (; i < n.length(); i++) {
int p = (n.charAt(i)-'0')+b*10;
b = p%2;
r += p/2;
}
if (r.length() == 0)
r = "0";
return r;
}
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
String s = "";
int n = 0;
if (b.charAt(b.length()-1) == '1')
n = 1;
else
n = 0;
int pow = 1; //INITIALIZE POWER # FROM THE SECOND TO LAST 2^1
for (int i=b.length()-2; i>=0; i--) // LIST #'S FROM MOST RIGHT-HAND SIDE
{
char ch = b.charAt(i);
String temp = "" + ch;
for (int j=1; j<=pow; j++)
temp = multiply2(temp);
//System.out.println(temp);
int n1 = 0;
for (int k=0; k<temp.length(); k++)
{
n1 = n1*10 + (int) (temp.charAt(k)-'0');
}
n = n + n1;
s = temp;
pow++;
}
s = s + n;
return s;
}
//convert decimal string d to an equivalent binary string.
public static String dToB(String d)
{
String s = "";
while (!d.equals("0"))
{
String d1 = divide2(d);
d1 = multiply2(d1);
if (d1.equals(d))
s = "0" + s;
else
s = "1" + s;
d = divide2(d);
}
return s;
}
//convert binary string b to an equivalent octal string.
public static String bToO(String b)
{
String s = "";
int groups = b.length()/3;
int index = 0;
//System.out.println(index); //bToD(b)
while (groups != index)
{
for (int i = b.length()-3; i >= 0; i--)
{
for (int j=1; j<=i; j++)
{
String temp = b.substring(b.length()-3,b.length()); //last 3 digits in binary
String sSub = b.substring(0,b.length()-3); //first digits in binary
s = bToD(temp);
}
}
index++;
}
return s;
}
//convert octal string o to an equivalent binary string.
public static String oToB(String o)
{
String s ="";
int digits = o.length();
int index = 0;
while (digits != index)
{
for (int i=o.length()-1; i>=0; i--)
{
char ch = o.charAt(i);
//System.out.println(digits);
switch (ch)
{
case '7':
s = s + "111";
index++;
break;
case '6':
s = s + "110";
index++;
break;
case '5':
s = s + "101";
index++;
break;
case '4':
s = s + "100";
index++;
break;
case '3':
s = s + "011";
index++;
break;
case '2':
s = s + "010";
index++;
break;
case '1':
s = s + "001";
index++;
break;
case '0':
s = s + "000";
index++;
break;
}
}
}
return s;
}
//convert binary string b to an equivalent hexadecimal string.
public static String bToH(String b)
{
String s ="";
return s;
}
//convert hexadecimal string h to an equivalent binary string.
public static String hToB(String h)
{
String s ="";
return s;
}
public static void main(String[] args) {
// TODO code application logic here
String b,d,o,h;
b = "101";
System.out.println("Binary to Decimal:");
System.out.println(b + " => " + bToD(b));
System.out.println();
System.out.println("Decimal to Binary:");
d = "45";
System.out.println(d + " => " + dToB(d));
System.out.println();
System.out.println("Binary to Octal:");
b = "100101101";
System.out.println(b + " => " + bToO(b));
System.out.println();
System.out.println("Octal to Binary:");
o = "";
System.out.println(o + " => " + oToB(o));
System.out.println();
System.out.println("Binary to Hexadecimal:");
b = "";
System.out.println(b + " => " + bToH(b));
System.out.println();
System.out.println("Hexadecimal to Binary:");
h = "";
System.out.println(h + " => " + hToB(h));
}
}
Here's a solution, yours is quite convoluted.
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
int ans = 0, pow = 0;
//For every digit in binary
for(int i=b.length()-1; i>=0; i--){
// Get string of current char
String cur = Character.toString(b.charAt(i));
for (int j=0; j<pow; j++)
cur = multiply2(cur);
ans += Integer.parseInt(cur);
pow++;
}
return Integer.toString(ans);
}
Related
I am working on this simple program that adds two polynomials. However, I am getting wrong results and could not spot the mistake.
import java.util.LinkedList;
public class Polynomial {
private LinkedList<Term> terms = new LinkedList<Term>();
private class Term {
private int coef;
private int exp;
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int getCoef() {
return coef;
}
public int getExp() {
return exp;
}
public String toString() {
return (this.coef + "x^" + this.exp);
}
}
public String addPoly(String first, String second) {
LinkedList<Term> otherTerms = new LinkedList<Term>();
String result = "";
String [] termsArray1 = first.split(";");
String [] termsArray2 = second.split(";");
for (int i = 0; i < termsArray1.length; i++) {
String [] temp = termsArray1[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
terms.add(currentTerm);
}
for (int i = 0; i < termsArray2.length; i++) {
String [] temp = termsArray2[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
otherTerms.add(currentTerm);
}
int i = 0;
int j = 0;
while (true){
if(i == terms.size() || j == otherTerms.size()) {
break;
}
if(terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
if(terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
result = result.substring(0, result.length()-1);
return result;
}
}
::Test::
String s3 = "5x^2;-4x^1;3x^0";
String s4 = "6x^4;-1x^3;3x^2";
Polynomial p = new Polynomial();
System.out.println(p.addPoly(s4, s3));
Expected result: 6x^4;-1x^3;7x^2;-4x^1;3x^0
Actual result: 3x^4;7x^2;-1x^1;10x^0
The problem is that when your loop exits, one of the following can still be true:
i < terms.size()
j < j == otherTerms.size()
And this is the case with your example input. This means that part of one of the terms has not been processed and integrated into the output.
A second problem is that your multiple if statements are not exclusive; after the first if block is executed and j++ has executed, it might well be that j is an invalid index in otherTerms when the second if is evaluated. This should be avoided by turning the second and third if into else if.
Here is a fix for that loop:
while (i < terms.size() || j < otherTerms.size()) {
if(i == terms.size() || j < otherTerms.size() && terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
else if(j == otherTerms.size() || i < terms.size() && terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
else if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
Better approach
Your approach is not really OOP. Ideally, the first expression should serve to create one instance of Polynomial and the other expression should serve to create another instance of Polynomial. Then there should be a method that can add another Polynomial instance to the own instance. Finally there should be a toString method that returns the instance as a string in the required format. Your driver code would then look like this:
Polynomial a = new Polynomial("5x^2;-4x^1;3x^0");
Polynomial b = new Polynomial("6x^4;-1x^3;3x^2");
Polynomial sum = a.addPoly(b);
System.out.println(sum.toString());
This is much more object oriented, and will automatically avoid the code repetition that you currently have.
i am asking for help on how i would go about reversing my code so that the input 'A2B5C2' will give me the output 'AABBBBBCC', any suggestions?
Thanks
public static void printRLE(String str) {
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
// Print character and its count
System.out.print(str.charAt(i));
System.out.print(count);
}
}
public static void main(String[] args) {
String str = "AABBBBBCC";
printRLE(str);
}
To get the case, the number will more than 9, I'd suggest a simple regex to match letter+number, then just repeat the letter the number of times you need :
static String getRevRLE(String str) {
StringBuilder res = new StringBuilder();
Matcher m = Pattern.compile("([a-zA-Z][0-9]+)").matcher(str);
while (m.find()) {
String g = m.group();
res.append(g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))));
}
return res.toString();
}
Using the Streams API you can reduce to
static String getRevRLE(String str) {
return Pattern.compile("([a-zA-Z][0-9]+)").matcher(str).results()
.map(MatchResult::group)
.map(g -> g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))))
.collect(Collectors.joining());
}
Testing
public static void main(String[] args) {
String str = "AABBBBBCCCCCCCCCCCCCCCCCCCC";
String rle = getRLE(str);
String res = getRevRLE(rle);
System.out.println(res + " " + res.equals(str)); // AABBBBBCCCCCCCCCCCCCCCCCCCC true
}
Here you go:
public static String encode(String input) {
String output = "";
while (true) {
char c = input.charAt(0);
String countStr = "";
char current;
for (int i = 1; i < input.length() && Character.isDigit(current = input.charAt(i)); i++)
countStr += current;
int count = Integer.parseInt(countStr);
for (int i = 0; i < count; i++)
output += c;
int trimLength = 1 + countStr.length();
if (trimLength >= input.length())
return output;
else
input = input.substring(trimLength);
}
}
You can do this task like this:
public static String printRLE(String str) {
int n = str.length();
String result = "";
for (int i = 0; i < n - 1; i++) {
char ch = str.charAt(i);
if (!Character.isDigit(ch)) {
if (Character.isDigit(str.charAt(i + 1))) {
int fi = i + 1;
i += 2;
while (i < n && Character.isDigit(str.charAt(i))) i++;
int repeat = Integer.parseInt(str.substring(fi, i));
result += String.valueOf(ch).repeat(repeat);
i--;
} else result += ch;
}
}
return result;
}
public static void main(String[] args) {
String str = "10A10B32C1";
System.out.println(printRLE(str));
}
, output
AAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBC
so I have a code that should multiplicate two Binary Numbers as String without using ParseInt. My code actually works by far but it's multiplicating as decimal numbers. Something in the part where it should do the addition is wrong.
Thanks for any kind of help!
public static String multiply(String binary1, String binary2)
String b1 = new StringBuilder(binary1).reverse().toString();
String b2 = new StringBuilder(binary2).reverse().toString();
int[] m = new int[binary1.length()+binary2.length()];
for (int i = 0; i < binary1.length(); i++) {
for (int j = 0; j < binary2.length(); j++) {
m[i+j] += (b1.charAt(i)-'0')*(b2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
for(int i=0; i < m.length; i++) {
int mod = m[i]%10;
int carry = m[i]/10;
if (i+1 < m.length) {
m[i + 1] = m[i + 1] + carry;
}
sb.insert(0, mod);
}
// delete leading zeros
while (sb.charAt(0) == '0' && sb.length() > 1) {
sb.deleteCharAt(0);
}
return sb.toString();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("1. Faktor: ");
String input1 = scan.next("(0|1)*");
System.out.print("2. Faktor: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Ergebnis: " + multiply(input1, input2));
}
}
You may not use Integer.parseInt but nobody forbid you to implement your own parser:
private static int parseBinaryString(String s) {
int binary = 0;
for (int i = s.length() - 1, c; i >= 0; i--) {
binary <<= 1;
c = s.charAt(i);
if (c == '1') {
binary++;
} else if (c != '0') {
throw new NumberFormatException(s);
}
}
return binary;
}
Which can then be simply used like this in your multiply method:
private static String multiply(String a, String b) {
return Integer.toBinaryString(parseBinaryString(a) * parseBinaryString(b));
}
And if you can't use Integer.toBinaryString you can implement that method yourself:
private static String toBinaryString(int i) {
StringBuilder binary = new StringBuilder();
for (int t = i; t != 0; t >>= 1) {
binary.append((i & t) != 0 ? 1 : 0);
}
return binary.toString();
}
I want to take the following matrix below and rearrange the chars TOAD to ADOT and the rearrange the corresponding columns below to where the char above moved, so for example A moved to col 0 so now VGD should all be in col 0 etc.
TOAD is a separate array by the way! im using that keyword to sort the martrix alphabetically.
//Matrix output and then the code.
T O A D
V V V X
D V G G
D F D V
public String printMatrix(String s [][]){
char key[] = polyCipher.getKeyword().toCharArray();
String keyOut = "";
for(int i=0;i<key.length;i++){
keyOut += key[i] + " ";
}
keyOut += "\n";
for (int i = 0; i < s.length; i++) {
// keyOut += PHRASE_KEY[i] + " ";
for (int j = 0; j < s[i].length; j++) {
keyOut += s[i][j] + " ";
}
keyOut += "\n";
}
return keyOut.toUpperCase();
}
public static String [][] buildMatrix (String translation, String outermarker, String innermarker) {
// outerdelim may be a group of characters
String [] sOuter = translation.split("[" + outermarker + "]");
int size = sOuter.length;
// one dimension of the array has to be known on declaration:
String [][] result = new String [size][size];
int count = 0;
for (String line : sOuter)
{
result [count] = line.split (innermarker);
++count;
}
return result;
}
public void sortArray(){
// do tomorrow
}
public String matrixFormatter(String x){
String resultstr = "";
int i = 0;
while(i < x.length()) {
// If end of string: only add character.
if (i == x.length() - 1) {
resultstr += x.substring(i, i + 1);
} else {
if ( ((i + 1) % 4) == 0) {
resultstr += x.substring(i, i + 1) + "|";
} else {
resultstr += x.substring(i, i + 1) + ",";
}
}
i++;
}
return resultstr;
}
}
I was hoping somebody could help me with with this. I am trying to add a constructor to allow the input of polynomial data from a string in the form 3x^y and put the coefficient, variable, and exponent values into the corresponding variables defined in a class. The constructor I have implemented allows the program to compile, but will freeze when running the application if...
this:
trinomial[0] = new Term (3,'x',2);
is set to:
trinomial[0] = new Term ("3x^y");
Basically, I'm trying to get the defined class to accept both forms of input (string and double/char/exponent formats). Any help with this would be greatly appreciated.
public class TrinomialTest {
static void printTrinomial(Term[] x) {
for (int i = 0; i < x.length; i++) {
//AUTOMATICALLY CALLS TOSTRING() WHEN PRINTLN
System.out.print(x[i]);
}
}
public static void main(String[] args) {
Term[] trinomial = new Term[3];
trinomial[0] = new Term(3, 'x', 2);
trinomial[1] = new Term(12, 'x', 1);
trinomial[2] = new Term(-23, 'x', 0);
printTrinomial(trinomial);
}
}
class Term {
private double coefficient; //the number
private char variable; // the letter
private int exponent;
public Term(double c, char v, int e) {
coefficient = c;
variable = v;
exponent = e;
}
//New Constructor
public Term(String Term) {
String c = "";
String v = "";
String e = "";
int exponentIndex = 0;
exponentIndex = Term.indexOf("^");
if (Term.substring(0, 1).matches("[0-9]")) {
c = Term.substring(0, 1);
v = Term.substring(1, 2);
} else {
c = "0";
v = Term.substring(0, 1);
}
do {
e = Term.substring(exponentIndex, exponentIndex + 1);
} while (Term.indexOf("^") != -1);
coefficient = Double.parseDouble(c);
variable = v.charAt(0);
exponent = Integer.parseInt(e);
}
public String toString() {
int c = (int) coefficient;
if (exponent == 1 && c > 0)
return ("" + "+" + c + variable);
else if (exponent == 1 && c < 0)
return ("" + c + variable);
else if (exponent == 0 && c > 0)
return ("" + "+" + c);
else if (exponent == 0 && c < 0)
return ("" + c);
return ("" + c + variable + "^" + exponent);
}
}
Simple solution:
String term = "32x^33";
String[] tokens = term.split("\\^");
String coeff = tokens[0].substring(0, tokens[0].length()-1);
String var = tokens[0].substring(tokens[0].length()-1, tokens[0].length());
String exp = tokens[1];
System.out.println("coeff = "+coeff+", var = "+var+", exp = "+exp);