instruction
stringlengths
71
71.9k
I am posting here to get a code review on my DatabaseManager and DatabaseConnection classes, and for answers on how I can improve. I won't spend too long drolling on, but this is a database manager that uses MySQL and creates a new DatabaseConnection for each operation. Database Manager - using System; using System.Col...
I've implemented the algorithm below for the maximum contiguous subarray problem and would like a review on three specific things: Making the code shorter Making the code faster Any other algorithms that can do the job with lower complexity def crossingsubarray(A, low, mid, high): negetiveinfinity = -1000000000...
I sometimes save nice fortune outputs to my Evernote. The data looks like this: / Abou Ben Adhem (may his tribe increase!) \ | Awoke one night from a deep dream of peace, | | And saw, within the moonlight in his room, | | Making it rich, and like a lily in bloom, ...
I want to make a general alert dialog to use across the whole app. I created a class called AlertDialogManager and just one method to show AlertDialog. Is there a way to refine my code or this code? import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class Ale...
Today's question will just be about a small utility that I needed at some point for one of my projects: a template to detect whether a template is specialized for a given type. The utility uses std::void_t from C++17, but this alias template is simle enough to be implemented in you favourite C++ revision, whichever it ...
I have written a BASH script to parse and compile HTML code into a single page. The script works as expected, although my code is not completely re-usable and the standard output messages could be more helpful. Besides my intended improvements, are there any other problems with my code? #!/bin/bash #Append each section...
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3. ** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *...
Is this a good method to render sprites (textured quads) or is there a faster or better way? Example use: renderer.beginTextureRendering(); for(Enemy enemy : enemies) { renderer.renderTexture(enemy.getX(), enemy.getY(), 0.5f, 0.5f, 0, 0, 1, 1, 1, 1, 1, 1); } renderer.endTextureRendering(cameraTransform, gameTexture...
Basically I solved this question on one of the competitive websites: Given the total n number of String on first input, n input follows: We have to find such pairs of string (i,j) such that that the inverse of j equals i. I implemented the code below, but for larger inputs, it exceeds 1 sec. What more can I do to m...
Calculator class: class Calculator { /** * @return array */ function doPowTable ($n) { $table = array(); for ($i = 1; $i <= $n; $i++) { $table[] = array( 'i' => $i, 'factor' => pow($i, 2) ); } return $t...
I am specifically looking for input on naming ModifierCalculator and Modifiers. I would also appreciate input on whether ModifierCalculator should extend EnumMap instead of having it as a field. These classes are for modifying the status of units. The StatType enum contains different types of ..stats, such as "life", "...
I am currently writing a decent amount of ajax to help me delete a section of a website. It's already becoming a pretty big piece of code, I wondered if it were possible to compact a section of my code. $('.trg-finished').on('click', function() { if(confirm('Are you sure?')) { var that = $(this); v...
First I create a .tar of the root directory with all the file permissions saved and excluding all irrelevant directories (are these the right folders to be excluding?). sudo tar -cvpzf /HDD/systemBackup/backup.tar.gz --one-file-system --exclude=/HDD --exclude=/NAS --exclude=/proc exclude=/tmp --exclude=/mnt --exclude=/...
I am trying to fill values based on group, in my case id. I would like to fill the missing values according to the available date info for each id. id date 1 1 23-04 2 1 23-04 3 1 <NA> 4 1 <NA> 5 2 24-04 6 2 <NA> 7 2 <NA> 8 2 <NA> 9 3 23-04 10 3 <NA> 11 3 <NA> 12 3 <NA> 13 4 <NA> 14 ...
I've created a small project that contains a league table from Premier League updated constantly using local node.js server. Data is fetched from local server. I'm wondering whether my solution is optimal, especially table ordering. 'use strict'; var React = require('../node_modules/react/addons'), GamesService = ...
For fun I decided to make an algorithm in Python that would create a 2D list of a specified size that it can populate with a list of words and fill the gaps with random characters. It's basically a wordsearch. You supply it with the words, optionally a size and then a count of how many times to retry when invalid board...
I have two objects, a bet and a match. A match has 2 teams and both teams get a score at the end of the match. A bet has two scores set up before the match begins. Here I need to know if the bet specified the same winner as it's set on the match (once it's done). // isGoodWinner // // @description :: return true if has...
My first learning project in C. Looking for general feedback e.g. gotchas, coding standards, formatting, naming etc. I'm here to learn! webserver.h #ifndef __Webserver__webserver__ #define __Webserver__webserver__ #include <stdio.h> struct webserver_connection { int status; int socket; char *path; }; st...
This function conditionally copies and pastes information from one sheet to another based on the column headings to standardize data before exported to SQL database. I am not an expert in VBA and started learning but when I run this code, it takes way too long to process huge data (ex: Excel sheet with 70k rows would t...
A Plane of existence is like a universe in the multiverse. At first, I thought that a Plane will consist of many Worlds, and each World consists of many Locations. But it is not so simple. Here are some instances of Planes: MaterialPlane: It has different Worlds, as I originally understood Planes to be. Arcadia: An ...
Given a string sequence and a string, the function should output the next string of that sequence. For example, for sequence "abc": a b c aa ab ac ba .. cc aaa aab How can I improve my code while maintaining a balance between performance and readability? data Sequence = Sequence { getSequence :: String, getF...
Here is a simple decompression implementation. I'd very much appreciate any advice or comments about the structure/logic of the program, style of the code, or reusability of the features. I'm a real novice and really eager to learn from people here, so fire away! : /** * lzw.h * Function declarations for lempel ziv...
I'm making a Mario clone in pygame and I have just wrote a function proccesses inputs and acts as a state machine for Mario. Everything is working just as I want it, but I was wondering if you can think of any more efficient way to write this code. A note that these methods are all a part of a class called mario. def _...
I'm about learning about implementing the solid principle in PHP. I want to create simple content crawler/grabber from some websites. This crawler will grab the content from the website url. Since we know that every website has different html tag structure, so I created an interface. <?php interface BotInterface { ...
I've got a list of geographic coordinates ([lat, long]) and want to compute the corresponding matrix of distances. Distance shall be spherical distance in km. def distance_on_unit_sphere(coord1, coord2): lat1 = coord1[0] long1 = coord1[1] lat2 = coord2[0] long2 = coord2[1] # Convert latitude and lon...
I've worked out a functioning Vigenère encryption in Scala, and while it doesn't seem like my code is too hideous, I'm sure I could make it more functional and Scala-esque. Primarily, it seems like: I've made the full key with a for-expression / zipWithIndex, I'm wondering if this is the best way to do this though. Wo...
This is my code for lazily reading a very large file which contains numbers separated by a new line character. Is there a way to simplify this using the ByteString module or would I have to use Data.Text import Data.ByteString.Lazy.Char8 as L main = do contents <- L.getContents print (sumFile contents) where s...
I would apreciate any suggestions on how to make my code better and more efficient. #include <stdio.h> #include <time.h> #include <windows.h> struct SnakeNode { int x; int y; struct SnakeNode *next; }; struct Food { int x; int y; int isEaten; }; void Gotoxy(int column,int row); int CreateScor...
I have a piece of parsec code that parses a unit optionally followed by ?, + or *. Depending on which type I build my Regex (this is a part of a regex parser) as follows: factor = unit >>= (\x -> (try (char '?' >> return (Or Epsilon x)) <|> try (char '+' >> return (Then x (Star x))) ...
I hate to have to write a custom exists promise every time I need to know if a file exists, so I came up with this. Thoughts? var Promise = require("bluebird") var fs = Promise.promisifyAll(require("fs")) function fsExists(_path){ return fs.lstatAsync(_path) .then(function(){ return true }) .catch(function(){ re...
I have been a developer for many years and get core development concepts, as well as unit testing ones such as DI/Ioc, Mocking etc. I also understand the values, importance of unit testing and writing good tests, as well as asking myself often: "What Would Roy Do?". I am however slightly unsure on some approaches and p...
A train operator has decided to hire an observer to track the different types of trains transiting at a major train platform in Europe. Write a program, using a for loop, to track the different train types at the major train station. The different types of trains are shown in the following table: Train types | ...
I'm writing a little math module in C to handle vectors and matrices. This will be column-major style but right now I've only finished the basics of the vector functions and wanted some feedback on optimization tips, naming conventions, etc. This is C so no real function overloading. I would like to keep it C style. ve...
I'm sorting my object by its property ActivityOrder, which will sometimes contain null values if the user has not explicitly stated an order which an activity should appear. Since null will always appear top most in the sort (unless reversed), it messed up my sort. The solution I came up with was to sort by the id if...
I wasn't quite sure where to go with this, and this seemed to be the best place I could think of so I thought why not. I threw together a build system for C++ projects today using CMake and I wanted your opinions on it, on things I could do better, or change to better comply with best practices. Here's my directory str...
I have the following code and I think it's almost impossible to read and to maintain. I prefer self-explaining and modular code where variable and function names tell what I'm trying to do, but I don't know how to change the part using Eval and inside an ascx. I'm doing much research but I still cannot understand it co...
Question Write a program which removes specific characters from a string. The first argument is a path to a file. The file contains the source strings and the characters that need to be scrubbed. Each source string and characters you need to scrub are delimited by comma. Input sample: how are you, abc hello wo...
Interface for logger: public interface ILogger { void Log(Exception ex, string contextualMessage = ""); void Log(string message); } Interface for web job logger: public interface IJobLogger : ILogger { void SetWriter(TextWriter logWriter); } Web job logger: public cl...
Following is my attempt for a simple implementation for the std string class. Please review my changes and share your feedback. string.h class string { char *pcString; int iCapacity; const static int npos = -1; public: string(void); string(int); string(const char*); string(const string&); ...
Here is an update to my previous thread which you can find here. Again, I'd very much appreciate any advice or comments about the structure/logic of the program, style of the code, or reusability of the features. The fread_twelve function has been heavily modified to deal with detecting and reading the last entry, whic...
The following problem is from codechef.com: Recently Chef become very much interested in perfect squares. We all know Chef and his weird interests. Anyways Chef will be soon writing his masters thesis on perfect squares revealing what-not-known properties of perfect squares. While doing his research, he happened...
I made a simple administrator page lock in PHP and I was wondering how secure it was. I want to use this script to secure administrator pages for my portfolio site but I want it to be fairly secure. <?php /* * Array of authenticated users */ $users = [ // Username => Password 'admin' => 'password' ]; /* * Exp...
Can you review my code? class Router { /** * Store the current URI [0] => Controller/ [1] => Method/ [2]=> parameter * @var array */ private $URI = array(); /** * Store an instance of configuration object * @var object */ private $config = NULL; /** * Store an...
I have a query that populates an array from the database. In some cases, this query returns a great amount of data, (let's say for purpose of an example, 100.000 records). Each row of the database has at least 6 or 7 columns. $results = [ ['id' => 1, 'name' => 'name', 'status' => true, 'date' => '10-01-2012'], ['id...
I am wanting to build web-based testing tools for test website environments utilizing the Selenium Web Driver. I am building a GUI which will contain the following: Drop-down for selecting the website, toggle button for selecting the testing environment and a button for launching the specified browser you wish to test ...
I wrote this Fortran module and I need its subroutines to run as fast as possible. My hope is to get some advice to optimize this code, and after having the serial version running as fast as it can run I will use MPI to make it parallel. Module smearingmodule IMPLICIT NONE contains subroutine smearing(i, nMCd, nPeriodT...
I have code that reads from files of surnames, female and male names and randomly generates a name in the following format: lastname, male/female name. The files are in the following format: JAMES 3.318 4,840,833 1 I have the following working code: def picks(filename): with open(filename) as f: li...
I need to expand the functionality of this project to encompass more commands (you may notice in GetSelectedFilePaths() I have a case that is not currently used, this is to support additional commands I plan to add in my next sprint). So, before going further with this project I thought I'd post it up here for review....
I wrote a simple Python app that is given an IP address and port and the app then finds the PID listening on that IP:PORT. I would like to hear constructive criticism regarding the bellow code. import argparse import sys import socket import subprocess import os def is_legal_ip(address): ip = address.split(":") ...
I have a search form that doesn't require much in terms of input parameters, but the Date Of Birth is import for this particular search. I have been working on creating a way that the form can be intuitive and keep people from attempting to search for a minor. Is there anything that I can make simpler or more efficient...
I have an Array of 5 objects, some key values need to be changed based on the browser width. ie: 5 cols, 4 cols, 3 cols or 2. vs.streams is an Array which is tied to a AngularJS model. When the selected value is true, that data will be called via an API And displays in their appropriate columns. function checkBrowserWi...
This method returns true if any arrays element is equal to another element value, returns False otherwise. public static boolean distinctValues(int[] tmp){ for (int i = tmp.length - 1; i > 0; i--) { for (int j = 1; j < i; j++) { System.out.println(j + ". " + tmp[i] + " and " + tmp[j] + ...
I started to code in C++ and tried to implement a simple BST data structure. Since at the moment I am learning about the Rule of Three, I tried to implement it in my code. Yet, I realize that my code might be far from efficient. I also doubt whether I've made a right destructor or not. What are the best practices to us...
This is my first calculator in Java. I just started learning a week ago so any feedback (positive and negative) is welcome. Tell me what's good and what I can improve on. import java.util.Scanner; public class Calculator { public static void main(String[] args) { // Creates scanner object Scanner...
It's pretty typical for Linux command-line utilities that deal with files to accept either a file as input, or stdin. It's also pretty common for them to be able to output to a file or to stdout. These should be supported: python myprogram.py input output cat input | python myprogram.py > output python myprogram.py in...
I am currently working on a binary serialization library written in C++11 for a personal project. I'd really like to have a review about my design, my implementation and everything else. The library is inspired from QDataStream. Here is the GitLab repository containing the project. Sery/Misc.hh #ifndef SERY_MISC_HH_ #d...
I have some code that checks to see what event data is being passed back from two different media players. The first player sends back play button clicked, but the second player sends back the data I want but it's I have to parse it and read it to see if it matches play and startPosition === 0. Wondering if there is a ...
I decided to roll out my own encryption algorithm, which I am calling "SBC" or Simple Byte Cipher. Essentially, I just take the bytes of the string data, do a Caesar cipher like shift to it, increment through an array of password bytes for each byte in the data (this enables the same letters such as "T" to not always h...
This is my attempt at implementing debounce in Scala without any 3rd party library. How can I improve the code/make it more idiomatic (and any bugs I might have missed)? import scala.compat.Platform.{currentTime => now} import scala.concurrent.duration._ import scala.util.control.NonFatal /** * Return a fun...
I've written my own local "source control". Rather than using a commit-based system, when you're ready to release a version, you can run a command which will create a .zip copy of your source code, and it's saved to a versions folder. How does it work? Each "project" written with this has a specific file structure tha...
What are your thoughts and comments relating to areas I could improve on? import csv import re import requests from bs4 import BeautifulSoup class Resto: def __init__(self,url,filename="default"): self.page = 1 url = url + "&page={0}" self.url = url self.filename = filename d...
I have made an interactive transition controller in Swift in two different ways. This interactive transition controller is the parent class and I have few child classes which adapt the parent for each situation where I need an interactive transition. The first way, the parent doesn't use a delegate and forces the child...
I was recently at a hackathon and saw quite a few people using Parse, so I decided to check it out and read some guides online. Can someone take a look at my code? I followed Parse documentation so it should be fairly readable. I'm trying to get the balance for the user when they log in and display it. Parse.User.logIn...
I have code that uses the brute force technique to find the message to a Caesar cipher. The program decrypts the message using different keys and then checks whether the resulting words are contained in a file called 'wordlist.txt'. if they are, it returns only that result. from collections import namedtuple Keycode = ...
I have model action in RequestAdmin like this: def offer_plan(modeladmin, request, queryset): class MembershipForm(forms.Form): plan = forms.ModelChoiceField(queryset=Plan.objects.all(), required=True,empty_label=None) _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) expi...
I have written the following function to empty and then populate multiple elements using jQuery: function drawHumanCard() { var random = generateRandom(); var humanEl = $('#human'); humanEl.find('#human-name').empty().text(cards[random]['name']); humanEl.find('#human-job').empty().text(cards[random]['...
I run a build system. Datawise the simplified description would be that I have Configurations and each config has 0..n Builds. Now builds produce artifacts and some of these are stored on server. What I am doing is writing kind of a rule, that sums all the bytes produced per configuration builds and checks if these ar...
I have to perform on some collection and return ranking based on some logic I wish to optimize this working code since I think it can be bettered (maybe using tasks?). I need to search on Counterparts item. I load this data from DB and I've got more aliases per counterpart. I need to return the result based on those cr...
I have an array of some arbitrary int values; I want to find the array containing the sum of the past elements in the current index. Example: int[] myArray = new int[5]{ 5, 7, 8, 2, 6 }; I would attempt to: myArray[0] = 5 myArray[1] = myArray[0] + myArray[currentIndex] = 5 + 7 myArray[2] = 5 + 12 + 8 and so forth ti...
I want to have a cross-cutting delete flag in my repository. I have the following repository pattern at the moment: public interface IRepo<TModel> where TModel : EntityBase<int> { TModel Add(TModel item); void Add(IEnumerable<TModel> entities); TModel Remove(TModel item); TModel Find...
I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array...
I am writing a program that updates bonds in an external system that I have database access to. The program is run in an 8-minute interval. Bonds are stored in a table called Debentur. Bonds need to be calculated if they are new or it's calculation method is changed. The calculation method is stored in the column Calle...
Please help me decide whether this should be good or bad idea to declare a Singleton variable in Global.asax file. (It is not actually singleton pattern, I just want to make sure that only one instance is created for this class.) public class Global : System.Web.HttpApplication { private HTML5Video dailyHtml5Video;...
I have several Google Maps on one page and each has its own set of Lat/Lng co-ordinates. As a result I have added in the JavaScript options for each one individually as follows: function initialize() { var myLatlng1 = new google.maps.LatLng(49.18589, -2.19917); var myLatlng2 = new google.maps.LatLng(101.1986, -50...
I'd like to get some feedback on this very basic JavaScript to update which tab is showing as "active" on my simple web page. This is all in a file titled adjustactive.js and included in my footer template for all pages like so: <script src="assets/js/adjustactive.js"></script> Here's the full content of that .js file...
I've been having fun with this program and trying to use different methods and such to achieve the fastest possible word cracking program I can come up with. I'm pretty happy with my current program which is able to crack any three letter word on my computer (Dell Latitude E6400 Dual Core) well under a tenth of a secon...
The following programs are bubble sorting, selection sorting and insertion sorting. As most of the programs online or in books are with Arrays and not ArrayList, I am unsure if they are correct. BubbleSort: public class BubbleSort { List<Integer> unsortedList; private BubbleSort() { unsortedL...
So I'm working on a project that sometimes requires me to switch my server configuration. This is due to some circumstances with database drivers and names that are "too expensive to fix" ... That made me think though: "Why do I always copy these files around manually?" I decided I won't and wrote this small script to ...
See the previous and initial iteration. I got rid of Run objects and just maintain two integer arrays in the RunHeap: one for starting indices, and another for ending indices. Also, thanks to a great suggestion by @maaartinus, the algorithm is now stable. The last, but not least: I do not longer sift up a newly pushed...
I am writing an application with the repositories concept in php with laravel framework. In my controller I have this method: /** * Update the specified resource in storage. * PUT /locais/{id} * * @param int $id * @return Response */ public function update($id) { $data = Input::all(); $data['str_cat...
Rubberduck's latest (and greatest?) feature is a regex search/replace: This is the defining interface: public interface IRegexSearchReplace { List<RegexSearchResult> Find(string pattern, RegexSearchReplaceScope scope = RegexSearchReplaceScope.CurrentFile); void Replace(string searchPattern, string replaceValue...
I am running this code as a macro in Excel, which copies two columns from sheet 1 and pastes them into sheet two. It then compares the first column to a column in sheet two before deleting any duplicates. The two columns I am copying are product code and price. I need to compare the product code to the existing ones. P...
How can I make this "War" card game code more visibly pleasing? import random import sys class Card: def __init__(self, rank, suit, value): self.rank = rank self.suit = suit self.value = value self.name = str(self.rank) + " of " + self.suit class War: def wincards(self, winner,...
I wrote this script to add some config to a Juniper device. It works well but the whole user input validation section (yes or no section) seems a little messy. Is there a better way I could have done it? from jnpr.junos import Device from jnpr.junos.utils.config import Config import getpass #Grab credentials username...
Recently, I reviewed this question about an LZW decoder. In order to properly review that question, I needed to write my own encoder and decoder to be able to test their program. Someone thought it would be interesting to submit these programs for review, so here they are: encode.c /* * LZW encoder * * - Uses fixe...
surface is a pygame.surface object from the Pygame graphics library. It actually runs way faster than I thought it would for a first try. Still, have I made any obvious mistakes here? Is there any way to make it go even faster? cdef mapped_chromatic_aberration(surface, numpy.ndarray[int,ndim=2] intensitymap): cdef ...
Have one div: Here's what scrolling of this div should look like: The only way I see is to duplicate div to left and right sides of original one, and then scroll the whole bunch. Here is a corner-cutting implementation sketch: Fiddle $(document).ready(function() { $original = $("#original"); // Duplicate div to...
I wrote this echo server in Haskell as a way to introduced myself to programming with sockets in Haskell and generally practice Haskell. The echo server has a simple purpose: accept connections from a port (provided as a command line argument) and echo data read from the port back one line at a time. import Control.App...
A class Array which contains two data members: a pointer on array of complex numbers and the length of the array. Implement a function for reading the array. The class should have a constructor, destructor and copy constructor. In the main program, enter the array of complex numbers. main.cpp #include <iostream> #inc...
The program downloads stock information from Yahoo! Finance and displays it in the spreadsheet. On my Mac the program takes 10 minutes to get data for approximately 4000 stocks and on the PC it takes 45 minutes. I wrote another version which copies and pastes the data instead of iterating through each price value, bu...
I've created some custom code that will capture how long a user spent viewing a picture. The timer will stop when the user clicks or escapes from the fancybox view. Is there an alternate way for me to implement this functionality without using the counterStop setInterval() variable? The specific reason why I added an...
I'm trying to print a binary tree in vertical strips. For instance, a tree like this: 8 / \ 6 10 / \ / \ 4 7 9 12 / \ 3 5 Is printed out as: 3 4 6 5 8 7 9 10 12 Here's how I'm doing it: Map<Integer,Set<Integer>> printStripsVertically(TreeNode root, Map<Integer,Set<Integer>> ...
I'm trying to improve my skills with the Task-based Asynchronous Pattern (TAP), by writing simple task-based wrappers around some WMI methods: void Main() { var driveLetter = "E:"; var query = string.Format("select * from Win32_Volume WHERE DriveLetter = '{0}'", driveLetter); var searcher = new ManagementOb...
I'm trying to unit test an AngularJS service that is dependent on another service, using QUnit as my testing framework. The first test I'm writing is one to verify that my service calls another service under specific circumstances. Below is a runnable example. I'm mainly looking to get feedback on the contents of the s...
This is for Java 6 and uses Guava. It's a little ugly and I'm worried I missed some obvious way to do it a lot better. If there is more than one element satisfying either condition I am saying it's false because the condition I am checking should be unique among the list. If and only if the one element satisfying cond...
This is a partial update of this question. An implementation of these interfaces is in this question. To summarize, the class is a generic container similar to MaxHeap, but only needs to support the following operations. create from an existing collection or finite IEnumerable (constructor / factory) with arbitrary co...
Problem You are planning a big programming conference and have received many proposals which have passed the initial screen process but you're having trouble fitting them into the time constraints of the day -- there are so many possibilities! So you write a program to do it for you. • The conference has multi...
Given a list of pairs of integers that represent closed numeric intervals, I need to output a list of intervals where the adjacent intervals are merged together. The code assumes that the intervals do not overlap and that a <= b in all pairs (a, b). Intervals (a,b) and (c,d) are adjacent if b + 1 == c. merge [] ...
fn basename<'a>(path: &'a str, sep: char) -> Cow<'a, str> { let pieces = path.split(sep); match pieces.last() { Some(p) => p.into(), None => path.into(), } } Usage: println!("'{}'", basename("foo", '/')); // outputs 'foo' println!("'{}'", basename("bob/", '/')); // outputs '' println!(...
This is the Matrix Rotation problem from hackerrank.com. You are given a 2D matrix, \$a\$, of dimension \$M×N\$ and a positive integer \$R\$. You have to rotate the matrix R times and print the resultant matrix. Rotation should be in anti-clockwise direction. Rotation of a \$4×5\$ matrix is represented by the foll...