How to generate a sequence of words?
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Karan Sandhu
am 16 Apr. 2016
Kommentiert: Karan Sandhu
am 16 Apr. 2016
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
0 Kommentare
Akzeptierte Antwort
Azzi Abdelmalek
am 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 Kommentare
Azzi Abdelmalek
am 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))
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!