How to generate a sequence of words?

15 views (last 30 days)
Hello, I am trying to create a program that generates the word "to" and determines how many repetitions it takes to reach said word. I had no problem generating the letter "t", but I became stuck once I had to generate a letter adjacent to another, in order to create "to". Any help would be appreciated. Here is my code to generate the letter "t":
Letters = 'abcdefghijklmnopqrstuvwxyz_';
% By using a random integer range from 1 to 27 we can randomly select letters.
MinInt = 1; MaxInt = 27;
% create a vector of random integers from 1 to 27
LetterPositions = floor((MaxInt - MinInt + 1)*rand(1,27) + MinInt);
% create a vector of random letters A to Z
RandomLetters = Letters(LetterPositions)';
fprintf('The attempted sequence is t\n')
tic
fprintf('It took %g attempts to create the sequence:t\n',sum(RandomLetters == 't'))
toc
fprintf('The attempted sequence is to\n')
tic
% here is where I'm stuck

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 16 Apr 2016
You can improve your code
Letters = ['a':'z' '_']
LetterPositions =randi(27,1,27)
RandomLetters = Letters(LetterPositions)'
%If you want to generate two letters
idx=randi(27,1,2)
Letters(idx)
  3 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 16 Apr 2016
Letters = ['a':'z' '_'];
LetterPositions =randi(27,1,27);
RandomLetters = Letters(LetterPositions)';
%If you want to generate two letters
idx=randi(27,1,2);
k=0;
while ~isequal(Letters(idx),'to')
k=k+1;
idx=randi(27,1,2);
end
disp(k)
disp(Letters(idx))

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!