Table of contents
1.
Introduction
2.
Examples
3.
Key Details
4.
Algorithm used
5.
Problem Statement
5.1.
C++ Program
5.2.
Python Program
5.3.
Java Program
5.4.
C# Program
5.5.
JavaScript Program
6.
Frequently Asked Questions
6.1.
What is a matrix in data structures and algorithms (DSA)?
6.2.
What is the difference between a square matrix and a sparse matrix?
6.3.
How to create an NxN matrix in python?
6.4.
In Java, how do you declare a 4x4 matrix?
7.
Conclusion
Last Updated: Mar 27, 2024

Shifting matrix elements row-wise by k

Author Ishita mishra
0 upvote

Introduction

Matrix-based questions are among the most popular questions in coding interviews and contests. Such problems are exciting; however, they require you to have excellent observatory skills to solve them. Shifting of matrix elements is one such type of matrix-based question that can be done in two ways, i.e., row-wise and column-wise. 

This article will help you understand the algorithm of shifting matrix elements row-wise by a shift value k with the help of code implementation in different languages. 

Examples

Let us understand this concept in a better way.

Suppose a square matrix Mat[][] and a number k are given. So now, the goal is to move each row's first k components to the right side of the matrix.

Input: Mat[a][a] = {{2, 4, 6},

                               {8, 10, 12},

                               {14, 16, 18}}

shift value = 2

Output: Mat[a][a] = {{6, 2, 4},

                                  {12, 8, 10},

                                  {18, 14, 16}}

 

Input: Mat[b][b] = {{ 3, 6, 9, 12},

                                 {15, 18, 21, 24},

                                 {27, 30, 33, 36},

                                 {39, 42, 45, 48}}

shift value = 2

Output: Mat[b][b] = {{9, 12, 3, 6},

                                  {21, 24, 15, 18},

                                  {33, 36, 27, 30},

                                   {45, 48, 39, 42}}

Key Details

  • The matrix should always be a square.
  • The original array is returned after shifting by a value equal to the array's size.
  • Shifting rows of the matrix do not occur if the shift value is greater than the order of the matrix.

Algorithm used

  • Firstly initialize an integer n, which defines the order of the square matrix.
  • Then define the function to perform row-wise shifting of the matrix.
  • If the shift value is more than the order of the given matrix, then the shifting of the matrix does not take place.
  • If the shift value is less than or equal to the order of the matrix, we initialize the loop to print the matrix.
  • The matrix to be shifted is given as the input, and row-wise shifting is done by calling the function.
  • The shifted matrix is printed.

Problem Statement

In this problem statement, we are provided with a matrix to perform row-wise shifting of matrix elements by a shift value k. Here, all the programs after implementation return the same output. So, let us see how we can implement this in different programming languages.

Input:  {{4, 8, 14, 16},

              {20, 24, 28, 32},

              {36, 40, 44, 48},

              {52, 56, 60, 64 }}


Output:  

16  4  8  14

32  20  24  28

48  36  40  44

64  52  56  60

C++ Program

// below is the code of C++ program to compute row-wise shifting of elements in a matrix by k.
#include <bits/stdc++.h>
using namespace std;
#define n 4


/* Function to shift first k elements of
 each row of matrix.*/
void shiftMatrixByK(int mat[n][n], int k)
{
if (k > n) {
cout << "Cannot shift" << endl;
return;
}
int y = 0;
while (y < n) {
// Print elements from index k
for (int x = k; x < n; x++)
cout << mat[y][x] << " ";
// Print elements before index k
for (int x = 0; x < k; x++)
cout << mat[y][x] << " ";
cout << endl;
y++;
}
}
// Driver code
int main()
{
int mat[n][n] = {{4, 8, 14, 16},
                 {20, 24, 28, 32},
                 {36, 40, 44, 48},
                 {52, 56, 60, 64 }};
int k = 3;
// Function call
shiftMatrixByK(mat, k);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output  

16  4  8  14
32  20  24  28
48  36  40  44
64  52  56  60

Python Program

# The following Python program 
# Helps to understand
# shifitng of elements in Matrix


n = 4
# Function to shift first k
# elements of each row of
# matrix.
def shiftMatrixByK(mat, k):
if (k > n) :
print ("Cannot Shift")
return
y = 0
while (y < n) :

# Print elements from
# index k
for x in range(k, n):
print ("{} " .
format(mat[y][x]), end="")

# Print elements before
# index k
for x in range(0, k):
print ("{} " .
format(mat[y][x]), end="")

print ("")
y = y + 1


# Driver code
mat = [[4, 8, 14, 16],
       [20, 24, 28, 32],
       [36, 40, 44, 48],
       [52, 56, 60, 64 ]];


k = 3
#Function call
shiftMatrixByK(mat, k)
You can also try this code with Online Python Compiler
Run Code

Output  

16  4  8  14
32  20  24  28
48  36  40  44
64  52  56  60

Java Program

/* Java program to compute row-wise shifting of elements in a
 matrix by k.*/
import java.io.*;
import java.util.*;


public class Coding_Ninjas  {
static int n = 4;

/* Function to shift first k elements
of each row of matrix. */
static void shiftMatrixByK(int [][]mat, int k)
{
if (k > n) {
System.out.print("Cannot Shift"); 
return;
}
int y = 0;
while (y < n) {
// Print elements from index k
for (int x = k; x < n; x++)
System.out.print(mat[y][x] + " ");
// Print elements before index k
for (int x = 0; x < k; x++)
System.out.print(mat[y][x] + " ");
System.out.println();
y++;
}
}
// Driver code
public static void main(String args[])
{
int [][]mat = new int [][]
{{4, 8, 14, 16},
 {20, 24, 28, 32},
 {36, 40, 44, 48},
 {52, 56, 60, 64 }};


int k = 3;
// Function call
shiftMatrixByK(mat, k);
}
}
You can also try this code with Online Java Compiler
Run Code

Output

16  4  8  14
32  20  24  28
48  36  40  44
64  52  56  60

C# Program

// C# program to compute row-wise shifting of elements in a matrix by k.


using System;


class Coding_Ninjas {

static int n = 4;

// Function to shift first k elements
// of each row of matrix.
static void shiftMatrixByK(int [,]mat,int k)
{
if (k > n) {
Console.WriteLine("Cannot Shift"); 
return;
}

int y = 0;
while (y < n) {

// Print elements from index k
for (int x = k; x < n; x++)
Console.Write(mat[y,x] + " ");

// Print elements before index k
for (int x = 0; x < k; x++)
Console.Write(mat[y,x] + " ");

Console.WriteLine();
y++;

}
}

// Driver code
public static void Main()
{
int [,]mat = new int [,]
{{4, 8, 14, 16},
 {20, 24, 28, 32},
 {36, 40, 44, 48},
 {52, 56, 60, 64 }};


int k = 3;


// Function call
shiftMatrixByK(mat, k);
}
}

Output

16  4  8  14
32  20  24  28
48  36  40  44
64  52  56  60

JavaScript Program

<script>
// Java Script program to compute row-wise shifting of elements in a
// matrix by k.
let n = 4;

// Function to shift first k elements
// of each row of matrix.
function shiftMatrixByK(mat,k)
{
if (k > n) {
document.write("Shifting is not possible");
return;
}
let y = 0;
while (y < n) { 
// Print elements from index k
for (let x = k; x < n; x++)
document.write(mat[y][x] + " ");

// Print elements before index k
for (let x = 0; x < k; x++)
document.write(mat[y][x] + " "); 
document.write("<br>");
y++;
}
}

// Driver code
let mat =  [[4, 8, 14, 16],
            [20, 24, 28, 32],
            [36, 40, 44, 48],
            [52, 56, 60, 64]];
let k = 3;
// Function call
shiftMatrixByK(mat, k);
</script>
You can also try this code with Online Javascript Compiler
Run Code

Output 

16  4  8  14
32  20  24  28
48  36  40  44
64  52  56  60

 

Also see,  Rabin Karp Algorithm

Frequently Asked Questions

What is a matrix in data structures and algorithms (DSA)?

A matrix is a set of numbers organized in a row-by-row and column-by-column arrangement in DSA. The matrix elements must be enclosed in parenthesis or brackets.

What is the difference between a square matrix and a sparse matrix?

A sparse matrix contains a large number of zero values, whereas a square matrix has the same number of rows and columns on both sides.

How to create an NxN matrix in python?

Multi-dimensional data structures are required to create a matrix in Python. Matrixes are not a built-in type in Python, but we can treat a nested list or a list of a list as one. The List is a ‘set of sorted and enclosed elements in square brackets [].

In Java, how do you declare a 4x4 matrix?

A basic 4x4 matrix We can use a 2 Dimensional Array to express this matrix in Java. A two-dimensional array has two dimensions, one for each row and one for each column.

Conclusion

In this article, we have extensively discussed matrix and shifting of matrix elements by a specific shift value in a row-wise manner. 

We hope this blog has taught you something new, and if you’re curious to know more about different types of matrices and their implementation in data structures, then do visit the following blogs on Unique elements in a matrixdiagonally dominant matrixscalar multiplication of a matrix, and C program to check symmetric matrix to get some more insights.

Happy learning!!

 

Live masterclass