Equivalent Arrays Consider the two arrays a and b. a: 1 2 3 4 5 b: 3 4 5 1 2 It
ID: 3541371 • Letter: E
Question
Equivalent Arrays
Consider the two arrays a and b.
a: 1 2 3 4 5
b: 3 4 5 1 2
It is possible to transform array a into array b by right shifting each element of a to the right
three places. If an element falls off the back of the array have it come around the front and
keep counting positions. That is how 3 in array ended up in the first position of array b. One
way to look at this is to imagine that we are moving the element around in a circular manner.
In the example above, we have right shifted the array 3 positions to the right.
Definition: Let a and b be two integer arrays of the same length. We say that they are shift
equivalent if array a can be right shifted to create array b.
Problem
Write a function in C ++
bool equivalent(int a, int b, int n)
which takes two arrays a and b of length n and returns true is they are shift equivalent and false
otherwise. please post the correct answer
Explanation / Answer
#include <iostream>
using namespace std;
bool equivalent(int a[], int b[], int n)
{
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
if (a[i] != b[(i + j)%n]) goto n_shift;
}
return true;
n_shift: ;
}
return false;
}
int main() {
int n;
cout << "Please enter a size (to be used for both arrays) " << endl;
cin >> n;
int *arr1 = new int[n];
int *arr2 = new int[n];
int x;
for (x = 0; x < n; x++) {
cout << "Please enter values for the first array: " << endl;
cin >> arr1[x];
}
x = 0;
for (x = 0; x < n; x++) {
cout << "Please enter values for the 2nd array: " << endl;
cin >> arr2[x];
}
bool answer = equivalent(arr1, arr2, n );
if (answer) {
cout << "They are shift equivalent." << endl;
} else {
cout << "They are not shift equivalent." << endl;
}
delete[] arr1;
delete[] arr2;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.