185k views
5 votes
A pincode consists of N integers between 1 and 9. In a valid pincode, no integer is allowed to repeat consecutively. Ex: The sequence 1, 2,1, 3 is valid because even though 1 occurs twice, it is not consecutive. However, the sequence 1, 2, 2, 1 is invalid because 2 occurs twice, consecutively. Utilize a for loop and branch statements to write a function called pinCodeCheck to detect and eliminate all the consecutive repetitions in the row array pinCode. The function outputs should be two row arrays. The row array repPos contains the positions pinCode where the consecutive repeats occurs, and the row array pinCodeFix is a valid pincode with all the consecutive repeats removed in pinCode. Hint: The empty array operator [] is will be helpful to use.

User Rishat
by
5.1k points

1 Answer

7 votes

Answer:

function [ repPos, pinCodeFix ] = pinCodeCheck( pinCode )

pinCodeFixTemp = pinCode;

repPosTemp = [];

for i = 1:length(pinCode)

if((i > 1)) & (pinCode(i) == pinCode(i - 1))

repPosTemp([i]) = i;

else

repPosTemp([i]) = 0;

end

end

for i = 1:length(pinCode)

if(repPosTemp(i) > 0)

pinCodeFixTemp(i) = 0;

end

end

repPosTemp = nonzeros(repPosTemp);

pinCodeFixTemp = nonzeros(pinCodeFixTemp);

repPos = repPosTemp';

pinCodeFix = pinCodeFixTemp';

end

Step-by-step explanation:

Let me start off by saying this isn't the most efficient way to do this, but it will work.

Temporary variables are created to hold the values of the return arrays.

pinCodeFixTemp = pinCode;

repPosTemp = [];

A for loop iterates through the length of the pinCode array

for i = 1:length(pinCode)

The if statement checks first to see if the index is greater than 1 to prevent the array from going out of scope and causing an error, then it also checks if the value in the pinCode array is equal to the value before it, if so, the index is stored in the temporary repPos.

if((i > 1)) & (pinCode(i) == pinCode(i - 1))

repPosTemp([i]) = i;

Otherwise, the index will be zero.

else

repPosTemp([i]) = 0;

Then another for loop is created to check the values of the temporary repPos to see if there are any repeating values, if so, those indexes will be set to zero.

for i = 1:length(pinCode)

if(repPosTemp(i) > 0)

pinCodeFixTemp(i) = 0;

Last, the zeros are removed from both temporary arrays by using the nonzeros function. This causes the row array to become a column array and the final answer is the temporary values transposed.

repPosTemp = nonzeros(repPosTemp);

pinCodeFixTemp = nonzeros(pinCodeFixTemp);

repPos = repPosTemp';

pinCodeFix = pinCodeFixTemp';

User Colriot
by
5.2k points