CS 100: Lecture L15
March 16
// The Perfect Shuffle with n=8. import java.io.*; public class L15A { public static void main(String args[]) { TokenReader in = new TokenReader(System.in); // Set up and display a short array: int[] a = {10,20,30,40,50,60,70,80}; System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]+" "+a[5]+" "+a[6]+" "+a[7]); // n= 8 version of the perfect shuffle: int[] b = new int[8]; b[0] = a[0]; b[1] = a[4]; b[2] = a[1]; b[3] = a[5]; b[4] = a[2]; b[5] = a[6]; b[6] = a[3]; b[7] = a[7]; // Same thing by loop: for(int i=0;i<4;i++) { b[2*i] = a[i]; b[2*i+1] = a[i+4]; } // Display b: System.out.println(b[0]+" "+b[1]+" "+b[2]+" "+b[3]+" "+b[4]+" "+b[5]+" "+b[6]+" "+b[7]); // Shuffle it again: for(int i=0;i<8;i++) { a[i] = b[i]; } for(int i=0;i<4;i++) { b[2*i] = a[i]; b[2*i+1] = a[i+4]; } // Display the modified b: System.out.println(b[0]+" "+b[1]+" "+b[2]+" "+b[3]+" "+b[4]+" "+b[5]+" "+b[6]+" "+b[7]); in.waitUntilEnter(); } }
import java.io.*; import java.awt.*; public class ShowShuffle extends Frame { public void Shuffle(Color[] a) { int n = a.length; Color[] b = new Color[n]; for(int k=0;k<n/2;k++) { b[2*k] = a[k]; b[2*k+1] = a[k+26]; } for(int k=0;k<n;k++) a[k] = b[k]; } public void Rainbow(Graphics g,Color[] a, int hL,int vT, int w) { int h=hL; for(int k=0;k<52;k++) { g.setColor(a[k]); g.fillRect(h,vT,w,2*w); g.setColor(Color.black); g.drawRect(h,vT,w,2*w); if (k==25) h = h+w+8; else h = h+w; } } public void paint(Graphics g) { Color[] D = new Color[52];; int b = 150; int s = 8; int p; for(int k=0;k<13;k++) { p = b+s*k; D[k] = new Color(p,0,0); D[k+13] = new Color(0,p,0); D[k+26] = new Color(0,0,p); D[k+39] = new Color(p,p,0); } int hL = 20; int vT = 30; int v = vT; int w = 18; Rainbow(g,D,hL,v,w); for(int q=1;q<=8;q++) { Shuffle(D); v = v+4*w; Rainbow(g,D,hL,v,w); } } } public class L15C { public static void main(String args[]) { ShowShuffle d = new ShowShuffle(); d.resize(1000,800); d.move(0,75); d.setTitle("Drawing"); d.show(); d.toFront(); } }