• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 8, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Matrix Layer Rotation – HackerRank Solution

Matrix Layer Rotation HackerRank Solution Java , Python 2,Python3 , C, C++

bhautik bhalala by bhautik bhalala
May 23, 2022
Reading Time: 1 min read
1
Spread the love

Matrix Layer Rotation HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Table of Contents

  • Python 3 Matrix Layer Rotation HackerRank Solution
  • C Matrix Layer Rotation HackerRank Solution
  • JAVA 3 Matrix Layer Rotation HackerRank Solution
  • C++ Matrix Layer Rotation HackerRank Solution
  • Python 2 Matrix Layer Rotation HackerRank Solution
      • Related posts:

Python 3 Matrix Layer Rotation HackerRank Solution

Copy Code Copied Use a different Browser

class RotationMatrix(object):
    def __init__(self, M, N, entries):
        self.M, self.N = M, N
        self.entries = dict(entries)
        self.tier_index = self._create_tier_index()
        
    def __str__(self):
        string = ""
        for i in range(self.M):
            for j in range(self.N):
                sep = " " if j < self.N-1 else "\n"
                string += str(self.entries[(i,j)]) + sep
        return string
   
    def rotate_matrix(self, R):
        for index in self.tier_index:
            tier_copy = {key:self.entries[key] for key in index}
            for list_index, key in enumerate(index):
                rkey = index[(list_index + R + 1) % len(index) - 1]
                self.entries[rkey] = tier_copy[key]
        
    def _create_tier_index(self):
        row, col, tier_index = 0, 0, []
        directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        while self.M - 2 * row > 0 and self.N - 2 * col > 0:
            i, j = row, col
            tier_list = []
            for move in directions:
                while True:
                    if i + move[0] > self.M - row - 1 or i + move[0] < row or \
                    j + move[1] > self.N - col - 1 or j + move[1] < col:
                        break
                    else:
                        i, j = i + move[0], j + move[1]
                    tier_list.append((i, j))
            tier_index.append(tier_list)
            row, col = row + 1, col + 1
        return tier_index

M, N, R = [int(value) for value in input().split()]
mat = {}
for i in range(M):
    values = input().split()
    for j in range(N):
        mat[(i,j)] = int(values[j])
A = RotationMatrix(M, N, mat)
A.rotate_matrix(R)
print(A)

C Matrix Layer Rotation HackerRank Solution

Copy Code Copied Use a different Browser

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int m, n, i, j, x, rings;
    long long int r, arr[300][300], p ,q, temp_r;;
    char str[10000];
    char* _p;
    scanf("%d%d%lld", &m, &n, &r);
    fgetc(stdin);
    
    for(i=0; i<m; i++)
        {
        fgets(str, 10000, stdin);
        for(_p=strtok(str, " "), j=0; _p!=NULL; _p=strtok(NULL, " "), j++)
            {
            arr[i][j] = atoll(_p);
        }
    }

    rings = (m<n)?m:n;
    int ring_m, ring_n;
    ring_m = m;
    ring_n = n;
    
    for(x=0; x<(rings/2); x++)
        {
        temp_r = r % ( ( (m-(x*2)) + (n-(x*2)) - 2 )*2 );

        while(temp_r>0)
            {
            i=j=x;
            p = arr[i][j];
            while(i<ring_m)
                {
                q = arr[i][j];
                arr[i][j] = p;
                p = q;
                i++;
            }
            i--;
            j++;
            while(j<ring_n)
                {
                q = arr[i][j];
                arr[i][j] = p;
                p = q;
                j++;
            }
            j--;
            i--;
            while(i>=x)
                {
                q = arr[i][j];
                arr[i][j] = p;
                p = q;
                i--;
            }
            i++;
            j--;
            while(j>=x)
                {
                q = arr[i][j];
                arr[i][j] = p;
                p = q;
                j--;
            }
        temp_r--;
        }
        ring_m--;
        ring_n--;
    }
    for(i=0; i<m; i++)
        {
        for(j=0; j<n; j++)
            {
            printf("%lld ",arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

JAVA 3 Matrix Layer Rotation HackerRank Solution

Copy Code Copied Use a different Browser

import java.io.*;
import java.math.*;
import java.util.*;

public class Solution {

    private StreamTokenizer in;
    private PrintWriter out;

    private int[] parent;
    private int[] rank;

    class Edge {
        public int v;
        public int u;
        public int cost;

        public Edge(int v, int u, int cost) {
            this.v = v;
            this.u = u;
            this.cost = cost;
        }
    }

    private int find(int v) {
        if (v == parent[v])
            return v;
        return parent[v] = find(parent[v]);
    }

    private void union(int a, int b) {
        a = find(a);
        b = find(b);
        if (a != b) {
            if (rank[a] < rank[b]) {
                int k = a;
                a = b;
                b = k;
            }
            parent[b] = a;
            if (rank[a] == rank[b]) {
                ++rank[a];
            }
        }
    }

    private int nextInt() throws IOException {
        in.nextToken();
        return (int)in.nval;
    }

    class Point {
        int x;
        int y;
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    private void run() throws IOException {
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = nextInt();
        int m = nextInt();
        int[][] a = new int[n][m];
        int[][] b = new int[n][m];
        int k = nextInt();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                a[i][j] = nextInt();
            }
        }
        int n1 = n;
        int m1 = m;
        int x0 = 0;
        int y0 = 0;
        int xn = n - 1;
        int yn = m - 1;
        while (x0 <= xn && y0 <= yn) {
            List<Point> points = new ArrayList<Point>();
            for (int i = x0; i <= xn; i++) {
                points.add(new Point(i, y0));
            }
            for (int i = y0 + 1; i <= yn - 1; i++) {
                points.add(new Point(xn, i));
            }
            for (int i = xn; i >= x0; i--) {
                points.add(new Point(i, yn));
            }

            for (int i = yn - 1; i >= y0 + 1; i--) {
                points.add(new Point(x0, i));
            }
            int size = points.size();
            int shift = k % size;
            for (int i = 0; i < size; i++) {
                int p = i;
                int q = (size + i - shift) % size;
                Point point1 = points.get(p);
                Point point2 = points.get(q);
                b[point1.x][point1.y] = a[point2.x][point2.y];
            }

            x0++;
            y0++;
            xn--;
            yn--;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                out.print(b[i][j] + " ");
            }
            out.println();
        }
        out.flush();
        out.close();
    }

    public static void main(String[] args) throws IOException {
        new Solution().run();
    }
}

C++ Matrix Layer Rotation HackerRank Solution

Copy Code Copied Use a different Browser

#include <iostream>
#include <vector>

using namespace::std;

struct element{
    int row,col,value;
};

int countLength(int highC,int highR,int lowC,int lowR,vector <element> &v){
    
    int a = lowC,b = lowR,count=0;
    struct element e;
    e.row = a;
    e.col = b;
    v.push_back(e);
     do{
        count++;
        a++;
        e.row = a;
        e.col = b;
        v.push_back(e);
     }while (a<highR);
    do{
        count++;
        b++;
        e.row = a;
        e.col = b;
        v.push_back(e);
    }while (b<highC);
    do{
        count++;
        a--;
        e.row = a;
        e.col = b;
        v.push_back(e);
    }while (a>lowR);
     do{
        count++;
        b--;
         e.row = a;
         e.col = b;
         v.push_back(e);
     }while (b>lowC);
    return count;
}

void changeMatrix(int arr[][300],int highC,int lowC,int highR,int lowR,int r,int c,int k){
    
    vector<element> v;
    int len = countLength(highC,highR,lowC,lowR,v);
    k = k%len;
    v.pop_back();
    
    for (int i=0; i<v.size();i++) {
        int n = (i+k)%len;
        v[n].value = arr[v[i].row][v[i].col];
    }
    
    for (int i=0; i<v.size(); i++) {
        int r = v[i].row;
        int c = v[i].col;
        arr[r][c] = v[i].value;
    }
    
}

int main(int argc, const char * argv[]) {
    
    int r,c,k,arr[300][300];
    cin>>r>>c>>k;
    for (int i=0; i<r; i++) {
        for (int j=0; j<c; j++) {
            cin>>arr[i][j];
        }
    }
    int highC=c-1,highR=r-1,lowC=0,lowR=0;
    while (true) {
        
        if (highC-lowC<1||highR-lowR<1) {
            break;
        }
        else{
            changeMatrix(arr,highC,lowC,highR,lowR,r,c,k);
        }
        highC--;
        highR--;
        lowC++;
        lowR++;
    }
    for (int i=0; i<r; i++) {
        for (int j=0; j<c; j++) {
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }
}

Python 2 Matrix Layer Rotation HackerRank Solution

Copy Code Copied Use a different Browser

# Enter your code here. Read input from STDIN. Print output to STDOUT

def iterate_circle(mat, m, n, i):
    for j in xrange(i, m - i - 1):
        yield (j, i)
    for j in xrange(i, n - i - 1):
        yield (m - i - 1, j)
    for j in xrange(m - i - 1, i, -1):
        yield (j, n - i - 1)
    for j in xrange(n - i - 1, i, -1):
        yield (i, j)

def rotate(mat, m, n, r):
    for i in xrange(min(m, n) / 2):
        circle_length = 2 * (m + n - 4 * i) - 4
        offset = circle_length - (r % circle_length)
        if offset == circle_length:
            continue
        line = [mat[x][y] for (x, y) in iterate_circle(mat, m, n, i)]
        for (x, y) in iterate_circle(mat, m, n, i):
            mat[x][y] = line[offset]
            offset = (offset + 1) % circle_length
    

[m, n, r] = [int(s) for s in raw_input().split(' ')]
mat = [[0 for j in xrange(n)] for i in xrange(m)]
for i in xrange(m):
    for (j, s) in enumerate(raw_input().split(' ')):
        mat[i][j] = int(s)
rotate(mat, m, n, r)
for i in xrange(m):
    for j in xrange(n):
        print mat[i][j],
    print ''


 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionInsertion Sort Advanced Analysis – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionGridland Provinces – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCircular Palindromes – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLetter Islands – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDistant Pairs – HackerRank Solution
Tags: C Matrix Layer RotationMatrix Layer RotationPython 3 Matrix Layer Rotation
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
41

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
27
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
53
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Grading Students HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Apple and Orange - HackerRank Solution

Comments 1

  1. Pingback: Solutions of Algorithms Data Structures Hard HackerRank - Zeroplusfour

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionInsertion Sort Advanced Analysis – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionGridland Provinces – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCircular Palindromes – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLetter Islands – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDistant Pairs – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Updates

Find out how the cast and crew of Classroom of the Elite II prepare for each episode.

September 8, 2022
0
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Circular Palindromes – HackerRank Solution

May 24, 2022
143
Leetcode All Problems Solutions
Code Solutions

Combination Sum – LeetCode Solution

September 3, 2022
72
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Binary Search Tree : Lowest Common Ancestor – HackerRank Solution

May 31, 2022
13

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?