31
\$\begingroup\$

The Task

This is quite a simple coding task, all your program has to do is place a point on a canvas (or your alternative in another coding language) and connect it to all the dots already placed. Your program must take in one input, the number of dots that should be placed, and output some sort of display with the dots connected. Example

Requirements

  • I have to be able to run it, which means that it has to have a compiler/tool to run it either online, or publicly available to download.
  • You are allowed to use any library created before this challenge was set, as long as it wasn't designed for the sole purpose of solving this.
  • This is a shortest code task, which means characters. Comments, code that changes colour (for prettiness) and libraries will be ignored.
  • Your answer must be unique, don't steal other peoples code, shorten it a few characters and repost it.
  • It must be able to run in less than 5 minutes, for the values of 5 and 100. It must also use a resolution of at least 200*200 and put each dot in a random location on the canvas using a non-trivial distribution.

Current Leaderboard

Flawr        - Matlab        - 22  - Confirmed
Falko        - Python 2      - 41  - Confirmed
Wyldstallyns - NetLogo       - 51  - Confirmed 
Ssdecontrol  - R             - 66  - Confirmed
9214         - Red           - 81  - Confirmed
David        - Mathematica   - 95  - Confirmed
Razetime     - Red           - 118 - Confirmed
ILoveQBasic  - QBasic        - 130 - Confirmed
Adriweb      - TI-Nspire Lua - 145 - Confirmed
Manatwork    - Bash          - 148 - Confirmed
Doorknob     - Python 2      - 158 - Confirmed
Kevin        - TCL           - 161 - Confirmed
M L          - HPPPL         - 231 - Confirmed
Manatwork    - HTML/JS       - 261 - Confirmed - Improved code of Scrblnrd3
Makando      - C#            - 278 - Confirmed
Scrblnrd3    - HTML/JS       - 281 - Confirmed
Geobits      - Java          - 282 - Confirmed

If I've missed you out, I'm very sorry, just add a comment to your work saying so and I'll add it as soon as I see it =)

TL;DR

  • Input - Number of dots (int, can be hard coded)
  • Output - Image of randomly placed dots, all connected to each other (graphic)
  • Winner - Shortest code
\$\endgroup\$
28
  • 1
    \$\begingroup\$ Am I allowed math libraries? What libraries exactly are you trying to avoid with requirement #2? \$\endgroup\$ Commented Aug 22, 2014 at 12:51
  • 3
    \$\begingroup\$ Is there any limitation for resolution? This is quite easy if you let me output a 1x1 image \$\endgroup\$ Commented Aug 22, 2014 at 12:54
  • 3
    \$\begingroup\$ When you say no "math" libraries, what about languages where the default PRNG is included in "math"? I don't want to write a generator. \$\endgroup\$
    – Geobits
    Commented Aug 22, 2014 at 13:02
  • 1
    \$\begingroup\$ Since you disallow library code that directly relates to the task, and that task is essentially to draw a random network graph, isn't use of native graph-drawing functions also disallowed? This restriction is far from well defined. \$\endgroup\$ Commented Aug 22, 2014 at 15:52
  • 3
    \$\begingroup\$ @PopeyGilbert I must say, I've never seen a new user so responsive to issues with their question and also individually test each answer and maintain a leaderboard. Good work and welcome to PPGC! \$\endgroup\$ Commented Aug 23, 2014 at 3:03

19 Answers 19

27
\$\begingroup\$

Java : 318 282 265

Because, ya know, Java:

class M{public static void main(String[]a){new Frame(){public void paint(Graphics g){int i=0,j,d=640,n=25,x[]=new int[n],y[]=x.clone();for(setSize(d,d);i<n;i++)for(j=0,x[i]=(int)(random()*d),y[i]=(int)(random()*d);j<i;g.drawLine(x[i],y[i],x[j],y[j++]));}}.show();}}

Its just a simple loop that makes random dots and draws lines between the current dot and all previous ones.

Example with 25 dots:

enter image description here

With line breaks and imports:

import java.awt.*;
import static java.lang.Math.*;

class M{
    public static void main(String[]a){
        new Frame(){
            public void paint(Graphics g){
                int i=0,j,d=640,n=25,x[]=new int[n],y[]=x.clone();
                for(setSize(d,d);i<n;i++)
                    for(j=0,x[i]=(int)(random()*d),y[i]=(int)(random()*d);
                        j<i;
                        g.drawLine(x[i],y[i],x[j],y[j++]));
            }
        }.show();
    }
}

Edit: Since we're not counting imports, I imported a couple more things to save some characters later.

Edit 2: OP added an allowance for hardcoding number of dots. -17 chars :)

\$\endgroup\$
15
  • \$\begingroup\$ Nice! Congrats on being first one. \$\endgroup\$ Commented Aug 22, 2014 at 13:17
  • 2
    \$\begingroup\$ First, but I'm sure it won't be the shortest by a long shot. Cause, ya know, Java ;) \$\endgroup\$
    – Geobits
    Commented Aug 22, 2014 at 13:19
  • 3
    \$\begingroup\$ I admire people who always solve the task in Java, even when hopeless, I'd even be too lazy to start eclipse... so +1 =) \$\endgroup\$
    – flawr
    Commented Aug 22, 2014 at 15:53
  • 1
    \$\begingroup\$ @Chruncher Yeah, java is most definitely not the best language for code golf. However it was the first language I learnt, and it is quite easy to pick up. It also held me in good stead however, and is personally, my favourite language. \$\endgroup\$ Commented Aug 22, 2014 at 15:53
  • 1
    \$\begingroup\$ It's not necessary to define main's parameter as final. You can cut off those 6 characters \$\endgroup\$
    – Cruncher
    Commented Aug 22, 2014 at 15:53
22
\$\begingroup\$

Matlab (22)

gplot(ones(n),rand(n))

It is assumend that n is the number of points, and it looks like this for n=10: random graph

n=6:

random

Explaination

gplot is a command for plotting graphs. The first argument is a n x n incidence matrix (full of ones, obviously). The second argument should be a n x 2 matrix with the coordinates of the points, but it does not matter if the second dimension is bigger that 2, so I just generate an n x n matrix of random values (which is 2 characters shorter than generating an n x 2 matrix).

Links to documentation

\$\endgroup\$
2
  • \$\begingroup\$ Never used Matlab, so it will take a moment to test - But from the image it looks okay! Congrats on doing it in 22 characters. EDIT - Turns out I can't test this, however looking at the image it seems correct so I'll allow it. However can someone else test it please? \$\endgroup\$ Commented Aug 22, 2014 at 15:31
  • 3
    \$\begingroup\$ Thanks=) You can test it here: octave-online.net Since octave is basically the opensource version of MatLab. \$\endgroup\$
    – flawr
    Commented Aug 22, 2014 at 15:36
11
\$\begingroup\$

Python 2 - 41 35

After importing some libraries as allowed for this challenge

from pylab import rand as r
from pylab import plot as p
from itertools import product as x
from itertools import chain as c

we can plot some number of connected points with just one line of code:

X=r(5,2);p(*zip(*c(*list(x(X,X)))))

(The screenshot was generated with 10 points.)

\$\endgroup\$
4
  • \$\begingroup\$ [Referring to a deleted comment:] I know, but here "libraries will be ignored". If not, I'd definitely implement it differently. Using those libraries does not save enough characters to justify the import statements in a normal code golf challenge. \$\endgroup\$
    – Falko
    Commented Aug 22, 2014 at 15:52
  • \$\begingroup\$ is pylab part of standard distribution? I would imagine we can't just import anything we like. Under that metric you can implement anything in python with a single import statement. \$\endgroup\$
    – Cruncher
    Commented Aug 22, 2014 at 16:02
  • \$\begingroup\$ Yes it is. I just did what I thought would be valid. But I'm not sure. And looking into the comments shows a huge discussion going on. As soon as this is clarified I'd be willing to adjust my code. \$\endgroup\$
    – Falko
    Commented Aug 22, 2014 at 16:09
  • \$\begingroup\$ Although this competitions view on what libraries are allowed seems to change from day to day, PyLab should definitely be allowed. \$\endgroup\$ Commented Aug 23, 2014 at 15:31
8
\$\begingroup\$

Mathematica 95 87

With some help from belisarius.

CompleteGraph[n, VertexSize -> {2, 2},
VertexCoordinates -> Table[RandomInteger[{0, 199}, 2], {n}]]

n=5

5


n=100

Timing: 2.082654 sec

100

\$\endgroup\$
6
  • \$\begingroup\$ This is verified, I've gotten it to work! Does Mathematica normally count as a language though? \$\endgroup\$ Commented Aug 22, 2014 at 13:36
  • 1
    \$\begingroup\$ @PopeyGilbert Sure it does. There are ~750 answers in Mathematica so far. \$\endgroup\$
    – Geobits
    Commented Aug 22, 2014 at 13:59
  • \$\begingroup\$ Oh, wow, Okay! Fair enough <3 \$\endgroup\$ Commented Aug 22, 2014 at 14:01
  • \$\begingroup\$ Methinks this is shorter and satisfies the rules CompleteGraph[100, VertexCoordinates -> RandomReal[{0, 199}, {100, 2}]] \$\endgroup\$ Commented Aug 24, 2014 at 3:24
  • \$\begingroup\$ Thanks, You are correct. I figured I couldn't win so I thought I'd make it pretty (VertexSize->{2,2}. I did, however, overlook the fact that 100 was unnecessary to include, and that Input[] was optional. \$\endgroup\$
    – DavidC
    Commented Aug 24, 2014 at 4:06
7
\$\begingroup\$

Python 2, 158

Import statements not included in character count, as noted in question ("libraries will be ignored").

from PIL import Image,ImageDraw
from random import randint

s=[(randint(0,200),randint(0,200))for _ in range(int(input()))]
i=Image.new('RGB',(200,200))
[ImageDraw.Draw(i).line((p,q),255)for p in s for q in s]
i.show()

Sample outputs:

n=2 (...):

n=2

n=10 (looks like fancy 3d thing or something):

n=10

n=100 (looks like someone went BLELEEEAARARGHHH with a red pen):

n=100

n=500, 1000, 10000 (runs in about 1.5 seconds, 5-6 seconds, and 3.5 minutes respectively):

Note: the 10000 points one was run with a slightly optimized version that changed line 3 (not including imports) to this:

d=ImageDraw.Draw
for p in s:
  for q in s:d.line((p,q),255)

Otherwise it would have taken forever. :P

Ungolfed:

from PIL import Image, ImageDraw
from random import randint
point_count = int(input())
image_size = 200
points = [(randint(0, image_size), randint(0, image_size)) for _ in range(point_count)]
image = Image.new('RGB', (200, 200))
draw = ImageDraw.Draw(image)
for start_point in points:
    for end_point in points:
        draw.line((start_point, end_point), 255)
image.show()
\$\endgroup\$
9
  • 1
    \$\begingroup\$ Congrats on currently being the shortest entrant! Love your comment on n=100. Might be best to put image.new and image_size to 800. Might look less weird =) \$\endgroup\$ Commented Aug 22, 2014 at 13:24
  • \$\begingroup\$ @PopeyGilbert So I can remove the import statements from mine? I assumed "ignore libraries" meant the library itself wasn't counted (as usual). \$\endgroup\$
    – Geobits
    Commented Aug 22, 2014 at 13:26
  • \$\begingroup\$ Yeah, because some languages have very few base functions, and have to import all their stuff. If you think this is not fair Geobits, then please say =) I want to try to make this fair. \$\endgroup\$ Commented Aug 22, 2014 at 13:27
  • \$\begingroup\$ @PopeyGilbert I just asked because it's not the norm and wanted to clear it up before I chopped a few more characters from my code :D \$\endgroup\$
    – Geobits
    Commented Aug 22, 2014 at 13:30
  • 1
    \$\begingroup\$ Since the resolution only has to be at least 200x200, you could save a few characters (5, I think) by setting x=255 and using it to replace the instances of 200 and 255. \$\endgroup\$ Commented Aug 22, 2014 at 13:38
5
\$\begingroup\$

R, 66

This one is borderline cheating but I still think it's within the rules. Set up by loading the igraph package with library(igraph), which can be downloaded from CRAN with install.packages("igraph"). Then assign the input to variable N. As per the rules, these are not counted in the total.

G=graph.adjacency(matrix(1,N,N),"un")
plot(G,layout=layout.random)

N = 50

enter image description here

Note that this code also draws self-connections. Eliminating them (although there's no rule against them) adds 6 characters:

G=graph.adjacency(matrix(1,N,N),"un",diag=F)
plot(G,layout=layout.random)

R, 141

This is an honest-to-goodness solution in base R:

p=replicate(2,runif(N))
g=as.matrix(expand.grid(1:N,1:N))
plot.new()
apply(g,1,function(i) segments(p[i[1],1],p[i[1],2],p[i[2],1],p[i[2],2]))

although you still have to enter N by hand.

N = 50

enter image description here

I'm wondering if a for loop would be fewer characters than apply but I'm happy with what I've got.

\$\endgroup\$
3
  • \$\begingroup\$ I'll accept self-connects, technically the question is draw a line to ALL points. I've tested it and confirmed it also. \$\endgroup\$ Commented Aug 23, 2014 at 15:44
  • \$\begingroup\$ Do you mind arrows connecting the points? That'll save another 5 by eliminating ,"un" at the end of the first line. \$\endgroup\$ Commented Aug 23, 2014 at 15:51
  • \$\begingroup\$ If you don't mind, I think we should keep it so it has to be lines connecting each of the points. That way the answer will appear similar in each of the answers. \$\endgroup\$ Commented Aug 23, 2014 at 16:00
5
\$\begingroup\$

QBasic or QuickBasic, 130 characters

SCREEN 1:RANDOMIZE:N=10:DIM X(100),Y(100):FOR I=1 TO N:X(I)=RND*320:Y(I)=RND*200:FOR J=1 TO I:LINE(X(I),Y(I))-(X(J),Y(J)):NEXT J,I

Code variations

  • If you do not want to be prompted for a seed, replace RANDOMIZE with RANDOMIZE TIMER.
  • If you want to be prompted for N, replace N=10 with INPUT N or INPUT "N";N.

Sample runs

For N=5, tested with QBasic 1.1 running on DOSBox 0.74:

For N=100, tested with QBasic 1.1 running on DOSBox 0.74:

\$\endgroup\$
1
  • \$\begingroup\$ Oh, wow, nice image for N=5! Love that it's a pentagram when the seed is 42. Tested and confirmed. \$\endgroup\$ Commented Aug 24, 2014 at 14:20
4
\$\begingroup\$

Bash + ImageMagick: 148 characters

c=()
while((i++<$1)); do
p=$[RANDOM%200],$[RANDOM%200]
c+=($p)
for e in ${c[@]};do
d+="line $p $e"
done
done
convert -size 200x200 xc: -draw "$d" x:

Sample run:

bash-4.3$ time ./line.sh 5

real    0m5.256s
user    0m0.137s
sys     0m0.017s

Sample output:

5 connected points

Sample run:

bash-4.3$ time ./line.sh 25

real    0m3.043s
user    0m0.574s
sys     0m0.023s

Sample output:

25 connected points

Sample run:

bash-4.3$ time ./line.sh 100

real    0m5.662s
user    0m11.156s
sys     0m0.076s

Sample output:

100 connected points

\$\endgroup\$
2
  • \$\begingroup\$ Tested and confirmed. Well done manatwork! \$\endgroup\$ Commented Aug 22, 2014 at 18:14
  • \$\begingroup\$ I'm very sorry, did I completely forget to add this to the leader boards? I will do that now. \$\endgroup\$ Commented Aug 23, 2014 at 18:19
4
\$\begingroup\$

TCL 161 chars

Clearly not going to win, but beats several others presented here, and I think it makes good use of a highly undervalued language.

for {set i 0} {$i<10} {incr i} {lappend l [expr rand()*291] [expr rand()*204]}
pack [canvas .c]
foreach {x y} $l {foreach {w z} $l {.c create line $x $y $w $z}}

Example

The default canvas size on my system appears to be 291x204. Not sure why, but using it saves 13 characters.

Fairly fast, 400 points in < 5 seconds, 500 in ~10 s. Size and points can be scaled arbitrarily and colors and line styles can be altered, at the cost of characters of course. Un-golfed and using variables to make it clearer and easier to scale and color:

set n 20
set width 500
set height 500
set bg_color black
set line_color white
for {set i 0} {$i < $n} {incr i} {
        lappend points [expr rand() * $width] [expr rand() * $height]
}
canvas .c -width $width -height $height -background $bg_color 
pack .c
foreach {x1 y1} $points {
        foreach {x2 y2} $points {
                .c create line $x1 $y1 $x2 $y2 -fill $line_color
        }
}       
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Image seems fine, unfortunately my computer isn't working so I'll test it later. Congratulations on using such an underappreciated language. \$\endgroup\$ Commented Aug 23, 2014 at 18:22
  • \$\begingroup\$ Just confirmed it, congratulations on a successful entry! \$\endgroup\$ Commented Aug 24, 2014 at 10:17
  • \$\begingroup\$ 129 \$\endgroup\$
    – sergiol
    Commented Apr 29, 2018 at 22:18
  • \$\begingroup\$ 122 \$\endgroup\$
    – sergiol
    Commented Apr 29, 2018 at 22:49
4
\$\begingroup\$

[TI-Nspire] Lua - 145 135 130

(Updated fixed version)

Screenshot with n=10

"Importing" math.random as "r", first, as allowed : r=math.random

Actual code :

function on.paint(g)t={}for b=1,2*n-1,2 do t[b]=r(318)t[b+1]=r(212)for c=1,b-1,2 do g:drawLine(t[b],t[b+1],t[c],t[c+1])end end end

Note : This code works on the TI-Nspire calculators (TI added Lua scripting to recent OSes of this platform, with an even-based API allowing users to graph stuff etc. for example.)
It can also be tried online here (just erase the demo script and prepend mine with n=10 for example)

\$\endgroup\$
5
  • \$\begingroup\$ Time for me to learn Lua! \$\endgroup\$
    – Beta Decay
    Commented Aug 23, 2014 at 12:30
  • 1
    \$\begingroup\$ This seems to suffer by the same mistake as fuandon's deleted PowerShell answer and Vlo's also deleted R answer: you connect the dots in pair, not every dot with all other dots. (Lua is so rare on this site. Please fix your code instead of deleting it.) \$\endgroup\$
    – manatwork
    Commented Aug 23, 2014 at 12:37
  • \$\begingroup\$ Oh, my bad - I'll fix that soon ! \$\endgroup\$
    – Adriweb
    Commented Aug 23, 2014 at 14:13
  • \$\begingroup\$ There we go, thanks for letting me know :) \$\endgroup\$
    – Adriweb
    Commented Aug 23, 2014 at 14:49
  • \$\begingroup\$ This has been tested and confirmed! Well done on using Lua. \$\endgroup\$ Commented Aug 23, 2014 at 15:36
4
+100
\$\begingroup\$

Red, 118 bytes

a: collect[loop n[keep random d: 200x200]]
view[base d draw collect[foreach p a[foreach q a[keep reduce['line p q]]]]]

This was fun to figure out. Thanks to Toomas Vooglaid on Gitter and 9214 for helping with this. n is hardcoded.

-1 byte from Bubbler.

-2 bytes from Galen Ivanov.

Screenshots

enter image description here

enter image description here

\$\endgroup\$
9
  • \$\begingroup\$ Is it possible to reuse the constant 200 (or 200x200)? \$\endgroup\$
    – Bubbler
    Commented Jun 8, 2021 at 4:13
  • \$\begingroup\$ the reuse saves a byte \$\endgroup\$
    – Razetime
    Commented Jun 8, 2021 at 4:15
  • \$\begingroup\$ You can put the initizlization d: 200x200 inside the expression for a: a: collect[loop n[keep random d: 200x200]] for 118 bytes \$\endgroup\$ Commented Jun 8, 2021 at 6:59
  • 1
    \$\begingroup\$ didn't know that it would be globally initialized, Thanks! \$\endgroup\$
    – Razetime
    Commented Jun 8, 2021 at 7:08
  • \$\begingroup\$ Your "Try it online!" doesn't seem to work. I get the following error: *** Red Compiler Internal Error: Script Error : copy expected value argument of type: series port bitset *** Where: rejoin *** Near: [mold copy/part pos 40] /srv/wrappers/red: line 5: ./.bin.tio: No such file or directory \$\endgroup\$ Commented Jun 9, 2021 at 20:15
3
\$\begingroup\$

C# Windows forms, 268

static void k(int n,int s){var f=new Form{Height=s+50,Width=s+25};f.Paint+=(u,v)=>{var r=new Random();var p=new Point[n];while(n>0)p[--n]=new Point(r.Next(s),r.Next(s));foreach(var a in p)foreach(var b in p)f.CreateGraphics().DrawLine(Pens.Tan,a,b);};f.ShowDialog();}

N=5

Plot using 5 points

N=50

Plot using N=50

Full code is given below

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    static class Program
    {
        static void Main()
        {
            k(50, 200);
        }
        static void k(int n, int s)
        {
            var f = new Form {Height = s + 50, Width = s + 25};
            f.Paint += (u, v) =>
            {
                var r = new Random();
                var p = new Point[n];
                while (n > 0)
                    p[--n] = new Point(r.Next(s), r.Next(s));
                foreach (var a in p)
                    foreach (var b in p)
                        f.CreateGraphics().DrawLine(Pens.Tan, a, b);
            };
            f.ShowDialog();
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Tested and confirmed! When I checked the character count, I used the full code and was surprised when it came to <700 characters... >.<. Anyway, congratulations on making a successful entry! \$\endgroup\$ Commented Aug 24, 2014 at 10:15
  • \$\begingroup\$ Isn't there some shortcut like Pens.Tan instead of new Pen(Color.Tan)? \$\endgroup\$
    – CompuChip
    Commented Aug 24, 2014 at 13:40
  • \$\begingroup\$ Changed to use Pens.Tan, saving an extra 10 \$\endgroup\$
    – Zed Coder
    Commented Aug 25, 2014 at 11:15
3
\$\begingroup\$

Red, 81 bytes

?(draw d: 200x200 loop n: 10[foreach x append[]y: random d[repend[]['line x y]]])

Try it locally in REPL

enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ Verified locally :) \$\endgroup\$ Commented Jun 9, 2021 at 20:20
2
\$\begingroup\$

HTML/JS, 210, thanks to manatwork

<canvas id=q /><script>c=q.getContext("2d");r=Math.random;e=prompt(a=[]);for(i=0;i<e;i++){a[i]={x:r()*300,y:r()*150};for(j in a)c.beginPath()+c.moveTo(a[i].x,a[i].y)+c.lineTo(a[j].x,a[j].y)+c.stroke()}</script>

JSFiddle

\$\endgroup\$
6
  • \$\begingroup\$ This is verified, I've gotten it to work! \$\endgroup\$ Commented Aug 22, 2014 at 14:03
  • \$\begingroup\$ You can use ~~ instead of m.floor to save 5 bytes \$\endgroup\$ Commented Aug 22, 2014 at 16:20
  • \$\begingroup\$ Make the canvas tag self-closing and remove the single quotes around the id value: <canvas id=q />. (Note that you have to leave one space between the last attribute value and the self-closing /.) BTW, in Firefox works fine without m.floor() and ~~. \$\endgroup\$
    – manatwork
    Commented Aug 22, 2014 at 17:08
  • \$\begingroup\$ 219 characters: jsfiddle.net/e866azzs/5 \$\endgroup\$
    – manatwork
    Commented Aug 22, 2014 at 17:33
  • \$\begingroup\$ The first time I tried manatwork's jsfiddle, I thought the alert box needed a password! I was perplexed. How stupid a person can be. I believe this is sufficiently different to another persons answer to warrant another place in the leader board. Do other people think this is different enough? \$\endgroup\$ Commented Aug 23, 2014 at 15:38
2
\$\begingroup\$

C# WPF 306 296

partial class W:Window{public W(){InitializeComponent();int x=5,i=0,j,z=200;int[]f=new int[x],s=new int[x];var r=new Random();var X=new Grid();AddChild(X);for(;i<x;i++){f[i]=r.Next(z);s[i]=r.Next(z);for(j=i;j>=0;)X.Children.Add(newLine(){X1=s[j],Y1=f[j--],X2=s[i],Y2=f[i],Stroke=Brushes.Red});}}}

I would like to say that I could remove Stroke=Brushed.Red. But Sadly that means that I am painting transparent lines, and my Guess is that it wouldn't really count. :P I can also shave of a couple of bytes by just creating a grid in the XAML view. But that seemed unfair, so I stripped the XAML to become a blank canvas. (I don't count the XAML as bytes...)

partial class W:Window
{
    public W()
    {
        InitializeComponent();
        int x=5,i=0,j,z=200;
        int[]f=new int[x],s=new int[x];
        var r = new Random();
        var X = new Grid();
        AddChild(X);
        for (;i<x;i++)
        {
            f[i]=r.Next(z);
            s[i]=r.Next(z);
            for (j=i;j>=0;)
                X.Children.Add(new Line()
                {
                    X1 = s[j],
                    Y1 = f[j--],
                    X2 = s[i],
                    Y2 = f[i],
                    Stroke = Brushes.Red
                });
        }
    }
}

XAML

<Window x:Class="W"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
</Window>

5

5

100

100

\$\endgroup\$
4
  • 4
    \$\begingroup\$ Since it is WPF it will crash at around 3k Points for Out of Memory exception. \$\endgroup\$
    – WozzeC
    Commented Aug 22, 2014 at 15:13
  • \$\begingroup\$ Tested and confirmed, well done on doing it in C# WPF! \$\endgroup\$ Commented Aug 22, 2014 at 15:15
  • 2
    \$\begingroup\$ Could be shorted a little by using var when declaring variables. \$\endgroup\$ Commented Aug 23, 2014 at 20:47
  • \$\begingroup\$ Yes, indeed. Thanks! I was also able to remove "this" from "this.AddChild". \$\endgroup\$
    – WozzeC
    Commented Aug 28, 2014 at 7:43
1
\$\begingroup\$

HPPPL, 231 220

(HP Prime Programming Language for the HP Prime color graphing calculator)

golfed it down. 11 fewer chars by drawing all possible new lines right after every new point creation. Only two nested loops instead of the previous three.

export c(n) begin rect();local g,h;a:=makemat(0,n,2);for g from 1 to n do a(g,1):=ip(random(1,320));a(g,2):=ip(random(1,240));if g>1 then for h from 1 to g-1 do line_p(a(h,1),a(h,2),a(g,1),a(g,2));end;end;end;freeze;end;

Ungolfed (270 chars):

export randomnet(n)
begin
rect();
local g,h;
a:=makemat(0,n,2);
for g from 1 to n do
  a(g,1):=ip(random(1,320));
  a(g,2):=ip(random(1,240));
    if g>1 then
      for h from 1 to g-1 do
        line_p(a(h,1),a(h,2),a(g,1),a(g,2));
      end;
    end;
end;
freeze;
end;

examples:

c(10)

connect_10_points_HPPPL

connect_10_points_HPPPL_2

c(30)

connect_30_points_HPPPL

The HP Prime color graphing calculator has a 320x240 pixel color display.

enter image description here

An emulator that also works with the connectivity kit is available at the HP website or here: http://www.hp-prime.de/en/category/6-downloads

... still waiting for the hardware to arrive. Update on the execution time will follow.

Today my HP Prime arrived. Here is the execution time for n=100 on an actual calculator:

average execution time

Around 0.65 s for n=100.

The emulator is about 4 times as fast (around 0.178 s) on my Core i5 2410M laptop.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Well, I have never even heard of that programming language, but it worked on the emulator so congratulations! I've added you to the leaderboard. \$\endgroup\$ Commented Aug 22, 2015 at 12:17
  • \$\begingroup\$ Thanks. As soon as I have the hardware, I’ll check the execution time. The emulator is faster than the actual calculator. But I think the 5 minutes limit for n=100 is very generous for the calculator. \$\endgroup\$
    – M L
    Commented Aug 22, 2015 at 16:06
1
\$\begingroup\$

NetLogo, 51 bytes

crt 9 [create-links-with other turtles fd random 9]

Replace 9s with other constants or variables as needed.

NetLogo output

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Added to the leaderboard! Afraid I'm not entirely sure how to test this. I've downloaded NetLogo and I've typed it into the observer section, then tried setting it as a pen command on a plot, neither appeared to function. If you could give me some pointers, I'd be able to confirm it =) \$\endgroup\$ Commented Dec 7, 2016 at 18:37
  • \$\begingroup\$ F'rinstance: go into the 'code' tab and wrap that line in a function that starts "to go" and stops with "end". Then you can add a button to the first that calls "go" and hit it. \$\endgroup\$ Commented Dec 7, 2016 at 19:49
  • 1
    \$\begingroup\$ Confirmed! Beautiful solution. It's great how if you know what a turtle is you can read the code like it's English. Almost certainly the most readable solution yet. \$\endgroup\$ Commented Dec 8, 2016 at 11:02
  • \$\begingroup\$ Neat! Thanks! I've been on the lookout for questions like this one that NetLogo is geared toward solving. Ironically, I'm also building a pyth-ish front end to remove that nice verbosity to try and make NetLogo a real golf contender. \$\endgroup\$ Commented Dec 8, 2016 at 15:54
  • 1
    \$\begingroup\$ Eh, I figured it was still an excellent answer! Can't wait to see your Pyth NetLogo code, should hopefully be a sight to behold! \$\endgroup\$ Commented Dec 8, 2016 at 17:30
1
\$\begingroup\$

PostScript, 48 bytes

00000000: 8814 3292 6c7b 7261 6e64 887f 9204 7d92  ..2.l{rand....}.
00000010: 837b 7b92 6b92 1a92 1992 1a34 9252 7b92  .{{.k......4.R{.
00000020: 4e92 6392 a792 4d7d 9283 7d92 657d 92a3  N.c...M}..}.e}..

Number of points is in the second byte (here it is 0x14 = 20 points).

Un-tokenized version:

20                          % number of points
2 mul{rand 127 and}repeat   % random points on stack
{
    {
        moveto              % move to top point on stack
        count copy          % duplicate stack
            count 4 idiv{   % for each duplicated point
            gsave
            lineto stroke   % draw a line to it
            grestore        % (removing it from the stack)
        }repeat
    }loop
}stopped                    % stop when stack is empty

output

\$\endgroup\$
2
  • \$\begingroup\$ Woah! Postscript! That's so cool, and surprisingly short. Got any ideas how to run it? \$\endgroup\$ Commented Jul 7, 2022 at 20:51
  • \$\begingroup\$ Sure - paste the hex dump into k20.txt and run it through xxd -r < k20.txt > k20.ps to get a binary, and then load it in a postscript viewer. For the screenshot, I used Preview.app on OS X, which converts to PDF internally. You can also use ghostscript by running gs k20.ps or load it in ghostview (aka gs or gsview). Or you can convert manually to PDF using gs -sDEVICE=pdfwrite -sOutputFile=k20.pdf k20.ps and then open k20.pdf in a PDF viewer. \$\endgroup\$ Commented Jul 8, 2022 at 6:57
0
\$\begingroup\$

05AB1E (legacy), 17 chars

Imports (excluded from character count):

"exec('global r,p;from pylab import rand as r,plot as p')".E\

’p(*Œ¬(*r(,2))’.E

Beats all other answers. Port of Falko's Python answer. Go upvote him! Input is hard-coded before the first ,.

’...’.E  # trimmed program
     .E  # evaluate...
’...’    # "p(*zip(*r(num,2)))"...
     .E  # as Python code

====================

p(*zip(*r(num,2)))  # full program
p(               )  # display plot with lines connecting all points at coordinates in ordered pairs...
  *                 # in...
   zip(         )   # each element of...
       *            # first element of...
        r(   , )    # array of...
          num       # input...
        r(     )    # arrays each containing...
              2     # literal...
        r(     )    # random numbers from 0 to 1, half-inclusive...
   zip(         )   # paired with corresponding element in...
       *            # second element of...
        r(   , )    # array of...
          num       # input...
        r(     )    # arrays each containing...
              2     # literal...
        r(     )    # random numbers from 0 to 1, half-inclusive

Character scoring abuse (actually longer), 20 characters

"񙕚𜯤󋒭𦕟𑨥"Ç6°βƵ6BÎ.:.E

"..."Ç6°βƵ6BÎ.:.E  # trimmed program
               .E  # evaluate...
     Ç             # list of charcodes of...
"..."              # literal...
        β          # converted from list of base-10 values of base...
       °           # 10 to the power of...
      6            # literal...
        β          # digits to decimal...
           B       # in base...
         Ƶ6        # 107...
             .:    # with all...
            Î      # 0...
             .:    # s replaced with...
            Î      # input

====================

p(*zip(*r(num,2)))  # full program
p(               )  # display plot with lines connecting all points at coordinates in ordered pairs...
  *                 # in...
   zip(         )   # each element of...
       *            # first element of...
        r(   , )    # array of...
          num       # input...
        r(     )    # arrays each containing...
              2     # literal...
        r(     )    # random numbers from 0 to 1, half-inclusive...
   zip(         )   # paired with corresponding element in...
       *            # second element of...
        r(   , )    # array of...
          num       # input...
        r(     )    # arrays each containing...
              2     # literal...
        r(     )    # random numbers from 0 to 1, half-inclusive
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.