Question

In: Computer Science

Given a square matrix of integers m, your task is to rearrange its numbers in the...

Given a square matrix of integers m, your task is to rearrange its numbers in the following way:

  • First, sort its values in ascending order of how frequently the number occurs in m. In the case of a tie, sort the equally frequent numbers by their values, in ascending order.
  • Second, place the sorted numbers diagonally, starting from the bottom right corner, like this:

Example

For

m = [[ 1, 4, -2],
     [-2, 3,  4],
     [ 3, 1,  3]]

the output should be

sortMatrixByOccurrences(m) = [[3,  3,  4],
                              [3,  4,  1],
                              [1, -2, -2]]
  • First we look at the frequency of each number:

    • Number 1 occurs 2 times;
    • Number -2 occurs 2 times;
    • Number 3 occurs 3 times;
    • Number 4 occurs 2 times.

    Because numbers 1, -2, and 4 occur the same number of times, we sort them by their values in ascending order. Number 3 occurs the most numbers of times, so it goes after all other numbers. Finally, after sorting we get the following array: [-2, -2, 1, 1, 4, 4, 3, 3, 3]

  • After sorting, the numbers should be placed diagonally starting from the bottom right corner, as follows:

    [[3,  3,  4],
     [3,  4,  1],
     [1, -2, -2]]
    

Input/Output

  • [execution time limit] 0.5 seconds (cpp)

  • [input] array.array.integer m

    A square matrix of integers.

    Guaranteed constraints:
    1 ≤ m.length ≤ 40,
    m[i].length = m.length,
    -1000 ≤ m[i][j] ≤ 1000.

  • [output] array.array.integer

    • The matrix m rearranged according to the specifications above.

code given:

std::vector> sortMatrixByOccurrences(std::vector> m) {

}

Solutions

Expert Solution

The following is the code for above question. It has met all the requirements stated in the question.

#include<bits/stdc++.h>
#include<vector>
#include<map>
using namespace std;
//comparator which sorts based on frequency value in ascending order
bool cmp(pair<int, int>& a, 
         pair<int, int>& b) 
{ 
    return a.second < b.second; 
} 
vector<int> sort(map<int, int>& m) 
{ 
    // Declare vector of pairs 
    vector<pair<int, int> > a; 
 
    for (auto& it : m) { 
        a.push_back(it); //push each pair to vector
    } 
 
    sort(a.begin(), a.end(), cmp); //now sort based on comparator
  
    int k=0,j;
    vector<int>vi;//declare one more vector to store the sorted values as stated in question
    for (auto& it : a) { 
  
        for(j=0;j<it.second;j++)
        {
            vi.push_back(it.first); //push the values into vector based on frequency
        }
    } 
    return vi;
} 
vector<vector<int>> sortMatrixByOccurences(vector<vector<int>> m)
{
     map<int,int> a;
    int i,j;
    //insert the values in vector into map
    for(i=0;i<m.size();i++)
    {
        for(j=0;j<m[i].size();j++)
        {
            if(a.find(m[i][j])==a.end())
            {
                a[m[i][j]]=1;
            }
            else
            {
                a[m[i][j]]++;
            }
        }
    }
   vector<int>v=sort(a);
    
    int mat_size=m.size(),sp=0;
     int mat[mat_size][mat_size]={0}, k, q;
     //now insert the values into matrix diagonally starting from bottom right corner
     //This loop is for creating upper triangle i.e starting from bottom right corner
      for ( k = mat_size-1; k >=1; k--){
      i=mat_size-1;
      for ( j = k; j <=mat_size-1; j++){
         mat[i][j] = v[sp++];
         i--;
      }
   }
   //now continue with lower triangle
   //this loop is for creating lower triangle
  for ( i = mat_size-1; i >=0; i--){
      k=i;
      for ( j = 0; j <=i; j++){
         mat[k][j] = v[sp++];
        k--;
      }
   }
   //store the matrix values back into original vector m
   for ( i = 0; i < mat_size; i++){
      for(j = 0; j < mat_size; j++){
          m[i][j]=mat[i][j];
      }
   }
   
   return m;
}

int main()
{
    vector<vector<int>> m{{1,4,-2},{-2,3,4},{3,1,3}};
    int i,j;
    m=sortMatrixByOccurences(m);
    int mat_size=m.size();
   //print the values of vector m
   for ( i = 0; i < mat_size; i++){
      for(j = 0; j < mat_size; j++){
         cout<<m[i][j]<<" ";
      }
      cout<<endl;
   }//hence required result
    return 0;
}

I will also attach the output for your reference.

Output and code screenshot:

#Please dont forget to upvote if you find the solution helpful. Feel free to ask doubts if any, in the comments section. Thank you.


Related Solutions

Using Java please You are given an array of integers arr. Your task is to count...
Using Java please You are given an array of integers arr. Your task is to count the number of contiguous subarrays, such that each element of the subarray appears at least twice. E.g For arr = [0, 0, 0], the output should be duplicatesOnSegment(arr) = 3.
Given a matrix ? (i.e., a 2D table) of positive integers of size ? × ?....
Given a matrix ? (i.e., a 2D table) of positive integers of size ? × ?. A robot starts at the top- left position ?[?, ?] and must reach the bottom-right position ?[?, ?]. From a position ?[?, ?], the robot can only go either right to ?[?, ? + ?] or down to ?[? + ?, ?]. Let us define the cost of a path the total values of integers in it. Find the least-cost path for the robot...
A square matrix A is said to be symmetric if its transpose AT satisfies AT= A,...
A square matrix A is said to be symmetric if its transpose AT satisfies AT= A, and a complex-valued square matrix A is said to be Hermitian if its conjugate transpose AH = (A)T = AT satisfies AH = A. Thus, a real-valued square matrix A is symmetric if and only if it is Hermitian. Which of the following is a vector space? (a) The set of all n xn real-valued symmetric matrices over R. (b) The set of all...
Given that the square matrix, A is nilpotent (Ak = 0 for some positive integer k)....
Given that the square matrix, A is nilpotent (Ak = 0 for some positive integer k). If A is n by n, show that An = 0.
Task 1: Remove Number Complete the function remove number such that given a list of integers...
Task 1: Remove Number Complete the function remove number such that given a list of integers and an integer n, the function removes every instance of n from the list. Remember that this function needs to modify the list, not return a new list. Task 2: Logged List The log2() function is one of an algorithm designer’s favourite functions. You’ll learn more about this later, but briefly – if your input size is 1048576 elements, but you only look at...
Statement: For a given integer N, print all the squares of positive integers where the square...
Statement: For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order. Programming Tasks: Prompt the user to input the value of N Output to the screen all squares of positive integers <= N Tests: Item Test 1 Test 2 Test 3 Inputs: 50 9 100 Outputs: 1 4 9 16 25 36 49 1 4 9 1 4 9 16 25 36 49 64 81...
Given an array A[1..n] of integers - all of whose numbers are in the range [0,...
Given an array A[1..n] of integers - all of whose numbers are in the range [0, n^3 − 1] give an algorithm which sorts them in O(n) time.
IN JAVA PLEASE Given an unsorted array numbers of integers with duplicate values. Sort the array...
IN JAVA PLEASE Given an unsorted array numbers of integers with duplicate values. Sort the array and remove the duplicates in-place such that each element appears only once in the input array and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Find the time complexity of your removeDuplicates() method in Big-O notation and write that in a comment line on the top...
Use Octave Given a matrix M ∈ M mn , each function should first ensure that...
Use Octave Given a matrix M ∈ M mn , each function should first ensure that the matrix has the proper size (e.g., be square if the definition involves a square matrix). Until CA4, we do not implement proper error handling, so for now, if the matrix is not of the proper size, the function should return FALSE. In this assignment, we create functions that characterise matrix properties or types. These definitions can be found easily. For reference, the location...
Question 3 You should form the list of integers with your student ID. The numbers are...
Question 3 You should form the list of integers with your student ID. The numbers are generated as follows: Number Based on your student ID number, formed by its … a 1 st and 2nd digits b 2 nd and 3rd digits c 3rd and 4th digits d 4th and 5th digits e 5th and 6th digits f 6th and 7th digits g 7th and 8th digits For example, the student ID is 19563755A. Values of a to g are:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT