Row-wise Maximum in Matrix
Print the maximum element of each row of a matrix.
Sample input
[[3,1,2],[9,5,7],[4,8,6]]
Sample output
3 9 8
Solution
matrix = [[3, 1, 2], [9, 5, 7], [4, 8, 6]]
result = [max(row) for row in matrix]
print(*result)
const matrix = [[3, 1, 2], [9, 5, 7], [4, 8, 6]];
const result = matrix.map(row => Math.max(...row));
console.log(result.join(" "));
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[][] matrix = {{3, 1, 2}, {9, 5, 7}, {4, 8, 6}};
System.out.println(Arrays.stream(matrix)
.map(row -> String.valueOf(Arrays.stream(row).max().getAsInt()))
.collect(Collectors.joining(" ")));
}
}
fun main() {
val matrix = arrayOf(intArrayOf(3, 1, 2), intArrayOf(9, 5, 7), intArrayOf(4, 8, 6))
val result = matrix.map { it.max() }
println(result.joinToString(" "))
}
let matrix = [[3, 1, 2], [9, 5, 7], [4, 8, 6]]
let result = matrix.map { $0.max()! }
print(result.map(String.init).joined(separator: " "))
void main() {
final matrix = [[3, 1, 2], [9, 5, 7], [4, 8, 6]];
final result = matrix.map((row) => row.reduce((a, b) => a > b ? a : b));
print(result.join(' '));
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> matrix = {{3, 1, 2}, {9, 5, 7}, {4, 8, 6}};
for (int i = 0; i < (int) matrix.size(); i++) {
cout << *max_element(matrix[i].begin(), matrix[i].end());
if (i < (int) matrix.size() - 1) cout << " ";
}
cout << endl;
return 0;
}
#include <stdio.h>
int main() {
int matrix[3][3] = {{3, 1, 2}, {9, 5, 7}, {4, 8, 6}};
int rows = 3, cols = 3;
for (int i = 0; i < rows; i++) {
int mx = matrix[i][0];
for (int j = 1; j < cols; j++) {
if (matrix[i][j] > mx) mx = matrix[i][j];
}
printf("%d", mx);
if (i < rows - 1) printf(" ");
}
printf("\n");
return 0;
}