Adjacent Repeat of Numbers in an Array

22 vues (au cours des 30 derniers jours)
Olivia Rose
Olivia Rose le 12 Avr 2022
Commenté : Jacob le 19 Avr 2023
This is the current function
function adjacentRepeat = HasAdjacentRepeat(inArray)
for inArray=diff(inArray)
adjacentRepeat=1;
end
It works to satisfy the following requirements:
  • Check for the use of a loop.
  • Assessment result: correctCheck adjacentRepeat = 1 for inArray = [2 1 3 3 4 2 5].
  • Assessment result: correctCheck adjacentRepeat = 1 for inArray = [4 5 7 6 3 8 9 7 2 8 9 7 3 3 3 7 1].
  • Assessment result: correctCheck for correct adjacentRepeat for an array of randomized size and values.
But not for this requirement:
  • Assessment result: incorrectCheck adjacentRepeat = 0 for inArray = [1 2 1 2 1].

Réponse acceptée

Image Analyst
Image Analyst le 12 Avr 2022
You never set adjacentRepeat to 0, EVER. So of course it doesn't work.
Did you try just going through your difference array checking if any are 0? If they are, then the adjacent values are the same and you can set the variable and exit.
function adjacentRepeat = HasAdjacentRepeat(inArray)
adjacentRepeat = 0;
d = diff(inArray);
for k = 1 : length(d)
if d(k) == 0
adjacentRepeat = 1;
return;
end
end
end
  2 commentaires
Olivia Rose
Olivia Rose le 12 Avr 2022
I attempted setting it to 0 and it wasn't working. Thank you for your help.
Jacob
Jacob le 19 Avr 2023
I realized the problem I was having is I didnt understand what was or how to use diff. Thank you, this worked perfectly!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 12 Avr 2022
Why do you have a for loop? Why not simply do this:
adjacentRepeat = HasAdjacentRepeat([2 1 3 3 4 2 5])
adjacentRepeat = HasAdjacentRepeat([4 5 7 6 3 8 9 7 2 8 9 7 3 3 3 7 1])
adjacentRepeat = HasAdjacentRepeat([1 2 1 2 1])
function adjacentRepeat = HasAdjacentRepeat(inArray)
adjacentRepeat = any(diff(inArray) == 0);
end
  1 commentaire
Olivia Rose
Olivia Rose le 12 Avr 2022
It has to have a for loop

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by