
// PrimeDigits.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/*  An assumption about primes is that they behave like 
    random numbers. However, it seems, there is a preference 
    about the final digits of the primes.

    i -> j is a transition if i is the last decimal digit of a prime, 
    and j the last decimal digit of the following prime. 

    Consider the first one million primes. Count, for any pair of 
    successive primes, the number of transitions i -> j and plot them 
    along with their relative frequency, sorted by i.

    You can see that, for a given i, frequencies are not 
    evenly distributed.

    https://rosettacode.miraheze.org/wiki/Prime_conspiracy

   Usage:
     > compile PrimeDigits.java
     > run PrimeDigits
*/


public class PrimeDigits
{

  public static void main(String[] args)
  {
    int[][] trans = new int[10][10];
         // stores all possible i --> j transitions
    int[] primes = Nut.loadPrimes("primes1M.txt");

    int prevDigit = primes[0] % 10;  // extract last digit
    for (int i = 1; i < primes.length; i++) {
      int digit = primes[i] % 10;    // extract last digit
      trans[prevDigit][digit]++;   // count prevDigit --> digit
      prevDigit = digit;
    }


    StdDraw.setScale(0, 10);

    // draw a grid of empty boxes
    StdDraw.setPenColor(StdDraw.BLACK);
    for(int i=0; i < 10; i++)
      for(int j=0; j < 10; j++)
        StdDraw.square(i+0.5, j+0.5, 0.5);

    // label the rows and columns, with (0,0) at top-left
    for(int i=0; i < 10; i++) {
      StdDraw.text(i+0.5, 9.5, ""+i);  // column labels
      StdDraw.text(0.5, i+0.5, ""+(9-i));  // row labels
    }

    // draw a grid of 'percentage' circles inside the boxes
    StdDraw.setPenColor(StdDraw.BLUE);

    System.out.println("First " + primes.length + " primes:");
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        if (trans[i][j] != 0) {
          double percent = ((double)trans[i][j])/primes.length*100.0;
          System.out.printf("%d -> %d : %.2f %%\n", i, j, percent);
          if (percent < 0.5)  // small percentage
            StdDraw.circle(j+0.5, 9-i+0.5, 1.0/20);  // unfilled, small
          else
            StdDraw.filledCircle(j+0.5, 9-i+0.5, percent/20);
               /* the (i, j) in i --> j is mapped to (j, 9-i)
                  so that i maps to a row, and j to a column;
                the "+0.5" is to center a circle inside a box */
        }
      }
    }
  } /* main */

}  // end of PrimeDigits class