Get a Matrix from another Matrix - java

So guys, I'm developping a program for Structural Analysis and I came across a problem that I'm having some problem to solve. Basically, I have a system of equations, of which I only need to solve some of them.
The ones I need to solve depend on a boolean array, true if I do, false if I don't. This way, having a true value in the nth element of the array means I'll have to solve the nth equation, therefore meaning that I have to get the nxn element of the matrix of the system of equations.
Do you guys have any insight on it?

So, this is what I've come up with:
//Firstly, define the size of the subsystem:
int size = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0)
size+= 1;
}
//Then we can assign the size values to the Matrix of the subsystem
System_A = Matrix.matrizEmpty(size,size);
System_B = Matriz.matrizEmpty(size, 1);
//This array will store the coordinates of the coefficients that
//will be used
int[] Coordinates = new int[size];
//We store these coordinates in the array
int count = 0;
for(int i = 0; i < TrueorFalseMatrix.m; i++) {
if(TrueorFalseMatrix.data[i][0] != 0) {
Dtrue[count] = i;
count++;
}
}
//We can now assign values to our system Matrix
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
System_A.data[i][j] = SourceMatrix.data[Dtrue[i]][Dtrue[j]];
}
System_B.data[i][0] = SourceResultVector.data[Dtrue[i]][0]
}
//Results
double[] Results = System.solve(System_A,System_B);

Related

How do I print nested ArrayLists?

My fourth for loop, for (int y), keeps printing the first m elements over and over again, how can i fix it so that it prints m elements at a time but not the same ones?
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) { //swimmers
myname.add(input.next());
for (int j = 0; j < m; j++) { //judges
myscore.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(myname.get(x));
for (int y = 0; y < m; y++) { //score
System.out.println(myscore.get(y));
}
}
Based on your code it seems that you have ‘n’ number of swimmers, each with ‘m’ number of scores. You are storing the names of the ‘n’ swimmers in an ArrayList, which is bad because you know the number will never change. A better approach to this would be to declare myname as a String[] of size n, and instead of calling myname.get(x) you would later call myname[x].
This however, is only symptomatically related to the problem at hand. You are storing all of your score results inside a single ArrayList. A better solution is to generate ‘n’ number of arrays (which is what I assume you would like to do based on the title of this question). This can be done by simply declaring
allScores[][] = new int[n][m]
This would let you access the values for swimmer number ‘n’ with allScores[n]. If this isn’t what you actually wanted to do then you can simply offset the values in your last get statement by the number of scores you’ve already processed (x*n).
TLDR: Change the line in your last for loop to read:
System.out.println(myscore.get(y + x*n)
Because you have a list myscore of n*m length not only m like you thought. You are adding at the end of the list every score.
So you have n blocks of m elements in the list. You could still print the value with
for(int y = x * m, to = x*m + m; y < to; ++y){
System.out.println(myscore.get(y));
}
class ScoreHolder{
String name = "";
ArrayList<Integer> scores = new ArrayList<Integer>;
public ScoreHolder(String name){
this.name = name
}
}
And then
ScoreHolder[] scores = new ScoreHolder[n];
for (int i = 0; i < n; i++) { //swimmers
scores[i] = new ScoreHolder(input.next());
for (int j = 0; j < m; j++) { //judges
scores[i].scores.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(scores[x].name);
for (int y = 0; y < m; y++) { //score
System.out.println(scores[x].scores.get(y));
}
}
It won't be just easy to work with now but also a lot easier to make any changes or do anything else you want.
What I have done is simply created a holder class which will hold the swimmer's name and a list of all his scores.
This abstraction will now help you in getting the scores of the swimmers or doing anything else you now want with it.

How to create multiple arrays with a loop?

I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}

Java Union array of 2 int arrays using nested loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to create a union array for two integer arrays using nested loops.
This is my attempt so far:
import java.util.Scanner ;
public class array4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first array size:");
int size = input.nextInt();
int x[] = new int[size];
System.out.println("Enter first array elements:");
for (int i = 0; i < size; i++) {
x[i] = input.nextInt();
}
System.out.print("Enter second array size:");
int size2 = input.nextInt();
int y[] = new int[size2];
for (int i = 0; i < size2; i++) {
y[i] = input.nextInt();
}
System.out.println("Union");
for (int i = 0; i < size; i++) {
System.out.println(x[i]);
}
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
}
}
}
}
}
Lets assume that we will print all numbers from second array, and only these numbers from first array which don't exist in second one. So
for each element in first array
test if it exist in second array (iterate over elements in second array and set some boolean flag like exists to true if x[i]==y[j])
if element doesn't exist in second array print it
iterate over elements from second array
and print them
Algorithm can look like
for (int i = 0; i <= x.length; i++) {// "<=" is not mistake,
// in last iteration we print all elements
// from second array
boolean exist = false;
for (int j = 0; j < y.length; j++) {
if (i < x.length) {
if (x[i] == y[j])
exist = true;
} else
System.out.println(y[j]);
}
if (!exist && i < x.length)
System.out.println(x[i]);
}
This algorithm can be probably rewritten to something simpler but I will leave it in this form for now.
For the lack of requirements, here is my answer for now... just basing on your current code.
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
break; //added break
}
}
}
The problem was you're printing array elements without duplicate multiple times, to avoid that, you should add a break after you print the element with no duplicate.
By the way, your code is just printing the elements on both arrays, I thought you're suppose to combine them? Shouldn't you have a new array that contains both of the elements on the two arrays?
EDIT 2:
Add these lines of code after you get the two set of arrays without duplicate:
I also added comments to explain what's happening.
System.out.println("Union");
int[] unionArray = new int[size + size2]; //created a new array that will contain two arrays
for (int i = 0; i < size; i++) { //put the first set of int in the new array
unionArray[i] = x[i];
}
for (int i = size; i < unionArray.length; i++) { //put the second set
unionArray[i] = y[i-size]; //i = size : started with the last index of the first array
//y[i-size] : we are getting the elements on the second array
}
for (int i = 0; i < unionArray.length; i++) { //output
System.out.println(unionArray[i]);
}
Hope this helps. :)
If it's just to play with arrays and you don't need to use loops - try using a Java collection for that task, that's how most people would probably implement it:
init collection 1 from array 1
init collection 2 from array 2
add collection 2 to collection 1
convert collection 1 back to an array
That can be a (more or less) neat one-liner.

MultiDimensional ArrayList in kmeans clustering algorithm

I am trying to implement kmeans algorithm for a certain Music Recommendation System in Java.
I have generated 2 arrays,playsFinal[](the total play-count of an artist by all users in the dataset) and artFinal[] (the unique artists in the entire dataset) . The playcount of every artFinal[i] is playsFinal[i]. For k,I have chosen kclusters=Math.sqrt(playsFinal.length)/2.
I have an array clusters[kclusters][playsFinal.length] and the first position clusters[i][0] for every 0<i<kclusters is filled with a certain value,which is basically the initial mean as in kmeans algorithm.
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
Here,weight[] is a certain score given to every artist.
Now,in the following function I am returning the index,ie,which cluster the plays[i] should be added to.
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
If not obvious,I am finding the minimum distance between playsFinal[i] and the initial element in every clusters[j][0] and the one that is the smallest,I am returning its index (kfound). Now at the index of the clusters[kfound][] I want to add the playsFinal[i] but here is where I am stuck. I can't use .add() function like in ArrayList. And I guess using an ArrayList would be way better. I have gone through most of the articles on ArrayList but found nothing that could help me. How can I implement this using a multidimensional ArrayList?
Thanks in advance.
My code is put together as follows:
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
double[] weighty = new double[artFinal.length];
for (int i = 0; i < artFinal.length; i++) {
weighty[i] = (playsFinal[i] * 10000 / playsFinal.length);
}
n = playsFinal.length;
kclusters = (int) (Math.sqrt(n) / 2);
double[][] clusters = new double[kclusters][playsFinal.length];
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
int kfound;
for (int i = 0; i < playsFinal.length; i++) {
kfound = smallestdistance(playsFinal[i], clusters);
//HERE IS WHERE I AM STUCK. I want to add playsFinal[i] to the corresponding clusters[kfound][]
}
}
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
Java's "multidimensional arrays" are really just arrays whose elements are themselves (references to) arrays. The ArrayList equivalent is to create a list containing other lists:
List<List<Foo>> l = new ArrayList<>(); //create outer ArrayList
for (int i = 0; i < 10; i++) //create 10 inner ArrayLists
l.add(new ArrayList<Foo>());
l.get(5).add(foo1); //add an element to the sixth inner list
l.get(5).set(0, foo2); //set that element to a different value
Unlike arrays, the lists are created empty (as any list), rather than with some specified number of slots; if you want to treat them as drop-in replacements for multidimensional arrays, you have to fill them in manually. This implies your inner lists can have different lengths. (You can actually get "ragged" multidimensional arrays by only specifying the outer dimension (int[][] x = new int[10][];), then manually initializing the slots (for (int i = 0; i < x.length; ++i) x[i] = new int[i]; for a "triangular" array), but the special syntax for multidimensional array creation strongly predisposes most programmers to thinking in terms of "rectangular" arrays only.)

Return position of value in a 2D array, Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm tired. This must be simple. wood... for.... trees....
I'm trying to return the position of a specific value in a 2D array.
I have a double array [300][300].
All values contained in it are 0 apart from one which is 255.
How do I write a method to return the [i][j] location of 255?
Thanks in advance.
Simply iterate over all the elements until you find the one that is 255:
for ( int i = 0; i < 300; ++i ) {
for ( int j = 0; j < 300; ++j ) {
if ( array[i][j] == 255 ) {
// Found the correct i,j - print them or return them or whatever
}
}
}
This works:
public int[] get255() {
for(int i = 0; i < array.length; i++)
for(int j = 0; j < (array[i].length/2)+1; j++)
if(array[i][j] == 255)
return new int[] {i,j};
else if(array[j][i] == 255) //This just slightly increases efficiency
return new int[] {j,i};
return null; //If not found, return null
}
This is possibly the fastest, though. It checks starting in each corner, progressively working inward to the center, horizontally first, then vertically:
public int[] get255() {
for(int i = 0; i < (array.length/2)+1; i++)
for(int j = 0; j < (array[i].length/2)+1; j++)
// Check the top-left
if(array[i][j] == 255)
return new int[] {i,j};
// Check the bottom-left
else if(array[array.length-i][j] == 255)
return new int[] {array.length-i,j};
// Check the top-right
else if(array[i][array[i].length-j] == 255)
return new int[] {i,array[i].length-j};
// Check the bottom-right
else if(array[array.length-i][array[i].length-j])
return new int[] {array.length-i, array[i].length-j};
return null; //If not found, return null
}
You can use binary search for each column.
Use for loop to iterate over each column as it is an 2d array.
Once you get all the rows from the specific column you are iterating ( which would be another array), do a binary search on them.
Conditions Apply:
1. If the array is sorted .
2. If you are sure that only one element is there in each column. ( No duplicates).
3. If there are duplicates in the rows( do linear search) .
I hope it helps. Please feel free to ask if still in doubt :)
For any size of Array, you have put to the size first, though I have used a scanner to input value directly, you can bring it from another method also, I am learning so if I am wrong please correct me. On your case value will be 255 instead of 1.
public class MagicSquareOwn {
public static int[] findValueByElement(int n) {
Scanner input = new Scanner(System.in);
int[][] squareMatrix = new int[n][n];
int[] position = null;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
squareMatrix[i][j] = input.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (squareMatrix[i][j] == 1) {
position= new int[] { i, j };
System.out.println("position is:" + Arrays.toString(position));
}
}
}
return position;
}
public static void main(String[] args) {
Scanner inputOfMatrixNo = new Scanner(System.in);
int n = inputOfMatrixNo.nextInt();
MagicSquareOwn.findValueByElement(n);
}
}

Categories

Resources