Is there anyway to make an array hold 2d array?
I want to somehow hold the value of matrixFinal based on what the user enters so I can later use it. I think I'd be able to do this if I can hold these values in an array but these are 2d arrays...
How would I go about doing this?
public class Driver {
public static void main(String[] args) {
int i, j, k, l ;
int sum = 0 ;
int matrixAColumnSize ;
int matrixARowSize ;
int raiseByPower ;
// Querying user
matrixARowSize = Tools.queryForInt("Enter the row size of Matrix A: ") ;
matrixAColumnSize = Tools.queryForInt("Enter the column size of Matrix A: ") ;
Tools.verifyMatrixSize(matrixAColumnSize, matrixARowSize) ; // Verification of matrix size 10x10 max
Tools.verifyMultiplication(matrixARowSize, matrixAColumnSize) ; // Verification of matrix size
raiseByPower = Tools.queryForInt("By what power would you like to raise the matrix? ") ;
Tools.verifyMatrixPower(raiseByPower) ; // Verification of power. ^6 max
//Making matrices
int matrixA[][] = new int[matrixARowSize][matrixAColumnSize] ;
int matrixFinal[][] = new int [matrixARowSize][matrixAColumnSize] ;
// Querying for elements of Matrix A
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++) {
matrixA[i][j] = Tools.queryForInt("Enter element in Matrix A" + (i+1) + "," + (j+1) + " :" ) ; }}
// Multiplying matrices
if (raiseByPower == 1) {
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++) {
matrixFinal[i][j] = matrixA[i][j] ;
}
}
} else if (raiseByPower == 2) {
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
for (k = 0; k < matrixARowSize; k++)
{
sum = sum + matrixA[i][j] * matrixA[i][j] ;
}
matrixFinal[i][j] = sum ;
sum = 0 ;
}
}
} else if (raiseByPower == 3) {
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
for (k = 0; k < matrixARowSize; k++)
{
sum += matrixA[i][j] * matrixA[i][j] * matrixA[i][j] ;
sum = 0 ;
}
matrixFinal[i][j] = sum ;
}
}
} else if (raiseByPower == 4) {
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
for (k = 0; k < matrixARowSize; k++)
{
sum += matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] ;
}
matrixFinal[i][j] = sum ;
sum = 0 ;
}
}} else if ( raiseByPower == 5) {
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
for (k = 0; k < matrixARowSize; k++)
{
sum += matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] ;
}
matrixFinal[i][j] = sum ;
sum = 0 ;
}
}
} else if ( raiseByPower == 6) {
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
for (k = 0; k < matrixARowSize; k++)
{
sum += matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] * matrixA[i][j] ;
}
matrixFinal[i][j] = sum ;
sum = 0 ;
}
}
}
System.out.println("Matrix A to the power of " + raiseByPower + " is: ") ;
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++)
System.out.print(matrixFinal[i][j] + "\t") ;
System.out.println();
}
} }
You can nest arrays as much as you want so something like int[][][] is certainly possible, which is an array of 2d arrays.
Well, you already have an int[][] so you can make an
int[][][] container = new int[numberofmatrixes][matrixsize][matrixsize];
and then add your matrixA or matrixFinal:
container[index] = matrixA;
and get values from matrixA:
int a = container[index][index2][index3];
where before you would have used
int a = matrixA[index2][index3];
You treat the 'container' array like any other array so the first matrix would be added at container[0], the second at container[1] and so on. You have to remember which matrix is at what index yourself.
In C, a 2d array and a 1d array are the "same thing", in that they are all calculated offsets from some memory address (a pointer, p). For example, to get the 5th element of an int array on a 32-bit compiler, you'd multiple (5-1)x4 and add that to the address p, which is written as p[4] (assuming that the type of p is a pointer to int and int is a 4-byte word). In Java, if p is an array of int, then you can likewise access the 5th one via p[4].
In C, you can access a 2d array in much the same way, e.g. p[4][2]. For example, see: http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm
The way it works in C is that the first number is multiplied by the size of the array in rows, then added to the second number, then multiplied by the element size. So p[4][2] is ((void*)p)+168 if the array is 10x10 and the "int" (aka word size) is 32 bits, i.e. it's the 42nd element.
Now to do a "two-dimensional array on an array" in Java is a little more complex, because the compiler doesn't do that math for you, but you can do it. Just make a class called Matrix, take rows & columns in the constructor, create the underlying 1-dimensional array, and have two methods called:
public T get(int row, int column)
put(int row, int column, T value)
etc.
Related
My goal is to create an adjacency matrix generator (the only value elements can have is 0 or 1; it has to be symmetric, meaning element in [i][j] == element [j][i]) in Java.
I have some code, but the result is an nx5 matrix (if I establish n = 13, the resulting matrix is a 13x5 matrix). It is symmetric and the values of elements is bounded between 0-1, so that is not an issue. Another problem is I don't really know how to have an array without doubles, which is more of an aesthetical problem + ideally, the diagonal would be filled with "-" instead of zeroes, as it is now.
Random random = new Random();
double[][] array = new double[n][n];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j <= i; j++)
{
int x = random.nextInt(2);
array[i][j] = x;
if (i != j)
{
array[j][i] = x;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j || (i + j + 1) == n)
{
array[i][j] = 0;
}
}
}
for (double[] a : array)
{
System.out.println(Arrays.toString(a));
}
}
My code is supposed to take the random number generated in the random method and sort them but it's only giving me one number.
My program is a random number generator that is supposed to make 1000 numbers that I can sort but my code only inserts one number into the array.
public static void main(String[] args) {
// write
int max = 1000;
int min=0;
int range = max - min + 1;
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
System.out.println ( rand );
int array[] = {rand};
int size = array.length;
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
}
}
You need to break your program into separate steps:
Insert all the random numbers into the array
Sort the array
Print the contents of the array
Few problems I noticed:
Since you want to generate 1000 numbers from 1-10, max and min should have values of 10 and 1, respectively.
array should be declared before you start inserting values. It should also have a fixed size of 1000.
Your bubble sort algorithm also had some errors which led to incorrect output. If you wish to sort the array from greatest to least instead, simply change the > to < in the condition of the if statement.
I also decided to use Arrays.toString() to print the array instead of the loop.
public static void main(String[] args) {
int max = 10;
int min = 1;
int range = max - min + 1;
int size = 1000;
int[] array = new int[size];
for (int i = 0; i < size; i++) {
int rand = (int) (Math.random() * range + min);
array[i] = rand;
}
int temp = 0;
for (int i = 0; i < size; i++) {
for (int j = 1; j < size - i; j++) {
if (array[j - 1] > array[j]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}
your code will result an ArrayIndexOutException. below is the code change from your code ,i dont change too much so you can compare them and find your mistakes,wish good :D
public static void main(String[] args) {
int max = 1000;
int min=0;
int range = max - min + 1;
int[] array = new int[range];
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
array[i] = rand;
}
int size = array.length;
for (int i = 0; i < size; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min1 = j;//here min1
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; k++) {
System.out.print(" " + array[k]);
}
}
let me explain it more clearly,in the OP's code there has some questions,two majors:
one:
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
will never run,because the array size is 1 ,so the for loop phrase will be ignore without running(mean for(int i = 0; i < 0; i++){....}).
two:
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
beacause the array size is 1,so when array[1] will throw index out exception.so the outermost loop will just run once then throw a exception.
:D
I am trying to solve this question:
Given an integer array, adjust each integers so that the difference of
every adjacent integers are not greater than a given number target.
If the array before adjustment is A, the array after adjustment is B,
you should minimize the sum of `| A[i]-B[i] |. You can assume each number in the array is a positive integer and not greater than 100.
`
I see a dp solution but I don't quite understand the recurrence equation.
public static int MinAdjustmentCost(ArrayList<Integer> A, int target) {
// write your code here
if (A == null || A.size() == 0) {
return 0;
}
// D[i][v]: 把index = i的值修改为v,所需要的最小花费
int[][] D = new int[A.size()][101];
int size = A.size();
for (int i = 0; i < size; i++) {
for (int j = 1; j <= 100; j++) {
D[i][j] = Integer.MAX_VALUE;
if (i == 0) {
// The first element.
D[i][j] = Math.abs(j - A.get(i));
} else {
for (int k = 1; k <= 100; k++) {
// 不符合条件
if (Math.abs(j - k) > target) {
continue;
}
int dif = Math.abs(j - A.get(i)) + D[i - 1][k];
D[i][j] = Math.min(D[i][j], dif);
}
}
}
}
int ret = Integer.MAX_VALUE;
for (int i = 1; i <= 100; i++) {
ret = Math.min(ret, D[size - 1][i]);
}
return ret;
}
Could someone explain it to me?
You need to minimize the cost of the adjustment, which is the value you increase/decrease every element such that the difference between every adjacent elements is less than or equal to target. The dp solution is to try every possible value and minimize the cost on the valid ones (when abs(A[i]-A[i-1]) <= target)
First thing is to fill the cost for adjusting first element to 1-100 which is done here:
for (int i = 0; i < size; i++) {
for (int j = 1; j <= 100; j++) {
D[i][j] = Integer.MAX_VALUE; // fill with MAX_VALUE because we want to minimize
if (i == 0) {
// for the first element we just set the cost of adjusting A[i] to j
D[i][j] = Math.abs(j - A.get(i));
}
Now you have D[0][j] as the cost to adjust the first element to be j. Then for every other element, you loop again (from k = 1 to k = 100) for other elements and try to change A[i] to j. And then you check if abs(k-j) is valid (less than or equal to target) then you can adjust A[i] to be j and A[i-1] to be k so you minimize on D[i][j].
Here D[i][j] means the cost of changing A[i] to j and D[i-1][k] is the cost of changing A[i-1] to k. so for every k and j if they are valid (abs(k-j)<=target) then you add them together and minimize the value saved in D[i][j] so you can use it for next element, which is done here:
else {
for (int k = 1; k <= 100; k++) {
// if abs(j-k) > target then changing A[i] to j isn't valid (when A[i-1] is k)
if (Math.abs(j - k) > target) {
continue;
}
// otherwise, calculate the the cost of changing A[i] to j and add to it the cost of changing A[i-1] to k
int dif = Math.abs(j - A.get(i)) + D[i - 1][k];
// minimize D[i][j]
D[i][j] = Math.min(D[i][j], dif);
}
}
At the end, you need to loop from 1 to 100 at the last element and check which is the minimum value over all, which is done here:
int ret = Integer.MAX_VALUE;
for (int i = 1; i <= 100; i++) {
ret = Math.min(ret, D[size - 1][i]);
}
I think if you split the initialization code and the DP calculation code it would be easier to understand, for example:
// fill the initial values
for (int i = 0; i < size; ++i) {
for (int j = 1; j <= 100; ++j) {
// on the first element just save the cost of changing
// A[i] to j
if (i == 0) {
DP[i][j] = abs(j-A.get(i));
} else {
// otherwise intialize with MAX_VALUE
D[i][j] = Integer.MAX_VALUE;
}
}
}
for (int i = 1; i < size; i++) {
for (int j = 1; j <= 100; j++) {
for (int k = 1; k <= 100; k++) {
// if abs(j-k) isn't valid skip it
if (Math.abs(j - k) > target) {
continue;
}
// if it is valid, calculate the cost of changing A[i] to j
// and add it to the cost of changing A[i-1] to k then minimize
// over all values of j and k
int dif = Math.abs(j - A.get(i)) + D[i - 1][k];
D[i][j] = Math.min(D[i][j], dif);
}
}
}
// calculate the minimum cost at the end
int ret = Integer.MAX_VALUE;
for (int i = 1; i <= 100; i++) {
ret = Math.min(ret, D[size - 1][i]);
}
public static void main(String[] args) {
// TODO code application logic here
int numRows = 5;
int numCols = numRows;
int[][] twoDimArray = new int[numRows][numCols];
Random randGen = new Random();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int randIndex = randGen.nextInt(4);
int value = randGen.nextInt(100);
twoDimArray[i][j] = value;
}
}
System.out.println("\nThe two-dimensional array: ");
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
}
}
I want to find a local minimum using a "brute force" approach. I know with a one dimensional array I would use a for-loop to compare all the elements in the array until I found a local minimum, but I don't know how to do that here.
Edit: Could I use binary search instead? Find the middle row and search there and if one isn't found, I search one of the halves.
The brute force method would be very similar to that of a 1D array, just with an extra loop, and a few more checks:
public int[] findLocalMinimum(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int current = arr[i][j];
if (i + 1 < arr.length && current >= arr[i + 1][j] ||
i - 1 >= 0 && current >= arr[i - 1][j] ||
j + 1 < arr[i].length && current >= arr[i][j + 1] ||
j - 1 >= 0 && current >= arr[i][j - 1]) {
continue;
} else {
return new int[] { i, j };
}
}
}
return new int[] { -1, -1 };
}
So I got a code with two arrays: one array contains tickets sold for three cinemas and the other one contains the adult and kid prices. My code outputs the total for every cinema separately (3 lines of output) but I need the total number of those 3. So instead of printing 828 for cinema1, 644 for cinema2, 1220 for cinema3 and I need it to print 2692 (total of 3 cinemas). How can I sum the 3 products with a for loop? Here's the code:
public class Arrays {
public Arrays() {}
public static void main(String[] args) {
float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
float[] b = new float[] {8, 4};
String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
String[] t = new String[] {"Adults", "Children"};
int i,j;
System.out.println("Cinema Complex Revenue\n\n");
for ( i = 0 ; i <= 2 ; i++ )
{
for ( j = 0 ; j < 1 ; j++ )
{
System.out.println(s[i] + "\t$" +
(a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
}
}
}
}
And the output: 1
Just code what you want.
int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length && j < b.length; j++) {
sum += a[i][j] * b[j];
}
}
System.out.println(sum);
Or if you want to use only one for loop, it may be
int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);
All you need is 1 nested for-loop:
Integer totalCost = 0;
for( i = 0 ; i<b.length; i++ ) {
//you should check if the a[i].length == b.length, and throw an exception if not!
for( j = 0 ; j<a.length; j++) {
totalCost += b[i]*a[j][i];
}
}
System.out.println("Total cost: "+totalCost.toString());