JMSL Tutorial: Weighted Integer Sequence

The WeightedIntegerSequence is a SequenceGenerator whose next() method returns a randomly chosen integer 0..N-1 whose probabilities of being chosen are weighted by an array of length N. So with an array { 1, 1 } would return 0 roughly half the time, and 1 roughly half the time. The array { 2, 0, 1 } would return 0 roughly 2/3 of the time, would never return 1, and would return 2 roughly 1/3 of the time.

This example uses a WeightedIntegerSequence to generate a random walk, where the intervals -1, 0, and 1 are weighted. The user can control the weighting by entering new relative weights in the TextFields and clicking the "apply" button.

Thanks to Larry Polansky for suggesting that WeightedIntegerSequence be part of JMSL.


See complete source here.

Essential code here:

   class WeightedMelodyMusicJob extends MusicJob {
    WeightedIntegerSequence weightedIntegerSequence;
    double pitch = 60;
    double duration = 0.25;

    public WeightedIntegerSequence getWeightedIntegerSequence() {
        return weightedIntegerSequence;
    }

    public void setWeightedIntegerSequence(WeightedIntegerSequence sequence) {
        weightedIntegerSequence = sequence;
    }

    public double repeat(double playTime) {
        int interval = weightedIntegerSequence.next(); // 0, 1, 2        
        int change = interval - 1; // -1, 0, 1
        System.out.println("change=" + change);
        pitch += change;
        // System.out.println(pitch);
        double[] data = { duration, pitch, 0.6, duration * 0.8 };
        return getInstrument().play(playTime, 1, data);
    }
}

 
 
  (C) Phil Burk and Nick Didkovsky, All Rights Reserved
  JMSL is based upon HMSL (C) Phil Burk, Larry Polansky and David Rosenboom.