I want to remove elements that are in routedClients from array, so I converted it to an ArrayList, then used remove, finally I converted it back to double[][] array. But when I execute it, it gives me this message about this line:
double[][] remainingStockout = (double[][]) stockout.toArray();
The error is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Double;
Any help would be really appreciated. :)
public double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray();
return remainingStockout;
}
The below appears to work
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][]{});
Full class for testing:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
static ArrayList<Double> routedClients = new ArrayList<Double>();
public static void main(String[] args) {
double[][] arr1 = { { 2, 4, 6 }, { 3, 6, 9 }, { 5, 10, 15 } };
routedClients.add(new Double(1));
routedClients.add(new Double(2));
routedClients.add(new Double(3));
print(arr1);
double[][] arr2 = removeSite(arr1);
print(arr2);
}
private static void print(double[][] arr1) {
for (int i = 0; i < arr1.length; i++) {
double[] arr2 = arr1[i];
for (int j = 0; j < arr2.length; j++) {
System.out.println("arr1[" + i + "][" + j + "] = " + arr1[i][j]);
}
}
}
public static double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
System.out.println("length before = " + stockout.size());
for (int i = array.length-1; i >= 0; i--) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
System.out.println("removing " + routedClients.get(j));
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][] {});
System.out.println("length after = " + remainingStockout.length);
return remainingStockout;
}
}
Here is the output
arr1[0][0] = 2.0
arr1[0][1] = 4.0
arr1[0][2] = 6.0
arr1[1][0] = 3.0
arr1[1][1] = 6.0
arr1[1][2] = 9.0
arr1[2][0] = 5.0
arr1[2][1] = 10.0
arr1[2][2] = 15.0
length before = 3
removing 3.0
removing 2.0
length after = 1
arr1[0][0] = 5.0
arr1[0][1] = 10.0
arr1[0][2] = 15.0
You are trying to cast an object into an array.
This cannot be done.
Instead you will need to convert each element in the array and then need to add it to they the 2D Array.
The following line will never work:
double[][] remainingStockout = (double[][]) stockout.toArray();
You can cast a double array into a list array because the compiler just makes a list with all the elements, but the compiler can't know which size to make a 2D array.
Maybe you could try creating a list of lists. You would need to traverse your array two more times though. One for assigning the values to the nested list and then to assign them again to the double array before returning the value.
you can use the overloaded method of toArray() .. like this -
double[][] remainingStockout = new double[array.length][array.length];
stockout.toArray(remainingStockout);
Related
I have the 2D array and printed them out backward. What I am trying to achieve is to copy each line of printed row to a regular array. Is it possible to do that?
Integer[][] testList;
testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
for (int i = 0; i < testList.length; i++) {
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
}
System.out.println();
}
This will copy any size 2D array of ints.
int[][] testData = { { 1, 2, 3 },{}, null, { 4, 5, 6, 7 },null,{ 8, 9 },
{ 10, 11, 12 } };
int[] result = copy2DArrays(testData);
System.out.println(Arrays.toString(result));
prints
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
First, compute size of result array. This also handles null rows.
if a null row is encountered, replace with an empty array for copy phase.
Allocate the return array of computed size
Then for each row
iterate thru the row, copying the value to result array indexed by k
When done, return the resultant array.
public static int[] copy2DArrays(int[][] array) {
int size = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
// replace null row with empty one
array[i] = new int[]{};
continue;
}
size += array[i].length;
}
int k = 0;
int[] result = new int[size];
for (int[] row : array) {
for (int v : row) {
result[k++] = v;
}
}
return result;
}
Another, simpler option is using streams.
stream the "2D" array
only pass nonNull rows
flatten each row into a single stream
then gather them into an array.
int[] array = Arrays.stream(testData)
.filter(Objects::nonNull)
.flatMapToInt(Arrays::stream)
.toArray();
You can create a new array and then copy the values into it:
for (int i = 0; i < testList.length; i++) {
int[] copy = new int[testList[i].length];
int copyIndex = 0;
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
copy[copyIndex++] = testList[i][j];
}
}
The Arrays class gives you a lot of nifty features:
public static void main(String[] args) {
Integer[][] testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
int max = 0;
for (Integer[] row : testList) {
max = Math.max(max, row.length);
}
Integer[][] copy = new Integer[testList.length][max];
for (int i = 0; i < testList.length; i++) {
copy[i] = Arrays.copyOf(testList[i], copy[i].length);
}
for (int i = 0; i < testList.length; i++) {
System.out.println("Source " + i + ": " + Arrays.toString(testList[i]));
System.out.println("Copy " + i + ": " + Arrays.toString(copy[i]));
}
}
So, I am trying to take an array input of 6,7,34,7,6 and create a method to have the ouput be 6 6 7 7 34 34 7 7 6 6.
How would i go about that?
So far I have:
public int [] twice (int[] ary)
int [] A = new int [ary.length * 2]
A [0] = 6;
A [1] = 7;
A [2] = 34;
A [3] = 7;
A [4] = 6;
But i don't know where to go from there.
Try this one:
public static int[] twice(int[] ary) {
int[] A = new int[ary.length * 2];
for(int i=0, j=0;j<ary.length;i=i+2,j++) {
A[i] = A[i+1] = ary[j];
}
return A;
}
Just use two for loops
{
for (int i=0;i<5;i++) System.print(ary[i]);
for (int i=0;i<5;i++) System.print(ary[4-i]);
}
If u want to add the values at the end
// Java program explaining System class method - arraycopy()
import java.lang.*;
import java.util.Arrays;
public class NewClass
{
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = Arrays.copyOf(s, s.length*2);
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 0;
dest_arr = d;
destPos = s.length;
len = s.length;
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
}
public static int [] twice (int[] ary)
{
int [] A = new int [ary.length * 2];
//take 2 variables one to point input array and 1 for output array
int c = 0;
for(int n: ary) {
//put each element of input array twice in output array
A[c] = A[c+1] = n;
c += 2;
}
//return output array
return A;
}
As your input values look like they're sorted and then you put the same values to destination array again in descending order, you might want to try attempt with sorting your input first depending on what you want to achieve:
public int [] twice(int[] ary) {
int[] temporary = new int[ary.length];
for (int i = 0; i < ary.length; i++) { // copying ary to temporary
temporary[i] = ary[i];
}
Arrays.sort(temporary); // sorting temporary in ascending order
int[] result = new int[ary.length * 2]; // creating double sized result array
for(int i = 0; i < temporary.length; i++) { // copying sorted contents of temporary at the beginning of result array
result[i] = temporary[i];
}
int j = 0 ;
for(int i = result.length - 1; i >= result.length / 2; i--) { // inserting contents of temporary from the end of result array to the middle ("from right to left")
result[i] = temporary[j++];
}
return result; // returning result array
}
I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList.
This is the function that can help you.
public void ArrayList<ArrayList<Integer>> convert2DStringTo2DIntegerArray(String[][] original) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < original.length; i++)
{
ArrayList<Integer> tempArray = new ArrayList<Integer>();
for (int j = 0; j < original[i].length; j++)
{
tempArray.add(Integer.valueOf(original[i][j]));
}
list.add(tempArray);
}
return list;
}
Updated. To convert multidimensional array of integers represented as strings:
import java.util.List;
import java.util.ArrayList;
public class Convert
{
public static void main(String[] args)
{
List<List<Integer>> list = convert2DStringToList(new String[][]{ {"0", "1", "2"}, {"3", "4", "5"}, {"100", "200", "300", "500"}, {"22"} });
System.out.println(list.toString());
}
public static List<List<Integer>> convert2DStringToList(String[][] original)
{
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < original.length; i++)
{
List<Integer> subList = new ArrayList<>();
list.add(subList);
for (int j = 0; j < original[i].length; j++)
{
subList.add(Integer.valueOf(original[i][j]));
}
}
return list;
}
}
For given code the output is [[0, 1, 2], [3, 4, 5], [100, 200, 300, 500], [22]].
Here is the code I have so far:
public static int mode(int[][] arr) {
ArrayList<Integer> list = new ArrayList<Integer>();
int temp = 0;
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr.length; s ++) {
temp = arr[i][s];
I seem to be stuck at this point on how to get [i][s] into a single dimensional array. When I do a print(temp) all the elements of my 2D array print out one a time in order but cannot figure out how to get them into the 1D array. I am a novice :(
How to convert a 2D array into a 1D array?
The current 2D array I am working with is a 3x3. I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.
In Java 8 you can use object streams to map a matrix to vector.
Convert any-type & any-length object matrix to vector (array)
String[][] matrix = {
{"a", "b", "c"},
{"d", "e"},
{"f"},
{"g", "h", "i", "j"}
};
String[] array = Stream.of(matrix)
.flatMap(Stream::of)
.toArray(String[]::new);
If you are looking for int-specific way, I would go for:
int[][] matrix = {
{1, 5, 2, 3, 4},
{2, 4, 5, 2},
{1, 2, 3, 4, 5, 6},
{}
};
int[] array = Stream.of(matrix) //we start with a stream of objects Stream<int[]>
.flatMapToInt(IntStream::of) //we I'll map each int[] to IntStream
.toArray(); //we're now IntStream, just collect the ints to array.
You've almost got it right. Just a tiny change:
public static int mode(int[][] arr) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
// tiny change 1: proper dimensions
for (int j = 0; j < arr[i].length; j++) {
// tiny change 2: actually store the values
list.add(arr[i][j]);
}
}
// now you need to find a mode in the list.
// tiny change 3, if you definitely need an array
int[] vector = new int[list.size()];
for (int i = 0; i < vector.length; i++) {
vector[i] = list.get(i);
}
}
I'm not sure if you're trying to convert your 2D array into a 1D array (as your question states), or put the values from your 2D array into the ArrayList you have. I'll assume the first, but I'll quickly say all you'd need to do for the latter is call list.add(temp), although temp is actually unneeded in your current code.
If you're trying to have a 1D array, then the following code should suffice:
public static int mode(int[][] arr)
{
int[] oneDArray = new int[arr.length * arr.length];
for(int i = 0; i < arr.length; i ++)
{
for(int s = 0; s < arr.length; s ++)
{
oneDArray[(i * arr.length) + s] = arr[i][s];
}
}
}
change to:
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr[i].length; s ++) {
temp = arr[i][s];
"How to convert a 2D array into a 1D array?"
String[][] my2Darr = .....(something)......
List<String> list = new ArrayList<>();
for(int i = 0; i < my2Darr.length; i++) {
list.addAll(Arrays.asList(my2Darr[i])); // java.util.Arrays
}
String[] my1Darr = new String[list.size()];
my1Darr = list.toArray(my1Darr);
I know its already been answered but here is my take. This function will take a 2d array input and return a 1d array output.
public int[] output(int[][] input){
int[] out = new int[input.length * input[0].length]
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
out[i + (j * input.length)] = input[i][j]
}
}
return out;
}
System.arraycopy should be faster than anything we can write. Also use the built-in java iterator on rows. Here is an example for double arrays. You should be able to use any type or class. If your rows are all the same length, then totalNumberElements = array2D.length * array2D[0].length;
static double[] doubleCopyToOneD(double[][] array2D, int totalNumberElements) {
double[] array1D = new double[totalNumberElements];
int pos = 0;
for (double[] row: array2D) {
System.arraycopy(row, 0, array1D, pos, row.length);
pos += row.length;
}
return array1D;
}
import java.util.*;
public class Main {
public static int A[][] = new int[3][3];
public static int B[] = new int[9];
public static void main(String[] args) {
int temo = 0,t;
Scanner s = new Scanner(System.in);
System.out.println("Enter No for Matrix A");
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
A[row][col] = s.nextInt();
}
System.out.print("\n");
}
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
t= A[row][col];
B[temo]= t;
temo++;
}
System.out.print("\n");
}
System.out.print("After Converted to one d \n");
for(int i =0;i<B.length;i++) {
System.out.print(" "+B[i]+" ");
}
}
}
private double[] myNumbers = {10, 2, 5, 3, 6, 4};
private double[][] result;
private double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
//System.out.println(result[0] +" "+ result[1]);
return result;
}
I'm trying to sort the one dimensional array in to a matrix, where numbers between 4 - 8 are in one, and all other numbers are in the other.
1) You're not initializing result[][]. You will get a NullPointerException.
Either loop through myNumbers, count the number of values for each category, and create result[][], or push your values into an ArrayList<Double>[2] and use List.toArray() to convert back to an array.
2) result[][] is declared outside your method. While technically valid, it's generally poor form if there is not a specific reason for doing so. Since you're already returning double[][] you might want to declare a double[][] inside your function to work with and return.
I'm not following exactly what you want, but this should allow your code to work.
class OneDimToTwoDim {
public static void main(String[] args) {
// declare myNumbers one dimensional array
double[] myNumbers = {10, 2, 5, 3, 6, 4};
// display two dimensional array
for (int x = 0; x < myNumbers.length; x++) {
System.out.print("[" + myNumbers[x] + "] "); // Display the string.
}
// pass in myNumbers argument for derp parameter, and return a two dimensional array called resultNumbers
double[][] resultNumbers = OneDimToTwoDim.divideNumbers(myNumbers);
System.out.println(); // Display the string.
System.out.println(); // Display the string.
for (int x = 0; x < resultNumbers.length; x++) {
for (int y = 0; y < resultNumbers[x].length; y++) {
System.out.print("[" + resultNumbers[x][y] + "] "); // Display the string.
}
System.out.println(); // Display the string.
}
}
private static double[][] divideNumbers(double[] derp) {
// declare result to be returned
double[][] result = new double[2][derp.length];
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
return result;
}
}
Your result array isn't initialized. Are you getting null pointer exceptions? Is that the problem?
private static double[] myNumbers = {10, 2, 5, 3, 6, 4};
private static double[][] result = new double[2][myNumbers.length];
private static double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
result[0] = Arrays.copyOfRange(result[0],0,k);
result[1] = Arrays.copyOfRange(result[1],0,j);
return result;
}