Finding the amount of times '101' appears and does not appear in a series of strings
Show older comments
Hello!
I am trying to answer two connected questions for my Computer Engineering class. The code runs, however, I do not think it is correct. I feel as if I have multiple errors or am overlooking some aspects. Please help! Thank you so much
My code:
%% possible different binary strings
A = 2;
B = 31;
C = A.^B;
fprintf('The number of different binary strings of length %d is: %d\n', B, C);
%% question "How many binary strings of length 31 DO contain the string 101?"
% Define the length of the binary strings
n = 31;
% Initialize the dynamic programming table
dp = zeros(n + 1, 2);
dp(1, :) = [1, 0]; % Base case
% Populate the dynamic programming table
for i = 2 : n + 1
dp(i, 1) = dp(i - 1, 1) + dp(i - 1, 2); % Ending with '0'
dp(i, 2) = dp(i - 1, 1); % Ending with '1'
% Check if "101" is formed at the current position
if i >= 4
dp(i, 2) = dp(i, 2) - dp(i - 3, 1); % Subtract the count without "101"
elseif i >= 3
dp(i, 2) = dp(i, 2) - dp(i - 2, 1); % Subtract the count of strings ending with "101"
end
end
% Compute the total count of binary strings containing '101'
count = dp(n + 1, 1) + dp(n + 1, 2);
% Display the result
fprintf('The number of binary strings of length %d that contain the string "101" is: %d\n', n, count);
%% question "How many binary strings of length 31 do NOT contain the string 101?"
% Define the length of the binary strings
n = 31;
% Initialize the dynamic programming table
dp = zeros(n + 1, 2);
dp(1, :) = [1, 1]; % Base case
% Populate the dynamic programming table
for i = 2 : n + 1
dp(i, 1) = dp(i - 1, 1) + dp(i - 1, 2); % Ending with '0'
dp(i, 2) = dp(i - 1, 1); % Ending with '1'
end
% Compute the total count of binary strings without '101'
count = dp(n + 1, 1) + dp(n + 1, 2);
% Display the result
fprintf('The number of binary strings of length %d that do not contain the string "101" is: %d\n', n, count);
Output:
The number of different binary strings of length 31 is: 2147483648
The number of binary strings of length 31 that contain the string "101" is: 7739
The number of binary strings of length 31 that do not contain the string "101" is: 5702887
1 Comment
Matt J
on 9 Jul 2023
I feel as if I have multiple errors or am overlooking some aspects. Please help!
Help with what? You haven't told us what you think is wrong.
Accepted Answer
More Answers (1)
dp = [0 1 0 1 0 1 1 1 0 1 0 1 0 0 0 1 0 1 1]
indexes = strfind(dp, [1 0 1])
numOccurrences = numel(indexes)
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!