Created
March 5, 2016 20:47
-
-
Save joriki/ebf97cca8c11ba078308 to your computer and use it in GitHub Desktop.
Compute the entropy of cards shuffled using a primitive shuffling method; see http://math.stackexchange.com/questions/1684658.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Question1684658 { | |
final static int n = 8; | |
static class Permutation { | |
int [] p = new int [n]; | |
public int hashCode () { | |
return Arrays.hashCode (p); | |
} | |
public boolean equals (Object o) { | |
return Arrays.equals (((Permutation) o).p,p); | |
} | |
public String toString () { | |
return Arrays.toString (p); | |
} | |
} | |
static class Distribution extends HashMap<Permutation,Double> { | |
public Double put (Permutation p,Double d) { | |
Double old = get (p); | |
return super.put (p,old == null ? d : d + old); | |
} | |
} | |
static Distribution distribution = new Distribution (); | |
public static void main (String [] args) { | |
Permutation id = new Permutation (); | |
for (int i = 0;i < n;i++) | |
id.p [i] = i; | |
distribution.put (id,1.); | |
double lim = 0; | |
for (int i = 2;i <= n;i++) | |
lim += Math.log (i); | |
for (int k = 0;k < 50;k++) { | |
System.out.println (Math.log (lim - entropy (distribution))); | |
Distribution newDistribution = new Distribution (); | |
for (Permutation p : distribution.keySet ()) { | |
double weight = distribution.get (p) / n; | |
for (int i = 0;i < n;i++) { | |
Permutation q = new Permutation (); | |
for (int j = 0;j < i;j++) | |
q.p [j] = p.p [j]; | |
q.p [i] = p.p [n - 1]; | |
for (int j = i + 1;j < n;j++) | |
q.p [j] = p.p [j - 1]; | |
newDistribution.put (q,weight); | |
} | |
} | |
distribution = newDistribution; | |
} | |
} | |
static double entropy (Map<Permutation,Double> distribution) { | |
double entropy = 0; | |
for (Double d : distribution.values ()) | |
if (d != 0) | |
entropy -= d * Math.log (d); | |
return entropy; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment