2-dimensional array with given number [duplicate] - java

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]+" ");
}
}
}

Related

how to reuse elements of an array out of its for loop?

I was trying to create a code that rearranges given elements in an array -by the user- in ascending order, and I have done that, but the program requires
printing the given elements after sorting them firstly, then printing them before sorting.
I have no problem with printing the elements after sorting
the problem is with printing them before sorting
how to re-use ar[S] = in.nextInt() the given elements by the user out of its for loop
import java.util.*;
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int ar[] = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
for (int i = 0; i < ar.length; i++) {
/* this nested for loop is used to compare the first element with the second one in the array
or the second element with the third.
*/
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
// I wanna do something like that
// System.out.println(ar[S]);
// but of course I cant cause array S is only defined in it's loop
}
}
You can't reuse it, you need to keep the original array stored in another array that stays untouched. Additionally, Arrays are usually declared as int[] ar in Java, instead of int ar[]. Something along the following lines should work as intended:
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int[] ar = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
System.out.println("::: Original Array :::");
int[] originalArray = Arrays.copyOf(ar, ar.length);
for (int j : originalArray) {
System.out.println(j);
}
System.out.println("::: Sorted Array :::");
for (int i = 0; i < ar.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
}
}
You can do a copy of the array using the copyOf method from the Arrays library (java.util.Arrays) before you start changing the array.
Here you can find some different approaches - https://www.softwaretestinghelp.com/java-copy-array/amp/
You can use System.out.print(Arrays.toString(arr)); to print the entire array.
public static void main(String... args) {
int[] arr = readArray(3);
System.out.print(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
System.out.print(Arrays.toString(arr));
}
}
}
}
private static int[] readArray(int size) {
System.out.format("Enter %d elements:\n", size);
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for(itn i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
return arr;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

How to create different column size in 2d array

I have two lists of elements and numbers but how can I put them into arrays if I don't know the exact array size? new int[elements.size()][I'm not sure about this size].
For example:
List of elements = [2,5]
List of numbers = [99,100], [1,9,8,10,70]
public static int[][] arrays(List<Integer> numbers, List<Integer> elements){
int count = 0;
int x = 0;
int y = 0;
int[][] list = new int[elements.size()][];
for (Integer e : elements) {
for (int i = count; i < count+e; i++) {
list[x][y] = numbers.get(i);
y++;
}
x++;
y = 0;
count += e;
}
return list;
}
The correct input for your method would be a list of lists, with each list in the parent list potentially having a different length:
public static int[][] arrays(List<List<Integer>> numbers) {
int[][] array = new int[numbers.size()][];
for (int i=0; i < numbers.size(); ++i) {
array[i] = new int[numbers.get(i).size()];
for (int j=0; j < numbers.get(i).size(); ++j) {
array[i][j] = numbers.get(i).get(j);
}
}
return array;
}

Trouble with splitting an array into chunks

I have an array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
I'm trying to split it into a two-dimensional array with x amount of chunks, where all of the chunks have an equal length (in my case, 2), then assign each value of the original array to a corresponding index within the array. It would then increment the index of the chunk number and reset the index iterating through the individual arrays hit the length of one.
Problem is, the code I wrote to perform all that isn't outputting anything:
public class Debug
{
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
private static void chunkArray(int chunkSize)
{
int chunkNumIndex = 0;
int chunkIndex = 0;
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++)
{
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
while(chunkNumIndex < numOfChunks)
{
if (chunkIndex == chunkSize)
{
chunkNumIndex++;
chunkIndex = 0;
}
}
}
for(int i = 0; i < chunkNumIndex; i++)
{
for(int j = 0; j < chunkIndex; j++)
{
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
chunkArray(2);
}
}
Could anyone be of assistance in debugging my program?
The problem is that you have an unnecessary while(chunkNumIndex < numOfChunks) which makes no sense. The if statement is sufficient to iterate your variables correctly:
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
if (chunkIndex == chunkSize) {
chunkNumIndex++;
chunkIndex = 0;
}
}
Also, remember that the values of chunkNumIndex and chunkIndex are dynamic, so for the last for loops, use twoDimensionalArray.length and twoDimensionalArray[0].length instead:
for(int i = 0; i < twoDimensionalArray.length; i++) {
for(int j = 0; j < twoDimensionalArray[0].length; j++) {
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
}
You're making this unnecessarily hard, there is no need to keep counters for chunkIndex and chunkNumIndex, we can just div and mod i.
int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}
Something like this should already do the job.

Adding the columns of a jagged 2D array

I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}

copy a 2d array in java

i have a 2d array called matrix of type int that i want to copy to a local variable in a method so i can edit it
whats the best way to copy the array, i am having some troubles
for example
int [][] myInt;
for(int i = 0; i< matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
myInt[i][j] = matrix[i][j];
}
}
//do some stuff here
return true;
}
There are two good ways to copy array is to use clone and System.arraycopy().
Here is how to use clone for 2D case:
int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
myInt[i] = matrix[i].clone();
For System.arraycopy(), you use:
int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
int[] aMatrix = matrix[i];
int aLength = aMatrix.length;
myInt[i] = new int[aLength];
System.arraycopy(aMatrix, 0, myInt[i], 0, aLength);
}
I don't have a benchmark but I can bet with my 2 cents that they are faster and less mistake-prone than doing it yourself. Especially, System.arraycopy() as it is implemented in native code.
It is possible to use streams in Java 8 to copy a 2D array.
#Test
public void testCopy2DArray() {
int[][] data = {{1, 2}, {3, 4}};
int[][] dataCopy = Arrays.stream(data)
.map((int[] row) -> row.clone())
.toArray((int length) -> new int[length][]);
assertNotSame(data, dataCopy);
assertNotSame(data[0], dataCopy[0]);
assertNotSame(data[1], dataCopy[1]);
dataCopy[0][1] = 5;
assertEquals(2, data[0][1]);
assertEquals(5, dataCopy[0][1]);
}
You are not initializing the local 2D array.
int[][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
myInt[i] = new int[matrix[i].length];
for (int j = 0; j < matrix[i].length; j++)
{
myInt[i][j] = matrix[i][j];
}
}
If the data is large you should consider using a proper linear algebra library like colt or nd4j. System.arraycopy will likely only be meaningfully faster if the array were single dimensional. Otherwise it can not copy the entire data as one unit and then reshape it as in numpy or R.
you can code like this also
myInt = matrix.clone();

Categories

Resources