Using Jython, I Need To Randomize A String Keeping The Words In Tact
Solution 1:
You should look at Wikipedia's article on the Fisher-Yates shuffle. It's efficient and simple. Here's the psuedo-code they give:
To shuffle an array a of n elements:
for i from n - 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
It should be easy enough to convert to Python.
Solution 2:
Not sure how the Python syntax would fit, but using Java, you would tokenize the String on the space delimiter, then use a random index less than the length of the token array, and access that element of the token array, pop it, print it, and repeat until the token array was empty.
Solution 3:
Regarding shuffling - one idea is to go over the list of items (for i in range(len(lst))
) and for each element at position i
, swap it with random element (say at position randrange(len(lst))
)
Regarding swapping two variables, remember in Python you can do a,b = b,a
and that works - instead of temp=a; a=b; b=temp
you have to do in other languages.
Regarding separating the words, it's as easy as strVar.split()
and re-assembling as easy as ' '.join(lst)
.
I am not including the exact code, since this being a homework you are expected to do the work... but with above in mind should be easy, no?
Solution 4:
It's a really simple algorithm:
- Split the Sentence at every space (don't know about jython but both java and python have built-in functions for that)
- Shuffle the Array
- Join the resulting string array
- Print the new string
For which part do you need help exactly?
UPDATE
Algorithm for shuffling
- Create a new (empty) Array
- While there are items in the old Array
- Take a random Number between 0 and the Number of Items in the old Array -1
- Remove the item from the old array and push it to the end of the new array
- Repeat until there are no more items in the old Array
There are more advanced and definatly more efficient shuffling algorithms but this simple algorithm should get you started.
Post a Comment for "Using Jython, I Need To Randomize A String Keeping The Words In Tact"