Rotate an array by k steps in c++ - c++

We have given an array of n size and we to have to rotate it by k times where k can be greater than n in some cases .
My try -
#include<iostream>
using namespace std;
void inputarray(int arr[],int size){
for(int i=0;i<size;i++){
cin>>arr[i];
}
}
int main(){
int n;
cin>>n;
int arr[100];
inputarray(arr,n);
int ansarr[n];
int k;
cin>>k;
k = k%n;
int j=0;
for(int i =n-k;i<n;i++){
ansarr[j++] = arr[i];
}
for(int i=0;i<=k;i++){
ansarr[j++]=arr[i];
}
for(int i=0;i<n;i++){
cout<<ansarr[i];
}
}
My output is coming correct for k>2 like my output for k=3 is -
6
1 2 3 4 5 6
3
456123
Which is correct but for k <2 like k = 2 , 1 and 0 my output is not coming correct . Like for K=2 my output is -
6
1 2 3 4 5 6
2
561234199699
So where am I doing wrong can anyone please tell .

You can perform the rotation with a single loop, and this is completely bulletproof, using
for (int i= 0; i < n; i++)
{
ans[i]= arr[(i + k) % n];
}
Now you can eliminate the modulo inside the loop by noting that i + k remains in [0, n) for i in [- k, n - k), thus in [0, n - k), and i + k - n remains in [0, n) for i in [n - k, 2n - k), thus in [n - k, n). So you can rewrite with two successive loops
k= k % n;
int i;
for (i= 0; i < n - k; i++)
{
ans[i]= arr[i + k];
}
for ( ; i < n ; i++)
{
ans[i]= arr[i + k - n];
}
Caution: due to the behavior of the operator %, the above code will fail for k < 0.

For starters pay attention to that variable length arrays like this
int ansarr[n];
are not a standard C++ feature. You should declare the array similarly to the array arr
int ansarr[100];
Or instead of arrays you could use standard container std::vector.
In any case your code is wrong at least because this for loop
for(int i =n-k;i<n;i++){
ansarr[j++] = arr[i];
}
should start from i equal to k instead of i = n - k
for(int i = k;i<n;i++){
ansarr[j++] = arr[i];
}
and correspondingly the second for loop should look like
for(int i=0;i < k;i++){
ansarr[j++]=arr[i];
}
That is the condition of the loop should look like i < k.
Your program works for k equal to 3 because the expression n - k when n is equal to 6 yields the same value 3.
Bear in mind that there is standard algorithm std::reverse_copy declared in the header <algorithm> that you could use.
Here is a demonstration program
#include <iostream>
#include <algorithm>
int main()
{
const size_t N = 6;
for (size_t k = 0; k < N; k++)
{
int a[N] = { 1, 2, 3, 4, 5, 6 };
int b[N];
std::rotate_copy( a, a + k, a + N, b );
std::cout << k << ":";
for (size_t i = 0; i < N; i++)
{
std::cout << ' ' << b[i];
}
std::cout << '\n';
}
}
The program output is
0: 1 2 3 4 5 6
1: 2 3 4 5 6 1
2: 3 4 5 6 1 2
3: 4 5 6 1 2 3
4: 5 6 1 2 3 4
5: 6 1 2 3 4 5
As for your approach with for loop then it is enough to use only one for loop. For example
#include <iostream>
int main()
{
const size_t N = 6;
for (size_t k = 0; k < N; k++)
{
int a[N] = { 1, 2, 3, 4, 5, 6 };
int b[N];
for (size_t j = 0, i = k; j < N; i = ( i + 1 ) % N)
{
b[j++] = a[i];
}
std::cout << k << ":";
for (size_t i = 0; i < N; i++)
{
std::cout << ' ' << b[i];
}
std::cout << '\n';
}
}
The program output is the same as shown above
0: 1 2 3 4 5 6
1: 2 3 4 5 6 1
2: 3 4 5 6 1 2
3: 4 5 6 1 2 3
4: 5 6 1 2 3 4
5: 6 1 2 3 4 5

I'm not sure how either the question description or the current answers are "rotate it by k times," where "it" is the give array. They all seem to create a new array.
To rotate an array by k, first take k modulo the array length, then perform three steps (for example, {1, 2, 3, 4, 5}, k = 3):
Reverse the part up to index k:
{3, 2, 1, 4, 5}
Reverse the part from index k to the end:
{3, 2, 1, 5, 4}
Reverse the whole array:
{4, 5, 1, 2, 3}

Related

Given a matrix of size nxm, how can we calculate the sum of all possible square matrices of size (L)?

Given this 3x3(nxm) matrix, how can I traverse and get the sum of all possible square-submatrices i.e(1x1,2x2 in this particular case)
2 2 3
3 4 5
4 5 5
I know here,
every element is an individual submatrix(1x1),
and the rest square-submatrices are as follow:
2 2
3 4
2 3
4 5
3 4
4 5
4 5
5 5
I've tried my approach and failed multiple times, the main reason is I get confused with matrices in programming.
My Approach:
Here, 'l' is size of square-sub matrix, 'n' size of rows of main matrix, 'm' size of cols of main matrix,
for (i=0; i<n-l; i++){
for (j=1; j<n-i+1; j++){
sum = 0;
for (p=i; p<l+i; p++){
for (q=1; q<l+j+1; q++){
sum += a[p][q];
}
}
cout << sum << endl;
}
l++;
}
This is the solution of your case.
for(int i=0; i+(l-1)<n; i++){
for(int j=0; j+(l-1)<m; j++){
int sum = 0;
for(int a=0; a<l; a++){
for(int b=0; b<l; b++){
sum += matrix[i+a][j+b];
}
}
cout << sum << endl;
}
}
or you can try to run the full code on Tio.run
I rewrote your code to make it correct, also made full example:
Try it online!
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<std::vector<int>> a = {{2, 2, 3}, {3, 4, 5}, {4, 5, 5}};
size_t n = a.size(), m = a.size() > 0 ? a[0].size() : 0;
for (size_t l = 1; l <= std::min(n, m); ++l)
for (size_t i = 0; i < n - l + 1; ++i)
for (size_t j = 0; j < m - l + 1; ++j) {
int sum = 0;
for (size_t p = i; p < i + l; ++p)
for (size_t q = j; q < j + l; ++q)
sum += a[p][q];
std::cout << l << ", " << i << ", " << j << ": " << sum << std::endl;
}
}
Input:
2 2 3
3 4 5
4 5 5
Output:
1, 0, 0: 2
1, 0, 1: 2
1, 0, 2: 3
1, 1, 0: 3
1, 1, 1: 4
1, 1, 2: 5
1, 2, 0: 4
1, 2, 1: 5
1, 2, 2: 5
2, 0, 0: 11
2, 0, 1: 14
2, 1, 0: 16
2, 1, 1: 19
3, 0, 0: 33

Google Kickstart 2013 Round B Problem Sudoku Checker gives a wrong answer, yet it is working

https://codingcompetitions.withgoogle.com/kickstart/round/0000000000434ad7/00000000004347b3
Sudoku is a popular single player game. The objective is to fill a 9x9 matrix with digits so that each column, each row, and all 9 non-overlapping 3x3 sub-matrices contain all of the digits from 1 through 9. Each 9x9 matrix is partially completed at the start of game play and typically has a unique solution.
Given a completed N2xN2 Sudoku matrix, your task is to determine whether it is a valid solution. A valid solution must satisfy the following criteria:
Each row contains each number from 1 to N2, once each.
Each column contains each number from 1 to N2, once each.
Divide the N2xN2 matrix into N2 non-overlapping NxN sub-matrices. Each sub-matrix contains each number from 1 to N2, once each.
My code:
#include <iostream>
using namespace std;
int main()
{
int i, j, k, no, n, sum, t[36][36], validsum;
cin >> no;
for (k = 0; k < no; k++)
{
cin >> n;
for (i = 0; i < n * n; i++)
{
for (j = 0; j < n * n; j++)
{
cin >> t[i][j];
}
}
bool valid = 1;
validsum = ((n*n)*(n*n+1))/2;
sum = 0;
if (valid == 1)
{
for (i = 0; (i < n * n) && valid == 1; i++)
{
sum = 0;
for (j = 0; (j < n * n) && sum < validsum; j = j+1) {
sum += t[i][j];
}
if (sum != validsum)
valid = 0;
}
}
if (valid == 1)
{
for (j = 0; j < n * n && valid == 1; j++)
{
sum = 0;
for (i = 0; i < n * n && sum < validsum; i++)
{
sum += t[i][j];
}
if (sum != validsum)
valid = 0;
}
}
cout << "Case #" << k + 1 << ": ";
if (valid == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}
My results:
Case #1: Yes
Case #2: No
Case #3: No
Example results:
Case #1: Yes
Case #2: No
Case #3: No
Is it because it's not fast enough?
As mentioned by #jabaa you forgot to check the sub-matrices.
Moreover, checking the sums is not enough, as for example 1 + 3 = 2 + 2.
An efficient solution consists in checking, in each line, column or sub-matrix, that no number arrives twice.
This is efficient, at the condition to first check that all numbers are in the good range [1, n^2]
#include <iostream>
#include <vector>
bool check_line (int sudo[36][36], const int &n, const int &n2, const int &line) {
std::vector<int> vali(n2 + 1, 0);
for (int i = 0; i < n2; i++) {
int num = sudo [line][i];
if (vali[num]) return false;
vali[num] = 1;
}
return true;
}
bool check_col (int sudo[36][36], const int &n, const int &n2, const int &col) {
std::vector<int> vali(n2 + 1, 0);
for (int i = 0; i < n2; i++) {
int num = sudo [i][col];
if (vali[num]) return false;
vali[num] = 1;
}
return true;
}
// line and col represent the position of the first cell of the submatrix
bool check_sub_matr (int sudo[36][36], const int &n, const int &n2, const int &line, const int &col) {
std::vector<int> vali(n2 + 1, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = sudo [line+i][col+j];
if (vali[num]) return false;
vali[num] = 1;
}
}
return true;
}
bool validity (int sudo[36][36], const int& n, const int& n2) {
// First check validity of numbers
for (int i = 0; i < n2; i++) {
for (int j = 0; j < n2; j++) {
int number = sudo[i][j];
if ((number < 1) || (number > n2)) return false;
}
}
// Check lines
for (int i = 0; i < n2; i++) {
auto check = check_line (sudo, n, n2, i);
if (!check) return false;
}
// Check columns
for (int i = 0; i < n2; i++) {
auto check = check_col (sudo, n, n2, i);
if (!check) return false;
}
// Check sub-matrices
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; ++j) {
auto check = check_sub_matr (sudo, n, n2, i*n, j*n);
if (!check) return false;
}
}
return true;
}
int main() {
int sudo[36][36];
int nt;
std::cin >> nt;
for (int t = 1; t <= nt; ++t) {
int n, n2;
std::cin >> n;
n2 = n*n;
for (int i = 0; i < n2; i++) {
for (int j = 0; j < n2; j++) {
std::cin >> sudo[i][j];
}
}
auto valid = validity (sudo, n, n2);
std::cout << "Case #" << t << ": ";
if (valid) std::cout << "Yes" << std::endl;
else std::cout << "No" << std::endl;
}
return 0;
}
Your code doesn't return correct answers in some cases. You have to check the sub-matrices, too and you can't check using a sum. Here are three test cases to demonstrate the problems in your code:
3
3
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
3
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
8 5 9 7 6 1 4 2 3
1 9 8 3 4 2 5 6 7
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
3
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
2 8 8 3 4 2 5 6 7
7 6 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
Your code returns Yes in both cases but the expected result is No in both cases.

Subarray with given sum

Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements.
Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010
Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5
My Code:
#include <iostream>
using namespace std;
int main() {
int t, n, s, a[1000], result[1000];
cin >> t;
for (int i = 0; i < t; i++) {
result[i * 2] = -1;
cin >> n >> s;
for (int j = 0; j < n; j++) {
cin >> a[j];
}
int flag = 0;
for (int j = 0; j < n; j++) {
if (flag == 0) {
int sum = 0;
for (int k = j; k < n && sum < s; k++) {
sum += a[k];
if (sum == s) {
result[i * 2] = j + 1;
result[(i * 2) + 1] = k + 1;
flag = 1;
break;
}
}
}
}
}
for (int i = 0; i < t * 2; i += 2) {
if (result[i] != -1) {
cout << result[i] << " " << result[i + 1] << endl;
} else {
cout << result[i];
}
}
}
Result:
Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
4 225
9 45 10 190
Its Correct output is:
-1
And Your Code's output is:
-1-1-1-138 42
I've just found this:
https://www.youtube.com/watch?v=G0ocgTgW464
However I believe that the time complexity is O(n*log(n)) given the fact that map::find is O(log(n))

How do I rotate M x N matrix 180 degrees in place?

I've seen several questions here that don't quite answer my question. I'm trying to do a rendition of the classic matrix rotation question used so often in interview questions. Instead of focusing on the square matrix, I'm interested in M x N matrices.
For input matrix
1 2 3
4 5 6
7 8 9
1 2 3
I'd like to transform the matrix into
3 2 1
9 8 7
6 5 4
3 2 1
Here is the code I've written:
#include <iostream>
#include <vector>
#include <algorithm>
void do_swaps(int& a, int& b, int& c, int& d) {
std::swap(a, b);
std::swap(c, d);
}
void rotate(std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m/2; ++i) {
for(size_t j = 0; j <= n/2; ++j) {
do_swaps(v[i][j], v[m-i-1][n-j-1], v[m-j-1][i], v[j][n-i-1]);
}
}
}
void print(const std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m; ++i) {
for(size_t j = 0; j < n; ++j) {
std::cout << v[i][j] << ' ';
}
std::cout << '\n';
}
}
int main() {
std::vector<std::vector<int>> m{{1,2,3}, {4,5,6}, {7,8,9}, {1, 2, 3}};
std::cout << "Before: \n";
print(m);
rotate(m);
std::cout << "\nAfter: \n";
print(m);
}
And here's my output:
Before:
1 2 3
4 5 6
7 8 9
1 2 3
After:
3 2 1
9 5 7
6 8 4
3 2 1
My code works for 3 x 3 matrices (haven't tested higher dimensional matrices), but I seem to have an off by one error in my code causing the inner-most elements to remain unswapped.
In the line for(size_t j = 0; j <= n/2; ++j) {, I've tried adjusting the stop condition to several things including j < (n+1)/2; and j < (n-1)/2;, but it remains the same.
Can someone explain where I've gone wrong in my algorithm?
You don't take care of middle line in case when lines number is odd.
Further, you swap elements that lie on the middle column (when columns number is odd) twice. You can check if m is odd with a bitwise-and with 1.
The following is an easier way to project swapped values is presented above and you don't even have to care about the middle column in this case.
void rotate(std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for (size_t i = 0; i < m / 2; ++i)
{
for (size_t j = 0; j < n; ++j)
std::swap(v[i][j], v[m - i - 1][n - j - 1]);
}
if (m&1)
for (size_t i = 0; i< n/2; ++i)
std::swap(v[m/2][i], v[m/2][n-i-1]);
}
I would use mirror x and then mirror y or vice versa. It is in-place and safe for any resolution (even/odd). So first swap all rows and then all columns (or vice versa). Here some code for this.
void rotate(std::vector<std::vector<int>>& v) {
size_t m= v.size();
size_t n=v[0].size();
for(size_t i=0;i<m;i++) {
for(size_t j=0,k=n-1;j<k;j++,k--) {
std::swap(v[i][j],v[i][k]);
}
}
for(size_t j=0;j<n;j++) {
for(size_t i=0, k=m-1; i<k; i++, k--) {
std::swap(v[i][j],v[k][j]);
}
}
}
A pythonish way (not in place):
d = (1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 2, 3)
[r[::-1] for r in d[::-1]]

C++ Multidimensional Array

i'm trying to figure out how to fill a multidimentional array in this way:
Input: rows = 3 , cols = 3 :
1 4 7
2 5 8
3 6 9
can somebody give me an idea?
P.S My task is to find how many nubers stay in the same position in both arrangements. Ex:
1 4 7 1 2 3
2 5 8 4 5 6
3 6 9 7 8 9
so the numbers that are in the same position are : 1 5 9.
i've tryied :
//n = 3 , m = 3
for(int i = 0; i <n; i++) {
for(int j = 0; j <m; j++){
if(array[i][j] == array2[i][j]) {
lol++;
}
}
}
cout<<lol;
/*
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 8 9
*/
it must show me 3 , but it shows 0, where is the problem?
Populate at initialization:
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
EDIT (unsure if resolved):
After update to question here is an example application that (with modification to accept input from user) will diff two arrays and construct an array indicating the elements that were the same and a count of the number of identical elements:
#include <iostream>
int** make_array(const size_t a_rows, const size_t a_columns)
{
int** result = new int*[a_rows];
for (size_t i = 0; i < a_rows; i++)
{
*(result + i) = new int[a_columns];
}
return result;
}
void print_array(int** a_array, const size_t a_rows, const size_t a_columns)
{
for (size_t r = 0; r < a_rows; r++)
{
for (size_t c = 0; c < a_columns; c++)
{
std::cout << *(*(a_array + r) + c) << " ";
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
// Example data.
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
int b[3][3] = { { 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
};
size_t rows = 3;
size_t columns = 3;
// Create three arrays:
// - two input arrays
// - array that represents which elements are the same
int** in_1 = make_array(rows, columns);
int** in_2 = make_array(rows, columns);
int** diff = make_array(rows, columns);
// Populate with example data.
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(in_1 + r) + c) = a[r][c];
*(*(in_2 + r) + c) = b[r][c];
}
}
// Diff.
// The 'diff' array will hold '1' for elements that
// were the same and '0' for elements that were not.
size_t same_count = 0;
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(diff + r) + c) = *(*(in_1 + r) + c) == *(*(in_2 + r) + c);
same_count += *(*(diff + r) + c);
}
}
std::cout << "\n";
// Results.
print_array(in_1, rows, columns);
print_array(in_2, rows, columns);
print_array(diff, rows, columns);
std::cout << "Same element count: " << same_count << "\n";
// Free...
return 0;
}
Output:
$ ./cpp/main.exe
1 4 7
2 5 8
3 6 9
1 2 3
4 5 6
7 8 9
1 0 0
0 1 0
0 0 1
Same element count: 3
Create a dynamically allocated array if you only know the dimensions at runtime:
int** x = new int*[rows];
for ( int i = 0 ; i < rows ; i++ )
x[i] = new int[cols];
And then populate it:
for ( int i = 0 ; i < rows ; i++ )
for ( int j = 0 ; i < cols ; j++ )
x[i][j] = y;
Or better yet, use a vector of vectors, this will give you more flexibility:
std::vector<std::vector<int> > x;
A simple solution would be this:-
int k = 1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
a[j][i] = k; // filling it in the column first order
++k;
}
}