I'm revising for a introduction to programming exam and I have a question which from a previous exam paper I am slightly stuck on.
The question:
Write a method that takes a double array as an argument with values representing the positions of train stations along a track. The method should return a two-dimensional array with the distances between each pair of stations in the argument. The array of distances should have only one entry for each pair of stations (i.e. do not use a rectangular array).
I have a solution to the question but I just can't get the last bit where there should only be one entry for each pair. I have thought about creating a look up table will all the entries to see if the distance for the two stations but then the array would have lots of empty cells for the later stations because the distance would have already been calculated.
Here is my current solution
//Set of locations on the train line
private static double[] stations = {0.0, 2.0, 3.0, 5.0};
//Method to take the array of doubles and create distance map
public static double[][] getDistances(double[] st){
double[][] distanceMap = new double[st.length][st.length-1];
int x;
for(int i=0; i<st.length; i++){
x=0;
for(int j=0; j<st.length; j++){
if(j != i){
distanceMap[i][x] = Math.abs(st[i]-st[j]);
x++;
}
}
}
return distanceMap;
}
//Main method to get the distance map then loop over results
public static void main(String[] args){
double[][] arrayMatrix = getDistances(stations);
for(int i=0; i<arrayMatrix.length; i++){
for(int j=0; j<arrayMatrix[0].length; j++){
System.out.print(arrayMatrix[i][j]+" ");
}
System.out.println("");
}
}
If anyone could point me in the right direction it would be really appreciated.
Thanks in advance.
//EDIT
After some great advice from #izomorphius I have managed to solve the question. Thanks.
Here is the complete solution
//Set of locations on the train line
private static double[] stations = {0.0, 2.0, 3.0, 5.0};
//Method to take the array of doubles and create distance map
public static double[][] getDistances(double[] st){
double[][] distanceMap = new double[st.length-1][];
int size = st.length-1;
for(int i=0; i<distanceMap.length; i++){
distanceMap[i] = new double[size];
size--;
}
ArrayList<String> lut = new ArrayList<String>();
int x;
for(int i=0; i<distanceMap.length; i++){
x=0;
for(int j=0; j<st.length; j++){
if(j != i && !lut.contains(i+"/"+j)){
distanceMap[i][x] = Math.abs(st[i]-st[j]);
lut.add(i+"/"+j);
lut.add(j+"/"+i);
x++;
}
}
}
return distanceMap;
}
//Main method to get the distance map then loop over results
public static void main(String[] args){
double[][] arrayMatrix = getDistances(stations);
for(int i=0; i<arrayMatrix.length; i++){
for(int j=0; j<arrayMatrix[i].length; j++){
System.out.print(arrayMatrix[i][j]+" ");
}
System.out.println("");
}
}
What the statement says is "i.e. don't use rectangular array". The idea is to store only one value for each pair. For instance if you have the pair (a,b) and a < b store the distance between a and b in the array of a but not in the one of b. Thus the array for the first station will be of size n - 1(distances to all the other stations), for the second station it will be of size n - 2(all other stations except the first one) and so on. Therefor your array will be triangular not rectangular. I hope this tip is enough as after all the idea is not to have me solve your problem.
Related
I coded a selection sort program and I was wondering if I wanted to add-on to it by showing how the positions of the values have changed, if it would be possible?
this is my selection sort code
import java.util.Scanner;
public class SelectionSort {
public static void main(String args[]) {
// int[] arr = {5,4,3,2,1}; // This is my array
int min = 0;
Scanner sc = new Scanner(System.in);
System.out.println("No of elements : ");
int noOfElements = sc.nextInt();
int[] arr = new int[noOfElements];
System.out.println("Give elements : ");
for (int i = 0; i < noOfElements; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < arr.length; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elemenst : " + arr[i]);
}
}
}
If you are trying to get array after each iteration, then you should print at the end of each iteration using Arrays#toString() to print complete array
for (int i = 0; i < arr.length; i++) {
...
.....
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elements : " + Arrays.toString(arr));
}
I don't know if your 'task' is to write your own sort method, but if you are looking for sorting an array you should use this:
public static void main(String[] args) {
int[] arr = {5,4,3,2,1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
Never assume what a User might enter and therefore never assume that the first entry will be the minimum value.
This question has been showing up a lot in StackOverflow and therefore I can only assume this is homework. With this in mind I'm sure the assignment intent is to accept a specific number of random integer values from the User, place those values into a Integer Array, then sort that array in ascending order. While the sorting process is taking place show (display in console) what steps are taking place (which values are swapped within the array).
Here's a tip, research the Bubble Sort and the little bit of code it takes to accomplish the sorting task of Integer numbers within a Integer Array. In general a Bubble Sort utilizes two for loops to carry out a sort. It is within the second for loop where you can detail the process (steps) taken to carry out the sort as towards which Array element values are swapped with other element values as the sort is carried out. It would be within the if statement code block which checks whether or not the previous Array element is greater than the current Array Element.
Good luck.
I need to create the input graph(graph with backward edges). Ex: 1-st graph has edges from 1 to 2, from 2 to 3; input graph has edges from 3 to 2, from 2 to 1.
The problem is that I'm creating matrix (N^N memory usage). How to use less memory for this task?
import java.util.Scanner;
public class ReverseGraph{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine()); // number of vertices
//matrix of vertices
int[][] matrix = new int[n][n];
Scanner sc;
//create graph by input method(if A vertex associates with B vert than put "1" on B row, A column)
for(int i = 0; i < n;i++){
String line = scan.nextLine();
sc = new Scanner(line);
while(sc.hasNextInt()){
matrix[sc.nextInt() - 1][i] = 1;
}
}
scan.close();
//Begin write the input graph
System.out.println(n); //write num of vertices
//write
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 1)
System.out.print((j+1) + " ");
}
System.out.println();
}
}
}
Options for reducing the memory footprint.
An adjacency list implemented as an ArrayList<int[]> where the int[] are 2-element arrays each of which represents a link.
As above, except using a custom class with two int fields to represent a link.
As a HashMap<Integer, HashSet<Integer>> or HashMap<Integer, HashSet<Integer>> or HashMap<Integer, TreeSet<Integer>>, where each set or list represents the destinations of the links.
The equivalent to the above using Trove collection types.
All of these1 are O(L) on the number of links rather O(N^2) on the number if nodes.
1 - Apart from the variations that use TreeSet ...
I've been trying to copy the columns of a 2D array into a 1D array. The Stock class I created has a double[] array named data. The last loop tries to print some values that should be in the first Stock object, but it actually prints the values from the last object.
Stock arr[] = new Stock[numcols]; // creates array with the same n of slots as columns
double[] temp = new double[numrows-1];
for(int i=1; i<numcols; i++){
for(int j=1; j<numrows; j++){
temp[j-1] = fluct[j][i];
}
arr[i-1] = new Stock(temp, compName[i-1], price[i-1]);
}
for(int i=0; i<numrows/20; i++)
System.out.println(arr[0].data[i] + arr[0].name);
In fact, if I loop printing arr[j].data[i] it will print the same values for all j. It seems the loop is creating all objects with the same values for each Stock, but I see no reason why it is doing so.
I've checked the 2D array fluct and all values there are in order. I start the loops at position 1 as the values in position 0 are of no interest. Also tried printing separately the values of temp[] and they were correct, but still the data in the objects was wrong.
Here's the Stock object (omitted the getMean/getDev methods for brevity):
public class Stock{
public static double[] data;
public static String name;
public static double stDev;
public static double price;
public static double mean;
public Stock(double[] newData, String newName, double newPrice){
this.data = newData;
this.name = newName;
this.price = newPrice;
this.mean = getMean();
this.stDev = getDev();
}
}
The problem is with were you define your temp array. You should do it inside the first for loop:
Stock arr[] = new Stock[numcols]; // creates array with the same n of slots as columns
for(int i=1; i<numcols; i++){
double[] temp = new double[numrows-1];
for(int j=1; j<numrows; j++){
temp[j-1] = fluct[j][i];
}
arr[i-1] = new Stock(temp, compName[i-1], price[i-1]);
}
for(int i=0; i<numrows-1; i++)
System.out.println(arr[0].data[i] + arr[0].name);
This way for every arr element a new temp will be used. Currently you are using the same temp object and it's values are being updated as well as the values for arr elements.
Also I've changed to condition for the last for loop to i<numrows-i. Don't know why you needed i<numrows/20 =)
Good luck with Java studying!
Well, this is embarrassing, but I finally figured out what was wrong. In my object class I had my variables static! Removing that solved it.
EDIT
The question is this: Scalar multiplication is defined as B = A * s, where B and A are equally sized matrices (2D array of numbers, in this example let's use integers) and s is a scalar value. Each element of A is multiplied to s, which is then stored in the corresponding element in matrix B.
Write a program that accepts a 4x4 matrix and a scalar value, and perform scalar multiplication, storing the result in a separate 4x4 matrix.
import java.util.*;
public class arrayExercises {
public static void main (String [] args){
//Scalar Value
Scanner sc = new Scanner (System.in);
int scalar = 0;
//Array for A
int matrix [][];
matrix = new int [4][4];
System.out.println("Enter the numbers in the 4x4 matrix");
for (int i=0; i < matrix.length; i++)
{
for (int j =0; j<matrix[i].length; j++)
matrix[i][j] = sc.nextInt();
}
System.out.println("Enter scaler value:");
scalar = sc.nextInt();
sc.close();
}
}
not giving a direct solution. giving you a hint instead.
so far from your code, you have created a matrix and withing 2 for loop you have set the values of the matrix from user input.
now to get a scalar multiplication you need to do a similar operation. create another matrix of the same size as the previous matrix. and in a similar way within 2 loop multiply each and every element of the old matrix with the scalar value and set it to the coresponding index of the new matrix.
System.out.println("Enter scaler value:");
scalar = sc.nextInt();
int scalarMatrix [][];
scalarMatrix = new int [4][4];
for (int i=0; i < scalarMatrix.length; i++)
{
for (int j =0; j<scalarMatrix[i].length; j++)
scalarMatrix[i][j] = (int)(matrix[i][j]*scalar);
}
Something along these lines should work. What you are doing is getting each result from the initial matrix and essentially copying them into the new matrix but multiplying it by the variable "scalar" as you do so.
2DI need to use a two-dimensional array of doubles to store grades. The first dimension of the array will represents each student while the second dimension represents the grade for each assignment. The maximum number of assignments for any course is provided when the course is created. I need to make it so that grades that have not been assigned are given an initial value of -1
I know that for single arrays you can do this
double[] grade = new double[10];
for (double i = 0; i < size; i++) {
array[i] = -1;
}
How would I do it for a 2D array?
try this
double[][] grade = new double[10][10];
for (double[] e : grade) {
Arrays.fill(e, -1);
}
First all, you can't do this
double[] grade = new int[10];
double[] and int[] are incompatible types.
To declare a 2D array just use two sets of square brackets
double[][] grade = new double[10][10];
This will give you a total of 100 indices, max index being [9][9], and min[0][0].
To iterate through the array you use a nested loop
for (int i = 0; i < grade.length; i++){ // iterates each student
for (int j = 0; j < grade[i].length; j++){ // iterates each grade
// do something with grade[i][j]
}
}