Two dimensional array - java

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.

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.

Finding Total of all Values in a Column [RNG]

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.

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));

A graphic representation of occurence of numbers and letters with asteriks

DISCLAIMER: THIS IS PART OF A HOMEWORK ASSIGNMENT
So i have created an array with the the count of each letter. It would look something like this:
Array charCount
charCount[0] = 10
charCount[1] = 6
charCount[2] = 4
I know that 0 = a, 1 = b etc.
Now I want to print these results to a graphic representation using asteriks. For example:
*
*
*
*
*
**
**
**
***
***
***
ABC
I found this rather difficult and don't really understand how to do this.
- I've made a function to check the max value of my array.
for (int i = 0; i < charCount.length; i++) {
if (letterCount[i] > maxInt) {
maxInt = charCount[i];
}
}
Then I've made a for loop to check if there are any matches.
My next part of code is:
for (int i = 0; i < letterCount.length; i++ ) {
for (int j = 0; j <= maxInt; j++) {
if (letterCount[i] == maxInt) {
System.out.println("*");
} if (letterCount[i] == maxInt - j ) {
System.out.println("*");
} if (letterCount[i] != maxInt ) {
System.out.println(" ");
}
}
But here it where I got stuck.
How do i print asteriks all the way down and next to each other? Should I work with spaces?
How do i know when to stop printing? Does my maxInt - j makes sense?
Can someone point my in the right direction?
I have to come up with a solution using for loops and arrays, So i cant use any fancy methods yet :)
Thank you :)
Imagine you wanna draw this like a bar graph to a grid, which has coordinates, similar to what you did in school with x and y coordinates.
To stay with your example, each y coordinate represents the index of your array, e.g. the specific letter, where the x - coordinate the amount.
Since those numbers may get quite large, it's, like you saw, not best practice to map +1 on the x-coordinate to +1 letter.
Therefore you need to determine the size of your diagram, let's say it shall be 10 letters wide:
y <- 10
^
a|**********
b|**********
c|**********
-------------> x
12345 ...10
Now it's important that the occurences of the letters relative to each other are represented correctly by those *-bars, that means the letter which occurs the most could be shown with a bar exactly as long as you draw the x-coordinate, in this case 10.
Lets use this as an example dataset
0 := 10
1 := 6
2 := 4
3 := 14
If the x-coordinate is 10 * long, the amount from entry 3 (highest in the array) is 14 and needs to be 10 * long. With this information you can calculate the factor by dividing 10(x-length) / 14(biggest amount) ~= 0.71 (the factor)
This factor you apply to all the numbers to get number of stars to draw.
Here as an example in java:
int xLength = 10;
int[] charCount = new int[5];
charCount[0] = 10;
charCount[1] = 4;
charCount[2] = 7;
charCount[3] = 14;
charCount[4] = 1;
// determine the biggest value:
int biggest = 0;
for(int n:charCount) {
if(n>biggest)
biggest = n;
}
System.out.println("Biggest no: " + biggest);
double factor = (double)xLength / (double)biggest;
System.out.println("Using factor: " + factor);
for(int i = 0; i < charCount.length; i++) {
System.out.print("no " + i + ":");
for(int j = 0; j < charCount[i] * factor; j++) {
System.out.print("*");
}
System.out.println();
}
This will output:
Biggest no: 14
Using factor: 0.7142857142857143
no 0:********
no 1:***
no 2:*****
no 3:**********
no 4:*
EDIT:
If you want to print the bars vertically (on the y-choordinate), or turn it any other way, store the bars in a grid, for example with a String[][] array, where arr[2][3] would be y-coordinate 2 and x-coordinate 3. Then you can calculate with the factor above and the maximum height of the chart whether or not a specific point / coordinate should be filled with a "*" or a " " (nothing):
// make a grid to draw the chart
// the height is the the number we defined as maximum height (xLength)
// and the width is one column for every char (charCount.length):
String[][] grid = new String[charCount.length][xLength];
// initialize the grid with spaces:
for(int x = 0; x < grid.length; x++) {
for(int y = 0; y < grid[x].length; y++) {
grid[x][y] = " ";
}
}
// We will go through the grid column by column:
for(int x = 0; x < grid.length; x++) {
// this will be called once for every char
// so just replace spaces in the grid in this column
// by "*" if it's a row (value of y) <= the amount
// of chars times the factor
for(int y = 0; y < grid[x].length; y++) {
if(y <= charCount[x] * factor) {
grid[x][y] = "*";
}
}
}
// print the grid row by row (think of it upside down, (0,0) is the upper left point
// so we start with the last (the no of elements in the array minus 1, counting from 0)
System.out.println("^");
for(int y = grid[0].length - 1; y >= 0; y--) {
System.out.print("|");
for(int x = 0; x < grid.length; x++) {
System.out.print(grid[x][y]);
}
// finish the line:
System.out.println();
}
// draw the bottom line:
System.out.println("------->");
System.out.println(" abcde");
Added this code just below the code from above, the output will be:
Biggest no: 14
Using factor: 0.7142857142857143
no 0:********
no 1:***
no 2:*****
no 3:**********
no 4:*
^
| *
| *
|* *
|* *
|* **
|* **
|* **
|****
|****
|*****
------->
abcde
If you want to put the amounts left to the y-bar, divide the row number by the factor.
If you want to use the absolute values without scaling up or down (which would fill the screen pretty fast for big numbers), just set the 'xLength' (height of the grid) to the biggest number in the input array.

Categories

Resources