patterncppMinor
Check if 2 arrays have (exactly) the same elements recursively
Viewed 0 times
samearraystheelementsrecursivelycheckexactlyhave
Problem
I've been given a homework assignment to make a function to check whether 2 given arrays with the same given size have exactly the same set of elements.
My function seems to be working but I feel like I don't use the principles of recursion properly in my function.
I'm not allowed to use dictionary like data structures or sorts of all kinds.
Could you think of a simpler recursive approach to this problem?
My function seems to be working but I feel like I don't use the principles of recursion properly in my function.
I'm not allowed to use dictionary like data structures or sorts of all kinds.
Could you think of a simpler recursive approach to this problem?
bool sameElements(int Arr1[], int Arr2[], int size) {
bool found; // flag to indicate whether element from Arr1 has been found in Arr2
found = false;
//base case
if (size == 1) {
if (Arr1[0] == Arr2[0])
return true;
else
return false;
}//if
else { //size != 1
int i; //index for loop
for (i = size - 1; i >= 0 && !found ; i--) {
if (Arr2[i] == Arr1[size-1]) { // check existence of element in Arr1
swapInArray(Arr2, i, (size - 1)); // swap elements
found = true;
}//if
}//for
if (found)
sameElements(Arr1, Arr2, size - 1); // send to recursion with size-1
else
return false;
}//else
}//sameElements
void swapInArray(int arr[], int i, int j) {
int temp; // temp value to hold arr[i]
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}//swapInArraySolution
Boolean return anti-pattern
It is a very common over-complication beginner make to write:
When all you need is:
So the block:
becomes:
Never comment when a block closes
Things like:
are not ok. If you need them to keep track of the code, your code has overly long blocks, and the problem must be fixed at its source.
It is a very common over-complication beginner make to write:
if (cond) {
return true;
else {
return false;
}When all you need is:
return cond;So the block:
if (Arr1[0] == Arr2[0])
return true;
else
return false;becomes:
return Arr1[0] == Arr2[0];Never comment when a block closes
Things like:
}//elseare not ok. If you need them to keep track of the code, your code has overly long blocks, and the problem must be fixed at its source.
Code Snippets
if (cond) {
return true;
else {
return false;
}return cond;if (Arr1[0] == Arr2[0])
return true;
else
return false;return Arr1[0] == Arr2[0];Context
StackExchange Code Review Q#114564, answer score: 7
Revisions (0)
No revisions yet.