Finding nearest neighbours in two overlapping 2D distributions

'   nomainwin

randomize( 0.666)  '   seed PRNGenerator

WindowWidth  =600
WindowHeight =600

'                                       Generate two data sets to play with....
s1 =1000 '1000
s2 =50000 '50000

dim dataSet1$( s1)    '   string holds x y and z as csv string
dim dataSet2$( s2)
dim dataSet3$( s1)    '   will add the closest from set2 to set1

open "Display" for graphics_nsb_nf as #wg

#wg "trapclose [quit]"
#wg "down ; fill 50 50 50 ; size 4"
#wg "up ; goto 50 20 ; down"
#wg "\"; time$()
'                                       Show them on screen....
#wg "color red"
for i =1 to s1
    x =50 +int( 400 *rnd( 1)): y =50 +int( 400 *rnd( 1)): z =int( 256 *rnd( 1))
    dataSet1$( i) =str$( x) +"," +str$( y) +"," +str$( z)
    #wg "set "; 50 +x; " ";50 +y
    scan
next i

#wg "color green ; size 1"
for i =1 to s2
    x =int( 500 *rnd( 1)): y =int( 500 *rnd( 1)): z =int( 256 *rnd( 1))
    dataSet2$( i) =str$( x) +"," +str$( y) +"," +str$( z)
    #wg "set "; 50 +x; " "; 50 +y
    scan
next i

#wg "flush ; getbmp scr 1 1 600 600"
bmpsave "scr", "unselected2.bmp"

'                                                   Go through all data in set1 and find closest in set2
for i =1 to s1
    sepnSqd =1E12
    Jn       =0
    for j =1 to s2
        dX =val( word$( dataSet1$( i), 1, ",")) -val( word$( dataSet2$( j), 1, ","))
        dY =val( word$( dataSet1$( i), 2, ",")) -val( word$( dataSet2$( j), 2, ","))
        dSqd =dX^2 +dY^2
        if dSqd <sepnSqd then sepnSqd =dSqd: Jn =j   '   Jn ends pointing to closest in set 2
    next j
    '                                               Create new dataset3
    dataSet3$( i) =dataSet1$( i) +"," +dataSet2$( Jn)
next i

'                                                   Clear screen and show only set1 and nearest neighbours
#wg "fill darkblue"
#wg "rule XOR"

for i =1 to s1
    print dataSet3$( i)
    xS =int( val( word$( dataSet3$( i), 1, ",")))
    yS =int( val( word$( dataSet3$( i), 2, ",")))
    #wg "size 4 ; color red  ; set "; 50 +xS; " "; 50 +yS

    xS =int( val( word$( dataSet3$( i), 4, ",")))
    yS =int( val( word$( dataSet3$( i), 5, ",")))
    #wg "size 4 ; color green ; set "; 50 +xS; " "; 50 +yS
    scan
next i

#wg "up ; goto 50 20 ; down"
#wg "\"; time$()
#wg "flush ; getbmp scr 1 1 600 600"
bmpsave "scr", "selected2.bmp"

wait

[quit]
    close #wg
    end