need help~testing shift equivalent by using bool function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 bool equivalent(int a[], int b[], int n){
	for(int i=0;i<n;++i){
	  for(int j=0;j<n;++j){
		if(a[(i+j)%n]==b[j]){
		 break; 
	}
	    else
		return false;
	}
	for(int shift=0;shift<n;++shift){
		  if(a[(i+shift)%n]==b[i])
		  return true;
		  return false;
	}
}
}

Hello, I am a beginner of c++. can anyone help me figure out this
problem? thank you! :) The code I wrote has some logical problem I guess. when I compile and run it, it does not show correct result.

Problem:
Write a function
bool equivalent(int a[], int b[], int n)
which takes two arrays a and b of length n and returns true if they are shift equivalent and false otherwise.
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.
Last edited on
The reason your code is not working is because you are terminating the program early at line 8. Basically that nested for-loop will not work unless both arrays are the same i.e. contain the same data at the same positions.

This the same problem for the next for-loop, you are terminating early again.
Explain what you are trying to accomplish here with the code you have written then someone can help you figure something out
hello, Smac89. thank you for your reply.
I am trying to create a Boolean function that determines whether two arrays,a and b, of length n are shift equivalent or not and returns true if they are shift equivalent and false otherwise.
ex: array a={1,2,3,4,5}
array b={3,4,5,1,2}
we can transform array a into array b by right shift each element of a to the “right” three places. So we can say that array a and array b are shift equivalent
Well thanks to your post i'm having fun to find the answer :D

Try ths
1
2
3
4
5
6
7
8
9
10
11
12
13
x=-1
for i -> n
  if(a[0]=b[i])
    x=i
    break
If(x=-1) return 0
int j=x
for i -> n
  if(b[j]!=a[i])
     return 0
  j+=1
  If(j>=n) j=0
Return true

Topic archived. No new replies allowed.