I am trying to write a simple code for polynomial multiplication. I think it is logical to take inputs as strings such as "3x^2".
Problem is I don't know what to do with the 'x's in it. How can I turn them into something that can be multiplied? What should the logic be? I am totally new in Java and I really need help.
For example:
String s = "x^2";
String s2 = "3x^5";
//(Multiply them)
result = 3x^7
public static int[] multiply(String term1, String term2)
{
int[] t1 = parse(term1);
int[] t2 = parse(term2);
int[] ret = new int[2];
ret[0] = t1[0] * t2[0];
ret[1] = t1[1] + t2[1];
return ret;
}
public static int[] parse(String term)
{
int pos = term.indexOf("x^");
String coeffStr = term.substring(0, pos);
int coeff = Integer.parseInt(coeffStr);
String powerStr = term.substring(pos + 2);
int power = Integer.parseInt(powerStr);
int[] ret = new int[2];
ret[0] = coeff;
ret[1] = power;
return ret;
}
This will work for multiplying polynomials in the format Ax^n, x^n or Ax. I would put the terms you want to multiply into a List, and then parse the coefficients and powers into a HashMap, then use those to get you get your final result
List<String> terms = new ArrayList<>(Arrays.asList("x^2", "3x^5", "5x"));
Map<Integer,Integer> map = new HashMap<>();
for ( String term : terms ) {
String coefficient = term.split("x")[0].matches("") ? "1" : term.split("x")[0];
String[] exponent = term.split("x");
String power = exponent.length > 1 ? exponent[1].split("\\^")[1] : "1";
map.put(Integer.parseInt(coefficient), Integer.parseInt(power));
}
Integer finalCoefficient = 1;
Integer finalPower = 0;
for ( Integer coefficient : map.keySet() ) {
finalCoefficient *= coefficient;
finalPower += map.get(coefficient);
}
System.out.println(finalCoefficient + "x" + finalPower);
Related
I know how to split decimal values. But I'm little bit confused how to split 31.07 or 71.008 something like this. if I'm using this below code , the value splitted like this 31 and 0.7
I need a Solution to be: 31 and 0.07. How can I solve my problem?
Here java code:
String decimal_value = String.format("%.2f", update_fare);
String[] arr = decimal_value.split("\\.");
if (arr.length == 2) {
int[] intArr = new int[2];
String before_decimal = String.valueOf(intArr[0] = Integer.parseInt(arr[0]));
String after_decimal = String.valueOf(intArr[1] = Integer.parseInt(arr[1]));
fare_tv.setText(String.valueOf(before_decimal));
fare_tv_decimal.setText(String.valueOf(after_decimal));
System.out.println("----------------updated fare intArr[0]---------" + intArr[0]);
System.out.println("----------------updated fare intArr[1]---------" + intArr[1]);
}
if A is your number, for example - A = 31.03,
And you want to split it like 31 and 0.03 into B and C, you can do something like that:
A = 31.03; // your number
B = a%1; // XX.00
C = A-B; // 00.XX
Assuming that you are working only with positive doubles, the following code might help you:
int total = (int)update_fare; //gets the whole part
double rem = update_fare - total; //gets the value after the dot
You can then use a proper formatter to convert them to strings as follows:
String rem_str = String.format("%.2f", rem);
String total_str = String.format("%d", total);
However, be careful of using this technique when dealing with negative numbers. You need to change some parts based on the sign of the value.
Try this
String value = "31.07";
String[] values = value.split("\\.");
if(values.length==2)
{
int[] intArr = new int[2];
String value1 = values[0];
String value2 = "0."+values[1];
fare_tv.setText(String.valueOf(value1));
fare_tv_decimal.setText(String.valueOf(value2));
intArr[0] = Integer.parseInt(value1);
intArr[0] = Integer.parseInt(value2);
}
Try this:
String value = "31.07";
String[] values = value.split("\\.");
if(values.length==2)
{
double[] intArr = new double[2];
String value1 = values[0];
String value2 = "0."+values[1];
fare_tv.setText(String.valueOf(value1));
fare_tv_decimal.setText(String.valueOf(value2));
intArr[0] = Double.parseDouble(value1);
intArr[1] = Double.parseDouble(value2);
System.out.println("----------------updated fare intArr[0]---------" + intArr[0]);
System.out.println("----------------updated fare intArr[1]---------" + intArr[1]);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I need to design an algorithm where each number is encoded to an alphabet, for example:
1=A, 2=B, 3=C...26=Z
Given a set of numbers, I have to translate them to a combination of strings. For example:
123 can be translated to - ABC(123), AW(1 23) and LC(12 3)
Write an algorithm to find the combinations for number - 123123123.
Now here is what I wrote and I find it inefficient because of multiple "for" loops. Is there any better way I can rewrite this algorithm?
public class ValidCombinations {
Map<Integer, String> mapping = new HashMap<Integer, String>();
public void run() {
String s = "123123123";
/*Convert String to int[]*/
char[] cArray = s.toCharArray();
int[] input = new int[cArray.length];
for (int i=0; i<cArray.length; i++) {
input[i] = Character.getNumericValue(cArray[i]);
}
Set<String> output = new HashSet<String>();
for (int i='A'; i<='Z'; i++) {
mapping.put(i - 'A' + 1, String.valueOf((char)i));
}
for (int i=0; i<input.length; i++) {
if (mapping.containsKey(input[i])) {
output.add(precombine(i, input) + mapping.get(input[i]) + postcombine(i, input));
if (i+1<input.length) {
if (mapping.containsKey(input[i]*10 + input[i+1])) {
output.add(precombine(i, input) + mapping.get(input[i]*10 + input[i+1]) + postcombine(i+1, input));
}
}
}
}
System.out.println(output);
}
public String precombine(int i, int[] input) {
String residue="";
for (int m=0; m<i; m++) {
residue += mapping.get(input[m]);
}
return residue;
}
public String postcombine(int i, int[] input) {
String residue="";
for (int k=i+1; k<input.length; k++) {
residue += mapping.get(input[k]);
}
return residue;
}
public static void main(String[] args) {
ValidCombinations v = new ValidCombinations();
v.run();
}
}
For '123' - [ABC, AW, LC]
For '123123123' - [LCABCABC, AWABCABC, ABCAWABC, ABCLCABC, ABCABCLC, ABCABCABC, ABCABCAW]
This problem is crying out for recursion. Here's a quick and dirty implementation that takes the input "number" in as a string and uses substring() to consume the digits. You could adapt it to use numerical methods to get the first (or first two) decimal digits from an integer if you prefer.
If you choose to work directly from an int, it would probably be easier to start at the end (working with the least-significant-digits) than at the beginning -- lastDigit = number % 10; otherDigits = number / 10
public List<String> encodings(String number) {
List<String> out = new ArrayList<>();
addEncodings("", number, out);
return out;
}
private void addEncodings(String prefix, String number, List<String> out) {
if (number.length() == 0) {
out.add(prefix);
} else {
addParsingNDigits(1, prefix, number, out);
addParsingNDigits(2, prefix, number, out);
}
}
private void addParsingNDigits(int digits, String prefix, String number, List<String> out) {
if (number.length() >= digits) {
char encodedChar = parseChars(number, digits);
if (encodedChar >= 'A' && encodedChar <= 'Z') {
addEncodings(prefix + encodedChar, number.substring(digits), out);
}
}
}
private char parseChars(String number, int length) {
int intVal = Integer.parseInt(number.substring(0, length));
return (char) ('A' + intVal - 1);
}
I don't think your solution will find all possible encodings -- I think you need some sort of stack to solve it. The solution above implicitly uses the execution stack, because of recursive method calls. Another solution could explicitly place objects representing "todo" calculations onto a stack data structure in the heap:
private static class StackItem {
public StackItem(String prefix, String number) {
this.prefix = prefix;
this.number = number;
}
public String prefix;
public String number;
}
public List<String> encodings(String number) {
List<String> results = new ArrayList<>();
Stack<StackItem> stack = new Stack<>();
stack.push(new StackItem("", number));
while (!stack.isEmpty()) {
StackItem current = stack.pop();
if (current.number.equals("")) {
results.add(current.prefix);
} else {
addToStackTakingNChars(2, current, stack);
addToStackTakingNChars(1, current, stack);
}
}
return results;
}
private void addToStackTakingNChars(int n, StackItem current, Stack<StackItem> stack) {
if (current.number.length() >= n) {
char c = parseChars(current.number, n);
if (c >= 'A' && c <= 'Z') {
stack.push(new StackItem(current.prefix + c, current.number.substring(n)));
}
}
}
Although "println debugging" is generally a bad habit, it would probably be a good learning exercise to run these examples with some println()s to observe how it works.
I think you could split the String in the middle (recursively), search for all combinations in both substrings and build the cross product. To not miss any combinations we have to also build the cross product for the two substrings you get by splitting in the middle with an offset of one. Something like this:
private static int[] values;
public static final Set<String> solve(String s) {
values = new int[s.length()];
for (int i = 0; i < values.length; i++)
values[i] = s.charAt(i) - '0';
return solve(0, values.length);
}
private static final Set<String> solve(int start, int len) {
Set<String> ret = new HashSet<>();
if (len == 1) {
ret.add("" + ((char)(values[start] - 1 + 'A')));
} else if (len == 2) {
ret.add("" + ((char)(values[start] - 1 + 'A')) +
((char)(values[start + 1] - 1 + 'A')));
int n = values[start] * 10 + values[start + 1];
if (n <= 26)
ret.add("" + ((char)(n - 1 + 'A')));
} else {
int next = start + len / 2;
cross(solve(start, next - start), solve(next, start + len - next), ret);
cross(solve(start, next - start + 1), solve(next + 1, start + len - next - 1), ret);
}
return ret;
}
private static final void cross(Set<String> a, Set<String> b, Set<String> target) {
for (Iterator<String> itr = a.iterator(); itr.hasNext();) {
String s = itr.next();
for (Iterator<String> itr2 = b.iterator(); itr2.hasNext();) {
target.add(s + itr2.next());
}
}
}
Btw. the solution for "123123123" are the following 27 strings: LCABCAW, LCABCLC, ABCLCABC, ABCLCAW, ABCAWLC, AWLCABC, ABCAWAW, ABCAWABC, ABCLCLC, ABCABCABC, LCAWLC, LCAWAW, AWABCLC, LCAWABC, AWABCAW, LCLCAW, AWABCABC, LCLCLC, LCLCABC, LCABCABC, AWAWLC, AWAWABC, AWAWAW, ABCABCLC, ABCABCAW, AWLCAW, AWLCLC.
Why not just use the ascii value?
All you would need to do would be to convert the number to a String Integer.toString(num) and then run a for-loop through the .length() of the String and pull the .charAt(i) from the String convert that back to an int and then add 16 to it. Then you would just need to cast to a char. like so:
int a = 123;
String str = Integer.toString(a);
char[] chars = new char[str.length()];
for(int i=0,n=str.length();i<n;i++){
chars[i] = (char)(str.charAt(i)+16);
}
String message = String.valueOf(chars);
This problem can be done in o(fib(n+2)) time with a standard DP algorithm.
We have exactly n sub problems and button up we can solve each problem in o(fib(i)) time.
Summing the series gives fib (n+2).
If you consider the question carefullly you see that it is a fibunacci series.
I took a standart code and just changed it a bit to fit our conditions.
The space is obviously bound to the size of all solutions o(fib(n)).
Consider this code:
Map<Integer, String> mapping = new HashMap<Integer, String>();
List<String > iterative_fib_sequence(int input) {
int length = Math.floor(Math.log10(Math.abs(input))) + 1;
if (length <= 1)
{
if (length==0)
{
return "";
}
else//input is a-j
{
return mapping.get(input);
}
}
List<String> b = new List<String>();
List<String> a = new List<String>(mapping.get(input.substring(0,0));
List<String> c = new List<String>();
for (int i = 1; i < length; ++i)
{
int dig2Prefix = input.substring(i-1, i); //Get a letter with 2 digit (k-z)
if (mapping.contains(dig2Prefix))
{
String word2Prefix = mapping.get(dig2Prefix);
foreach (String s in b)
{
c.Add(s.append(word2Prefix));
}
}
int dig1Prefix = input.substring(i, i); //Get a letter with 1 digit (a-j)
String word1Prefix = mapping.get(dig1Prefix);
foreach (String s in a)
{
c.Add(s.append(word1Prefix));
}
b = a;
a = c;
c = new List<String>();
}
return a;
}
How to best print 2 float numbers in scientific-notation but with same exponent?
eg: I'd like to print numbers like this:
1.234e-6
11.234e-6
And I would like some function to detect automatically best exponent - that is smaller number always start at first decimal digit and bigger number prints how it must with same exponent.
eg: 0.1 and 100 would print
1.000e-1
1000.000e-1
But even when I ask explicitly for 2 decimal places String.format("%2.3e",11.234e-6) I got 1.123e-5
So far I come up with code bellow. It works as I want. But as you can see it is not exactly short or swift... It would be great if someone would point to some Java native functions which helps me to do it more elegant...
public static String repeat(int count, String with) {
if(count<0){
return "";
}
if(count>1e5){
return "";
}
return new String(new char[count]).replace("\0", with);
}
public static String getFormattedDouble(double num,int posInt,int posFrac){
if(num == 0) return "0"; // correct 0 value to be print only with one 0
String sInt = repeat(posInt,"0");
String sFrac = repeat(posFrac,"0");
String sSing = num<0 ? "" : "+";
DecimalFormat form = new DecimalFormat(sSing+sInt+"."+sFrac+"E0");
String s = form.format(num);
s = s.replace("E","e"); // I really thing capital E looks ugly
return s;
}
public static String[] get2doublesSameExp(double a, double b){
String[] s = new String[2];
int expA;
if(a == 0) expA = 0;
else expA = (int)Math.floor(Math.log10(Math.abs(a)));
int expB;
if(b == 0) expB = 0;
else expB = (int)Math.floor(Math.log10(Math.abs(b)));
double expDif = Math.abs((double)expA-(double)expB);
int fractPos = 3;
if(expDif > 4) fractPos = 1; // too big exponent difference reduce fraction digits
if(expDif > 6){
// too big exponent difference print it normally it will be nicer
s[0] = String.format("%1.3e",a);
s[1] = String.format("%1.3e",b);
return s;
}
int minExp = Math.min(expA,expB) - 1;
s[0] = getFormattedDouble(a, expA - minExp, fractPos );
s[1] = getFormattedDouble(b, expB - minExp, fractPos );
// just text right justification
String rightJust = repeat((int)expDif," ");
int justIdx = expA < expB ? 0 : 1;
s[justIdx] = rightJust + s[justIdx];
return s;
}
String[] s = get2doublesSameExp(1.234e-6,11.234e-6);
I have written the following code:
public String alphabets = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#$%";
public Integer findBase(String input) {
int i = 0;
Integer base = 0;
Integer temp = 0;
while (i != input.length()) {
temp = alphabets.indexOf(input.charAt(i)) + 1;
if (temp > base) {
base = temp;
}
i ++;
}
public String convert(String input, Integer to_base, Integer from_base) {
int i;
Long base_ten = 0L;
Integer input_base = 0;
// If specified, then consider that base as input from base, or else,
// calculate the base of the number
if (from_base == 0) {
input_base = findBase(input);
} else {
input_base = from_base;
}
Integer power = 0;
Double temp_power = 0.0;
while (!input.equals("")) {
temp_power = Math.pow(input_base, power);
base_ten = base_ten + alphabets.indexOf(input.charAt(input.length() - 1)) * temp_power.intValue();
input = input.substring(0, input.length() - 1);
power = power + 1;
}
Long rem = 0L;
String result = "";
while (base_ten != 0L) {
rem = base_ten % to_base;
base_ten = base_ten / to_base;
result = result + alphabets.charAt(rem.intValue());
}
String reverse = new StringBuffer(result).reverse().toString();
return reverse;
}
Using the above code, it is possible to convert strings like say "suchin" (Base 31) to other bases. But whenever I use something larger, like say "suchind", I get an exception at the following line in above code:
result = result + alphabets.charAt(rem.intValue());
saying that the index is -1. When I dug a little deeper, I felt that rem.intValue() is somehow going negative (-1) for some large values. Not sure how to get this solved. Is there a way of converting between bases for large numbers in java?
BigInteger version of code is below:
public String convert(String input, BigInteger to_base, BigInteger from_base) {
int i;
BigInteger base_ten = new BigInteger("0");
BigInteger input_base = new BigInteger("0");
if (from_base.equals(BigInteger.valueOf(0))) {
input_base = BigInteger.valueOf(findBase(input));
} else {
input_base = from_base;
}
BigInteger power = new BigInteger("0");
BigInteger temp_power = new BigInteger("0");
BigInteger to_add = new BigInteger("0");
while (!input.equals("")) {
temp_power = input_base.pow(power.intValue());
to_add = BigInteger.valueOf(alphabets.indexOf(input.charAt(input.length() - 1)));
to_add = to_add.multiply(temp_power);
base_ten = base_ten.add(to_add);
input = input.substring(0, input.length() - 1);
power = power.add(BigInteger.valueOf(1));
}
BigInteger rem = new BigInteger("0");
String result = "";
while (!base_ten.equals(BigInteger.valueOf(0))) {
rem = base_ten.remainder(to_base);
base_ten = base_ten.divide(to_base);
result = result + alphabets.charAt(rem.intValue());
}
String reverse = new StringBuffer(result).reverse().toString();
return reverse;
}
The above code works fine now. Earlier I had done the following:
while( base_ten != BigInteger.valueOf(0)) {
Which was causing infinite loop, as apparently that was not the way to compare in BigIntegers :)
I was recently asked this question in an interview(3+ experience). No String function allowed including String.length. I was given 5 minutes to write the complete code.
Example
String ="abcfedbca"
subString = "fed"
Actually i asked him to elaborate a little more to which he said "it's easy java implementation what should i elaborate" and on basis of this question only he said my core java is very weak.
Note that you're question is not very precise and hence your requirements are not very clear.
Simple way :
String st = new StringBuilder(s).substring(3,6);
Or you can directly construct the new String using reflection to get the char array:
public static String substring(String s, int from, int to){
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
char [] tab = (char[])f.get(s);
f.setAccessible(false);
return new String(tab, from, to - from);
}
Those can also be options (note that it works only if the original String fits an hexadecimal format) :
String s ="abcfedbca";
BigInteger bi = new BigInteger(s, 16);
bi = bi.and(new BigInteger("16699392")); //0xfed000 in hexa
bi = bi.shiftRight(12);
System.out.println(bi.toString(16));
Or more simple :
String s ="abcfedbca";
System.out.println(Integer.toHexString((int)(Long.parseLong(s, 16) & 16699392) >> 12));
If you want a more general method, this one might suits your case :
public static void main(String [] args){
String s ="abcfedbca";
System.out.println(substring(s, 2, 5, 9));
}
public static String substring (String s, int from, int to, int length){
long shiftLeft = 0;
long shiftRight = (length - to - 1) * 4;
for(int i = 0; i < to - from - 1; i++){
shiftLeft += 15;
shiftLeft = shiftLeft << 4;
}
shiftLeft += 15;
return Long.toHexString((Long.parseLong(s, 16) & (shiftLeft << shiftRight)) >> shiftRight);
}
You can use a StringBuilder and call substring on it. Don't know whether that'd be allowed.
Here is the other way (although I am ashamed of this solution):
String str = "abcfedbca";
int from = 3, length = 3;
java.lang.reflect.Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
char[] value = (char[]) valueField.get(str);
char[] sub = new char[length];
System.arraycopy(value, from, sub, 0, length);
String substring = new String(sub);
String buff = "abcfedbca";
System.out.println("substring is = " + buff.substring(3, 6));
how about this?
StringBuilder seems like a cheat to me since it's based on strings. I'd argue that you have to go down to byte primitives to meet the spirit of the test. Of course this calls getBytes which is technically a String function, so that breaks it also.
public static void main(String[] args) {
String full ="abcfedbca";
String desiredsubString = "fed";
byte[] fullByte = full.getBytes();
byte[] desiredByte = desiredsubString.getBytes();
byte[] foundStorage = new byte[desiredByte.length];
boolean foundStart = false;
int inserted = 0;
for (byte b : fullByte) {
if ( !foundStart && (b == desiredByte[0]) )
{
foundStorage[0] = b;
inserted++;
foundStart = true;
}
else if (foundStart && (inserted < foundStorage.length))
{
foundStorage[inserted] = b;
inserted++;
if ( inserted >= foundStorage.length )
{
break;
}
}
}
System.out.println("These should be equal: " + new String(desiredByte).equals(new String(foundStorage)));
}
Maybe:
String value = "abcfedbca";
BigInteger bi = new BigInteger(value, 16);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
bi = bi.divide(BigInteger.TEN);
int val = bi.subtract(BigInteger.valueOf(535)).intValue();
String hex = Integer.toHexString(val);
System.out.println(hex);
Output: fed
How about using a JPasswordField to get the chars:
private static String substring(String str, int beginIndex, int endIndex) {
return new String(new JPasswordField(str).getPassword(), beginIndex, endIndex - beginIndex);
}
And the String constructor is not a String method, isn't it?
public String submethod(String data, int firstindex, int lastindex) {
char[] chars=data.toCharArray();
char[]charnew= new char [lastindex];
for(int i=firstindex; i< lastindex;i++) {
charnew[i]=chars[i];
}
return new String(charnew);
}