I'm having a pratice to create a n matrices with the same size. And I want to put it in a loop. Each matrix have a name.
So I decided to use OOP to implement these matrices:
In class matrix:
public class Matrix
{
static double mat[][] = null;
public matrix(int size)
{
mat = new double[size][size];
for (int i = 0; i< size; i++)
{
for(int j = 0 ; j< size;j++)
{
mat[i][j] = 0;
}
}
}
}
I have sucessfully create a loop but now the problem is I can't control the matrix. Like I want to change values in each matrix.
In main class:
for(int i = 0 ; i<n ;i++)
{
Matrix m = new Matrix(4);
m.print(plan);
System.out.println( );
}
My expectation is:
input: n = 4
output: 4 matrices
Using your class, here's some pseudo-code to help you:
-- Read user desired size
-- create a list of Matrix objects (List<Matrix> matrixList = new ArrayList<>();)
-- loop over the user input : for(int cur =0; cur<desiredNumberOfMatrices; cur++)
-- in each loop initiate a new matrix and add it to the list:
Matrix mat = new Matrix(size);
matrixList.add(mat);
-- do whatever you want next
I don't see why you might be stuck.
Related
I need to arrange numbers of a given size (provided by user at runtime), to 3 dimensional array to represent these numbers in real 3D space.
For example if user enters 7 then I need to create an array of size 2,2,2 and arrange the first 7 numbers given by user into the array starting from position 0,0,0 .
The cube should always be smallest possible for example cube of size 2 can contain 2*2*2 = 8 values. And need a function that can take input numbers and return 3D integer array with values inserted from input array (input[0] will become result[0][0][0] and so on).
int input[7] ;
int[][][] result = bestFunction(int[] input) {...}
I have implemented with 3 nested for loops by checking each value at a time.
Is there a better or faster approach to implement it?
Do a Math.floor(Math.cbrt(val)) to get the dimension size.
I think we can reduce it to level 1 nesting, or using two loops, using a string input for the z-axis values.
for(int i = 0; i<size; i++)
for(int j = 0;j<size;j++)
arr[i][j]= Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
where Scanner sc = new Scanner(System.in); if you're taking in user input.
Three for loops would be O(n) as long as you break right after the last element of the input is put in.
int[][][] func(int[] input) {
int size = (int) Math.ceil(Math.cbrt(input.length));
int[][][] result = new int[size][size][size];
int x = 0;
loop: for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
result[i][j][k] = input[x++];
if (x == input.length)
break loop; //Finish processing
}
}
}
return result;
}
I want to create dynamic matrix 2d using loop in java. My code is
class Mat {
public static void main (String[] args) throws java.lang.Exception {
List<List<Integer>> group = new ArrayList<>();
List<Integer> single = new ArrayList<>();
for (int i=0; i < 3; i++){
for (int j=0; j < 3; j++){
single.add(i);
}
group.add(single);
}
group.remove(3);
System.out.println(group);
}
}
First question, how to create dynamic matrix 2D with loop? I want an output like [[0,1,2], [0,1,2], [0,1,2]] and the matrix value saved in the variable group.
Second question, after being saved in the variable group, how about if I want to remove list (number 3) in the variable? So, output is [[0,1,2], [0,1,2]].
Thanks.
For the rest of your code creates a list List<List<Integer>> by changing
single.add(i);
to
single = new ArrayList<>(); // reset every iteration
for (int j=0; j < 3; j++) {
single.add(j); // add 0,1,2
}
how if i want remove list (number 3) in the variable?
group.remove(2); //removes the element at index 2
Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
I have the following code in which a matrix is defined through system input:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//define size of matrix
int size = in.nextInt();
int primeSum = 0;
int secSum = 0;
int[] matrix = new int[size*size];
//create matrix
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
in.close();
//sum primary diagonal
for (int i=0; i < size*size;i += (size + 1)) {
primeSum = primeSum + matrix[i];
}
////sum secondary diagonal
// for (int i=(size - 1); i < size*size; i += (size - 2)) {
// secSum = secSum + matrix[i];
// }
System.out.println(Math.abs(secSum - primeSum));
}
}
The code above works in that it allows the user to define an NxN matrix through inputting N as the size - so in the case size = 2 the user would define 4 matrix elements. However, after commenting back in the code for the secondary diagonal, the scanner object keeps expecting input past 4 integers - I have no idea why this would affect the program as I close the input stream before that block of code is reached.
You wrote a potentially infinite loop. I.e. if size is not greater than 2, then i will count down or stay 0. You should cover these corner cases, then your code will be fine.
As far as I can see, you're emulating a two-dimensional array on a one-dimensional. This is something that's hard to understand and easy to mess up. You are better off with a two-dimensional array and some nested loops:
int[][] matrix = new int[size][size];
//create matrix
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
matrix[i][j] = in.nextInt();
}
}
// and so on...
Your this part of code:
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
calls the method nextInt which demands for input as long as the array is filled.
I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}