Random probability (Customizing random function)

The idea of customizing the random function consists in creating an array of for instance 1000 integers, each with a value from 0 to, for instance, 500. Such an array can be created by drawing a line in a window from left to right with the height y giving the value of index x.

When these indexes are randomly accessed, the chance of picking a lower or higher value is determined by the shape of the line shown in the picture. Customized random tables are sometimes used in games. Another usage you can find on this topic.
The code will generate a one-line string of the customized random table in the console that can be copied/pasted into the other sketch.

float x, y, old_x, old_y, targetX, targetY;
float easing = 0.11; // increase for more details
boolean down, begin = true;
String str = "";
int i, j=0;

void setup() {
  size(1000, 500);
  smooth();
  erase();
}

void draw() {
  if (down) {
    if (begin) {
      old_x = 0; 
      old_y =  mouseY;
      x = mouseX;
      y = mouseY;
      begin = false;
    }
    targetX = mouseX;
    targetY = mouseY;
    x += (targetX - x) * easing;
    y += (targetY - y) * easing;   
    line(old_x, old_y, x, y);
    old_x = x;
    old_y = y;
  }
}

void mousePressed() {
  if (mouseX > width-200 && mouseX < width-120 && mouseY < 30) send();
  if (mouseX > width-100 && mouseY < 30) erase();
} 

void mouseDragged() {
  down  = true;
} 

void mouseReleased() {
  down  = false;
} 

void send() {
  // searching for black pixels is needed because when drawing
  // some pixels may have been missed
  down = false;
  for ( i = 0; i <= width; i++) {
    for (j = 0; j <= height; j++) {
      color c = get(i, j);
      if (c == color(0)) {
        str +=  str(height-j)+',';  
        break;
      }
    }
  }
  println ("int[]num={"+str+"};");
  exit();
}

void erase() {
  begin = true;
  stroke(0);
  strokeWeight(2);
  background(255);
  fill(230);
  rect(width-200, 5, 80, 30);
  rect(width-100, 5, 80, 30);
  fill(0);
  text("Save", width-190, 25);
  text("Clear", width-90, 25);
}

table

1 Like