Algorithm to solve unfinished equations in Java - java

I am trying to write a program that when given unfinished equations will output the lowest digit that will work or -1 if none will work. I have all my input set up but at this stage I am not sure how to continue.
Example inputs are: 1+1=?, 123*45?=5?088, -5?*-1=5, 19--45=5?, ??*??=302?
Any tips on how to tackle this would be appreciated.
import java.util.Scanner;
import java.util.regex.*;
public class Runes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int caseNo = sc.nextInt();
for (int c = 0; c < caseNo; c++) {
String input = sc.next();
String re1="([-]?[0-9?]+)"; // -int1 or int1
String re2="([+\\-*])"; //+ or - or *
String re3="([-]?[0-9?]+)"; // -int2 or int2
String re4="(=)"; // Equals
String re5="([-]?[0-9?]+)"; // -int3 or int3
Pattern pattern = Pattern.compile(re1+re2+re3+re4+re5,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String int1 = matcher.group(1);
String op1 = matcher.group(2);
String int2 = matcher.group(3);
String op2 = matcher.group(4);
String int3 = matcher.group(5);
System.out.println(int1 + " " + op1 + " " + int2 + " " + op2 + " " + int3);
}
}
}
}

Here's one way to create your Java application.
Create an Integer index array with a value for each question mark. In other words, if there are 5 question marks, your Integer index array has 5 elements.
Loop through the Integer index array. In other words, for 5 question marks, the values ought to be (see layout below).
Looping through the Integer index array, substitute the index values for the question marks.
Check to see if the string is a valid equation. If so, save it in a List.
When the looping is finished, print the List values.
Here's the layout for point 2.
0, 0, 0, 0, 0
1, 0, 0, 0, 0
...
9, 0, 0, 0, 0
0, 1, 0, 0, 0
...
9, 9, 9, 9, 9
I used your input examples to create this output. I added spaces to the equations to make them easier to read. I manually formatted this output to fit on the screen
1 + 1 = ? --> 1 + 1 = 2
123 * 45? = 5?088 --> 123 * 456 = 56088
-5? * -1 = 5 --> No equation exists
19 - -45 = 5? --> No equation exists
?? * ?? = 302? --> 57 * 53 = 3021 53 * 57 = 3021 72 * 42 = 3024
42 * 72 = 3024 48 * 63 = 3024 56 * 54 = 3024
36 * 84 = 3024 84 * 36 = 3024 54 * 56 = 3024
63 * 48 = 3024 55 * 55 = 3025 89 * 34 = 3026
34 * 89 = 3026

Related

How to calculate byte as 16 bits in Java

I have a value of 2 bytes. 9C 80
Among them
2 bits in the first byte are the mode values ​​as shown in the picture below,
The next 12bit is the number of steps.
This way, you have a total of 2 bytes.
But I don't know how to calculate it in 16 bits.
The result of extracting 12 bits using 9C 80 bytes is 114.
This is wrong.
The correct answer is 39 steps.
39 steps
Can it come out of the 12bit of the 9C 80?
Help.
Below is the bit position of the byte values ​​passed from c.
struct ble_sync_sport_item
{
uint16_t mode : 2;
uint16_t sport_count : 12;
uint16_t active_time : 4;
uint16_t calories : 10;
uint16_t distance : 12;
};
This is the android code I made to calculate the byte value.
private int bytesToInt(byte[] bytes , String value) {
int binaryToDecimal = 0;
int binaryToDecimal2 = 0;
int binaryToDecimal3 = 0;
int result = 0;
String s1 = "";
String s2 = "";
String s3 = "";
byteLog("5bytes ",bytes);
switch (value) {
case "ACT_STEP":
s1 = String.format("%8s", Integer.toBinaryString(bytes[0] & 0xFF)).replace(' ', '0');
s2 = String.format("%8s", Integer.toBinaryString(bytes[1] & 0xFF)).replace(' ', '0');
Log.d("FASDF ", "s1 == " + s1 + " s2 = " + s2 );
s1 = s1.substring(2, 8).concat(s2.substring(0,2));
s2 = s2.substring(2, 8).concat("00");
Log.d("FASDF ", "s1 == " + s1 + " s2 = " + s2 );
binaryToDecimal = Integer.parseInt(s1, 2);
binaryToDecimal2 = Integer.parseInt(s2, 2);
result = (int) ((int) binaryToDecimal) + ((int) binaryToDecimal2 << 8);
Log.d(tag,"result_step = " + result);
break;
This is the logarithm of the result I calculated.
39 should come out
114 came out.
As the result
The mode value of binary number 10 and
I want to get the sprot_count value of 100111 binary.
D/FASDF: s1 == 10011100 = 0x9C ,, s2 = 10000000 = 0x80
D/SevenHL5ConnectSync: result_step = 114
This could be an issue with bit order in the byte. Please check Big Endian vs Little Endian mode. The result you're getting 114 (1110010) is just the opposite of 39 (0100111) that is a reverse order in the bit.

3D multidimensional array output not matching initialization data

I've been working on a code segment that flattens a 3D dimensional array, however I've encountered a rather baffling situation with the following code.
The array used is initialized as follows:
int array[][][] = {
{
{000, 001, 002},
{010, 011, 012},
{020, 021, 022},
},
{
{100, 101, 102},
{110, 111, 112},
{120, 121, 122},
},
{
{200, 201, 202},
{210, 211, 212},
{220, 221, 222},
}
};
And then outputting the array through a basic nested for loop.
The output is formatted through a custom DecimalFormat that allows me to print the floating 0's.
DecimalFormat xFormat = new DecimalFormat("000");
for(int z = 0; z < array[0].length; z++) {
for(int y = 0; y < array[1].length; y++) {
for(int x = 0; x < array[2].length; x++) {
System.out.println("I = "+ i + " Element at i = " + xFormat.format(array[z][y][x]));
}
}
}
This loop is used immediately after the initialization of the array, yet the output is what completely baffles me
I = 0 Element at i = 000
I = 1 Element at i = 001
I = 2 Element at i = 002
I = 3 Element at i = 008 <------- =/= 010
I = 4 Element at i = 009 <------- =/= 011
I = 5 Element at i = 010 <------- =/= 012
I = 6 Element at i = 016 <------- =/= 020
I = 7 Element at i = 017 <------- =/= 021
I = 8 Element at i = 018 <------- =/= 022
I = 9 Element at i = 100
I = 10 Element at i = 101
I = 11 Element at i = 102
I = 12 Element at i = 110
I = 13 Element at i = 111
I = 14 Element at i = 112
I = 15 Element at i = 120
I = 16 Element at i = 121
I = 17 Element at i = 122
I = 18 Element at i = 200
I = 19 Element at i = 201
I = 20 Element at i = 202
I = 21 Element at i = 210
I = 22 Element at i = 211
I = 23 Element at i = 212
I = 24 Element at i = 220
I = 25 Element at i = 221
I = 26 Element at i = 222
This seems rather elementary to me, yet I'm not sure what I'm missing at this point. The majority of the loop prints out right, yet it's this part in the middle that's not outputting correctly, and searches on multidimensional array issues haven't yielded much in the way of solutions
Its because 0* (0 prefix) is used to store octal numbers (base8)
{000, 001, 002}, //0,1,2
{010, 011, 012}, //8,9,10
{020, 021, 022}, //16,17,18
That swhy 010 translates to 8 decimal, 11 to 9 etc etc. Just like 0x*is used to store hexadecimals, aod ***b to store binaries. DecimalFormat gets value of octal 010, that equals to 9, and this is what you are getting in the output.
Rest of the values are decimals, because they do not start with 0. You can prefix every other walue with 0 and see what will happen.

java multiplying numbers get from the input

I have a problem with multiplying numbers.
From my input I get:
number of digits of the number
how many numbers i have to multiply
Example: if I get from the input 3,2 it means I need to multiply all two digits numbers three times
For now I got some code which works only when I get two numbers with two digits.
How can I implement a method which multiplies as many numbers as user need? I made only this kind of method which prints number of digits got from the input. I can handle method which can multiply them as many times as variable multiplier says...
public static void test(int digits, int multiplier) {
int number = 0;
int result = 0;
ArrayList<String> numbers = new ArrayList<String>();
number = (int) Math.pow(10, digits);
for (int i = (int) (Math.pow(10, digits - 1)); i < number; i++) {
System.out.println(i);
for (int j = (int) (Math.pow(10, digits - 1)); j < number; j++) {
result = j * i;
}
}
System.out.println(number);
}
Sample Input And Output
If number of digits = 2, number of times = 2
We need to multiply all 2 digit numbers 10, 11, 12 .... 99 two times.
10 * 10
10 * 11
.
.
10 * 99
.
.
.
99 * 98
99 * 98
In the same way, if the no of digits is 2, and the no of times is 3
10 * 10 * 10
10 * 10 * 11
.
.
10 * 99 * 99
.
.
.
99 * 99 * 98
99 * 99 * 99
I would not use recursion, but use a for loop in combination with the Java8 streaming API.
The code example:
import java.util.stream.IntStream;
public class Multiplier {
private final int digits;
public Multiplier(int digits) {
this.digits = digits;
}
/**
* #param multiplificationSteps
* #return a stream, containing all numbers of the given digits, each multiplied several times with each other
*
* digits=1 with multiplificationSteps=1 => output [1;9]
* digits=2 with multiplificationSteps=1 => output [10;99]
* digits=1 with multiplificationSteps=2 => output [1;9] & [2;19] & ... & [9;81]
*/
public IntStream createFullStream(int multiplificationSteps) {
IntStream intStream = makeIntStream();
for (int i = 1; i < multiplificationSteps; i++)
intStream = intStream.flatMap(this::multiplyStream);
return intStream;
}
/**
* #param input a multiplier
* #return the stream, having each number multiplied by the multiplier
*
* input [1;9] and 1 => output [1;9]
* input [1;9] and 2 => output [2;18]
* input [10;99] and 3 => output [30;297]
*/
private IntStream multiplyStream(int input) {
return makeIntStream().map(k -> input * k);
}
/**
* #return a stream of all numbers with the given number of digits
*
* input 1 => output [1;9]
* input 2 => output [10;99]
* input 3 => output [100;999]
*/
private IntStream makeIntStream() {
int startNumber = (int) Math.pow(10, digits - 1);
int endNumber = (int) Math.pow(10, digits);
return IntStream.range(startNumber, endNumber);
}
public static void main(String[] args) {
new Multiplier(1).createFullStream(2).forEach(System.out::println);
}
}
sample input and outputs
For the input 1,1 it outputs:
1
2
3
4
5
6
7
8
9
For 1,2 it outputs:
1
2
3
4
5
6
7
8
9
2
4
6
8
10
12
14
16
18
3
6
9
12
15
18
21
24
27
4
8
12
16
20
24
28
32
36
5
10
15
20
25
30
35
40
45
6
12
18
24
30
36
42
48
54
7
14
21
28
35
42
49
56
63
8
16
24
32
40
48
56
64
72
9
18
27
36
45
54
63
72
81
it also will work without Java8
import java.util.*;
public class PlainOldMultiplier {
private final int digits;
public PlainOldMultiplier(int digits) {
this.digits = digits;
}
public void printAllMultipliedNumbers(int multiplicationSteps) {
// define the result
Collection<Integer> numbers = new ArrayList<>();
numbers.add(1);// multiply by 1 in first iteration
// foreach multiplicationStep once multiply all existing stuff with [start;end[
for (int multiplicationStepCount = 0; multiplicationStepCount < multiplicationSteps; multiplicationStepCount++) {
numbers = multiplyEverything(numbers);
}
// output numbers to console
for (Integer number : numbers) {
System.out.println(number);
}
}
private Collection<Integer> multiplyEverything(Collection<Integer> numbersOfPreviousIteration) {
Collection<Integer> result = new ArrayList<>();
// define start and end by taking account "digits"
int start = (int) Math.pow(10, digits-1);
int end = (int) Math.pow(10, digits);
// foreach number within [start;end[ multiply existing stuff
for (int number = start; number < end; number++) {
for (Integer numberOfPreviousIteration : numbersOfPreviousIteration) {
result.add(numberOfPreviousIteration * number);
}
}
return result;
}
public static void main(String[] args) {
new PlainOldMultiplier(1).printAllMultipliedNumbers(1); // outputs [1;9]
new PlainOldMultiplier(2).printAllMultipliedNumbers(1); // outputs [10;99]
new PlainOldMultiplier(1).printAllMultipliedNumbers(2); // outputs [1;9] & [2;18] & ... & [9;81]
}
}

Subtract elements in an array

I have an array with this values 80 82 84 90 94 is it possible to subtract the values so the output could be 0 2 2 6 4?
I´ve edited the question:Now I want to use this in an android cursor adapter but I´m getting index out of bounds when it reaches the calculation of the difference.
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
double weight = cursor.getDouble(cursor
.getColumnIndex(DbHelper.ENTRY_USER_WEIGHT));
int count=cursor.getCount();
Double[] input = new Double[count];
// Obtaining the number of records
System.out.println("number of records "+input.length);
// Array for storing differences
double[] difference= new double[count ];
difference [0] = 0; // First record difference is 0 only
int i;
// Looping number of records times
for( i=0; i<count-1 ;i++)
{
input[i]=weight;
System.out.println("i value"+i);
System. out.println(""+input[i]);
// Difference = next record - current record
difference [i]= input [i+1] - input[i];
// System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i]);
}
// Setting the input array.
int input[]= {80, 82, 84, 90, 94};
// Obtaining the number of records
int noOfRecords = input.length;
// Array for storing differences
double[] difference= new double[noOfRecords ];
difference [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecords -1 ;i++)
{
// Difference = next record - current record
difference [i+1]= input [i+1] - input[i];
System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i+1]);
}
System.out.println("My final difference array Output is : "+java.util.Arrays.toString( difference ));
OUTPUT:
Difference between 82 and 80 is : 2.0
Difference between 84 and 82 is : 2.0
Difference between 90 and 84 is : 6.0
Difference between 94 and 90 is : 4.0
My final difference array Output is : [0.0, 2.0, 2.0, 6.0, 4.0]
If you replace double[] difference = new double[noOfRecords ]; by
int [] difference = new int [noOfRecords];
You get an output exactly as you wanted :
Difference between 82 and 80 is : 2
Difference between 84 and 82 is : 2
Difference between 90 and 84 is : 6
Difference between 94 and 90 is : 4
My difference array Output is : [0, 2, 2, 6, 4]
Logic:
for array Arr[] = {80 82 84 90 94}
Required output = {0,2,2,6,4}
Sol:
output[0] = 0;
for( i=1;i<cursor.getCount();i++)
{
output[i] = Arr[i]-Arr[i-1];
}
Note that the output array elements are obtained by subtracting current index element with the element at previous index.
Example 82-80 =2, 84-82=2, 90-84=6 and 94-90=4
You can subtract a number from its next number.
int[] numbers={80, 82, 84, 90, 94};
for (int i = 0; i < numbers.length; i++) {
if(i < numbers.length - 1)
System.out.println(numbers[i + 1] - numbers[i]);
}
}
Output-
2
2
6
4

Formatting output in Java

I want to format the numbers so that it gets displayed in proper format. At the moment 1-12 left side is displaying correctly apart from 1 because it has moved into another space due to pushing the 8 into the format.
The Wrong outcome is shown below... The (-) act as spaces on here because I cant attach an image.
--1 * 8 = -8
-2 * 8 = 16
-3 * 8 = 24
-4 * 8 = 32
-5 * 8 = 40
-6 * 8 = 48
-7 * 8 = 56
-8 * 8 = 64
-9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96
The outcome I want is shown below... The (-) act as spaces on here because I cant attach an image.
--1 * 8 = --8
--2 * 8 = 16
--3 * 8 = 24
--4 * 8 = 32
--5 * 8 = 40
--6 * 8 = 48
--7 * 8 = 56
--8 * 8 = 64
--9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96
I appreciate if anyone can help me with this... has been driving me insane.
Here is my code so far:
public class Main {
public static void main(String [] args) {
int end_value = 13;
int result = 0;
System.out.print("Enter a Number:");
int num_input = BIO.getInt();
for (int numberLoop = 1; numberLoop < end_value; numberLoop++)
{
result = numberLoop * num_input;
System.out.printf("%11s\n", numberLoop + " * " + num_input +
" = " + result);
}
}
}
You should apply formatting on individual elements : -
System.out.format("%3d * %4d = %5d\n", numberLoop, num_input, result);
And you should use %d as you are printing integers..
%3d will be replaced by numberLoop.
%4d will be replaced by num_input
%5d will be replaced by result
And you will get the output like: -
numberLoop(3 spaces) * num_input(4 spaces) = result(5 spaces)
%3d is for right justification.. and %-3d is for left justification.. You can use either of them..
You can also store your formatted string into a String variable by using String.format(), and you can later print that string variable: -
String result = String.format("%3d * %4d = %5d\n", numberLoop, num_input, result)
NOTE: - For more formatting options, you can go through documentation of Formatter class..

Categories