0

Using js, I'd like to create a paragraph made up of a randomly ordered list of items (in paragraph form) for a simple website.

So the input would be:

apples
concrete
a finite amount of happiness
North Carolina

and the resulting randomized paragraph would look like:

concrete, North Carolina, a finite amount of happiness, apples.

  • What part isn't working for you? – Matt Bryant Oct 01 '13 at 16:00
  • Create a jsfiddle and show us your code. Have you tried taking the input and putting it into an array and printing comma separated array elements. – poodle Oct 01 '13 at 16:01
  • Good that you would like to create, then please create and come back with your code if you get stuck in between... – UID Oct 01 '13 at 16:02
  • 1
    Welcome to SO! If you're having specific issues coding this, feel free to share. If you just need a general idea, here you go: put your items in an array and [shuffle](http://stackoverflow.com/q/2450954/989121) it randomly. – georg Oct 01 '13 at 16:04

2 Answers2

2
var list = [
  'apples',
  'concrete',
  'a finite amount of happiness',
  'North Carolina'
];

var paragraph = list.sort(function() { return Math.random() - 0.5 }).join(', ');

The shuffle function isn't truly random apparently, but it's good enough for your purposes.

Fiddle

Andy
  • 61,948
  • 13
  • 68
  • 95
1

Create an array that holds the user inputs, and an array that is empty, but the same length as the inputs array. Every time you append a new value, using a random number as the array index from the inputs, add that value at the index of the random number, to the second empty array. When the second initially empty array is then full, you know you have used all values, and in a random order.

The first array is to get the values of the input, and how many there are. The second array, is strictly used to just keep track of what has been used, and what hasn't yet.

Casey ScriptFu Pharr
  • 1,672
  • 1
  • 16
  • 36