182k views
2 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.

User Smitrp
by
3.5k points

1 Answer

2 votes

Answer:

The function definition to this question can be defined as follows:

Function definition:%defining method

function [ rep_Pos, pincode_Fix ] = pincode_check( pincode )

pincode_Fix_Temp = pincode; %defining variable that holds a value

rep_Pos_Temp = []; %defining array

for i = 1:length(pincode) %defining a loop to count value

if((i > 1)) & (pincode(i) == pincode(i - 1)) %checking value

rep_Pos_Temp([i]) = i; %store value in rep_Pos_Temp array

else

rep_Pos_Temp([i]) = 0; %array assign as 0

end

end

for i = 1:length(pincode) %loop to count value length

if(rep_Pos_Temp(i) > 0)%check condition

pincode_Fix_Temp(i) = 0; %assign value to 0

end

end

%removing all array value

rep_Pos_Temp = nonzeros(rep_Pos_Temp); %assign value in rep_Pos_Temp

pincode_Fix_Temp = nonzeros(pincode_Fix_Temp); %assign value in pincode_Fix_Temp

rep_Pos = rep_Pos_Temp; %re positing value

pincode_Fix = pincode_Fix_Temp'; % assign value in pincode_Fix

end

Step-by-step explanation:

In the given method definition a method a temporary variable "pincode_Fix_Temp" and an array "rep_Pos_Temp" is declared, which holds the values of the return arrays.

  • In the next step, a for loop is declare, that counts the length of the array, and inside the loop, a conditional statement is used, that checks if the index is greater than 1, it will go to array out of scope and causing an error, otherwise, the array is equal to the value, and index value stored in the rep_Pos variable.
  • Then another for loop is declared, that checks the values of the rep_Pos variable and see if there are repeated value, so, indexes will be set to zero. At the last step, it removes all the zeros.
User Jim Smart
by
3.9k points