2

I'm looking for a way to randomize lists in python (which I already know how to do) but to then make sure that two things aren't next to each other. For example, if I were to be seating people and numbering the listing going down by 0, 1, 2, 3, 4, 5 based on tables but 2 people couldn't sit next to each other how would I make the list organized in a way to prohibit the 2 people from sitting next to each other.

6
  • 2
    simply check the shuffled list you know how to create for your condition. Did you try anything? Commented Jun 8, 2018 at 11:16
  • @Ev.Kounis O(∞)? :) Commented Jun 8, 2018 at 11:18
  • @timgeb If you construct the list instead to make sure it satisfies your condition, it is not actually random any more, is it? And i guess it is more like O(?). Commented Jun 8, 2018 at 11:23
  • @Ev.Kounis I'd call it random with respect to a constraint. You could create all the permutations of the list that satisfy the condition and then pick one randomly. One way is probably to construct a generator that enumerates these permutations and then create a random integer (edit: between 1 and #<allowed permutations>) and advance the generator as many times as that integer. Commented Jun 8, 2018 at 11:25
  • What two things shouldn't be next to each other? This is unclear. Commented Jun 8, 2018 at 11:28

1 Answer 1

1

As you say that you know how to shuffle a list, the only requirement is that two elements are not next to each other.

A simple way is to:

  • shuffle the full list
  • if the two elements are close, choose a random possible position for the second one
  • exchange the two elements

Maximum cost: one shuffle, one random choice, one exchange

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.