0

I am trying to implement the following program in Ocaml: Write a shuffle : α list → α list → α list procedure, which will return a list with elements from 2 lists shuffled according to the following rules:

  • all of the lists from 2 input lists are on the output lists
  • elements from both lists are in the same order as previously
  • elements of at least one the input lists are not next to each other on the output list

Example outputs of shuffle [5; 7; 0; 5] [3; 2; 8; 9; 3]:

  • [5; 3; 2; 7; 8; 9; 0; 3; 5]
  • [3; 5; 2; 7; 8; 0; 9; 5; 3]

I know how to implement a simple shuffle function (taken from here):

let shuffle d =
    let nd = List.map (fun c -> (Random.bits (), c)) d in
    let sond = List.sort compare nd in
    List.map snd sond

Can you please give me any tips on how should I go from there?

Community
  • 1
  • 1
syntagma
  • 23,346
  • 16
  • 78
  • 134
  • I suppose the lengths of the two input lists should be the same? – Jackson Tale Oct 21 '14 at 16:21
  • or you mean, in the output list, at least for one embedded list, the elements are not next to each other? `shuffle [1;2] [3;4;5;6]` will output `[1;3;2;4;5;6]`, 5 and 6 are neighbours, but at least for [1;2] they are not. do you mean this? – Jackson Tale Oct 21 '14 at 16:24

1 Answers1

1

Here's a simple random interspersal that meets the first two requirements:

let shuffle a b =
  let rec loop a b = match a, b with
     | [], r
     | r, [] -> r
     | x::xs, y::ys ->
        if Random.bool () then x::loop xs b
        else y::loop a ys in
  loop a b

See if you can adapt the way it selects which list to take an element from to also meet the third requirement. You might want to collect some information about the lists before starting that you can feed into the decision.

gsg
  • 9,167
  • 1
  • 21
  • 23