I am coming today with a very basic task that somehow confused me really hard.
I have an array that looks like that :
Here is the code:
double population[][] = {{281.0, 296.0, 325.0, 371.0, 384.5},
{298.6, 241.2, 301.2, 342.8, 388.7},
{362.9, 284.1, 276.8, 353.6, 395.1},
{393.4, 344.8, 295.6, 298.3, 375.0}};
int year[] = {2011, 2016, 2021, 2026, 2031};
String ageGroup[] = {"15-19", "20-24", "25-29", "30-34",};
String output = "Actual and Projected Population in thousands by Age Group (CSO 2016)";
output += String.format("\n%10s", "");
for (int i = 0; i < year.length; i++) {
output += String.format("%10s", year[i]);
}
output += String.format("%10s", "%Change");
double change[] = new double[ageGroup.length];
for (int i = 0; i < population.length; i++) {
output += String.format("\n%10s ", ageGroup[i]);
for (int j = 0; j < population[i].length; j++) {
output += String.format("%10.1f", population[i][j]);
}
change[i] = (((population[i][4] - population[i][0])/
population[i][0]) * 100);
output += String.format("%10.1f", change[i]);
}
output += String.format("\n\nTotal (15 - 34): ");
System.out.println(output);
}
As you can clearly see I am missing the bottom values - 1335.9, 1166.1, 1198.6, 1543.3. These values are gained by adding full year e.g. 2011 - 281 + 298.6 + 362.9 + 393.4
I cannot figure out how to make a for loop in order for this to print out the way I want to.
I tried :
double total[] = new double[ageGroup.length];
double hold = 0;
for(int i = 0; i < population.length; i++){
total[i] += hold;
for(int j = 0; j < population[i].length; j++){
hold += population[j][i];
I also tried adding it here
for (int i = 0; i < population.length; i++) {
output += String.format("\n%10s ", ageGroup[i]);
for (int j = 0; j < population[i].length; j++) {
output += String.format("%10.1f", population[i][j]);
}
change[i] = (((population[i][4] - population[i][0])/
population[i][0]) * 100);
output += String.format("%10.1f", change[i]);
total[i] = (population[0][i] + population[1][i]+ population[2][i]+population[3][i]+population[4][i]);
}
Now I am just left confused on how such an easy task made me stuck so hard.
It is a crime that instructors do not teach OO thinking out of the gate, forcing students to muddle through arrays rather than modeling the domain. sigh.
There are two keys here, I think. First, separate the calculation from presentation. Second, realize that rows are age groups and columns are years. Really there should be methods for this stuff rather than just in a single main method. Also, the title and some fluff can be fixed in the final output.
Also, rather than hard coding, e.g., [4], this code uses the .length of the array to make it somewhat easier to deal with adding another year or another age group.
//
// a 2d array, where row is for a given agent group, and column
// is for a given year
//
static double population[][] = { { 281.0, 296.0, 325.0, 371.0, 384.5 },
{ 298.6, 241.2, 301.2, 342.8, 388.7 },
{ 362.9, 284.1, 276.8, 353.6, 395.1 },
{ 393.4, 344.8, 295.6, 298.3, 375.0 } };
static int year[] = { 2011, 2016, 2021, 2026, 2031 };
static String ageGroup[] = { "15-19", "20-24", "25-29", "30-34", };
public static void main(String[] args)
{
//
// hold the totals
//
double[] yearTot = new double[year.length]; // total by year
double[] agTot = new double[ageGroup.length]; //total by ag
double[] chngAG = new double[ageGroup.length]; //change
// loop over every age group
for (int ag = 0; ag < ageGroup.length; ++ag) {
// get the population for the age group, which is
// one row in the data
double[] valsForAG = population[ag];
// loop over every year, which a column in a given age group
for (int yr = 0; yr < year.length; ++yr) {
// get the specific value
double valForAgInYear = valsForAG[yr];
// add to the total for the year and to the age group value
yearTot[yr] += valForAgInYear;
agTot[ag] += valForAgInYear;
} // for every year
int en = ageGroup.length;
int st = 0;
// after processing an age group, calculate the change
chngAG[ag] = ( ( (valsForAG[en] - valsForAG[st]) /
valsForAG[st]) * 100);
} // for every age group
//
// do the output
//
// header row
System.out.printf("%10s", "");
for (int y = 0; y < year.length; ++y) {
System.out.printf("\t%7d", year[y]);
}
System.out.printf("\t%10s%n", "%Change");
// data
for (int ag = 0; ag < ageGroup.length; ++ag) {
System.out.printf("%10s", ageGroup[ag]);
for (int yr = 0; yr < year.length; ++yr) {
System.out.printf("\t%7.1f", population[ag][yr]);
}
System.out.printf("%10.1f", chngAG[ag]);
System.out.println();
}
//output the totals
System.out.println();
System.out.printf("%10s", "Totals:");
for (int t = 0; t < yearTot.length; ++t) {
System.out.printf("\t%7.1f", yearTot[t]);
}
System.out.println();
}
Output
2011 2016 2021 2026 2031 %Change
15-19 281.0 296.0 325.0 371.0 384.5 36.8
20-24 298.6 241.2 301.2 342.8 388.7 30.2
25-29 362.9 284.1 276.8 353.6 395.1 8.9
30-34 393.4 344.8 295.6 298.3 375.0 -4.7
Totals: 1335.9 1166.1 1198.6 1365.7 1543.3
public static void main(String[] args) {
double population[][] = {{281.0, 296.0, 325.0, 371.0, 384.5}, {298.6, 241.2, 301.2, 342.8, 388.7}, {362.9, 284.1, 276.8, 353.6, 395.1}, {393.4, 344.8, 295.6, 298.3, 375.0}};
//1. Step: Find the longest of the arrays
//You need this if the length of the arrays is different, for example:
/*
double population[][] = {
{281.0, 296.0, 325.0, 371.0, 384.5},
{298.6, 241.2, 301.2, 342.8, 388.7, 0},
{362.9, 284.1, 276.8, 353.6, 395.1, 1, 2},
{393.4, 344.8, 295.6, 298.3, 375.0, 0.5}
};
*/
int lengthOfLongestArray = population[0].length;
for(int i = 0; i < population.length; i++){
if(population[i].length > lengthOfLongestArray){
lengthOfLongestArray = population[i].length;
}
}
//2. Step: calculate the sum
double result[] = new double[lengthOfLongestArray];
for(int i = 0; i < population.length; i++){
for(int j = 0; j < population[i].length; j++){
result[j] += population[i][j];
}
}
System.out.println(Arrays.toString(result));
}
Explanation:
To avoid confusing loops and fancy logic I created an array which will hold the result of the calculation called result.
Step:
By setting the length of this result array to the length longest of the rows in the population 2D array (aka. matrix) we handle the situation when the rows are not exactly the same length (see the example I commented out).
Step:
Then we just loop through the 2D array and sum the values. As we go through of a row in your 2D array we can take the value from the 'j' position of the row we are checking and add it to the value we have in the 'j' position in the result array.
Cheers,
A.
double population[][] = { { 281.0, 296.0, 325.0, 371.0, 384.5 }, { 298.6, 241.2, 301.2, 342.8, 388.7 },
{ 362.9, 284.1, 276.8, 353.6, 395.1 }, { 393.4, 344.8, 295.6, 298.3, 375.0 } };
int year[] = { 2011, 2016, 2021, 2026, 2031 };
String ageGroup[] = { "15-19", "20-24", "25-29", "30-34", };
String output = "Actual and Projected Population in thousands by Age Group (CSO 2016)";
output += String.format("\n%10s", "");
for (int i = 0; i < year.length; i++) {
output += String.format("%10s", year[i]);
}
output += String.format("%10s", "%Change");
double change[] = new double[ageGroup.length];
for (int i = 0; i < population.length; i++) {
output += String.format("\n%10s ", ageGroup[i]);
for (int j = 0; j < population[i].length; j++) {
output += String.format("%10.1f", population[i][j]);
}
change[i] = (((population[i][4] - population[i][0]) / population[i][0]) * 100);
output += String.format("%10.1f", change[i]);
}
output += String.format("\n\nTotal (15 - 34): ");
// here i changed the code
// this loop will print the last from (15 to 35)
// the outer loop iterate like 2011 2016 and so one
for (int i = 0; i < 5; i++) {
double temp = 0;
// the inner loop iterate from up to down and add values
for (int j = 0; j < 4; j++) {
temp = temp + population[j][i];
}
output += String.format("%10.1f", temp);
}
System.out.println(output);
Related
The code below is supposed to generate random day of year, and matche every 2 people who have same birthday. This is know as birthday problem. The code works but the output is wrong.
public double simulate(int size, int count) {
Random random = new Random();
double x[] = new double[size];
double matches = 0;
boolean isMatch = false;
random.setSeed(count);
for (int i = 0; i < count; i++) {
for (int j = 0; j < size; j++) {
x[j] = random.nextInt(365);
for (int k = j + 1; k < size; k++) {
if (x[j] == x[k]) {
matches++;
isMatch = true;
break;
}
}
if (isMatch) {
isMatch = false;
break;
}
}
}
return (matches/count)*100;
}
and here is the Expected output result
simulate(number of people,number of simulation)
simulate(5, 10000) output = 2.71
simulate(7, 5000) output = 5.34
simulate(2, 10000) output = 0.27
simulate(9, 10000) output = 9.47
simulate(30, 20000) output = 70.675
simulate(15, 50000) output = 25.576
simulate(35, 50000) output = 81.434
simulate(45, 50000) output = 94.2
and this what Actual output :
simulate(5, 10000) output = 2.54
simulate(7, 5000) output = 5.64
simulate(2, 10000) output = 0.18
simulate(9, 10000) output = 9.05
simulate(30, 20000) output = 68.98
simulate(15, 50000) output = 25.12
simulate(35, 50000) output = 79.90
simulate(45, 50000) output = 92.99
thanks for you time .
There is one big problem in your code. You're initializing the array x with random data, but before you've fully initialized it, you are already checking if there are two values that are the same. At that point, the end of the array will not yet be fully initialized. Change that to:
// First fully filly the array x with values
for (int j = 0; j < size; j++) {
x[j] = random.nextInt(365);
}
// And then go checking for duplicates
for (int j = 0; j < size; j++) {
// etc.
After that, your results will be a closer to the expected output, but still not exactly the same. That could have something to do with the exact value for the random seed.
I am writing code that reads an integer array in from a file, checks for an increasing sequence of numbers, and prints the length of the array as well as the sequence of numbers itself. The code I have written appears to correctly print the array, showing that is has found the array in the file, and count off the longest sequence of numbers, but it doesn't quite get the exact sequence right. Below is the code in its entirety and the output.
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
Scanner s = null;
final int MAX_SIZE = 100;
int count = 0;
int[] tempArray = new int[MAX_SIZE];
try {
s = new Scanner(file);
int arrayAddress = 0;
System.out.println("File found!");
while (s.hasNextInt()) {
count++;
tempArray[arrayAddress] = s.nextInt();
arrayAddress++;
}
s.close();
}
catch (FileNotFoundException noFile) {
System.out.println("File not found.");
}
int[] inputArray = new int[count];
for (int i = 0; i < count; i++)
{
inputArray[i] = tempArray[i];
}
int sequence = 0;
int maxSequence = 0;
int sequenceEnd = 0;
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
if (inputArray[k + 1] == inputArray[k] + 1 ) {
sequence++;
sequenceEnd = k;
}
if (sequence > maxSequence) {
maxSequence = sequence;
sequence = 0;
}
}
}
int temp = 0;
System.out.println("The array is: " + Arrays.toString(inputArray));
System.out.println("The longest sequence of increasing numbers is " + maxSequence);
System.out.println("The sequence is as follows: ");
for (int i = sequenceEnd - maxSequence; i < sequenceEnd; i++) {
temp = inputArray[i];
System.out.println(temp);
}
}
The output for the code above on my sequence was as follows:
File found!
The array is: [7, 2, 13, 4, 5, 18, 11, 1, 20, 17, 15, 10, 19, 8, 16, 12, 6, 14, 9, 3]
The longest sequence of increasing numbers is 2
The sequence is as follows:
2
13
I really hope this isn't a minor oversight, but I can't seem to figure out where I have made an error. Thanks in advance if you have time to look over this and assist me.
There are two problems in your code:
(1) Finding the maximum length of the sequence
Your reset of the sequenc length
if (sequence > maxSequence) {
maxSequence = sequence;
sequence = 0;
}
should not be located within the inner loop. That is the one, where you are still counting the elements. You want to move it to the outer loop, i.e. from
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
//current location
}
}
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
}
//assumingly desired location
}
(2) Print sequence
The offset of your print-loop is off by one element and should be
for (int i = sequenceEnd - maxSequence1; i < sequenceEnd; i++) {
temp = inputArray[i-1];
System.out.println(temp);
}
Once maxSequence contains the correct amount of elements (i.e. not 2 as it is currently the case), it will print the entire sequence.
Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.
I'm not sure how to set the differences to store in the array differences. The numbers stored should be 5-(1+2+3), 7-(1,2,4), 8-(3,5,9) : the output should be differences[0]= 1, differences[1] = 0, differences[2] = 9
import java.util.Scanner;
public class Main {
public static int[][] Array = { { 5, 1, 2, 3 }, { 7, 1, 2, 4 }, { 8,3,5,9 } }; //My 2D array//
int [] differences = new int [3];
public static int[] Sum(int[][] array) {
int index = 0; //setting the index to 0//
int temp[] = new int[array[index].length]; //making a temperary variable//
for (int i = 0; i < array.length; i++) {
int sum = 0;
for (int j = 1; j < array[i].length; j++) {
sum += array[i][j]; //going to add the rows after the first column//
}
temp[index] = sum;
for(int a = 0; a<differences.length; a++){
if(sum != array[index][0])
sum -= array[i][j];
System.out.println("the first integer " + array[index][0] + " the answer is " + sum); //going to print out the first integer each row and print out the sum of each row after the first column//
index++; //index is going to increment//
}
return temp;
}
public static void main(String[] args) {
new Main().Sum(Array);
}
}
Output:
the first integer 5 the answer is 6
the first integer 7 the answer is 7
the first integer 8 the answer is 17
Why do you want to complicate the task of yours when it is this simple? :)
public int[] Sum(int[][] array)
{
int sum;
for(int i = 0; i < Array.length; i++)
{
sum = Array[i][0] * -1;
for(int j = 1; j < Array[i].length; j++)
{
sum += Array[i][j];
}
differences[i] = sum;
}
return differences;
}
If I understand your problem correctly, I think that you want to put a
differences[i] = Array[i][0] - sum
somewhere in your code
I do some calculation inside for loop and when I println values inside the loop, I got the expected values,
now, I need also that these values will be available outside loop and not only get the latest value.
example :
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
int value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value ); //it print me only third value
I would like that the value 1,2,3 will be also available outside loop
If you want to have access to all three variables. you have to declare a data structure that holds all the values.
e.g.
String[][] matrix = { { "1", "2", "3" } };
List<Integer> list = new ArrayList();
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
list.add(value);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
Declare the variable value outside of your loop:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
But if you need all three values available you should use array or some other containers like ArrayList:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
Arraylist<Integer> values = new Arraylist<Integer>();
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
values.add(Integer.parseInt(matrix[i][j - 1]));
System.out.println(values); //this is OK it print me 3 values
}
}
System.out.println(values);
you have to declare your variable (that you want to use outside of the for-loop) on top of your code.
Example:
for (...) {
//only valid in this for loop
int i = 1;
}
//valid also after this for loop
int i = 1;
for (...) {
}