Problem accessing multidimensional array length and fields - arrays

Here is code to test a multidimensional array
public class Multiarraytest {
public int size_main = 5;
public int size_aux = 20;
Multiarraytest() {
float[][] float_mul = new float[size_main][size_aux];
}
void init_int(Multiarraytest mul) {
int i, j = 0;
while(i < mul.length) {
while(j < mul[i].length) {
mul[i][j] = (i + (j/10));
j++;
}
i++;
}
}
public static void main(String[] args) {
}
}
But
here are the results of javac Multiarraytest.java.
error: cannot find symbol While(i < mul.length)
^
symbol: variable length
location: variable mul of type Multiarraytest
error: array required, but Multiarraytest found while(j < mul[i].length
^
error: array required, but Multiarraytest found mul[i][j] = (i + (j/10));
I have not found what's going wrong.
mul is a 2 dimensional array
mul.length should give the length of the first array
mul[1] should lead to the array nested in the first case of mul
mul[1].length should give the length of the array nested in the first case of mul
mul[1][2] should give access to read/write of the second case of the array nested in the first case of mul.
Where have I made a mistake?
This is a cut down version of what I was doing but same errors are reported. I read tutorial and close copy-cut it. Except it's a float multidimensional array instead of int multidimensional array and I try to fill it in a loop instead at the initializing time.

Related

Given an array in which arr[i] = i-1 with the following method, what will be the output?

I'm given the following method written in pseudo-code
for i=1 to floor(n/2)
if arr[i] != 0 then
for(j=2 to floor(n/i)
arr[i*j] = 0
I need to find the output and to prove that it's indeed the output.
So far I tried to write the code in Java and to try different inputs and array sizes but to no avail.
Putting it here if it's of any help:
public class Checking
{
private static int method(int[] A,int n)
{
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
if(A[i] != 0)
{
for(int j=2;j<=java.lang.Math.floor(n/i);j++)
{
A[i*j]=0;
System.out.println("The index ofA["+i*j+"] became "+A[i*j]);
}
}
//System.out.print(", "+A[i]);
}
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
return 0;
}
public static void main(String[] args)
{
int[] A = {-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
System.out.println(method(A,20));
}
}
Thank you.
You can change the following:
In your main method remove
System.out.println(method(A,20));
as it will always print 0 as you return 0; from the method().
As you print everything in your method() change the following (as it does not print the full array but from index 1 (missing index 0) to floor n/2)
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
to
for (int i=0;i<A.length; i++)
{
System.out.print(", "+A[i]);
}
So you can print the whole array.
For simplicity you can use Array's print method to print the array without a for loop
System.out.println(Arrays.toString(A));

How to print values from a multidimensional array in MQL5?

In MQL4, I could use the following function to print values from a two-dimensional array:
string Arr2ToString(double& arr[][], string dlm = ",", int digits = 2) {
string res = "";
int i, j;
for (i = 0; i < ArrayRange(arr, 0); i++) {
res += "[";
for (j = 0; j < ArrayRange(arr, 1); j++) {
res += StringFormat("%g%s", NormalizeDouble(arr[i][j], digits), dlm);
}
res = StringSubstr(res, 0, StringLen(res) - StringLen(dlm));
res += "]" + dlm;
}
res = StringSubstr(res, 0, StringLen(res) - StringLen(dlm));
return res;
}
However in MQL5 (version 5.00, build 1966), above function no longer works and it errors with:
'[' - invalid index value Array.mqh
in the first line when arr[][] is passed.
I've checked and MQL5 no longer allows passing an array with no dimension sizes.
When passing multidimensional arrays to a function, dimension sizes (except for the first one) should be specified:
double var[][3][3];
void Func(double &arg[][3][3]){ // ... }
Source: MQL5 PROGRAMMING BASICS: ARRAYS.
This doesn't make sense.
Assuming I don't know the size of my array (as I want to re-use this function for multiple array types, and defining dozens of separate functions for each size is ridiculous), how it is possible now to print values from a multidimensional array storing double values (such as two-dimensional array as example)?
I know this is not ideal, but we can use ArrayPrint() to print array.
Refer here for the documentation
void ArrayPrint(
const void& array[], // printed array
uint digits=_Digits, // number of decimal places
const string separator=NULL, // separator of the structure field values
ulong start=0, // first printed element index
ulong count=WHOLE_ARRAY, // number of printed elements
ulong flags=ARRAYPRINT_HEADER|ARRAYPRINT_INDEX|ARRAYPRINT_LIMIT|ARRAYPRINT_ALIGN
);
Here is another approach to pass multi-dimentional array to a function, again it is not ideal, but it works properly.
//+------------------------------------------------------------------+
//| Struct that is used to hold multi-dimentional array |
//+------------------------------------------------------------------+
template<typename T>
struct MultiDimentionalArray
{
T index2[];
};
//+------------------------------------------------------------------+
//| Array print function that accepts MultiDimentionalArray struct |
//+------------------------------------------------------------------+
string Arr2ToString(MultiDimentionalArray<double> &arr[],string dlm=",",int digits=2)
{
string res="";
int i,j;
for(i=0; i<ArraySize(arr); i++)
{
res+="[";
for(j=0; j<ArraySize(arr[i].index2); j++)
{
res+=StringFormat("%g%s",NormalizeDouble(arr[i].index2[j],digits),dlm);
}
res = StringSubstr(res,0,StringLen(res) - StringLen(dlm));
res+= "]" + dlm;
}
res=StringSubstr(res,0,StringLen(res)-StringLen(dlm));
return res;
}
Here is an example execution
void OnStart()
{
//--- Declaring an array
MultiDimentionalArray<double> arr[];
//--- Adding values to the array
for(int i=0;i<10;i++)
{
//--- Resizing the array - 1st dimention
if(ArraySize(arr)<=i) ArrayResize(arr,ArraySize(arr)+1);
for(int j=0;j<10;j++)
{
//--- Resizing the array - 2nd dimention
if(ArraySize(arr[i].index2)<=j) ArrayResize(arr[i].index2,ArraySize(arr[i].index2)+1);
arr[i].index2[j]=i*j;
}
}
//--- Getting the result as string
string arrResult=Arr2ToString(arr);
//--- Printing the result string
Print(arrResult);
}
Here is the result I got in the experts tab, from the execution of the above code
2019.06.11 16:25:47.078 Arrays (EURUSD,H1) [0,0,0,0,0,0,0,0,0,0],[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,10,12,14,16,18],[0,3,6,9,12,15,18,21,24,27],[0,4,8,12,16,20,24,28,32,36],[0,5,10,15,20,25,30,35,40,45],[0,6,12,18,24,30,36,42,48,54],[0,7,14,21,28,35,42,49,56,63],[0,8,16,24,32,40,48,56,64,72],[0,9,18

I getting ArrayIndexOutOfBoundsException

I am trying to convert a String array to int array and then compare elements if they are equal so far i am getting an error, first this is the method that converts string array to to int array
private static int[] convertStringArrayToIntArray(String[] strVals) {
int[] intVals = new int[strVals.length];
for (int i=0; i < strVals.length; i++) {
intVals[i] = Integer.parseInt(strVals[i]);
}
Arrays.sort(intVals);
return intVals;
}
Now the method below is where i am getting the exception
public static String ScaleBalancingCorrect(String[] strArr) {
int[] startWeights = convertStringArrayToIntArray(strArr[0].replaceAll("[^0-9,]", "").split(","));
int[] availWeights = convertStringArrayToIntArray(("0," + strArr[1]).replaceAll("[^0-9,]", "").split(","));
if (startWeights[0] != startWeights[1]) { //I get exception here
for (int i = 0; i < availWeights.length; i++) {
// omited code for brevity
this is what i was running when i got the exception
public static void main(String [] arg) {
String [] arr = {"34","1277"};
ScaleBalancingCorrect(arr);
}
Maybe it's just a typo and you wanted to write if (startWeights[0] != availWeights[1]).
availWeights will always have at least two elements, since you add 0 as a first element before the supplied other element(s).
startWeights, however, as in your example, may only have one element (in your example, it's 34).

Have to create 2d array (4x4) array and has to fill the diagnal with 1s and rest of the spaces with 0s

public class sampleq8
{
public static void main(String args[])
{
int size =4;
int array[][]=new int[size][size];
for(int i=0; i<array.length;i++)
{
for(int j=0;j<array.length;j++)
{
array[0][0]=1;
}
//array[4][4]=1;
// array[
System.out.println(array[i][i]);
}
}
}
i got to print out the first column correctly i cant produce the rest of the rows or the columns i need some suggestions please thanks.
Java initializes all the values of your array to 0 automatically, you only need to assign values to the diagonal.
int size =4;
int array [][] = new int[size][size];
for (int i =0;i<size;i++){
array[i][i]=1;
}
System.out.println(Arrays.deepToString(array));
This does the job.
In your version you are only setting the value 1 to the element with coordinates 0,0 in your array
To print your array you need to import java.util.Arrays;
This one will print the matrix nicely
for (int i =0 ;i<4;i++){System.out.println(Arrays.toString(array[i]));}
Your assignment is always using the 0,0 element.
array[0][0]=1
You need to set the assignment like this:
array[i][j]=1
try something like this, dont know if it works, i cant run it right now
for(int i = 0; i<size; i++)
{
array[i][i] = 1;
}
for(int i=0; i<array.length;i++)
{
for(int j=0;j<array.length;j++)
{
if(array[i][j] != 1)
array[i][j]=0;
}
}

Sum Specified Column Jagged Array

My homework assignment is asking to output the sum of a specified column of a Jagged 2D Array. I've seen other solutions that show how to get the sum of ALL columns, but not a specific one. The issue I'm running into is that I get a java.lang.ArrayIndexOutOfBoundsException if a column is entered and no element exists in a row of the 2D array.
// returns sum of specified column 'col' of 2D jagged array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
for (int j = 0; j < array[col].length; j++) {
sum += array[j][col];
}
return sum;
} // end columnSum()
Example: Ragged Array Input (class is named RaggedArray)
int[][] ragArray = { {1,2,3},
{4,5},
{6,7,8,9} };
System.out.println(RaggedArray.columnSum(ragArray, 2));
This obviously gives me an ArrayIndexOutOfBoundsException, but I don't know how to fix it if a specified column is asked for as an argument. Any ideas? I appreciate any help or suggestions!
In your loop, do a
try{
sum += array[j][col];
}catch(ArrayIndexOutOfBoundsException e){
}
block, where it simply skips over if there is nothing, and keeps going to the next one.
you will have to import that exception as well. If you run into trouble, just look up how try/catch blocks work
Here is another solution I found.
// returns sum of the column 'col' of array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
try {
for (int j = 0; j < array.length; j++) {
if (col < array[j].length)
sum += array[j][col];
}
}
catch (ArrayIndexOutOfBoundsException e){
}
return sum;
} // end columnSum()
public class JaggedArrayColSum {
int[] jackedArrayColSum(int arr[][]){
int sum;
int maxLen=0;
boolean status;
//START #MAX LENGTH
//Finding the max length of inner array
for(var a=0;a<arr.length;a++) {
status=true;
for(var b=0;b<arr.length;b++) {
if(a==b)continue;
if(arr[a].length<arr[b].length) {
status=false;
break;
}
if(status)maxLen=arr[a].length;
}
}
//END #MAX LENGTH
//START #SUM JAGGED ARRAY
int [ ] arr1=new int[maxLen];
for(var a=0;a<maxLen;a++) {
sum=0;
for(var b=0;b<arr.length;b++) {
if(arr[b].length>a)sum+=arr[b][a];
}
arr1[a]=sum; //Adding values to the the return array index
}
//END #SUM JAGGED ARRAY
return arr1;
}
public static void main ( String [ ] args ) {
int [][]arr= {{1},{1,3},{1,2,3,4},{1,2,3,4,5,6,7}};
for(int x:new JaggedArrayColSum().jackedArrayColSum ( arr ))System.out.print ( x +" " ) ;
}
}

Resources