HackerRank Flipping the Matrix Problem Solution Yashwant Parihar, June 13, 2023August 1, 2024 In this post, we will solve HackerRank Flipping the Matrix Problem Solution. Sean invented a game involving a 2n x 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n x n submatrix located in the upper- left quadrant of the matrix.Given the initial configurations for a matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix’s upper- left quadrant is maximal.Examplematrix [[1, 2], [3, 4]] 1 2 3 4 It is 2 x 2 and we want to maximize the top left quadrant, a 1 x 1 matrix. Reverse row 1: 1 2 4 3 And now reverse column 0: 4 2 1 3 The maximal sum isĀ 4. Function Description Complete the flippingMatrix function in the editor below. flippingMatrix has the following parameters:– int matrix[2n][2n]: a 2-dimensional array of integers Returns– int: the maximum sum possible. Input FormatThe first line contains an integer q, the number of queries.The next q sets of lines are in the following format: The first line of each query contains an integer, n. Each of the next 2n lines contains 2n space-separated integers matrix[i][j] in row i ofthe matrix. Sample Input STDIN Function ----- -------- 1 q = 1 2 n = 2 112 42 83 119 matrix = [[112, 42, 83, 119], [56, 125, 56, 49], \ 56 125 56 49 [15, 78, 101, 43], [62, 98, 114, 108]] 15 78 101 43 62 98 114 108 Sample Output 414 HackerRank Flipping the Matrix Problem Solution Flipping the Matrix C Solution #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int GREATER(int x,int y) { return(x>y?x:y); } int main() { int test; scanf("%d",&test); int n; int i,j,k; int ANSWER,s; while(test--) { ANSWER=0; scanf("%d",&n); int arr[2*n][2*n]; for(i=0;i<2*n;i++) for(j=0;j<2*n;j++) { scanf("%d",&arr[i][j]); } k=(2*n)-1; s=2*n-1; for(i=0;i<n;i++) { for(j=0;j<n;j++) { ANSWER+=(GREATER(GREATER(arr[i][j],arr[i][k]),GREATER(arr[s][j],arr[s][k]))); k--; } k=(2*n)-1; s--; } printf("%d\n",ANSWER); } return 0; } Flipping the Matrix C++ Solution #include <ios> #include <iostream> int a[257][257] = {}; int maxi(int a, int b) { return (a > b ? a : b); } int maximum(int a, int b, int c, int d) { return maxi(maxi(a, b), maxi(c, d)); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int tc, n, awesome; std::cin >> tc; while (tc--) { std::cin >> n; for (int i = 0; i < 2*n; i++) for (int j = 0; j < 2*n; j++) std::cin >> a[i][j]; awesome = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { awesome += maximum(a[i][j], a[2*n-i-1][j], a[i][2*n-j-1], a[2*n-i-1][2*n-j-1]); } } std::cout << awesome << '\n'; } } Flipping the Matrix C Sharp Solution using System; using System.Collections.Generic; using System.IO; class Solution { static void Main(String[] args) { int numMatrix = Convert.ToInt32(Console.ReadLine()); for(int i = 0; i < numMatrix; i++) { int n = Convert.ToInt32(Console.ReadLine()); var matrix = ReadMatrix(2*n); var solvedMatrix = SolveMatrix(n, matrix); Console.WriteLine(GetTotal(n, solvedMatrix)); } } static int GetTotal(int n, int[,] matrix) { int total = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ total+= matrix[i,j]; } } return total; } static int[,] SolveMatrix(int n, int[,] matrix){ int m = 2*n; int[,] newMatrix = new int[n,n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++){ int a = matrix[i,j]; int b = matrix[i, m-j-1]; int c = matrix[m-i-1, j]; int d = matrix[m-i-1, m-j-1]; newMatrix[i,j] = Math.Max(Math.Max(Math.Max(a,b),c),d); } } return newMatrix; } static int[,] ReadMatrix(int n) { int[,] matrix = new int[n,n]; for(int i = 0; i < n; i++) { List<int> row = ReadInput(); for(int j = 0; j < n; j++){ matrix[i,j] = row[j]; } } return matrix; } static List<int> ReadInput() { string temp = Console.ReadLine(); string[] tempList = temp.Split(' '); List<int> intList = new List<int>(); foreach (string input in tempList) { intList.Add(Convert.ToInt32(input)); } return intList; } } Flipping the Matrix Java Solution import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'flippingMatrix' function below. * * The function is expected to return an INTEGER. * The function accepts 2D_INTEGER_ARRAY matrix as parameter. */ public static int flippingMatrix(List<List<Integer>> mat) { Objects.requireNonNull(mat); if (mat.size() == 0) return 0; int m = mat.size(), n = mat.get(0).size(); int ans = 0; for (int i = 0; i < m/2; i++) { for (int j = 0; j < n/2; j++) { List<Integer> up = mat.get(i), down = mat.get(n-i-1); int maxUpper = Math.max(up.get(j), up.get(n-j-1)); int maxBelow = Math.max(down.get(j), down.get(n-j-1)); ans += Math.max(maxUpper, maxBelow); } } return ans; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int q = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0, q).forEach(qItr -> { try { int n = Integer.parseInt(bufferedReader.readLine().trim()); List<List<Integer>> matrix = new ArrayList<>(); IntStream.range(0, 2 * n).forEach(i -> { try { matrix.add( Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()) ); } catch (IOException ex) { throw new RuntimeException(ex); } }); int result = Result.flippingMatrix(matrix); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); bufferedWriter.close(); } } Flipping the Matrix JavaScript Solution function processData(input) { //Enter your code here let arr = input.split('\n'); let q = arr.shift(); for (let k = 0; k < q; k++) { let sum = 0; let n = arr.shift(); let a = []; for (let i = 0; i < n * 2; i++) { a[i] = arr.shift().split(' '); } for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { let otherI = 2 * n - 1 - i; let otherJ = 2 * n - 1 - j; sum += Math.max(a[i][j], a[otherI][j], a[i][otherJ], a[otherI][otherJ]); } } console.log(sum); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); Flipping the Matrix Python Solution from time import sleep def print_matrix(matrix): for row in range(len(matrix)): print("".join("{:>4}".format(e) for e in matrix[row])) print() def improve(matrix, n): def reverse_row(row): matrix[row] = list(reversed(matrix[row])) def reverse_column(col): for row in range(n): other_row = len(matrix) - row - 1 matrix[row][col], matrix[other_row][col] = matrix[other_row][col], matrix[row][col] def is_row_perfect(row): return sum(matrix[row][:n]) >= sum(matrix[row][n:]) def is_column_perfect(col): return sum(matrix[row][col] for row in range(n)) >= sum(matrix[row][col] for row in range(n, len(matrix))) for row in range(len(matrix)): if not is_row_perfect(row): reverse_row(row) return True for col in range(len(matrix)): if not is_column_perfect(col): reverse_column(col) return True return False def main(): for _ in range(int(input())): n = int(input()) size = 2 * n matrix = [None] * size for row in range(size): matrix[row] = list(map(int, input().split())) total = 0 for row in range(n): for column in range(n): other_row = size - 1 - row other_column = size - 1 - column locations = [(row, column), (other_row, column), (row, other_column), (other_row, other_column)] total += max(matrix[r][c] for r, c in locations) print(total) if __name__ == '__main__': main() c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython