Finding Total of all Values in a Column [RNG] - java

I am working on a program that prints out a table filled with randomly-generated integers. Most of the logic is relatively straightforward and works pretty well. One thing I would like to do is to add up and print out total values for each column, as well as the final total of all the values in the table. I have searched around trying to find an answer but have had no luck with figuring it out.
rowNbr = 7; // ROW CONTROLS
colNbr = 5; //COLUMN CONTROLS
rpt01 = String.format("%0" + (colNbr-1) + "d", 0).replace("0",dash); //Redefine rpt01
colBld = String.format("|---------------|%s\n",rpt01); //Redefine colBld
String cnrTxt = "First Quarter";
System.out.printf(colBld);
System.out.printf("|%-15s",cnrTxt);
for(int i = 1; i < colNbr; i = i++){ //Open for loop (columns)
String regTxt = "Region " + i++;
System.out.printf("|%-10s",regTxt);
} //End for
System.out.printf("|\n");
//Initialize array
int sales[] = new int[100];
int idx = 0;
for(int i = 1; i <= rowNbr-3; i++){
String prodTxt = "Product " + i;
System.out.printf(colBld);
System.out.printf("|%-15s|",prodTxt);
for(int j = 0; j < colNbr-1; j++){ //Open for loop (columns 2)
sales[idx] = (int)(Math.random() * 16 + 1);
System.out.printf("%-10d|",sales[idx]);
idx++;
} //End for
System.out.printf("\n");
} //End for
int totalNbr = 0; //Placeholder zero
int regNbr = 0; //Placeholder zero
String totalTxt = "Final Total: ";
String regTxt = "Region Totals";
System.out.printf(colBld);
System.out.printf("|%-15s|%-10s|\n",regTxt,regNbr);
System.out.printf(colBld);
System.out.printf("|%s%s\n",totalTxt,totalNbr);
System.out.printf(colBld);
Here is what the code currently looks like once run:
|---------------|----------|----------|----------|----------|
|First Quarter |Region 1 |Region 2 |Region 3 |Region 4 |
|---------------|----------|----------|----------|----------|
|Product 1 |2 |10 |3 |1 |
|---------------|----------|----------|----------|----------|
|Product 2 |15 |15 |7 |16 |
|---------------|----------|----------|----------|----------|
|Product 3 |15 |13 |7 |9 |
|---------------|----------|----------|----------|----------|
|Product 4 |4 |14 |11 |11 |
|---------------|----------|----------|----------|----------|
|Region Totals |0 |
|---------------|----------|----------|----------|----------|
|Final total: 0
|---------------|----------|----------|----------|----------|
Honestly have no idea where to even begin with this. Any help is appreciated!

Since you have already sequentially filled the sales array with random Integer values to represent sequentially displayed Regions it is then a simple matter of stepping through the array elements in increments of the number of regions and summing the elements detected in each step.
To determine the actual number of Regions that will be displayed and the number of Region Totals to keep track of, we can base it from the value contained within the colNbr variable less 1 (5 - 1 = 4 regions will be displayed).
Knowing this we declare yet another integer Array named regionTotals and give it a length of 4:
int[] regionTotals = new int[colNbr-1];
Now it's a matter of stepping through the sales array elements and summing the proper sales array element to the proper regionTotal element, like this:
int regionCols = colNbr-1;
int[] regionTotals = new int[regionCols];
int stepCounter = 0;
for (int i = 0; i < sales.length; i++) {
stepCounter++;
if (stepCounter > regionCols) { stepCounter = 1; }
int regionIndex = (stepCounter - 1);
regionTotals[regionIndex]+= sales[i];
}
System.out.println("\nRegion Totals: " + Arrays.toString(regionTotals) + "\n");
Place the above code directly above the declaration & initialization of the totalNbr integer variable:
int totalNbr = 0; //Placeholder zero
How you format the regionTotals array elements into your table is up to you but do remember, the Array is zero based so the element at index 0 of the array contains the summation for Region 1.

Related

How can I solve java.lang.ArrayIndexOutOfBoundsException error in Java

I'm solving a challenge about making an algorithm.
There is a game of land.
The Land of Landing game consists of 4 rows in total N rows, with scores in all the columns.
When stepping down from the first row, down one row, you must step down on one of the four squares of each row.
However, there is a special rule that can not be repeated in the same row when landing one row at a time.
For example,
| 1 | 2 | 3 | 5 |
| 5 | 6 | 7 | 8 |
| 4 | 3 | 2 | 1 |
If you have stepped on line 1 through line 4 (5), you can not step on line 4 (8) on line 2.
I was trying to use Dynamic Programming in Java.
import java.lang.Math;
import java.util.*;
class Solution {
int [][] dp = new int[100001][4];
int solution(int[][] land) {
int r = land.length;
for (int i = 0; i < 4; i++)
{
dp[0][i] = land[0][i];
}
for (int i = 0; i <r; i++)
{
for (int j = 0; j < 4; ++j)
{
for(int k = 0; k < 4; ++k)
{
if (j != k)
{
dp[i][j] = Math.max(dp[i][j], land[i][j] + dp[i-1][k]);
}
}
}
}
int ans = 0;
for (int i = 0; i < 4; ++i)
{
ans = Math.max(ans, dp[r-1][i]);
}
return ans;
}
}
it shows error
java.lang.ArrayIndexOutOfBoundsException: -1
I was thinking that it was probably something wrong with the Conditional statement.
In C++, these conditional statements are right. It's running perfect. Why am I getting an error in Java? Is there any difference using array between Java and C++?
Can you please tell me how can I solve this error?
dp[i-1][k] - i starts from ZERO in upper loop, so results of this expression becomes -1 as index.
Java array index starts from ZERO, not -1, which is why ArrayIndexOutOfBoundsException.
I don't know the business case, but one way to solve this is, start first for loop from 1 instead 0.

Can I get integer values for a 2D array instead of characters?

I was trying to create the simpliest matrix - 2d array and I have trouble with my code, it is kind of working, but not correctly.
Code:
int result = 0;
int[][] matrix = new int[2][2];
for(int rows = 0; rows < matrix.length; rows++)
for(int cols = 0; cols < matrix[rows].length; cols++)
matrix[rows][cols] = (rows + cols);
System.out.println("matrix is: "+matrix);
result = matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
System.out.println("Result is: "+result);
Output:
matrix is: [[I#1db9742
Result is: -1
I had this one:
int result = 0;
char[][] matrix= new char[2][2];
for(int rows = 0; rows < 2; rows++)
for(int cols = 0; cols < 2; cols++)
matrix[rows][cols] = (char)('1' + rows * 2 + cols);
for(int rows = 0; rows < 2; rows++)
for(int cols = 0; cols < 2; cols++)
System.out.println("matrix is: "+matrix[rows][cols]);
result = matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
System.out.println("Result is: "+result);
Output:
matrix is: 1
matrix is: 2
matrix is: 3
matrix is: 4
Result is: -2
But I do not want char, I want integer (because what if work with big matrix calculations later) and I do not understand tis part:
('1' + rows * 2 + cols)
because I copied it from some other code. How to get the first one to work like second and what is that part in brackets (why writen like that)? Thanks in advance!
I got nice stuff with 1 2 3 4 that is what I wanted, but I also need explanation for what that "('1' + rows * 2 + cols)" means. I want to get 1 2 3 4 for matrix 2D array, and then 1*4-2*3 for result. Maybe '1' is to start from 1, not from 0 in loop and write from 1 in array. I found it in some other code, not my solution, first one is mine and not working properly. I added:
for(int cols = 0; cols < matrix[rows].length; cols++)
as you suggested.
*I rewrote it to english.
Sorry for language confusion.
I don’t understand why I get characters instead of 2D array when printing matrix after loop, before calculating.
I think the result is correct.
This is your matrix :
| 0 1 |
| 1 2 |
And this is what you do : 0 * 2 - 1 * 1
and the good answer is = -1.
The code for what you want is :
int i = 1;
for(int redovi = 0; redovi < matrica.length; redovi++)
for(int kolone = 0; kolone < matrica.length; kolone++)
matrica[redovi][kolone] = i;
++i;
So we will get a matrix like this one :
|1 2|
|3 4|
And so the good answer for what you want. If I well understood.
You should look closer on what you write into matrix. The first looks like:
0 1
1 2
and second:
'1' '2'
'3' '4'
So both determinants are calculated almost as you expect. You can change one line in the first code to this:
matrix[rows][cols] = (1 + rows*matrix[rows].length + cols);
So that your matrix is 1234.
By the way, using char[][] worked because any char can be represented as a number that is an index in character map.
I also need explanation for what that "('1' + rows * 2 + cols)" means
Character '1' is 49th in character map, '2' is 50th and so on. Try to compile this, for example:
System.out.println((int)'1');
So "('1' + rows * 2 + cols)" generates a matrix that can be represented as int[][]:
49 50
51 52

Most Efficient Integer Array to Histogram Algortihm JAVA (CountingSort?)

I'm trying to implement an algorithm in java which takes in an array of integers from 1 to 100 and prints them as a histogram. I believe I've deduced a linear solution for this but don't know if it is O(n) or O(10n) etc. I have based the algorithm on a counting sort as I understand it to be the most efficient array sorting algorithm. Are there more efficient ways to sort arrays in the context of displaying them as histograms than a manipulated counting sort?
The method so far:
public static void histogram(int[] array){
for(int i = 0; i< array.length; i++){
array[i] = (array[i] - 1)/10;
}
//create quantity array of size 10 and fill with 0
int[] quantity = new int[10];
for(int i = 0; i <= 9; i++){
quantity[i] = 0;
}
//increment value of quantity index = array[i]
for(int i = 0; i< array.length; i++){
quantity[array[i]]++;
}
//set values of number group column in histogram
int low = 1;
int high = 10;
//string to pad the rows with shorter group names (1-10)
String pad = " ";
//start building histogram
StringBuilder his = new StringBuilder(
"______________________________________________ \n"); //ceiling
//loop 10 times (number of groups = 10)
for(int i = 0; i<= 9; i++){
his.append(low + " - " + high + pad + " | "); //number group column
//append asterisks equal to value stored in quantity[i]
for(int j = 0; j < quantity[i]; j++){
his.append("*");
}
his.append("\n"); //move to next line
//set values of next number group
low += 10;
high += 10;
//pad for 11-20 ... 81-90
pad = " ";
if (high == 100){
pad = ""; //pad for 91-100
}
}
his.append("______________________________________________"); //floor
System.out.print(his); //print entire historgram
}
Here is an example of the output:
1 - 10 | **********
11 - 20 | **********
21 - 30 | *********
31 - 40 | *******
41 - 50 | ***********
51 - 60 | ***********
61 - 70 | **********
71 - 80 | **********
81 - 90 | ************
91 - 100 | **********
FOR ARRAY OF SIZE 100 TOTAL TIME TO PERFORM ALGORITHM: 473397ns
(stackoverflow seems to mess up the formatting a bit but everything prints in line)

Fill the last n elements of a 2d array

How can I fill the last n cells (inclusive) of a 2d array in java?
This is what I've tried:
if(numOfUnusedCells != 0) {
for (int k = matrix[0].length; k >= numOfUnusedCells; k--) {
matrix[rows-1][k -1] = "*";
}
}
Example
for a 2d array as such as 2 elements to fill:
+---+---+---+
| | | |
+---+---+---+
| | * | * |
+---+---+---+
Arrays.fill can do that for you:
see this example where you can fill the 1st element of the array with -21
example:
final int[][] a2dArr = new int[3][3];
System.out.println("Before: " + Arrays.deepToString(a2dArr));
for (int i = 0; i < a2dArr.length; i++) {
Arrays.fill(a2dArr[i], 0, 1, -21);
}
System.out.println("After: " + Arrays.deepToString(a2dArr));

Two dimensional array

I am working on a little program to calculate and draw a parabola. But I'm stuck at a little part in the program where I need to calculate the valuetable.
The quadratic function is the following one: y = a * (x - alpha)² + Beta.
So if I fill in the following values for this function: y = 2 * (x - 1)² + (-12). I need to become this value table:
x | -4.0 | -3.0 | -2.0 | -1.0 | 0.0 | 1.0 | 2.0 | 3.0 | 4.0 |
y | 38.0 | 20.0 | 6.0 | -4.0 |-10.0|-12.0|-10.0|-4.0 | 6.0 |
I managed to get the first row right, but the second row (the one that calculates te values), is totally wrong.
public double[][] berekenWaardentabel(int input[], int AANTALKOLOMMEN, double startWaarde) {
double[][] waarden = new double[RIJEN][AANTALKOLOMMEN];
System.out.println(waarden.length);
System.out.println(startWaarde + "\n");
for(int i = 0; i < RIJEN; i++) {
for(int j = 0; j < AANTALKOLOMMEN; j++) {
waarden[0][j] = startWaarde++; //value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
System.out.print(waarden[i][j] + " ");
}
System.out.println();
}
return waarden;
}
This is the output I get:
-4.0 -3.0 -2.0 -1.0 0.0 1.0 2.0 3.0 4.0 5.0 6.0
86.0 | 116.0 | 150.0 | 188.0 | 230.0 | 276.0 | 326.0 | 380.0 | 438.0 | 500.0 | 566.0
Anyone an idea how to solve this problem? Thanks!
You have to mistakes :
you want to fill two lines of your array (the 0-th (x) and the first(y)). Then you store the value of x in the first row and compute y(x+1) in the second row.
you need to fill your array with :
for (int j = 0; j < AANTALKOLOMMEN; j++) {
waarden[0][j] = startWaarde; // value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
startWaarde++;
}
Then you can display your values :
for (int i = 0; i < 2; i++) {
for (int j = 0; j < AANTALKOLOMMEN; j++) {
System.out.print(waarden[i][j] + " ");
}
System.out.println();
}
First error is this:
waarden[0][j] = startWaarde++; //value of first row (start from -4.0, counts upwards)
waarden[1][j] = input[0] * (Math.pow((startWaarde - input[1]), 2)) + input[2];
You put the value of startWaarde in waarden[0][j]. And then you increment it by one.
Then you calculate the value of the function for the updated startWaarde.
So your waarden[0][j] is, perhaps, 4.0, but you calculate the value waarden[1][j] for 5.0 rather than 4.0.
Your other problem is that you are looping with this line:
for(int i = 0; i < RIJEN; i++) {
I don't know what the value of RIJEN is. But your waarden array is only supposed to have two rows. Once you go through the loop again and again, startWaarde keeps growing and growing. Because you print the second row only after this loop iterates the second time, you see the wrong values.
You shouldn't have this loop at all.

Categories

Resources