0 Replies - 2269 Views - Last Post: 05 February 2012 - 09:21 AM

#1 sarmanu   User is offline

  • D.I.C Lover
  • member icon

Reputation: 967
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Word scrambler

Posted 05 February 2012 - 09:21 AM

Description: Simply compile, then call the function Scramble with a string as parameter.Scrambles a word (changes the order of letters in a random manner).
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <ctime>

// The idea: put every index from 0 -> input.length() - 1
// in a vector, then shuffle the elements of that vector.
// Now, the indexes are randomized. Calling input[indexes[index]]
// will now give you the letter at position indexes[index], which
// is a randomized index.
std::string Scramble(const std::string &input)
{
	std::vector<size_t> indexes;
	for (size_t i = 0; i < input.size(); i++)
		indexes.push_back(i);
	std::random_shuffle(indexes.begin(), indexes.end());
	std::string ret;
	for (size_t i = 0; i < indexes.size(); i++)
		ret += input[indexes[i]];
	return ret;
}

int main()
{
        // for random_shuffle
	srand(size_t(time(NULL)));
	std::cout << Scramble("DreamInCode") << std::endl;

	return 0;
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1