Dealing with arrays as method results - java

So I've got this method:
public static int[] select(int maxWidth, int maxHeight) {
int rHeight = StdRandom.uniform(0, maxHeight);
int rWidth = StdRandom.uniform(0, maxWidth);
return new int[] {rHeight, rWidth};
}
And I'm not advanced enough to work with it on the right way.
I've got a second method where I want to execute 'select' several times. My idea was to do it with a for-loop like that (in which 'n' is a int):
for(int i = 0; i < n; i++){
select(h, w);
}
But now I don't know how to save the result from this for-loop in an 1d-array, since I will always get an error when trying to save like that:
int[] a = new int[select(h, w)];
I'm very aware that this looks very strange and wrong but I just don't know how to do it in the right way and I don't know for what I have to search on google.

Here is a way you could do it:
int[][] a = new int[n][];
for(int i = 0; i < n; i++){
a[i] = select(h, w);
}
Basically this code creates a 2d array, then in the for loop, adds the result of select to each element of the array.

I don't think you can do this in a 1D array, if you want to run select multiple times, and each time it returns an array, you'll have to have an array of arrays. If you are adamant about having a 1D array to store the answers, you'll have to implement a tuple class, although I think you're better off just doing a 2D array the way Sub 6 Resources showed.

int[] combined = new int[n*2];
for(int i = 0; i < n; i++){
int a[] = select(h, w);
System.arraycopy(a, 0, combined, i*2, 2);
}

Related

Java method to multiply an ArrayList of decimal values by an array of doubles to get an array of ints?

Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

Inserting number in an array

How do I add a number(73) into the middle of an array and then move all the numbers from the middle up one so no number is overwriting. Here is my code so far the 73 should go into the middle and the numbers after it should all move over. Can't use an ARRAYLIST.
int midpoint = length/2;
array[midpoint] = 73;
for (int i = midpoint; i<length; i++){
aNums[i+1] = array[i];
System.out.print(array[i] + " ");
}
displayArray1(array,length);
You can't add to an array. You first have to create a bigger array.
int[] newArray = new int[array.length + 1];
Then you have to copy the first half of the array
for(int i = 0; i < midpoint; i++) {
newArray[i] = array[i];
}
Then put the new midpoint in
newArray[midpoint] = 73;
Then copy the other half
for(int i = midpoint + 1; i < array.length; i++) {
newArray[i+1] = array[i];
}
And then newArray has the new midpoint.
Technically the last three steps could be done in any order, but it is much more readable to do them in that order. Now you can call your display method or really do whatever you want with it.
There is a utility method called arrayCopy that can assist with moving the array elements. You may or may not be permitted to use it. It's a bit wordy with its parameters, but is a bit faster than a typical for-loop at runtime because it leverages native code.
int[] newArray = new int[array.length + 1];
System.arrayCopy(array,0,newArray,0,midpoint);
newArray[midpoint] = 73;
System.arrayCopy(array,midpoint,newArray,midpoint+1,array.length - midpoint);
To explain those calls, the arraycopy uses:
System.arrayCopy(arrayFrom,
startPosInArrayFrom,
arrayTo,
startPosInArrayTo,
numElementsToCopy);
Use a List, or more specifically an ArrayList:
ArrayList<Integer> list = new ArrayList<>();
// ... put stuff in list
int midpoint = list.size()/2;
list.add(midpoint, 73);
you are causing yourself a lot more trouble using an array.
use an ArrayList, which is backed by an array
ArrayList l = new ArrayList();
//...fill contents
int index = l.size()/2;
l.add(index, 72);

add values in a array list

I have the following ArrayList
ArrayList<double[]> db_results = new ArrayList<double[]>();
Which is populated by the following loop
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
How can i add the values from the same position in each array to make another array??
So 1+1+1=3 would be position one of the new array 2+2+2=6 would be position two of the new array and 3+3+3=9 would be position three of the new array??
Cheers
A nested loop would do it.
I would encourage you to take the time to do a Java tutorial or read a textbook. This is really basic stuff, and you'd do better learning the language properly than learning by trial and error interspersed with random SO questions.
By the way, this line from your code won't compile:
double val = Double.parseDouble(i);
The i variable is declared as an int and the parseXxx methods take a String argument. To convert an int to double, just assign it:
double val = i;
This might be what you're looking for:
double[] newArray = new double[3];
for (double[] array : db_results) {
for (int i = 0; i < 3; ++i) {
newArray[i] += array[i];
}
}
It will work after db_results has been populated. You can also compute the sum array at the same time that db_results is being populated using slukian's method.
Either a java math function or a nested loop its for your answer. Try yourself its just a mathematical calculation.

Categories