I am trying to add asterisks on a line equal to the Int array. This starts at index 0 until the last index of the array. Here is what I have tried to do so far.
int e = 0;
int z = 0;
int[] yValuesInt = new int[yValues.length];
for (z=0; z<yValues.length; z++) {
yValuesInt[z] = (int) yValues[z]; // converted array from double to int
}
System.out.println("" + yValuesInt.length);
for (e = 0; e<yValuesInt.length; e++) { // outside loop to continue until last index
for (int j = 0; j<yValuesInt[z]; j++) { //inside loop to print asterisks
System.out.println(":" + asterisk);
}
}
Just a quick glance at your code at the printing of asterisks there. I didn't check on the loop though.
for (e = 0; e<yValuesInt.length; e++) { // outside loop to continue until last index
System.out.println(":");
for (int j = 0; j<yValuesInt[z]; j++) { //inside loop to print asterisks
System.out.print("*");
}
}
I believe this is what you're looking for as long as your loop count is correct.
Related
My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.
I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me
I Need to Write a Solution That Checks for Duplicate Values (Like Birthdays) in Each Iteration and Return the Number of Iterations That Have a Duplicate value within It. If One Duplicate is Found You Can Stop The Current Iteration And Start the Next.
What Of My Solution Should Be Altered. How Should A Solution Be Written To Solve This Duplicates Problem.
static int runSim(int thePeople, int theCount) {
int count = 0;
// Runs the Sim by Count
for(int i = 1; i <= theCount; i++) {
List<Integer> listOfGenNums = new ArrayList<>();
Random rand = new Random();
rand.setSeed(i);
ppl: for (int j = 0; j <= thePeople; j++) {
int genN = rand.nextInt(365);
// Add Values to Arraylist
listOfGenNums.add(j, genN);
// Converted ArrayList to Array
Object[] array = listOfGenNums.toArray();
// Check Item by Item
for(int h = 0; h <= array.length; h++) {
for(int k = i+1; k <= array.length-2; k++) {
// Checks if Index[i] is Same as Index[j]
if (array[h].equals(array[k])) {
count += 1;
break ppl;
} // End IF
} // End Inner Loop
} // End Loop
} // End People Loop
} // End Simulation Loop
return count;
}
I would use a HashSet. This would allow constant access to see if you have already visited the current number. If it has already been visited you can break and increment count, otherwise add it to the hashset and continue.
Here is your code rewritten to be much more efficient.
static int runSim(int thePeople, int theCount) {
int count = 0;
// Runs the Sim by Count
for(int i = 1; i <= theCount; i++) {
Hash<Integer> setOfGenNums = new HashSet<Integer>();
Random rand = new Random();
rand.setSeed(i);
for (int j = 0; j < thePeople; j++) {
int genN = rand.nextInt(365);
if(setOfGenNums.contains(genN)){
count++; break;
}
listOfGenNums.add(genN);
} // End People Loop
} //End Count Loop
return count;
}
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.charAt(0) != '#') {
c++;
// looking to get dimensions from file.
// getting size of array from lines of input.
dimensions = new int[c][4];
// Split my file input into an array of tokens(strings)
tokens = line.split(",");
for (int i = 0; i < tokens.length; i++) {
// Parse strings to int.
dimtoke[i] = Integer.parseInt(tokens[i]);
}
int n = 0;
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
// Error here when trying to put dimtoke into dimensions
(ERROR HERE)dimensions[k][j] = dimtoke[n];
n++;
}
}
}
The for loop to fill the dimensions array runs twice correctly, on the third iteration however, I am getting an ArrayIndexOutOfBounds:4 exception and I can't figure why. The size of the 2d array is correct, I need that counter n so that i can go through dimtoke array and it should reset itself each time through the while loop.
(This is all contained in a try/catch block, but couldn't add the 'try' for formatting issues on this sight.)
Here's the stack trace.
java.lang.ArrayIndexOutOfBoundsException: 4
at P1.readLineSegments(P1.java:49)
at P1.main(P1.java:16)
You have n++ in the wrong spot.
int n = 0;
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
// Error here when trying to put dimtoke into dimensions
(ERROR HERE)dimensions[k][j] = dimtoke[n];
}
n++; //it should be here
}
Where you have n++ it will go up 16 if it is a 4x4 array.
it can be dimensions[k][j] or dimtoke[n]. k is the length of dimension so it is out of question. j is 0..3 ( if it is as simple as code shows. so dimensions[0].length can be replaced with 4.)
the only problem is with dimtoke[n] and it seems size of your tokens are less than 4 * dimensions.length
My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}