I think I am missing something fundamental here about Java, I am not sure why my code below do not work, my steps:
the input is a 2x2 matrix,
copy the original matrix,
loop through rows then column,
assign original matrix's column values to the rows of the transpose matrix.
static void transpose(int[][] matrix) {
int[][] temp = matrix.clone();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix[i][j] = temp[j][i];
}
}
}
The problem is use the function clone() because that will create a new matrix sharing only row arrays.
Using the same code style, that works:
int[][] temp = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = matrix[j][i];
}
}
Note that, as temp is an empty matrix, the comparsion will be temp = matrix.
So this works for a simple 2x2 matrix, but if you need other dimensions, instead of
int[][] temp = new int[2][2];
Use
int[][] temp = new int[matrix[0].length][matrix.length];
By the way, update the reference memory of the matrix is not a good practice. I think your method should return temp matrix.
An entire update, a better method could be this one. Is almost the same you have but it can accept diferent lengths.
public static int[][] transpose(int [][] matrix){
int[][] temp = new int[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
temp[j][i] = matrix[i][j];
}
}
return temp;
}
You can use IntStream instead of for loop:
public static void main(String[] args) {
int[][] m1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int[][] m2 = transpose(m1);
Arrays.stream(m2).map(Arrays::toString).forEach(System.out::println);
// [1, 4, 7]
// [2, 5, 8]
// [3, 6, 9]
}
static int[][] transpose(int[][] matrix) {
return IntStream.range(0, matrix.length).mapToObj(i ->
IntStream.range(0, matrix[i].length).map(j ->
matrix[j][i]).toArray())
.toArray(int[][]::new);
}
Related
Example: expand(new int[]{3, 2, 5}) -> {0, 0, 0, 1, 1, 2, 2, 2, 2, 2}
I am trying to have it make a a new array to print the index of say 3, 3 times. So 3 would be 0,0,0.
public static int[] expand(int[] input) {
int c = 0;
int[] myArray = new int[sum(input)];
if(input.length == 0){
return new int[0];
}
for(int i = 0; i < input.length; i++) {
int a = input[i];
for(int j = c; j < a; j++) {
c += j;
myArray[j] = i;
}
}
return myArray;
}
Currently this only partially works and I cant seem to figure out how to go through the full array properly. In addition, index zero seems to get skipped.
You were close! It seems that you just need to modify your nested for-loop slightly:
for (int j = 0; j < a; j++) {
myArray[c++] = i;
}
Seeing as you're using c to keep track of the current index, this simply sets the element at index c to i and increments c. You can also remove a and use input[i] in place of it.
Note: It is easier to start j from 0 rather than from c.
Functional method
public class Main {
public static void main(final String... args) {
int[] items = expand(new int[]{3, 2, 5});
System.out.println(Arrays.toString(items));
}
public static int[] expand(int[] input) {
return IntStream.range(0, input.length)
.flatMap(p -> IntStream.generate(() -> p).limit(input[p]))
.toArray();
}
}
This makes a stream of the index, and for each item takes that many of the index, putting all of them into an array
I'm having trouble with splitting up a vector into a 2D matrix or a given side. For example, given the vector {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, the rows (3), and columns (4) can be turned into {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}.
As of right now, the code just prints out the entire vector in a an array for however many rows their are.
int[][] reshape(int[] vector, int row, int col) {
if (!isReshapable(vector.length, row, col)) {
return null;
} else {
int[][] matrix = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
Arrays.fill(matrix, vector);
}
}
return matrix;
}
}
You're iterating both i and j. You could use them (and the position in the vector) with something like,
int p = 0;
int[][] matrix = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++, p++) {
matrix[i][j] = vector[p];
}
}
I'm trying to take the sum of each row in a 2d array and store the values in a new array. Right now sum[] is only returning the values stored in the first row. Please help me understand what I'm missing here.
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[row] += matrix[col][row];
}
}
return sum;
}
Since you use Java 8 you can use:
return Arrays.stream(matrix) // Stream<int[]>
.mapToInt(row -> Arrays.stream(row).sum()) // IntStream
.toArray(); // int[]
Following code works for 2D arrays of different size as well.
public static void main(String[] args) {
int[][] matrix = {
{2, 3, 4, 5, 6, 7, 8, 9}, // 8 elements
{2, 1, 4, 5, 7, 2, 86} // 7 elements
};
int[] sum = rowSum(matrix);
for (int i : sum) {
System.out.println(i);
}
}
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum[i] = sum[i] + matrix[i][j];
}
}
return sum;
}
simple
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
ARRAY_LENGTH = 6;
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[col] += matrix[col][row];
}
}
}
careful with ARRAY_LENGTH
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]+" ");
}
}
}
How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}