
// GapFreq.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Plot a graph of the frequency of gaps in the primes
   loaded from primes1M.txt, but restricted to a 
   maximum gap of MAX_GAP.

   https://en.wikipedia.org/wiki/Prime_gap

   Usage:
     > compile GapFreq.java
     > run GapFreq
   e.g.
     > run GapFreq
*/

import java.awt.Color;

import com.github.plot.Plot;
import com.github.plot.Plot.*;


public class GapFreq
{
  private static final int MAX_GAP = 100;

  public static void main(String[] args)
  {
    int[] primes = Nut.loadPrimes("primes1M.txt");
    System.out.println("Loaded " + primes.length + " primes");

    // calculate gaps frequency
    int[] numGaps = new int[MAX_GAP];
    for(int i= 1; i < primes.length; i++) {
      int gap = primes[i] - primes[i-1];
      if (gap < MAX_GAP)
        numGaps[gap]++;
    }

/*
    System.out.println("\nWith a maximum gap size of " + MAX_GAP + ":");
    System.out.println(" Gap  Count");
    for (int i=2; i < MAX_GAP; i++) {  // start at gap == 2
      if (numGaps[i] > 0)
        System.out.printf("%3d  %6d\n", i, numGaps[i]);
    }
    System.out.println();
*/

    // plot configuration
    Plot plot = Plot.plot( Plot.plotOpts().
                      title("Prime Gap Freq (< " + MAX_GAP + ")").
                      width(1300).height(500));

    plot.xAxis("gap", Plot.axisOpts().
                      format(Plot.AxisFormat.NUMBER_INT));
    plot.yAxis("freq", Plot.axisOpts().
                      format(Plot.AxisFormat.NUMBER_INT));

    Plot.Data plotGaps = Plot.data();
    for (int i = 2; i < MAX_GAP; i++) {   // start at gap == 2
      if (numGaps[i] > 0)
        plotGaps.xy(i, numGaps[i]);
    }

    DataSeriesOptions dOpts = Plot.seriesOpts().
                       line(Plot.Line.NONE).
                       marker(Plot.Marker.COLUMN).  // bar chart
                       color(Color.RED).
                       markerColor(Color.RED);
          
    // add data and draw
    plot.series("", plotGaps, dOpts);
    PlotUtils.viewPlot("Prime Gap Freq", plot);
  } /* main */

}