How do I print nested ArrayLists? - java

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.

Related

I need help in this (Sums In Loops)

Hello Guys i just need help this is the problem I want to solve:
Input data will contain the total count of pairs to process in the
first line.
The following lines will contain pairs themselves - one pair at each
line.
Answer should contain the results separated by spaces.
Example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
i write the code and here it is
public class SumsInLoopAdvanced {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
int a =0;
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
a = arr[j]+arr[i];
}
System.out.print("Answer: \n" + a);
}
}
}
it just 245+15 the wrong answer so could you help me ??
your code is broken here:
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
because you are overwriting the previously filled array: arr[i]
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
If i got it right you need to print a sum of two arrays entries for each index.
First of all you are using the same array and you are overwriting everything that you did in a first loop by the second loop.
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
//writing into the same array starting with 0 index
arr[j] = reader.nextInt();
}
And if I got this exercise right you don't need a nested loop, you need to to find a sum of two array elements from different arrays with the same index.
something like this:
for (int i = 0; i < num; i++) {
a = arr1[i] + arr2[i];
System.out.print(a + " ");
}
You're overwriting the values in arr on your second loop.
If you want to collect two sets of values, you'll need two arrays. (Well, not need, but that would be the reasonable way.) Also note that you don't need or want the nested loop at the end; just add the ith entry from the first array to the ith entry of the second.
Side note: Instead of a hardcoded upper bound on the array (250), use num so you know it's always big enough (e.g., if I tell you I'm going to enter 300 numbers, your code will blow up). int[] arr = new int[num];
But, now that the problem you're trying to solve is quoted in the question, note that your code doesn't want to read in a bunch of values, then read in a second bunch of values, and then add those together. The assignments says you'll enter things like "100 8" and then "15 245" and be meant to add those to get 108 and 260.
So you'll need to read the first number, then the second, add those and store them in your (one) array; then read the next third number, and the fourth, add those together and store them; and then output the results.

Get a Matrix from another Matrix

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);

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.)

Categories

Resources