Function Repository Resource:

RandomBinMove

Source Notebook

Randomly move an item between lists in a collection

Contributed by: Ed Pegg Jr

ResourceFunction["RandomBinMove"][{bin1,bin2,}]

randomly picks an item in a random bin and moves it to a different bin.

Details

Bins is a common way to reference a list of lists.
If a bin is empty, nothing will be moved from it, but something can move to it.
The Head of each bin need not be List.
Bin moves are useful in annealing algorithms. For example, a puzzle based on color binning has 480 different states. The solutions for a million random states are tested, and cases {193, 72345} are interesting. RandomBinMoves can check if a minor change to the bins produces a more interesting solution.

Examples

Basic Examples (4) 

From a set of four bins with the numbers 1 to 10, randomly move one item:

In[1]:=
bins = {{1, 4, 5}, {2, 6, 7, 8, 10}, {}, {3, 9}};
ResourceFunction["RandomBinMove"][bins]
Out[2]=

Try it again:

In[3]:=
ResourceFunction["RandomBinMove"][bins]
Out[3]=

Make 30 bin moves in sequence:

In[4]:=
Nest[ResourceFunction["RandomBinMove"][#] &, bins, 30]
Out[4]=

There are thirty possible ways to move a single item in the bins above:

In[5]:=
Union[Table[ResourceFunction["RandomBinMove"][bins], {10000}]]
Out[5]=
In[6]:=
Length[%]
Out[6]=

Scope (2) 

Bins can have repeated items:

In[7]:=
bins = RandomInteger[{1, 3}, {4, 4}]
Out[7]=
In[8]:=
ResourceFunction["RandomBinMove"][bins]
Out[8]=

Bin items can be arbitrary expressions:

In[9]:=
bins = Partition[Characters["hippopotamus"], 4];
ResourceFunction["RandomBinMove"][bins]
Out[10]=

Possible Issues (2) 

Bins must be non-atomic:

In[11]:=
bins = {{{"h", "p", "p"}, {"o", "p", "o", "t", "i"}, {"a", "m", "u", "s"}}, "hippo"};
ResourceFunction["RandomBinMove"][bins]
Out[12]=

Bins need not be a List:

In[13]:=
bins = {f["h", "p", "p"], f["o", "p", "o", "t", "i"], f["a", "m", "u", "s"]}
Out[13]=
In[14]:=
ResourceFunction["RandomBinMove"][bins]
Out[14]=

With two nested random bin moves, it is possible to get back to the starting bins:

In[15]:=
bins = {{1, 4, 5}, {2, 6, 7, 8, 10}, {}, {3, 9}};
Count[Table[
  Nest[ResourceFunction["RandomBinMove"][#] &, bins, 2], {1000}], bins]
Out[16]=

Requirements

Wolfram Language 13.0 (December 2021) or above

Version History

  • 1.0.0 – 12 September 2023

Related Resources

License Information