Write the c++ code for the function scramble. Use the following header exactly f
ID: 3620152 • Letter: W
Question
Write the c++ code for the function scramble.Use the following header exactly for your function that scrambles words:
string scramble(string word) {
}
Use the following algorithm for the scramble() function:
if the word length is greater than 3
r1 = random number between 1 and length of word - 1
r2 = r1
repeat while r2 equals r1
r2 = random number between 1 and length of word - 1
swap word[r1] with word[r2]
return word
Input: I don't give a damn for a man that can only spell a word one way
Output after scramble: I d'not gvie a dman for a man taht can olny sepll a wrod one way
Explanation / Answer
please rate - thanks #include <iostream>#include <string>
using namespace std;
string scramble(string word);
main()
{srand(time(0));
int i,prev=0;
string s,word,scrambled="";
cout<<"Enter a string: ";
getline(cin,s);
cout<<"Input: ";
cout<<s<<endl<<endl;
cout<<"Output after scramble: ";
i=s.find(' ',0);
while(i>0)
{
word=s.substr(prev,i-prev);
prev=i+1;
scrambled=scramble(word);
cout<<scrambled<<" ";
i=s.find(' ',prev);
}
word=s.substr(prev,s.length()-prev);
scrambled=scramble(word);
cout<<scrambled<<" ";
system("pause");
return 0;
}
string scramble(string word)
{char c;
int r1,r2;
if(word.length()<=3)
return word;
r1=rand()%(word.length()-1)+1;
r2=r1;
while(r2==r1)
r2=rand()%(word.length()-1)+1;
c=word[r1];
word[r1]=word[r2];
word[r2]=c;
return word;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.