Skip to content

Instantly share code, notes, and snippets.

@Sedose
Last active July 13, 2025 17:39
Show Gist options
  • Select an option

  • Save Sedose/919f7c21621dafce48cc615dd8ddc97d to your computer and use it in GitHub Desktop.

Select an option

Save Sedose/919f7c21621dafce48cc615dd8ddc97d to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.stream.IntStream;
class Solution {
public int[][] matrixReshape(int[][] originalMatrix, int targetRows, int targetCols) {
int totalElements = originalMatrix.length * originalMatrix[0].length;
if (totalElements != targetRows * targetCols) {
return originalMatrix;
}
int[] allElements = Arrays.stream(originalMatrix)
.flatMapToInt(Arrays::stream)
.toArray();
return IntStream.range(0, targetRows)
.mapToObj(row -> rowElements(allElements, row, targetCols))
.toArray(int[][]::new);
}
private int[] rowElements(int[] elements, int row, int cols) {
int start = row * cols;
return Arrays.copyOfRange(elements, start, start + cols);
}
}
class Solution {
fun matrixReshape(
originalMatrix: Array<IntArray>,
targetRowCount: Int,
targetColumnCount: Int,
): Array<IntArray> {
val flattened = originalMatrix.flatMap(IntArray::asList)
if (flattened.size != targetRowCount * targetColumnCount) return originalMatrix
return flattened
.chunked(targetColumnCount)
.map(List<Int>::toIntArray)
.toTypedArray()
}
}
def matrix_reshape(originalMatrix, targetRowCount, targetColumnCount)
elements = originalMatrix.flatten
return originalMatrix if elements.size != targetRowCount * targetColumnCount
elements.each_slice(targetColumnCount).to_a
end
object Solution {
def matrixReshape(
originalMatrix: Array[Array[Int]],
targetRowCount: Int,
targetColumnCount: Int
): Array[Array[Int]] = {
val flattenedElements = originalMatrix.flatten
if (flattenedElements.length != targetRowCount * targetColumnCount)
originalMatrix
else
flattenedElements.grouped(targetColumnCount).toArray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment