hi everybody,
today I tried to write a very simple k-NN algorithm for class. unfortunetally I did not succeed so far. can someone see where the code is erroneous? my best guess is that the error occurs in the colour assignment.
also if someone has a simple k-NN code model, I would be greateful to take an educational look.
with best regards
anna
// a simple knn algorithm 
int[][] balls = new int[3][200];
int[] abstand = new int[200];
int[] minabstand = new int[3];
int l = 0;
/*
Definition:
 rot hat den Wert 0 --> red is 0
 blau hat den Wert 1 --> blue is 1
 */
int ballanzahl = 10;
void setup() {
  size (800, 800);
  frameRate(1);
}
void ballsfunction() {
  for (int i=0; i <10; i=i+1) { // die Koordinaten der BÀlle werden erzeugt zufÀllig 
    balls[0][i]=10+ int(random(0, 790));
    balls[1][i]=10+ int(random(0, 790));
    balls[2][i]=int(random(0, 2));
    //println(balls[2][i]);
  }
  for (int i=0; i <10; i=i+1) { // die BĂ€lle werden gezeichnet
    if (balls[2][i]==0)
    {
      fill(255, 0, 0);
      ellipse(balls[0][i], balls[1][i], 10, 10);
    } else
    {
      fill(0, 0, 255);
      ellipse(balls[0][i], balls[1][i], 10, 10);
    }
  }
}
/*void drawballs()
 {
 for (int i=0; i <ballanzahl; i=i+1) { // die BĂ€lle werden gezeichnet
 if (balls[2][i]==0)
 {
 fill(255, 0, 0);
 ellipse(balls[0][i], balls[1][i], 10, 10);
 } else
 {
 fill(0, 0, 255);
 ellipse(balls[0][i], balls[1][i], 10, 10);
 }
 } 
 //println(ballanzahl);
 }
 */
void draw() { 
  l = l +1;
  if (l == 1)
    ballsfunction();
  else if (l==2) {
        balls[0][11]=10+ int(random(0, 790));
    balls[1][11]=10+ int(random(0, 790));
    fill(255);
    ellipse(balls[0][11], balls[1][11], 10, 10);
  } else if (l==3)
  action();
}
void bubbleSort()
{
  int tausch;
  for (int n=ballanzahl-1; n>1; n=n-1)
  {
    for (int i=0; i<n-1; i=i+1)
    {
      if (abstand[i] < abstand[i+1])
      {
        tausch = abstand[i];
        abstand[i]=abstand[i+1];
        abstand[i+1]=tausch;
      } // Ende if
    } // Ende innere for-Schleife
  } // Ende Ă€uĂere for-Schleife
  
}
void regel() // error here?
{
  int rot=0;
  int blau=0;
  for (int i=1; i<=3; i=i+1)
  {
    if (balls[2][ballanzahl-i] > 0)
      blau=blau+1;
    else 
    rot=rot+1;
    println(rot);
  }
  if (rot > blau)
    balls[2][ballanzahl]=0;
  else balls[2][ballanzahl]=1;
  //println(balls[2][ballanzahl]);
}
//void mouseClicked()
void action()
{
  ballanzahl=ballanzahl+1;
  //balls[0][ballanzahl]=mouseX;
  //balls[1][ballanzahl]=mouseY;
  for (int k = 0; k<ballanzahl-1; k=k+1) {
    abstand[k]=int(sqrt(sq(balls[0][k]-balls[0][ballanzahl])+sq(balls[1][k]- balls[1][ballanzahl])));
  }
  bubbleSort();
  regel(); 
  if (balls[2][ballanzahl]>0)
  {
    fill(0, 0, 255);
    ellipse(balls[0][ballanzahl], balls[1][ballanzahl], 10, 10);
  } else
  {
    fill(255, 0, 0);
    ellipse(balls[0][ballanzahl], balls[1][ballanzahl], 10, 10);
  }
}

