Welcome, guest | Sign In | My Account | Store | Cart

It creates a curve that passes through N random points using inverse distance weighted averages.

Java, 92 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// <applet code="Curve" width=512 height=512></applet>
// FB 201003265
// Create a curve that passes thru N randomly selected points.
import java.applet.Applet;
import java.awt.*;
import java.awt.image.*;
import java.util.Random;

public class Curve extends Applet
{
    Image img;
    int w,h,x,y,pix[],red,green,blue,alpha;
    Random rng=new Random();

    int n=rng.nextInt(10)+5; // n random points
    int[] arx=new int[n];
    int[] ary=new int[n];
    
    public void init()
    {
        w=getSize().width;
        h=getSize().height;
        alpha=255;
        pix=new int[w*h];
        img = createImage(new MemoryImageSource(w, h, pix, 0, w));

        // n random points
        for(int i=0;i<n;i++)
        {
            arx[i]=rng.nextInt(w);
            ary[i]=rng.nextInt(h);
        }

        double wgh;
        int y;
        double sum;
        double sumw;
        boolean flag;

        for(x=0;x<w;x++)
        {
            flag=false;
            sum=0.0;
            sumw=0.0;
            y=0;
            for(int i=0;i<n;i++)
            {
                if(x!=arx[i])
                {
                    //wgh=1.0/Math.pow(Math.abs((double)(x-arx[i])),1.0); // linear
                    wgh=1.0/Math.pow(Math.abs((double)(x-arx[i])),2.0); // quadratic
                    //wgh=1.0/Math.pow(Math.abs((double)(x-arx[i])),3.0); // cubic
                    sumw+=wgh;
                    sum+=(ary[i]*wgh);
                }
                else
                {
                    flag=true;
                    y=ary[i];
                    break;
                }
            }
            if(flag==false)
            {
                y=(int)(sum/sumw);
            }
            
            red=36;
            green=76;
            blue=16;
            pix[w*y+x]=(alpha<<24)|(red<<16)|(green<<8)|blue;

        }
            
        img = createImage(new MemoryImageSource(w, h, pix, 0, w));
    }

    public void paint(Graphics g)
    {
        g.drawImage(img,0,0,this);
        
        // show the n points on the curve
        for(int i=0;i<n;i++)
        {
            g.drawOval(arx[i]-5,ary[i]-5,10,10);
        }

        long ctm=System.currentTimeMillis();
        while((System.currentTimeMillis()-ctm)<3000) {;}
        init();
    }
}

1 comment

Michael Millthorn 11 years, 5 months ago  # | flag

Nice! I ran linear, quadratic and cubic. They look very sharp. How do I get them to look like smooth waves?