I want to calculate the coefficients of x^i(and the last number) resulted from calculating (x+i1)*(x+i2)*....*(x+in), where in is integer.
Having for instance, (x-1)(x-3)=x^2-4x+3, I calculate the coefficients like this:
x^2's is always 1
x's is i1+i2
and the last number is `i1*i2`
The problem comes when I have >2 parenthesis. I will get (grade 2 poly)*( grade 1 poly) and the algorithm that I described doesn't work, because there will be 3 coef. in the first parenthesis and my algorithm works only for 2. Basicly, I am looking for a generalization. What algorithm can I use, or is there any Java library or function to use?
the easiest way to do this is to repeatedly multiply by each additional term.
assuming you have a double[] coe where coe[j] is the ij in your example and you have a term where in=nextTerm:
double[] multiply(double[] coe, double nextTerm){
double[] product=Arrays.copyof(coe,coe.length+1);
for(int i=0;i<coe.length;++i)
product[i+1]+=nextTerm*coe[i]
return product;
}
with some modifications this can be used for terms of the form ax+b.
Did it after a few hours of hard work. Time to get a beer. Here is the code, feel free to use it.
private static int[] S_desfaparanteze(int[] poli) {
int size = poli.length;
List<Integer> rez = new ArrayList<>();
List<Integer> rezc = new ArrayList<>();
// rez.add(1); adauga 1 in coada
//rez.set(0, 2); pune 2 pe pozitia 0
//rez.size() dimensiunea
//rez.get(1) afiseaza elementul pe pozitia 1
//pentru fiecare paranteza aka element al lui poli
for (int i = 0; i < size; i++) {
//pas curent
//adaug un 0 la sfarsit
rez.add(0);
//fac o copie a vectorului rezultat
rezc = new ArrayList(rez);
/*System.out.println("rez initial");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc initial");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
/*System.out.println("primul element: " + rez.get(0));
System.out.println("primul element in copie: " + rezc.get(0));*/
//primul element e calculat diferit
rezc.set(0, rez.get(0) - poli[i]);
/*System.out.println("rez dupa calcularea primului element");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc dupa calcularea primului element");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
//calculez si restul elementelor
for (int j = 1; j < rez.size(); j++) {
//System.out.println("pe" + j + "pun" + rez.get(j) + "+" + rez.get(j - 1) + "*" + (-poli[i]));
rezc.set(j, rez.get(j) + rez.get(j - 1) * (-poli[i]));
}
//copii vectorul
rez = rezc;
/*System.out.println("la sfarsitul fiecarui pas, REZ");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("---------------------");*/
}
/*System.out.println("la final");
for (int s : rez) {
System.out.print(s + " ");
}*/
//convertesc arraylist la array simplu
int[] ret = new int[rez.size() + 1];
for (int j = 0; j < rez.size(); j++) {
ret[j + 1] = rez.get(j);
}
ret[0] = 1;
return ret;
}
Related
Introduction
I'm doing some homework where we are tasked for making a game of finding pairs.
I made a matrix and filled it with letters as such:
Display
----------------
C H F E
G F D D
E C H B
A B G A
Right now I'm currently testing the display method which uses an empty matrix and fills it with the given input (row_1, col_1, row_2, col_2, gameMatrix)
Problem
While creating a "cheat/test function" to test my display method. I encounter some trouble with finding the position of both A's (or any other letter).
This is my try at such method:
Code
public static void PlayMeBoi(String[][] gameMatrix)
{
int row_1 = 0;
int col_1 = 0;
int row_2 = 0;
int col_2 = 0;
for (int i = 0; i < gameMatrix.length; i++)
{
for (int j = 0; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_1 = i;
col_1 = j;
break;
}
}
}
for (int i = (row_1+1); i < gameMatrix.length; i++)
{
for (int j = (col_1+1); j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
Turn(row_1, col_1, row_2, col_2, gameMatrix);
}
Notes about the code
I'm working with String not char
Turn is the function which evaluates if a letter equals a letter (if "A".equals("A"))
The (row_1+1) and (col_1+1) it's my thought at "if I haven't found my letter previously, then the second 'for' will handle the rest of the matrix)
gameMatrix is the matrix where all the letters are loaded
Question
I want to be able to find the position of both "A" or any other letter inside the matrix. As of now, I'm not getting my desired result with my current idea
Feel free to comment about the code as much as you can. I might post it on GitHub later on for those who are interested or find anything useful in it.
Thanks for the interest in this question.
The second for is wrong. let's look at your example matrix:
C H F E
G F D D
E C H B
A B G A
If you're looking for the value D you'll find it first at row = 1 and col = 2. then in the second for you only runs from row = 2 and col = 3 which means in practice you'll iterate only over the right down cells from the position you found, which in this example will result in only 2 cells instead of 9 (marked in *):
C H F E
G F D D
E C H *B*
A B G *A*
So in the second for what you should do is continue the search from the same row and the next column:
for (int i = row_1; i < gameMatrix.length; i++)
{
// In the first row starting from the next cell, in the next rows start
// from column 0
int j = i == row_1 ? col_1 + 1 : 0;
for (; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
if I haven't found my letter previously, then the second 'for' will
handle the rest of the matrix
Correct, but what exactly is the rest of the matrix?
If the 1st A is found in row = 1 and col = 1, is the rest of the matrix every item with indices > 1. This would leave out items with indices (1,2) and (2,1) and (1,3) etc.
There are other issues also.
When you put a break inside a nested loop it only breaks form the nested loop and not the outer.
Here's a solution I came up with, maybe it's not optimal but I think it works:
public static void PlayMeBoi(String[][] gameMatrix) {
int row_1 = -1;
int col_1 = -1;
int row_2 = -1;
int col_2 = -1;
boolean found = false;
for (int i = 0; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 0; j < gameMatrix[0].length; j++) {
if ("A".equals(gameMatrix[i][j])) {
row_1 = i;
col_1 = j;
found = true;
break;
}
}
}
if (!found) {
System.out.println("Not Found");
return;
}
found = false;
for (int i = 1; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 1; j < gameMatrix[0].length; j++) {
if (i * gameMatrix[0].length + j > row_1 * gameMatrix[0].length + col_1) {
if ("A".equals(gameMatrix[i][j])) {
row_2 = i;
col_2 = j;
found = true;
break;
}
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
if (!found) {
System.out.println("Second Not Found");
return;
}
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
}
I'm trying to calculate the sum of the numbers in my pyramid in java. For this, mathematical rule is 2+5+8+9. I mean first row+first number of second row+ second number of third row like that.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
System.out.println(" " + numbers[0]);
System.out.println(" " + numbers[1] + " " + numbers[2]);
System.out.println(" " + numbers[3] + " " + numbers[4] + " " + numbers[5]);
System.out.println("" + numbers[6] + " " + numbers[7] + " " + numbers[8] + " " + numbers[9]);
For example:
2
5 7
1 8 3
6 0 9 4
How can I calculate 2+5+8+9 in Java?
The simplest way of calculating 2+5+8+9 is using Java build-in feature:
int result = 2+5+8+9;
You should construct your pyramid as a 2D array.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int addedElements = 0;
int nextSize = 1;
ArrayList<int[]> pyramid = new ArrayList<>();
while(addedElements< numbers.size()) {
int[] level = new int[nextSize++];
for (int i = 0; i < nextSize - 1; i++) {
level[i] = numbers[addedElements++];
}
}
int result = 0;
//add maximum of each `int[]` in pyramid.
for (int[] array : pyramid) {
int currentMax = array[0];
for (int i = 0; i < array.size(); i++) {
if (array[i] > currentMax) {
currentMax = array[i];
}
result+=currentMax;
}
System.out.println(result);
Try the follwoing code :
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int index = 1;
int number = 2;
int result = numbers[0];
while (index < numbers.length) {
result += numbers[index + number -2];
index += number;
number += 1;
}
System.out.println(result);
But the whole whing would be much easier and clearer if you just put your pyramide into a 2 dimensional array.
int[][] numbers = { {2},
{5,7},
{1,8,3},
{6,0,9,4} };
int result = numbers[0][0];
for (int i = 1; i < numbers.length; i++) {
result += numbers[i][i-1];
}
System.out.println(result);
I'm having trouble with my search method. What I want to do is have my search method print the statement only once. So if my array contains "3" more than once, I only want to print "3 was found." once instead of checking each value and reporting that there is or is not a "3" at that point in the array. How would I do that?
To clarify, this is what I have:
`0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was found.
2 was not found.
2 was not found.`
And this is what I want:
0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was found.
2 was not found.
So this is my complete class. I created a method called initialize that will assign each element in my array a random integer between 0 and 10; a method called print to print out the contents of my array; a method called printStats to find and then print the average, maximum, and minimum value in my array; and a method called search that searches my array (and prints the result) for an integer parameter passed to my method.
Everything works correctly.
public class ArrayLab
{
private int[] array;
public ArrayLab(int numElements)
{
array = new int[numElements];
}
public void initialize()
{
array[0] = (int) (Math.random()*11);
array[1] = (int) (Math.random()*11);
array[2] = (int) (Math.random()*11);
array[3] = (int) (Math.random()*11);
array[4] = (int) (Math.random()*11);
array[5] = (int) (Math.random()*11);
array[6] = (int) (Math.random()*11);
array[7] = (int) (Math.random()*11);
array[8] = (int) (Math.random()*11);
array[9] = (int) (Math.random()*11);
}
public void print() {
System.out.println(array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "," + array[4] + "," + array[5] + "," + array[6] + "," + array[7] + "," + array[8] + "," + array[9]);
System.out.println();
}
public void printStats()
{
double sum = 0;
int max = 0;
int min = 0;
min = array[0];
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
double average = sum/array.length;
System.out.println("Average Value: " + average);
System.out.println("Maximum Value: " + max);
System.out.println("Minimum Value: " + min);
}
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
}
else
{
System.out.println(numChosen + " was not found.");
}
}
}
}
Start using return or break statement to break the loop after you hit the first successful search.
Also, you should not print the Was Not Found every time while iterating the array. You should print it only once in the end when your array gets exhausted completely and search query is not found.
Here is the modified code snippet:
boolean flag = false;
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
flag = true;
break;
}
}
if(!flag) {
System.out.println(numChosen + " was not found.");
}
Alternatively, you can also do the following:
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
Well, you don't need to keep iterating through the loop once you found the number. Also, you want to print "was not found" in a case it didn't find anything, meaning the loop finished without printing anything yet.
So this is how you should implement it:
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
}
In a case it found something, it will print the message and exit the method and never reach the printing of second message. It will only print the second message when the loop is over.
You are displaying results in your public void search(int numChosen) function. In your case, instead of printing every time you encounter a match, put a counter instead, then print once: that counter with the rest of you sentence.
Try this:
public void search(int numChosen)
{
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == numChosen)
count++;
if (count == 0)
System.out.println(numChosen + " was not found.");
else
System.out.println(numChosen + " was found " + count + " times.");
}
I have a group of multidimensional arrays that consist of a food and a price for that food. The user enters foods and their price and these are put in the arrays. I know the arrays are successfully populating from the what the user enters because I have tested it by printing it out. That piece of code is still in my example but can be ignored. But what I need to do is print out the possible combinations of meals that are under a limited amount of money and the meal must have 1 piece of meat, 2 fruits, 3 vegetables, and 1 pasta. I can't figure out how to make it work. I know I need to parse the prices of the food to use them for the math. I appreciate any help.
public static void fillarrays(){
String meatarray [][] = {{meat1,meat2,meat3},{meatprice1,meatprice2,meatprice3}};
String fruitarray [][] = {{fruit1,fruit2,fruit3,fruit4,fruit5,fruit6},{fruitprice1,fruitprice2,fruitprice3,fruitprice4,fruitprice5,fruitprice6}};
String vegetablearray [][] = {{veg1,veg2,veg3,veg4,veg5,veg6,veg7,veg8},{vegprice1,vegprice2,vegprice3,vegprice4,vegprice5,vegprice6,vegprice7,vegprice8}};
String pastaarray [][] = {{pasta1,pasta2,pasta3,pasta4},{pastaprice1,pastaprice2,pastaprice3,pastaprice4}};
System.out.println("Meat");
displayarray(meatarray);
System.out.println("Fruit");
displayarray(fruitarray);
System.out.println("Vegetables");
displayarray(vegetablearray);
System.out.println("Pasta");
displayarray(pastaarray);
}
public static void displayarray(String x[][]){
for(int row=0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
System.out.print(x[row][column] + "\t\t" );
}
System.out.println();
}
}
You can do:
long maxPrice = // ...
for(int m = 0 ; m < meatarray[1].length ; ++m) {
if(meatarray[1][m] <= maxPrice) {
for(int f = 0 ; f < fruitarray[1].length ; ++f) {
if(meatarray[1][m] + fruitarray[1][f] <= maxPrice) {
for(int v = 0 ; v < vegetablearray[1].length ; ++v) {
if(meatarray[1][m] + fruitarray[1][f] + vegetablearray[1][v] <= maxPrice) {
for(int p = 0 ; v < pastaarray[1].length ; ++p) {
if(meatarray[1][m] + fruitarray[1][f] + vegetablearray[1][v]
+ pastaarray[1][p] <= maxPrice) {
System.out.println(meatarray[0][m] + " " + fruitarray[0][f] + " "
+ vegetablearray[0][v] + " " + pastaarray[0][p]);
}
}
}
}
}
}
}
}
I have a question on the method and process of how to look at these generated arrays.
Basically I want to create an array of [a,b,c,(a+b+c)] and as well as a second array of [d,e,f,(d+e+f)] and if the third element in array1 and array2 are the same, display the arrays to strings.
int num = 10;
for(int a = 0; a < num; a++){
for(int b = 0; b < num; b++){
for(int c = 0; c < num; c++){
if(a<=b && b<=c){
arrayOne[0] = a;
arrayOne[1] = b;
arrayOne[2] = c;
arrayOne[3] = (a+b+c);
}
}
}
}
for(int d = 0; d < num; e++){
for(int e = 0; e < num; e++){
for(int f = 0; f < num; f++){
if(d<=e && e<=f){
arrayTwo[0] = d;
arrayTwo[1] = e;
arrayTwo[2] = f;
arrayTwo[3] = (f -(d+e));
}
}
}
}
as you can see I am beyond stump.I am not quite sure where i can get each iteration of the arrays and compare the values by matching the sums in each array and as well as displaying the respective array they are in. Thank you all in advanced.
If I understand your question correctly if a=1, b=3, c=4 and d=2, e=3, f=3 you'd like to print something along the lines of 1 + 3 + 4 = 8 = 2 + 3 + 3. First, what you're doing right now is creating two arrays like Floris described in the comment. What you want to do is store all the values in one array of arrays, as follows:
int max; \\ To determine the value of max see the edit below.
int array[][] = new int[max][num];
int index = 0;
for (int a=0; a < num; a++) {
for (int b=a; b < num; b++) {
for (int c=b; c < num; c++) {
array[index][0] = a;
array[index][1] = b;
array[index][2] = c;
array[index][3] = a + b + c;
index++;
}
}
}
for (int i = 0; i < max; i++) {
for (int j = i; j < max; j++) {
if (array[i][3] == array[j][3]) {
string outString = array[i][0] + " + " + array[i][1] + " + " + array[i][2] + " = " + array[i][3] + " = " + array[j][0] + " + " + array[j][1] + " + " + array[i][2];
System.out.println(outString);
}
}
}
You can see that I improved performance by starting b from a and c from b since you are throw out all the values where b < a or c < b. This also should eliminate the need for your if statement (I say should only because I haven't tested this). I needed to use an independent index due to the complexities of the triple nested loop.
Edit 2: Ignore me. I did the combinatorics wrong. Let An,k be the number of unordered sets of length k having elements in [n] (this will achieve what you desire). Then An,k = An-1,k + An,k-1. We know that An,1 = n (since the values are 0, 1, 2, 3, 4, ..., n), and A1,n = 1 (since the only value can be 11111...1 n times). In this case we are interested in n= num and k = 3 , so plugging in the values we get
A_num,3 = A_num-1,3 + A_num,2
Apply the equation recursively until you come to an answer. For example, if num is 5:
A_5,3 = A_4,3 + A_5,2
= A_3,3 + A_4,2 + A_4,2 + A_5,1
= A_3,3 + 2(A_4,2) + 5
= A_2,3 + A_3,2 + 2(A_3,2) + 2(A_4,1) + 5
= A_2,3 + 3(A_3,2) + 2(4) + 5
= A_1,3 + A_2,2 + 3(A_2,2) + 3(A_3,1) + 2(4) + 5
= 1 + 4(A_2,2) + 3(3) + 2(4) + 5
= 1 + 4(A_1,2) + 4(A_2,1) + 3(3) + 2(4) + 5
= 1 + 4(1) + 4(2) + 3(3) + 2(4) + 5
= 5(1) + 4(2) + 3(3) + 2(4) + 5
It looks like this may simplify to (num + (num - 1)(2) + (num - 2)(3) + ... + (2)(num - 1) + num) which is binomial(num, num) but I haven't done the work to say for sure.
int givenNumber = 10;
int []arrayOne = new int [4];
int []arrayTwo = new int [4];
int count = 0;
for ( int i = 0; i < givenNumber; i ++)
{
for ( int x = 0; x < givenNumber; x ++ )
{
for ( int a = 0; a < givenNumber; a++ ){
arrayOne[0] = (int)(a * java.lang.Math.random() + x);
arrayOne[1] = (int)(a * java.lang.Math.random() + x);
arrayOne[2] = (int)(a * java.lang.Math.random() + x);
arrayOne[3] = (int)(arrayOne[0]+arrayOne[1]+arrayOne[2]);
}
for ( int b = 0; b < givenNumber; b++ ){
arrayTwo[0] = (int)(b * java.lang.Math.random() + x);
arrayTwo[1] = (int)(b * java.lang.Math.random() + x);
arrayTwo[2] = (int)(b * java.lang.Math.random() + x);
arrayTwo[3] = (int)(arrayTwo[0]+arrayTwo[1]+arrayTwo[2]);
}
if (arrayOne[3] == arrayTwo[3])
{
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayOne[a] + " + ");
} System.out.print(arrayOne[2] + " = " + arrayOne[3] + " = ");
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayTwo[a] + " + ");
} System.out.print(arrayTwo[2]);
System.out.println("\n");
count += 1;
}
}
}
if (count == 0)
System.out.println(
"\nOops! you dont have a match...\n" +
"Please try running the program again.\n");