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);
Related
So I'm new to Java and I'm trying a different solution for Project Euler Problem 8. In this I have used BigInteger class datatype to store the 1000-digit number but I'm not able to traverse the particular values at any index or multiply it like I'm trying. Although I was able to do it with String, I want to try this method. It would be a great help.
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class newexp{
public static void main(String[] args) {
BigInteger myBigInteger = new BigInteger(
"73167176531330624919225119674426574742355349194934\n" +
"96983520312774506326239578318016984801869478851843\n" +
"85861560789112949495459501737958331952853208805511\n" +
"12540698747158523863050715693290963295227443043557\n" +
"66896648950445244523161731856403098711121722383113\n" +
"62229893423380308135336276614282806444486645238749\n" +
"30358907296290491560440772390713810515859307960866\n" +
"70172427121883998797908792274921901699720888093776\n" +
"65727333001053367881220235421809751254540594752243\n" +
"52584907711670556013604839586446706324415722155397\n" +
"53697817977846174064955149290862569321978468622482\n" +
"83972241375657056057490261407972968652414535100474\n" +
"82166370484403199890008895243450658541227588666881\n" +
"16427171479924442928230863465674813919123162824586\n" +
"17866458359124566529476545682848912883142607690042\n" +
"24219022671055626321111109370544217506941658960408\n" +
"07198403850962455444362981230987879927244284909188\n" +
"84580156166097919133875499200524063689912560717606\n" +
"05886116467109405077541002256983155200055935729725\n" +
"71636269561882670428252483600823257530420752963450\n" +
"\n");
long s = 0;
int n = 1000;
long maxval = 0;
long currval = 1;
for (int i = 13; i <= n; i++){
for (long j = s; j <= 13; j++){
currval *= myBigInteger.valueOf(s);
}
s++;
}
if (maxval < currval){
maxval = currval;
}
System.out.println(maxval);
}
}
You don't really need BigInteger for this. The long's are sufficient to hold the product.
public class BigFib {
public static void main(String[] args) {
String bigNum =
"73167176531330624919225119674426574742355349194934"
+ "96983520312774506326239578318016984801869478851843"
+ "85861560789112949495459501737958331952853208805511"
+ "12540698747158523863050715693290963295227443043557"
+ "66896648950445244523161731856403098711121722383113"
+ "62229893423380308135336276614282806444486645238749"
+ "30358907296290491560440772390713810515859307960866"
+ "70172427121883998797908792274921901699720888093776"
+ "65727333001053367881220235421809751254540594752243"
+ "52584907711670556013604839586446706324415722155397"
+ "53697817977846174064955149290862569321978468622482"
+ "83972241375657056057490261407972968652414535100474"
+ "82166370484403199890008895243450658541227588666881"
+ "16427171479924442928230863465674813919123162824586"
+ "17866458359124566529476545682848912883142607690042"
+ "24219022671055626321111109370544217506941658960408"
+ "07198403850962455444362981230987879927244284909188"
+ "84580156166097919133875499200524063689912560717606"
+ "05886116467109405077541002256983155200055935729725"
+ "71636269561882670428252483600823257530420752963450";
int n = bigNum.length();
int start = 0;
long maxval = 0;
// count from 0 to the length of the string less 13.
for (int i = 0; i < n - 13; i++) {
// now starting at the first character, start taking the product of the
// digits.
long currval = 1;
for (int j = i; j < i+13; j++) {
// subtracting '0' from digit converts it to
// to an 'int'
currval *= (bigNum.charAt(j) - '0');
}
// if the current value is > maxval, assign to maxval
if (maxval < currval) {
maxval = currval;
start = i;
}
}
// now print the maxproduct and the string of digits.
System.out.println(maxval);
System.out.println("digits = " + bigNum.substring(start,start+13));
}
}
So in my advanced algorithms class, we are to write an algorithm for a program to find two numbers in two sorted arrays of integers. The format is A[i] + B[j] == x. The runtime of the algorithm needs to be O(n).
I thought i had it and wanted to check so I emailed my professor and she told me my runtime was O(n^2). Here is my code:
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5,6};
int x = 4;
int i = 0;
int j = 0;
for(int n = 0; n < (A.length*B.length); n++) {
if(i >= A.length)
i = 0;
if(n % B.length == 0)
j++;
if(A[i] + B[j] == x) {
System.out.println(A[i] + " + " + B[j] + " = " + x);
break;
}
i++;
}
EDIT
I do apologize if this is still incorrect. I never really grasped the concept of Big-Oh. Would this change the runtime to O(n)? I got rid of the A.length*B.length and tried something a little different.
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5};
int x = 5;
int i = 0;
int j = 0;
while(i < A.length) {
if(B[j] == x - A[i]) {
/* exit */ }
if(j >= B.length) {
j = 0;
i++; }
j++;
}
Solution 1:
Add all values in B to a Map with B value as the map key, and B-index as the map value.
Iterate A, and calculate desired B value as B = x - A. Look for it in the map, and if found, you then have the index.
You will only iterate A and B once each. Adding a single value to map is O(1), and looking up a value is O(1), assuming a HashMap, so overall is O(n).
Solution 2:
Iterate A ascending, and B descending.
For each value in A, look at current B value. Walk down B until A + B <= x (or you reach beginning of B).
You will only iterate A and B once each, so O(n).
Solution 2 requires less memory (no map), and is likely faster (no time spent building map).
UPDATE Here is code:
The above descriptions were based on need for index of values, and the code for each solution is:
Solution 1
private static void findSum(int[] a, int[] b, int x) {
Map<Integer, Integer> bIdx = new HashMap<>();
for (int j = 0; j < b.length; j++)
bIdx.put(b[j], j);
for (int i = 0; i < a.length; i++) {
Integer j = bIdx.get(x - a[i]);
if (j != null)
System.out.println("a[" + i + "] + b[" + j + "] = " + a[i] + " + " + b[j] + " = " + x);
}
}
Solution 2
private static void findSum(int[] a, int[] b, int x) {
for (int i = 0, j = b.length - 1, sum; i < a.length && j >= 0; i++) {
while (j >= 0 && (sum = a[i] + b[j]) >= x) {
if (sum == x)
System.out.println("a[" + i + "] + b[" + j + "] = " + a[i] + " + " + b[j] + " = " + x);
j--;
}
}
}
Test
int[] a = {1,2,3,4,5};
int[] b = {1,2,3,4,5,6};
findSum(a, b, 4);
Output (same from both)
a[0] + b[2] = 1 + 3 = 4
a[1] + b[1] = 2 + 2 = 4
a[2] + b[0] = 3 + 1 = 4
Solution 1 using Set
If you don't need index position, then a Set is better for solution 1:
private static void findSum(int[] aArr, int[] bArr, int x) {
Set<Integer> bSet = new HashSet<>();
for (int b : bArr)
bSet.add(b);
for (int a : aArr)
if (bSet.contains(x - a))
System.out.println(a + " + " + (x - a) + " = " + x);
}
Output
1 + 3 = 4
2 + 2 = 4
3 + 1 = 4
Here is an example of how you can measure your time, i've included another method to find the numbers you mentioned. See the difference in runtime:
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5,6};
int x = 4;
int i = 0;
int j = 0;
long t1 = System.nanoTime();
for(int n = 0; n < (A.length*B.length); n++) {
if(i >= A.length)
i = 0;
if(n % B.length == 0)
j++;
if(A[i] + B[j] == x) {
System.out.println(A[i] + " + " + B[j] + " = " + x);
break;
}
i++;
}
long t2 = System.nanoTime();
System.out.println("Time 1: "+(t2-t1));
//Here's the other method
long t3 = System.nanoTime();
for (int n = 0;n<B.length;n++){
for (int m =0;m<A.length;m++){
if(A[m]+B[n]==x){
System.out.println(A[m] +" + "+B[n] +" = "+ x);
}
}
}
long t4 = System.nanoTime();
System.out.println("Time 2: "+(t4-t3));
Here is the code, for Andreas's Solution 1, that I came up with:
int[] A = {2,3,4};
int[] B = {7,9};
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
int x = 10;
int b;
for(int i = 0; i < B.length; i++) {
hashMap.put(B[i], i);
}
for (int n = 0; n < A.length; n++){
b = x - A[n];
if(hashMap.get(b) != null)
System.out.println(A[n] + " + " + b + " = " + x);
}
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 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;
}
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");