text:
Write biSp in point-free form using as few terms as possible
The Haskell function biSp has type signature
biSp :: (a -> c) -> (b -> d) -> (c -> d -> e) -> a -> b -> e

and (for those who prefer combinator calculus) can be defined as
biSp g h f x y = f (g x) (h y)

Your task is to implement biSp in point-free form (equivalently: as a combinator without any lambdas) using only two primitives:
(.) :: (b -> c) -> (a -> b) -> a -> c
flip :: (a -> b -> c) -> b -> a -> c

or
(.) f g x = f (g x)
flip f x y = f y x

For those with a background in combinator calculus, these are respectively the B and C combinators.
You may define helper functions so long as they are point-free. Your score is the total number of terms in all right-hand-side expressions.
Testing
You can test a Haskell solution without installing any software using Ideone. By providing an explicit type alongside the definition you ensure a compile-time error if the function is incorrect. E.g. using the :pl reference implementation (online demo):
biSp :: (a -> c) -> (b -> d) -> (c -> d -> e) -> a -> b -> e
biSp = flip . ((flip . ((.) .)) .) . flip (.)
main = putStrLn "Compiled ok"

I'm not really sure what it is the above is doing (note that I'm not very familiar with functional programming).

I added a link.  Why so many close votes?  Is this not a good programming puzzle?

@dspyz the close-vote reason selected so far is "it's unclear what you're asking". so I guess that's the reason.

Even with the link, I'm still not sure what you want (possibly due to my lack of familiarity with functional languages). In general, language-specific tasks are looked down because not everyone can participate.

Yeah, I guess this could be written in any functional language.  But it lends itself more nicely to haskell.  I'll remove the haskell tag.  What's unclear about it?

This is indeed very language specific. But the question is certainly clear, for someone with minimal knowledge of Haskell (very minimal in my case).

Actually, I'm starting to wonder if an optimal solution could be found with some sort of BFS.  There's probably a lot of theory I don't know revolving around this sort of thing.

Looks like an interesting problem, but perhaps out of reach for those unfamiliar with haskell.  If possible, can you provide some examples of expected input and output?

I don't think the problem really lends itself to input and output.  However, I think anything which matches the type signature and compiles (not including recursive functions and calls to "error") is correct.  So, in that sense, you could say the input is the GHC compiler together with the type signature and the output is no compilation error

Edited to clarify for people who are familiar with combinator calculus but not Haskell, or who know other FP languages but don't want to try finding proper definitions of flip and (.). I was tempted to delete the [tag:haskell] tag, but I wasn't sure why you had edited it back in after once editing it out. I don't think there's anything Haskell-specific about this other than the names of the functions: the type signature syntax is the same as SML, and the core question could be an exercise in To Mock a Mockingbird.

7 terms
We again define a helper combinator BBQ = B B (C B), which has reduction rule
BBQ w x y z = x y (w z)

Then biSp = BBQ BBQ BBQ
  BBQ BBQ BBQ g h f x y
= BBQ g (BBQ h) f x y
= BBQ h f (g x) y
= f (g x) (h y)

Online demo
By brute force, this is the only 7-term solution and there is no smaller solution.
8 terms
There are a handful of 8-term solutions. Firstly, the obvious
C BBQ BBQ BBQ

which reduces in one step to BBQ BBQ BBQ.
Then there are three solutions of the form X X X with a five-term X:

X = B (B B) C B which reduces in one step to BBQ
X = C B (C B) B which reduces in one step to BBQ and allows the further extraction, for no net gain or loss, of a helper combinator Q = C B
X = C (B C (B B))

There is one solution of the form X X with a six-term X:

X = C B (B B (C B)) (again, with an equivalent version which extracts Q = C B)

And there is one solution which can only be written in 8 terms with two helper combinators:
Q = C B
X = Q (Q Q B)
biSp = X X

9 terms
Define a helper combinator BBQ = B B (C B), which has reduction rule
BBQ w x y z = x y (w z)

Then we have three options:

C (B B BBQ) BBQ
B (C B BBQ) BBQ
C (B (C BBQ) BBQ)

To show the equivalence of the first two:
  C (B B BBQ) BBQ g h f x y
= B B BBQ g BBQ h f x y
= B (BBQ g) BBQ h f x y

  B (C B BBQ) BBQ g h f x y
= C B BBQ (BBQ g) h f x y
= B (BBQ g) BBQ h f x y

We can then continue:
= BBQ g (BBQ h) f x y

That then gives the equivalence with the third:
  C (B (C BBQ) BBQ) g h f x y
= B (C BBQ) BBQ h g f x y
= C BBQ (BBQ h) g f x y
= BBQ g (BBQ h) f x y

Finally
= BBQ h f (g x) y
= f (g x) (h y)

In Haskell this is (picking one of the options):
bbq = (.) (.) (flip (.))
biSp = flip ((.) (.) bbq) bbq

Online demo

9 terms
This uses an intermediate combinator which I shall call Par for parity, because of the way it groups its arguments. Par = B C (B B) has reduction rule
Par w x y z = (w y) (x z)

Then biSp = C (B Par (C Par)). To demonstrate:
  C (B Par (C Par)) g h f x y
= B Par (C Par) h g f x y
= Par (C Par h) g f x y
= C Par h f (g x) y
= Par f h (g x) y
= f (g x) (h y)

In Haskell this is
par = (.) flip ((.) (.))
biSp = flip ((.) par (flip par))

Online demo

10 terms
         1  2     3  4   5  6   7  8   9  10
biSp = flip . ((flip . ((.) .)) .) . flip (.)

Another reference solution, that from ghci-on-acid's :pl command.

10 terms
        1   2    3   4   5    6   7   8
biSp = cf ((.) (cf ((.) (.))) . flip (.))

      9   10
cf = (.) flip

Another 10 term solution
        1   2  3  4  5  6 7  8
biSp = fc ((.) . fc) . fc . fc

       9  10
fc = flip (.)

authors: Андрей Лукьянов


text:
How many IP addresses are in a given range?
Inspired by...

Networking - How can I work out how many IP addresses there are in a given range?

Write a program or function that takes two strings as input, each being an IPv4 address expressed in standard dotted notation and outputs or returns the number of IP addresses covered by this range, including the two IP addresses input.

You must not use any external code, libraries or services designed to parse an IP address. (Other string processing standard library functions are acceptable.)
All 2^32 IP addresses are equal. No distinction is made to broadcast, class E, etc.
Normal code-golf rules apply.

For example:
"0.0.0.0","255.255.255.255" returns 4294967296.
"255.255.255.255","0.0.0.0" also returns 4294967296.
"1.2.3.4","1.2.3.4" returns 1.
"56.57.58.59","60.61.62.63" returns 67372037.
"1","2" is invalid input. Your code may do anything you like.

I saw this question on programmers, and was thinking about asking it on code golf lol.

I thought this is a StackOverflow question about what IP addresses are impossible according to the standards.

Isn't IPv4 a bit passe?

GolfScript, 20 bytes
~]7/${2%256base}/)\-

Try it online.
Test cases
$ echo 0.0.0.0 255.255.255.255 | golfscript range.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | golfscript test.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | golfscript test.gs
1
$ echo 56.57.58.59 60.61.62.63 | golfscript test.gs
67372037

How it works
~]        # Evaluate and collect into an array.
          #
          # “.” duplicates, so for "5.6.7.8 1.2.3.4", this leaves
          # [ 5 5 6 6 7 7 8 1 1 2 2 3 3 4 ] on the stack.
          #
7/        # Split into chunks of length 7: [ [ 5 5 6 6 7 7 8 ] [ 1 1 2 2 3 3 4 ] ]
$         # Sort the array of arrays: [ [ 1 1 2 2 3 3 4 ] [ 5 5 6 6 7 7 8 ] ]
{         # For each array:
  2%      # Extract every second element. Example: [ 1 2 3 4 ]
  256base # Convert the IP into an integer by considering it a base 256 number.
}/        #
)         # Add 1 to the second integer.
\-        # Swap and subtract. Since the integers were sorted, the result is positive.

Very nice, and nice use of $ to avoid abs.

~] is also really clever.

Python 2 - 106
See it here.
def a():x=map(int,raw_input().split("."));return x[0]*2**24+x[1]*2**16+x[2]*2**8+x[3]
print abs(a()-a())+1

Example Input

0.0.0.0
0.0.0.255

Example Output

256

def a():return reduce(lambda c,d:c*256+d,map(int,raw_input().split("."))) is a lot shorter

@Michael Thanks for the suggestion. I used it for a few minutes, then looked at it and thought, "I didn't write 90% of that." so I rolled it back.

@Michael a=lambda: instead of def a():return  saves 6 characters

@Rusher It's 107 characters, not 106

@avall: I assume you're counting the final LF.

@Rusher No i don't. I double checked it. Maybe you don't count LF between both lines.

@avall: I've copied, pasted and tested. It's 106 bytes. Any chance you have a CR before your LF?

Yes, it was LF. Edited it in HEX Editor. I'm on linux.

@Michael: if using reduce, you don't even need the map reduce(lambda c,d:c*256+int(d),raw_input().split("."),0), gains 2 more chars

CJam - 15
{r'./256b}2*-z)

Try it at http://cjam.aditsu.net/
Thanks Dennis, wow, I don't know how to get the best out of my own language :p

You can save two bytes by eliminating :i (b seems to cast to integer) and one by using {r...}2* instead of qS/{...}/

Pure bash, 66 bytes
p()(printf %02x ${1//./ })
r=$[0x`p $1`-0x`p $2`]
echo $[1+${r/-}]

Notes:

Defines a function p that is passed a dotted decimal IP address, and outputs the hex representation of that address:

${1//./ } is a parameter expansion that replaces . with   in the IP address passed to p()
The printf is mostly self explanatory.  Since there is only one format specifier %02x and four remaining args, the format specifier is reused for each remaining arg, effectively concatenating the 2 hex digits of each of the 4 octets together

$[] causes arithmetic expansion.  We do a basic subtraction, and assign to the variable r
${r/-} is a parameter expansion to remove a possible - character - effectively abs()
Display 1 + the absolute difference to give the range.

Output:
$ ./iprangesize.sh 0.0.0.0 255.255.255.255
4294967296
$ ./iprangesize.sh 255.255.255.255 0.0.0.0
4294967296
$ ./iprangesize.sh 1.2.3.4 1.2.3.4
1
$ ./iprangesize.sh 56.57.58.59 60.61.62.63
67372037
$ ./iprangesize.sh 1 2
2
$

I detect printf and echo. Are those part of bash?

@CatsAreFluffy They're builtins.

Python 2.7 - 96 91 90 87
Made a function.
f=lambda a:reduce(lambda x,y:x*256+int(y),a.split("."),0)
p=lambda a,b:abs(f(a)-f(b))+1

Usage:

>>> p("1.2.3.4","1.2.3.5")
2

Edit: Removed unnecessary int() from f function. Thanks to isaacg
Edit2: Removed LF at the end of file (thanks to @Rusher) and removed map() at cost of reduce() initializer (thanks to @njzk2)

why does the f function need int() on the outside?

Well. I had no idea :D

can gain 2 chars by putting the int in the reduce instead of using the map (only 2 as you need to add ,0 parameter to your reduce function)

I just wrote something that is almost exactly your code, so I won't bother submitting now. Actually, mine is three characters longer!

CoffeeScript - 94, 92, 79, 72
I=(a)->a.split(".").reduce((x,y)->+y+x*256)
R=(a,b)->1+Math.abs I(b)-I a

Un-golfed:
I = ( a ) ->
    return a.split( "." ).reduce( ( x, y ) -> +y + x * 256 )

R = ( a, b ) ->
    return 1 + Math.abs I( b ) - I( a )

Equivalent JavaScript:
function ip2long( ip_str )
{
    var parts = ip_str.split( "." );
    return parts.reduce( function( x, y ) {
        return ( +y ) + x * 256; //Note: the unary '+' prefix operator casts the variable to an int without the need for parseInt()
    } );
}

function ip_range( ip1, ip2 )
{
    var ip1 = ip2long( ip1 );
    var ip2 = ip2long( ip2 );

    return 1 + Math.abs( ip2 - ip1 );
}

Try it online.

You can save some characters by replacing some parentheses with spaces: I=(a)->n=0;a.split(".").forEach((x)->n<<=8;n+=parseInt x);n>>>0 R=(a,b)->1+Math.abs I(b)-I a

It feels like you're losing a lot of space to Math.abs, but I can't come up with anything shorter.  (z>0)*z||-z is the best I've got (same length, and it needs a single-char input).  Do you have anything cleverer than that?

this javascript version really helps me, ive been searching for this for like an hour. thanks!

GolfScript, 27 bytes
' '/{'.'/{~}%256base}/-abs)

Examples:
$ echo 0.0.0.0 255.255.255.255 | ruby golfscript.rb iprange.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | ruby golfscript.rb iprange.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | ruby golfscript.rb iprange.gs
1
$ echo 56.57.58.59 60.61.62.63 | ruby golfscript.rb iprange.gs
67372037

You can save one char by using / instead of %~.

Perl, 43 bytes
#!perl -pa
$_=1+abs${\map{$_=vec eval,0,32}@F}-$F[0]

Counting the shebang as two bytes.
Sample Usage:
$ echo 0.0.0.0 255.255.255.255 | perl count-ips.pl
4294967296

$ echo 255.255.255.255 0.0.0.0 | perl count-ips.pl
4294967296

$ echo 56.57.58.59 60.61.62.63 | perl count-ips.pl
67372037

Notes

vec eval,0,32 is a drop-in for ip2long. Perl allows character literals to be expressed as their ordinal prefixed with a v, for example v0 can be used for the null char. These can also be chained together, for example v65.66.67.68 → ABCD. When three or more values are present, the initial v is unnecessary. The vec function interprets a string as an integer array, each cell having the specified number of bits (here, 32). unpack N,eval would have worked equally as well.

Powershell - 112 108 92 78 bytes
This is my first time golfing. Here goes nothing:
Golfed (Old):
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f[int]$_};[uint32]$t};1+[math]::abs($a-$b)

Golfed (new)
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f+$_};[long]$t}|sort;1+$b-$a

Ungolfed:
$a, $b = $args | % {           #powershell's way of popping an array. In a larger array
                               #$a would equal the first member and $b would be the rest.
    $t = '0x';                 #string prefix of 0x for hex notation
    $_ -split '\.' | % {       #split by escaped period (unary split uses regex)
        $t += "{0:X2}" -f +$_  #convert a dirty casted int into a hex value (1 octet)
    };
    [long]$t                   #and then cast to long
} | sort;                      #sort to avoid needing absolute value
1 + $b - $a                    #perform the calculation

Usage
Save as file (in this case getipamount.ps1) and then call from the console
getipamount.ps1 255.255.255.255 0.0.0.0

C# with LINQ - 139 bytes
(From 140 after applying Bob's suggestion.)
long f(params string[] a){return Math.Abs(a.Select(b=>b.Split('.').Select(long.Parse).Aggregate((c,d)=>c*256+d)).Aggregate((e,f)=>e-f))+1;}

Ungolfed....
    long f(params string[] a)                           // params is shorter than two parameters.
    {
        return Math.Abs(                                // At the end, make all values +ve.
             a.Select(                                  // Go through both items in the array...
                b =>                                    // Calling each one 'b'.
                    b.Split('.')                        // Separating out each "." separated byte...
                    .Select(long.Parse)                 // Converting them to a long.
                    .Aggregate((c, d) => c*256 + d)     // Shift each byte along and add the next one.
             )
             .Aggregate((e,f) => e-f)                   // Find the difference between the two remaining values.
         )+1;                                           // Add one to the result of Math.Abs.
    }

https://dotnetfiddle.net/XPTDlt

Could someone explain to me how this whole shifting bytes along thing works?

@Obversity a.b.c.d is equivalent to (a << 24) | (b << 16) | (c << 8) | (d << 0) is equivalent to (((a << 8) << 8) << 8) + ((b << 8) << 8) + (c << 8) + d). Basically, each iteration of the aggregation takes the existing sum and shifts it left by one octet, then adds the next octet.

You can save a character by using c*256 instead of (c<<8).

@Bob Well spotted.

You can save two more characters by replacing e-f with e<f?f-e:e-f and dropping the Math.Abs()

Scrap my last comment, you can save 4 by using Math.Abs(a.Select((b,i)=>b.Split('.').Select(long.Parse).Aggregate((c,d)=>c*256+d)*(1-2*i)).Sum())+1. The (1-2*i) will result in 1 for the first item and -1 for the second, thus making the second item negative, which will then be 'summed' to the first item.

And another 5 by replacing .Select(long.Parse).Aggregate((c,d)=>c*256+d) with .Select((c,j)=>long.Parse(c)<<8*j).Sum().

And 2 more by replacing a.Select((b,i)=>b.Split('.').Select((c,j)=>long.Parse(c)<<8*j).Sum()*(1-2*i)).Sum() with a.SelectMany((b,i)=>b.Split('.').Select((c,j)=>(1-2*i)*long.Parse(c)<<8*j)).Sum(). Assign the sign when parsing the part. Then use SelectMany, instead of Select with a Sum inside, to get 8 numbers (one for each part of each address), which already get Summed in the end anyway.

@PatrickHuizinga I think your combined suggestions are a significant enough departure from my original code that you should submit a separate answer. (Unless there are prizes. I want to keep the prizes.)

dc, 61 characters
?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p

I think it's pretty amazing that this can be solved with dc at all since it has no ability to parse strings. The trick is that 192.168.123.185 goes on the stack as
.185
.123
192.168

and dXIr^* shifts the decimal point right as many fraction digits as there are and it even works for .100.
$ echo 56.57.58.59 60.61.62.63 | dc -e '?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p'
67372037.00

Subtract a character if you let the input already be on the stack.

JavaScript ES6 - 68 bytes
f=x=>prompt().split('.').reduce((a,b)=>+b+a*256);1+Math.abs(f()-f())

Try it with the console (press F12) of Firefox.

You should be using alert or console.log. Console output is cheap.

@nderscore, absolutely no difference between console.log and direct output. This is code-golf, it's not about do clean code.

The most upvoted answer to this meta post disagrees: JavaScript Standards for IO. It's not a matter of clean code. It's a matter of not actually outputting anything.

@DigitalTrauma, it won't work due to operator precedence. (addition vs bitwise shift)

PHP, 138 110 bytes
<?php

function d($a,$b){foreach(explode('.',"$a.$b")as$i=>$v){$r+=$v*(1<<24-$i%4*8)*($i<4?1:-1);}return 1+abs($r);}

// use it as
d('0.0.0.0','255.255.255.255');

As there's no mention of 'no deprecation warnings', you can save a char by replacing explode('.',"$a.$b") with split('\.',"$a.$b").

I count 109, not 110. Save 9 bytes with a program instead of a function and 8 more with these golfing steps: http://sandbox.onlinephpfunctions.com/code/6d6e403b7f9f188644f9b4ced77da93de13ec97b

Perl, 72 bytes
#!perl -ap
@a=map{unpack N,pack C4,split/\./,$_}@F;$_=abs($a[1]-$a[0])+1

Usage:
$ echo 10.0.2.0 10.0.3.255 | perl ip-range.pl
512$

This is already longer than primo's Perl program, so not too interesting.
Perl, 119 bytes, for obsolete IP address format
#!perl -ap
sub v(){/^0/?oct:$_}@a=map{$m=3;@p=split/\./,$_;$_=pop@p;$s=v;$s+=v<<8*$m--for@p;$s}@F;$_=abs($a[1]-$a[0])+1

Usage:
$ echo 10.0.2.0 10.0.3.255 | perl ip-obsolete.pl
512$
$ echo 10.512 10.1023 | perl ip-obsolete.pl
512$
$ echo 0xa.0x200 012.01777 | perl ip-obsolete.pl
512$

This program accepts the obsolete format for IP addresses! This includes addresses with 1, 2, or 3 parts, or with hexadecimal or octal parts. Quoting the inet_addr(3) manual page,

Values specified using dot notation take one of the following forms:
a.b.c.d
a.b.c
a.b
a

... When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. ... When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the rightmost three bytes of the network address. ... When only one part is given, the value is stored directly in the network address without any byte rearrangement.
All numbers supplied as ``parts'' in a dot notation may be decimal, octal, or hexadecimal, as specified in the C language (i.e., a leading 0x or 0X implies hexadecimal; a leading 0 implies octal; otherwise, the number is interpreted as decimal).

Most programs no longer accept this obsolete format, but ping 0177.1 still worked in OpenBSD 5.5.

The fact you're using BSD is more surprising than the IP thing.

Python 2.7, 104 bytes
y=lambda:map(int,input().split("."));a,b=y(),y();print sum(256**(3-i)*abs(a[i]-b[i])for i in range(4))+1

Thanks for the solution. Do you think you could: 1. Switch from semicolons to newlines, for readability without sacrificing length. 2. Explain how the code works?

Mathematica 9, 108 bytes
c[f_,s_]:=1+First@Total@MapIndexed[#1*256^(4-#2)&,First@Abs@Differences@ToExpression@StringSplit[{f,s},"."]]

Ungolfed:
countIpAddresses[first_, second_] := Module[{digitArrays, differences},

  (* Split the strings and parse them into numbers.
  Mathematica automatically maps many/most of its functions across/
  through lists *)

  digitArrays = ToExpression[StringSplit[{first, second}, "."]];

  (* Find the absolute value of the differences of the two lists,
  element-wise *)
  differences = Abs[Differences[digitArrays]];

  (* differences looks like {{4, 4, 4, 4}} right now,
  so take the first element *)
  differences = First[differences];

  (* now map a function across the differences,
  taking the nth element (in code, '#2') which we will call x (in
  code, '#1') and setting it to be equal to (x * 256^(4-n)).
  To do this we need to track the index, so we use MapIndexed.
  Which is a shame,
  because Map can be written '/@' and is generally a huge character-
  saver. *)
  powersOf256 = MapIndexed[#1*256^(4 - #2) &, differences];

  (* now we essentially have a list (of singleton lists,
  due to MapIndexed quirk) which represents the digits of a base-256,
  converted to decimal form.
  Example: {{67108864},{262144},{1024},{4}}

  We add them all up using Total,
  which will give us a nested list as such: {67372036}

  We need to add 1 to this result no matter what. But also,
  to be fair to the challenge, we want to return a number -
  not a list containing one number.
  So we take the First element of our result. If we did not do this,
  we could chop off 6 characters from our code. *)

  1 + First[Total[powersOf256]]
]

PHP, 46 Bytes
<?=abs(ip2long($argv[1])-ip2long($argv[2]))+1;

Try it online!
ip2long

J, 25 bytes
Takes the dotted-quad IP strings as left and right arguments.
>:@|@-&(256#.".;.2@,&'.')

Explained:
>:@|@-&(256#.".;.2@,&'.')  NB. ip range
      &(                )  NB. on both args, do:
                   ,&'.'   NB.   append a .
               ;.2@        NB.   split by last character:
             ".            NB.     convert each split to number
        256#.              NB. convert from base 256
   |@-                     NB. absolute difference
>:@                        NB. add 1 to make range inclusive

Examples:
   '0.0.0.0' >:@|@-&(256#.".;.2@,&'.') '255.255.255.255'
4294967296
   iprange =: >:@|@-&(256#.".;.2@,&'.')
   '255.255.255.255' iprange '0.0.0.0'
4294967296
   '1.2.3.4' iprange '1.2.3.4'
1
   '56.57.58.59' iprange '60.61.62.63'
67372037

Ruby, 93 bytes
a=->(x){s=i=0;x.split('.').map{|p|s+=256**(3-i)*p.to_i;i+=1};s}
s=->(x,y){1+(a[x]-a[y]).abs}

Output
irb(main):003:0> s['1.1.1.1', '1.1.1.2']
=> 2
irb(main):006:0> s['0.0.0.0', '255.255.255.255']
=> 4294967296

C# - 135
long f(string x,string y){Func<string,long>b=s=>s.Split('.').Select((c,i)=>long.Parse(c)<<(3-i)*8).Sum();return Math.Abs(b(x)-b(y))+1;}

Properly formatted
long g(string x, string y) {
    Func<string, long> b = s => s.Split('.').Select((c, i) => long.Parse(c) << (3 - i) * 8).Sum();
    return Math.Abs(b(x) - b(y)) + 1;
}

https://dotnetfiddle.net/Q0jkdA

Suggest 24-i*8 instead of (3-i)*8 and return-~Math.Abs(b(x)-b(y)) instead of return Math.Abs(b(x)-b(y))+1

Factor, 73 bytes
Translation of the CoffeeScript answer.
[ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ]

Javascript ES6, 81 chars
(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1

Test:
f=(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1
;`0.0.0.0,255.255.255.255,4294967296
255.255.255.255,0.0.0.0,4294967296
1.2.3.4,1.2.3.4,1
56.57.58.59,60.61.62.63,67372037`.split`
`.map(x=>x.split`,`).every(x=>f(x[0],x[1])==x[2])

PS: I'll try to optimise it a bit later.

Lua, 153 Bytes
It's a shame that lua doesn't have a split function, I had to define mine!
a,b=...r=0y=8^8x={}t={}function f(t,s)s:gsub("%d+",function(d)t[#t+1]=d end)end
f(x,a)f(t,b)for i=1,4 do r=r+y*math.abs(t[i]-x[i])y=y/256 end print(r+1)

Ungolfed
a,b=...                    -- unpack the arguments into two variables
r=0                        -- initialise the sume of ip adress
y=8^8                      -- weight for the rightmost value
x={}t={}                   -- two empty arrays -> will contains the splittedip adresses
function f(t,s)            -- define a split function that takes:
                           --   a pointer to an array
                           --   a string
  s:gsub("%d+",function(d) -- iterate over the group of digits in the string
    t[#t+1]=d              -- and insert them into the array
  end)
end
f(x,a)                     -- fill the array x with the first address
f(t,b)                     -- fill the array t with the second address
for i=1,4                  -- iterate over t and x
do
  r=r+y*math.abs(t[i]-x[i])-- incr r by weight*abs(range a- range b)
  y=y/256                  -- reduce the weight
end
print(r+1)                 -- output the result

Jelly, 12 bytes, language postdates challenge
ṣ”.V€ḅ⁹µ€ạ/‘

Try it online!
Explanation
ṣ”.V€ḅ⁹µ€ạ/‘
       µ€     On each element of input:
ṣ”.             Split on periods
   V€           Convert string to number in each section
     ḅ⁹         Convert base 256 to integer
         ạ/   Take absolute difference of the resulting integers
           ‘  Increment

The number of elements in an inclusive range is the absolute difference of their endpoints, plus 1.

Axiom, 385 bytes
c(a:String):INT==(d:=digit();s:NNI:=#a;t:INT:=0;for i in 1..s repeat(~member?(a.i,d)=>return-1;t:=t+(ord(a.i)-48)*10^(s-i)::NNI);t)
g(x:String):List NNI==(a:=split(x,char".");s:NNI:=#a;r:=[];for i in s..1 by -1 repeat(y:=c(a.i);y=-1=>return [];r:=concat(y,r));r)
m(x:NNI,y:NNI):NNI==x*256+y
f(a:String,b:String):INT==(x:=g(a);y:=g(b);#x~=4 or #y~=4=>-1;1+abs(reduce(m,x)-reduce(m,y)))

ungolf it and test
-- convert the string only digit a in one not negative number
-- return -1 in case of error
cc(a:String):INT==
     d:=digit();s:NNI:=#a;t:INT:=0
     for i in 1..s repeat
               ~member?(a.i,d)=>return -1
               t:=t+(ord(a.i)-48)*10^(s-i)::NNI
     t

-- Split the string x using '.' as divisor in a list of NNI
-- if error return []
gg(x:String):List NNI==
    a:=split(x,char".");s:NNI:=#a;r:=[]
    for i in s..1 by -1 repeat
          y:=cc(a.i)
          y=-1=>return []
          r:=concat(y,r)
    r

mm(x:NNI,y:NNI):NNI==x*256+y

-- Return absolute value of difference of address for IP strings in a and in b
-- Retrun -1 for error
-- [Convert the IP strings in a and in b in numbers ad subtract and return the difference]
ff(a:String,b:String):INT==(x:=gg(a);y:=gg(b);#x~=4 or #y~=4=>-1;1+abs(reduce(mm,x)-reduce(mm,y)))

(14) -> f("0.0.0.0", "255.255.255.255")
   (14)  4294967296
                                                    Type: PositiveInteger
(15) -> f("255.255.255.255", "0.0.0.0")
   (15)  4294967296
                                                    Type: PositiveInteger
(16) -> f("1.2.3.4", "1.2.3.4")
   (16)  1
                                                    Type: PositiveInteger
(17) -> f("56.57.58.59", "60.61.62.63")
   (17)  67372037
                                                    Type: PositiveInteger
(18) -> f("1", "2")
   (18)  - 1
                                                            Type: Integer

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Can the dog reach the neighbour's house?
A dog is leashed to a pole and the owner wants to know if it can venture to the neighbour's building. You're given a map, which contains the pole (represented by x), the owner's buildings (represented by 1) and the neighbour's building (represented by 2). Empty areas are padded with dots and every line has the same length. EDIT: I forgot to mention, neighbour is always to the right from the dog. Every tile represents an area of one square meter. You're also given the length of the dog's leash (as meters). The pole is at the center of the tile. For input you must use the STDIN (and respectively STDOUT for output), if it's available in your language. Otherwise create a function, which takes the input as parameters and returns the answer. An example input to the STDIN would look like this.
6
............
...11..222..
...11..222..
...11.......
.x.11.......
............

Additional newline is guaranteed after the input. The program should output Yes if the dog can reach the neighbour's building and otherwise No.
Assumptions

There can be several buildings belonging to the owner.
There can only be one neighbour's building.
The dog can't venture outside the map or through the buildings.
The dog can't be trapped inside a building.
The length of the leash is always an integer
Distances are calculated in Euclidean metric.

This is a codegolf, shortest code wins.
Test cases
Input:
6
............
...11..222..
...11..222..
...11.......
.x.11.......
............

Output: No
Input:
7
............
...11..222..
...11..222..
...11.......
.x.11.......
............

Output: Yes
Input:
7
........
...11...
..111.22
..111.22
.x111.22
..111.22
..111...

Output: No
Input:
8
........
...11...
..111.22
..111.22
.x111.22
..111.22
..111...

Output: Yes

What metric is used here? Manhattan?

@JanDvorak Euclidean metric

Could the downvoter explain?

Do you intend this to be a flood-fill solve?  In other words, the dog can traverse only dots and if he can get from the x to any of the 2's in <= leash length dots then output yes, else no?

Also, does "reaching" mean being "next to" or "on top of"?

@DreamWarrior Reaching means even the slightest bit on top of. Also, the distance is not counted as dots but as Euclidean geometry's metres. This means the distance most often is a decimal number.

@TheRare noticed the edge case after I commented, sorry -- comment removed.  As for the "not counted by dots", well...it is, if you think about it.  Each dot is 1 meter squared, if I traverse the whole dot I move 1 meter, unless traversed diagonally, in which case sqrt(2) meters.

@DreamWarrior The diagonal traverse is not the only case. Think about moving 2 down and 1 right.

@TheRare I think you misunderstood me, I meant for each dot I "consume" (traverse) it is either counted as 1 or sqrt(2) meters of leash length.  At which point, this is flood fill from x to any 2 with <= leash consumed.

@DreamWarrior Think about the example I gave. It can't result in either because you want the shortest path.

Since there are no answers yet, may I suggest that the input parsing is left out from the source length? I.e. problem rewritten to "Write a function that uses input encoding of your choice..."

@MrBackend Actually, come to think about it, I think the input parsing is a core piece of this challenge.

@TheRare then may I suggest you remove "if it's available in your language"

@MrBackend That would rule out some languages. Almost every real language has stdin anyways.

I don't understand why test case 3 is not reachable with a leash of 7 meters, please explain. Edit: My calculation gives (going the lower route): sqrt(6.5)+3+sqrt(2) ~ 6.96

@MrBackend "The dog can't venture outside the map or through the buildings."

Ah, so that includes along the outside of a building adjacent to the map border.

@MrBackend Here's an illustration. http://puu.sh/96DzF/5f011d4bf1.png (smallest circle is of length 7 and second smallest of length 8)

@TheRare, I'm not sure I understand what that picture is trying to show.  Maybe it'd be useful if you could show us how much leash you think it should optimally take to "solve" each of those examples.  For the second example, I get sqrt(6.5)+2+2*sqrt(2) = approx 7.378.

@DreamWarrior My graphical skills are limited. Every circle represents the remaining area at each corner. The last 2 examples would take ~7.38 meters in minimum.

http://en.wikipedia.org/wiki/Dijkstra's_algorithm might come in handy here.

@TheRare A lot of people seem confused about how the dog can move here. Does http://i.stack.imgur.com/AtrmO.png show a correct example (for your first sample)? If so then how can the dog get there in 7 units?

@Calvin'sHobbies Not quite. See http://puu.sh/ahQ77/19d71e488e.png

@TheRare Ah of course. I apparently cannot count to 2 correctly. But at least the images explain that the distance is not "by cell".

@Calvin'sHobbies I tried to make that clear in the question itself. Sorry about that.

PHP 781 chars
I know this can be smaller but I am sorry that I am confused. If I take your first two examples (answers no and yes), if diagonal moves are not allowed, answers should be no and no, surely. If diagonal moves are allowed, answers should be yes and yes. Have I misunderstood?
I also took beside to be the criteria of 'reached' as the dog can then wee on the building - however changing that to on top of can easily be done changing the pass counter which currently equals leash length.
Anyway, this allows for diagonal movement, non diagonal would be smaller than this.
<?php
$a.='7
............
...11..222..
...11..222..
...11.......
.x.11.......
...........';$b='No';$c=array();$d=array();function check_2($e,$f){if(($c[$e+1][$f-1]=='2')OR($c[$e+1][$f]=='2')OR($c[$e+1][$f+1]=='2')OR($c[$e][$f-1]=='2')OR($c[$e][$f]=='2')OR($c[$e][$f+1]=='2')OR($c[$e-1][$f-1]=='2')OR($c[$e-1][$f]=='2')OR($c[$e-1][$f+1]=='2')){return TRUE;;}else{return FALSE;}}str_replace("\n\r","\n",$a);$g=explode("\n",$a);$h=$g[0];unset($g[0]);$i=count($g);$j=0;foreach($g as $k){$l=str_split($k);$m=count($l)+1;unset($l[$m]);$c[$j]=$l;++$j;}$d=$c;for($n=0;$n<=$h;++$n){for($e=0;$e<$i;++$e){for($f=0;$f<$m;++$f){if($c[$e][$f]=='2'){$b='Yes';}if($c[$e][$f]=='x'){for($o=-1;$o<2;++$o){for($p=-1;$p<2;++$p){if($c[$e+$o][$f+$p]=='.'){$d[$e+$o][$f+$p]='x';}}}}}}$c=$d;}echo $b;?>

I am pretty sure I can make this smaller but with the confusion not sure which way to go.
Anyway this is my first flood fill so I am sure it can be done more efficiently. Most of the work was getting the input into a variable and a multi dimensional array.
The input it contained in the first variable $a. You can see it here on codepad.
I hope you like it. As a relative newbie and since this is the only answer I suppose I am officially winning here at the moment. Although I cannot imagine this will last long if someone else enters :-)

Sorry about the confusion and thanks for trying! The challenge itself is a bit flawed. Diagonal movement is totally allowed, but you should always strive for the shortest path. In the first example, shortest path from the first house to the second is diagonally. Also, I hope you're not counting the map in your score :)

Yes I was counting the map, although I asked on a chat room about it and they said it was ok not to. I suppose I could take 90 characters off but as I haven't tested it nor redone the codepad fiddle I will leave it for now. :-)
PS I thought it had the makings of a great question.

I also elaborated the distannce calculation with this picture http://puu.sh/ahQ77/19d71e488e.png

I can see how to do it with one building. But with multiple owner buildings it seems I can always produce a map that makes my method incomplete. I am also assuming that the neighbour is always to the right of x, which is not correct either and again would make the program enourmous. (Also assuming the buildings are always rectangular, not L shapes or more complex, and not touching corners either. :-(

Wow, I completely forgot to mention that. Neighbours are always to the right.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Implement an integer parser
Implement an integer parser in the shortest code possible, with the following restrictions:

The function or program can only take one argument: a string (or equivalent). Assume it to be signed and always valid (don't worry about decimals, etc.). The input may optionally omit the sign, in which it is assumed to be positive.
The function or program must output an integer (or equivalent).
No pattern matching, regular expressions, etc. are allowed. This includes utilities such as tr for *nix.
No string parsing utilities are permitted, even from the standard library. This includes, but is not limited to,  parseInt() from JavaScript, int() in Python, and Int32.parse() from VBScript.
The only permitted predefined string manipulation functions, methods, etc. fall into one of the following categories:

extract a substring (e.g. substr(), slice())
get code point from character, vice versa (e.g. toCodePoint(),  fromCodePoint())
concatenate strings (e.g. append(),  concat(), strcpy())

No external libraries are permitted.
No string parsing utilities are permitted, even from the standard library.
Implicit conversion to string is disallowed (e.g. 1+'' in JavaScript)

Shortest code wins, so happy golfing!
EDIT: Sorry for the confusion, but implicit conversion is also disallowed.

What if the input string isn't an integer? what to output?

Addressed. Question updated.

Both positive and negative?

Also addressed. Assume it's already valid and is signed.

Is split an extract a substring method?

Okay, I'm going to use 0 + $string in PHP (implicit integer cast). Or is using language syntax for string parsing forbidden too? :-P

@PeterTaylor Yes.

@bwoebi That is forbidden. I apologize for missing the implicit string conversion side of things. I'm a little embarassed for not even catching that, considering my primary language of choice (JavaScript) uses that on a regular basis.

"The function or program must output an integer": how can you distinguish an integer output from a string one?

@Blackhole This basically excludes languages that don't have an integer type.

Here is a short PostScript function that will convert a string to an integer: exec. (It even allows you to express it symbolically as the result of a computation!)

To be pedantic, you haven't specified how (or if) the output integer should correspond to the input string, so a solution that always outputs 42 would seem to be technically valid, as 42 is definitely an integer.

Also, you might want to include some examples of valid and invalid input strings. For example, I'd like to know which of the following strings are valid inputs: 0, 1, -1, +1, +-1, -0, +0, 0000, 0001, +, -, (empty string), - 1, 123 456, 9999999999, 2147483648, -2147483648.

@AJMansfield: If that's allowed, I can beat it in GolfScript: ~

Do we have to treat both 123 and +123, or does one of them suffice? (if so, I presume the former suffices)

@ajmansfield, ilmari Not allowed.

@firefly Either one.

The exec is effectively equivalent to a parseInt method.

GolfScript, 19 / 24 / 28 chars
Assuming that positive numbers are always preceded by a + sign (19 chars; online demo):
(45-~0@{48-\10*+}/*

Assuming that positive numbers never have a + sign (24 chars; online demo):
"-"/)0\{48-\10*+}/-1@,?*

Assuming that positive numbers may or may not have a + sign (28 chars; online demo):
"+"-"-"/)0\{48-\10*+}/-1@,?*

(This is the same as the 24-char solution about, but with "+"- prepended to strip away any + signs.)
All of these are based on the following 13-character program, which converts an unsigned base-10 digit string into an integer:
0\{48-\10*+}/

It works by keeping a running total on the stack and iterating over (the ASCII codes of) the characters in the string.  For each character, it subtracts 48 (the ASCII code of 0) from the ASCII code, multiplies the running total by 10, and adds the two together to give the new running total.
The rest of the code is for sign handling.  The always-signed case is easiest, because we can just chop the first character off the string and test its ASCII code to see if it's + (43) or - (45).  Conveniently, the ASCII codes of those two characters differ by two, so we can easily remap them to 1 and -1 via subtraction and negation.  (The code happens to also give the right answer for an unsigned zero, but mostly by accident.)
For the only-negatives-signed case, we use a different strategy: we split the input string at - signs, take the last segment as the number, and count the number of earlier segments to determine whether to negate the number or not.  The code for the maybe-signed case is exactly the same, but we first strip off any plus signs to reduce it to the previous case.

Ps. If we can cheat and use eval, the obvious GolfScript solution is just one character long:
~

It doesn't handle leading + signs, though, since GolfScript integer literals don't allow them.

This (the 28-character version) is the winner.

Python 3 (68)
s=input()
n=s<'0'
t=0
for c in s[n:]:t=t*10+ord(c)-48
print(t-t*2*n)

The Boolean n remembers whether the string started with a minus sign by using the lexicographic string ordering, in which '-' is less then the lowest digit '0'. The expression s[n:] casts n to a number (0 or 1), skipping the minus sign if it was there. The expression t-t*2*n is a shortening of [t,-t][n].

GolfScript, 33 characters
I'm still pretty new to GolfScript, so I'm not sure how well this came out. I could be missing some better approaches/optimizations. If you see any, let me know so I can hopefully learn!
I believe this code works correctly for any signed integer of the form: [-+]?[0-9]+
Fully golfed:
(.45=!2*(:s;48-.0>*\{48-s*\10*+}/

Expanded source with C-ish pseudocode:
"-01234567890"  # char in[] = "-01234567890";

(               # char c0 = in[0];
.45=!2*(:s;     # int s = c0 == '-' ? -1 : 1;
48-.0>*\        # int x = c0 > '0' ? c0 - '0' : 0;
{               # for (char c : in[1-]) {
  48-s*\10*+    #   x = x * 10 + (c - '0') * s;
}/              # }
                # return x;

Mine's a little bit shorter, but works basically the same way, although I only multiply the result with the sign at the end. Still, have a +1.

Python, 164 125 121 characters
n=raw_input()
d=[i-48for i in map(ord,n[::-1])if i!=45]
x=0
for i in range(len(d)):x+=d[i]*10**i
if'-'==n[0]:x=-x
print x

Prints out the value with a .0 on the end but that should be all right for the purposes of the exercise, right?  Either way, it's a complete script in and of itself.  Idea's pretty simple: get ASCII values of the characters passed in, convert those to numbers, multiply each digit by a relevant power of 10 and sum the lot.  Test the first character passed in to see if it's negative.
It can almost certainly be shortened but since I'm really new to this whole golfing thing (2nd submission) I reckon it's not bad.
Edit: further golfed by TheRare

i!=45 can written as i>45 since all digits have larger values.The last two lines can be shortened to print[x,-x]['-'==n[0]].

@xnor Or even print[-x,x]['-'<n[0]]

C 75 76 80 chars
p(char*s){int c,r=0,m=*s-45;for(;c=*s++;)r=c<48?r:r*10+c-48;return m?r:-r;}

No checks for valid inputs, as by rule 1.
THX bebe for edit - Now still 1 less

CJam - 14
q(',\-\'0f-Ab*

It assumes the input is signed, that is, it always starts with a "+" or "-".
Try it online at http://cjam.aditsu.net/
q reads the input
( takes out the first character
',\- subtracts it from the ',' character, resulting in 1 for '+' and -1 for '-'
\ swaps the sign with the rest of the number
'0f- subtracts the character '0' from each character, obtaining an integer array
Ab converts this array to a number in base 10 (A=10)
* multiplies the number with the sign
Thanks Runer112

The ASCII codes for + and - are 43 and 45; that's a difference of 2, just like between -1 and 1. You can use this fact to squeeze out two characters, by replacing '+=2*( with 44\-, or using the character literal, ',\-. As a side note, I should really start using a hyper-golfed language like CJam instead of GolfScript... it seems objectively better. No way I can beat your answer with GolfScript.

Haskell - 51 69 chars
p('-':n)= -p n
p n=foldl(\v->(10*v-48+).fromEnum)0n

Python 3  - 92 84
I'm pretty happy with this.
x=lambda n:[1,-1][n<'0']*sum(10**i*(ord(c)-48)for i,c in enumerate(n[n<'0':][::-1]))

Alternatively, without a lambda: (92)
def x(n):j=n[0]=='-';return((j*2-1)*sum(10**i*(ord(c)-48)for i,c in enumerate(n[j:][::-1])))

Thanks to xnor for n<'0'.

You need to deal with negative numbers.

@xnor There, fixed. :)

Mathematica - 33 or 37
Fold[10#+#2&,0,ToCharacterCode@#-48]&

or
FromDigits[ToCharacterCode@#-48]&

if FromDigits is permissible.  FromDigits takes a list of integers and interprets it as the digits of a number (in arbitrary base).
In contrast, Fold can be considered a fundamental part of the language (even though what is fundamental and what isn't is a bit subjective in Mathematica).

AWK, 120 characters
{for(i=0;i<10;i++)o[sprintf("%c",i+48)]=i;for(i=l=length($0);i>0;i--)(c=substr($0,i,1))in o?r+=o[c]*10^(l-i):r=-r;$0=r}1

Usage:
$ echo -0123456789 | awk -f parse-int.awk
-123456789

AWK is a language where numbers are strings. (Perl, Tcl, and the Unix shell are also such languages.) My code is stupid because it pretends that numbers and strings are different.
AWK has no function to convert a string to a code point, so I do the inverse, using sprintf("%c",i+48) to convert a code point to a string. I then loop from 0 to 9, storing o["0"] = 0 through o["9"] = 9 in an associative array. Later, I use o[c] to get the number 9 from the string "9". This is stupid because 9 and "9" are already the same thing.
The usual ways to split a string into characters are with FS="" or split(string,array,""), but these use "" as an empty regular expression, and I can't use regular expressions. So, I use c=substr($0,i,1) to get each character c from the input line $0. I check if c is an index in array o. If yes, I add the product of o[c] and a power of 10 to the result. If no, I assume that c is a negative sign and negate the result.
AWK, 1 character, no parser!
1

Usage:
$ echo -0123456789 | awk 1
-01234567890

This 1-character answer implements all the requirements except for parsing the integer, just by copying input to output.
To print the parsed integer, I must format it as a string. The input is already a valid integer formatted as a string. So I optimize my program to skip the parse!

C (82 chars)
I'm late to the party and I guess my answer is really close to edc's.
int i(char*s){int v=0,n=*s-'-';if(!n)s++;for(;*s;s++)v=v*10+*s-'0';return n?v:-v;}

JavaScript (ECMAScript 6) - 83 80 71 67 Characters
Version 4:
Since the input is always signed (i.e. has a leading + or -) then:
f=x=>(t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t)

However, if it can be unsigned then (+5 characters):
f=x=>(s=-1,t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t)

Version 3:
Since the input is always signed (i.e. has a leading + or -) then:
f=x=>[...x].reduce((p,c)=>(k=48-c.charCodeAt())>0?(s=4-k,0):10*p+k*s,0)

Version 2:
f=x=>[...x].reduce((p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1)

Version 1:
f=x=>[].reduce.call(x,(p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1)

JavaScript (ECMAScript 6) - 8 Characters
JavaScript will implicitly try to convert any variable to a number if you perform an arithmetic operation on it as part of the language (i.e. without using any external libraries). So any of the solutions below will convert a string containing a valid number to a number.
f=x=>~~x
f=x=>x-0
f=x=>x*1
f=x=>x|0

JavaScript (ECMAScript 6) - 7 Characters
f=x=>+x

JavaScript (ECMAScript 6) - 5 Characters
Or as an anonymous function:
x=>+x

+1 for applying an array function over a string. Learn something new every day

Now with the sign handling our soluctions could collide. Beware, the sign is not mandatory: +nnn, -nnn, nnn are handled.

The OP states Assume it to be signed - and then reconfirms this in the comment dated May 30 7:00. Based on this I would say that the sign is mandatory and various other answers have also made that deduction.

Java 7 - 107
Boring and long (typical for Java), but the other Java answer is an embarrassment so I had to remedy the situation.
int p(String i){for(int x=1,l=i.length(),a=0;;a=a*10+i.charAt(x++)-48)if(x==l)return i.charAt(0)==45?-a:a;}

Ungolfed:
int parseInt(String input) {
  for(int index = 1,len = input.length(),accumulator=0,num;;
      num = input.charAt(index) - '0',
      accumulator = accumulator * 10 + num,index++)
    if (index == len) return input.charAt(0)=='-'?-accumulator:accumulator;
}

Fortran - 46 characters
function i(s);character(len=*)s;read(s,*)i;end

Call like:
i('100')

Hmm, this might be close to breaking #4.

Javascript (E6) 80 92
Edit: apply 'reduce' directly, no need to 'split'. Thanks to MTO
Esoteric
Q=S=>(m=1,[].reduce.call(S,(p,x)=>(c=48-x.charCodeAt())>0?(m=c-4)&0:p*10-c*m,0))

Simple loop stay behind at 92
P=S=>{for(n=i=0,m=S[0]>'/'||(S[i++]>'+'?-1:1);d=S.charCodeAt(i++);n=n*10+m*(d-48));return n}

Anyway, assume valid input: first letter can be '-' or '+' or digit, then digits only
... or even
F=S=>1*S

No library function used

Scala, 115 characters
def p(s:String)=((0,1)/:s.reverse){case(a,'+')=>a;case(a,'-')=>(-a._1,0);case((t,n),d)=>(t+(d.toInt-48)*n,n*10)}._1

Ungolfed:
def parseInt(input: String) = ((0, 1) /: input.reverse) {
  case (acc, '+') => acc
  case (acc, '-') => (-acc._1, 0) // place never used again
  case ((total, place), digit) =>
    (total + (digit.toInt - 48) * place, place * 10)
}._1

C# - 82 characters
int p(string t)
{
 var n=t(0)=='-';
 var i=n?1:0;
 var v=0;
 while(i<t.length)
 {
   v=(10*v)+(t(i)-'0');
   i++;
 }
 return n ? -v : v;
}

I think this would also parse a string t into an int.
 var i = t.skip(t(0)=='-'?1:0).Aggregate(0,(p,c)=>(10*p)+(c-'0'))*(t(0)=='-'?-1:1);

J, 41 chars
Here's a J solution that should follow the spec... I'm not very fond of the sign handling; it's too verbose.  I can't think of a more compact way, though.
(u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|.

Sample use:
   atoi =: (u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|.
   atoi '-1234'
_1234

Python 116 108 146
O=b=0
I=list(input())
if I[0]=='-':I.pop(0);b=1
a=range(len(I))
for c in a:I[c]=ord(I[c])-48
for i in a:O+=I[i]*10**(len(I)-i-1)
if b:O=-O
print O

Python 2.7 - 102 bytes
def p(n):
 a,r,l=0,range(10),list(n);d=dict(zip(map(str,r),r))
 while l:a*=10;a+=d[l.pop(0)]
 return a

I believe this is valid, but I'm not 100% sure about rule 3.
Creates a dictionary where the keys are the strings '0', '1', '2'... '9' and the values are the int representing that key. Creates a list of the characters in the input, and assigns ato 0. While the list we made isn't empty, multiply a by 10, take off the first item of that list and use it as a key in the dictionary, adding the value to a. Then just return a.

Java  - 274 Characters
static int parseInt(String arg)
{
    int length = arg.length();
    String reversed = new StringBuilder(arg).reverse().toString();
    int sum = 0;
    for(int i=0; i<length-1; i++)
        sum += (reversed.charAt(i)-48) * Math.pow(10, i);
    if(arg.charAt(0) == '-')
        sum = -1*sum;
    else
        sum += (reversed.charAt(length-1)-48) * Math.pow(10, length-1);
    return sum;
}

Whoops, what a fail :) Sorry for that.

For code-golf, you need to supply the number of bytes/characters. No-one will count them for you, but someone will tell you if you are off by one :-)

By byte, you mean, copy+pase to a text file and write the length?

C 226
Parses positive and negative integers.
#include <stdio.h>
#define P(x) printf("%d",x)
char c;
int n,x,y;
int main()
{
while(((c=getchar())=='-') || ((c>='0')&&(c<='9')))
{
if(c=='-')y=1;
else{
n*=10;
x=c-'0';
n+=x;
}
}
if(y)n=-1*n;
P(n);
getchar();
return 0;
}

Overkill? The number is guaranted valid and a full program is not requested, just a function.

Go - 141 characters
func p(s string) (t int) {
    for i, x := range s {
        y := int(x) - 48
        for j := len(s) - 1; j > i;  j-- {
            y *= 10
        }
        t += y
    }
    return
}

int() here is a straight conversion from a rune (a type identical to int32) to a longer int - and it has to be in the code somewhere to get the function to return an int rather than a rune. The above code is standard go formatting, but technically some of the whitespace is optional.
(If you copy/paste the above, before you count the characters, put it in play.golang.org and hit format.)

in :r4 (http://code.google.com/p/reda4/)
::str>int | str -- int
    0 swap ( c@+ $2f >? )(
        $39 >? ( 2drop ; )
        $30 - rot 10 * + swap )
    2drop ;

is in standard library
http://code.google.com/p/reda4/source/browse/trunk/r4/Lib/parse.txt
line 92

C - 69 characters
c,r,m;p(char*s){for(m=2,r=0;c=15&*s++;r=c>9?m=r:r*10+c);return--m*r;}

J - 19 characters
10#.'0123456789'&i.

No string manipulation at all. Just index each character into the vector of decimal digits, and take the base-10 representation of that array.

Does that handle negative numbers too?  It seems to me it doesn't, but I don't really know J.

Ruby, 43 characters
a=0;$*[0].each_char{|n|a=a*10+n.ord-48};p a

Alternate answer (also 43 characters)
p $*[0].chars.inject(0){|a,b|a*10+b.ord-48}

authors: พิพัฒน์พงศ์ หยังดี


text:
The Star-Spangled Code Challenge
The flag of the United States of America contains, in its canton, 50 stars, representing the 50 states.

In the past, when there were fewer states, there were of course fewer stars, and they were arranged differently.  For example, from 1912-1959 (after the admission of New Mexico and Arizona but before Alaska), there were 48 stars in a 6×8 rectangular arrangement.

The 37-star flag used from 1867-1877 (after the admission of Nebraska but before Colorado) had an asymmetric star pattern.

In case a 51st state is added in the future, the Army Institute of Heraldry has already developed a preliminary design for a new flag.

But there's no general algorithm for arranging the stars, so let's make one!
The challenge
Write a program that will, for a given number of stars to place in the canton (blue part) of a US flag, output optimal coordinates at which to place those stars.  The coordinate system is defined with the canton [not the flag as a whole] with 0≤x≤W and 0≤y≤H.
For the purpose of this challenge, an “optimal” arrangement is defined as one that minimizes the mean (Euclidean) distance between a point in the canton and the center of the nearest star.
A straightforward (if maybe suboptimal) algorithm to approximate this value is:
def mean_distance_to_nearest_star(stars, width, height, point_density=100):
   """
   Approximate the mean distance between a point in the rectangle
   0 < x < width and 0 < y < height, and the nearest point in stars.

   stars -- list of (x, y) points
   width, height -- dimensions of the canton
   """
   total = 0.0
   nx = round(width * point_density)
   ny = round(height * point_density)
   for ix in range(nx):
       x = (ix + 0.5) * width / nx
       for iy in range(ny):
          y = (iy + 0.5) * width / ny
          min_dist = float('inf')
          for sx, sy in stars:
              min_dist = min(min_dist, math.hypot(x - sx, y - sy))
          total += min_dist
   return total / (nx * ny)

Your program shall take three command-line arguments (not counting the program name itself):

The number of stars to put in the canton.
The width of the canton.  (Must accept floating-point values.)
The height of the canton.  (Must accept floating-point values.)

(If your preferred programming language doesn't support command-line arguments, do something reasonably equivalent, and document it in your answer.)
The output should consist of comma-separated X and Y values, one to a line.  (Order of the points doesn't matter.)
For example:
~$ flagstar 5 1.4 1.0
0.20,0.20
0.20,0.80
0.70,0.50
1.20,0.20
1.20,0.80

Additional rules & notes

I have the right to close loopholes in the rules at any time.
Deadline for answers is Friday, July 4 at 24:00 CDT (UTC-05:00).  Due to lack of answers, the deadline has been extended.  TBA.
Include in your answer:

Your program's code
An explanation of how it works
Its output with the command-line arguments 50 1.4 1.0

Your program must run within a reasonable amount of time: At most 5 min on a typical PC.  I won't be ultra-strict about this, but will disqualify your program if it takes hours.
Your program must be deterministic, i.e., always give exactly the same output for the same arguments.  So, don't depend on time() or rand().  Monte Carlo methods are OK as long as you roll your own PRNG.
Only the center points of the stars matter.  Don't worry about trying to avoid overlap or anything like that.

Scoring

Minimize the mean distance from a point in the canton to the nearest star.  (See above.)
You may be scored based on any historical US flags, between 13 and 50 stars.  The exact algorithm for weighting scores into a single ranking will be posted later.
In case of a tie, the winner will be chosen by number of net upvotes.
I will probably post a program of my own, but will exclude myself from being eligible for the checkmark.

@primo: How do you figure that?  My example has a mean distance to the nearest star of 0.289, whereas placing all 5 points in the center has a MDNS of 0.561.

You may disregard my previous commment. I misread mean distance from every point on the canton to the nearest star, as mean distance from every star to the nearest star.

Feel free to include https://jsfiddle.net/nf2mk2gr/ as a Stack Snippet in the question to check the output of answers, if it meets your approval. It displays the mean distance based on an N by N grid, with N progressively increasing the longer you wait. (It was written specifically for this question.)

Javascript - move stars towards most isolated point
(with an animation of the process)
The approach is very simple:

choose a large number of random points
find the nearest star to each
choose the point for which the nearest star is most distant
move that star nearer to that point

This process is repeated a large number of times, gradually decreasing the amount by which the stars are moved. This reduces the maximum distance from a point to the nearest star, indirectly reducing the mean distance from a point to the nearest star.
As required by the question, this does not use the built in random function, instead using xorshift.
Much of the code covers set up and animation - the part that applies the algorithm is the function adjustStars.
Code
You can watch the process in progress in the Stack Snippet below.

stars = [];
timeoutId = 0;

resetRandomNumberGenerator();

function resetRandomNumberGenerator() {
  rng_x = 114; // Numbers for the random number generator.
  rng_y = 342;
  rng_z = 982;
  rng_w = 443;
}

$(document).ready(function() {
  c = document.getElementById('canton');
  ctx = c.getContext('2d');
  resizeCanvas();
});

function stop() {
  clearTimeout(timeoutId);
}

function arrange() {
  clearTimeout(timeoutId);
  resetStars();
  resetRandomNumberGenerator();
  maxStepSize = Math.min(cantonWidth, cantonHeight) / 4;
  adjustStars(maxStepSize, 8000, 10000);
}

function resizeCanvas() {
  cantonWidth = parseFloat($('#width').val());
  cantonHeight = parseFloat($('#height').val());
  starRadius = cantonHeight / 20;
  document.getElementById('canton').width = cantonWidth;
  document.getElementById('canton').height = cantonHeight;
  ctx.fillStyle = 'white';
  resetStars();
}

function resetStars() {
  stop();
  stars = [];
  population = parseInt($('#stars').val(), 10);
  shortSide = Math.floor(Math.sqrt(population));
  longSide = Math.ceil(population / shortSide);
  if (cantonWidth < cantonHeight) {
    horizontalStars = shortSide;
    verticalStars = longSide;
  } else {
    horizontalStars = longSide;
    verticalStars = shortSide;
  }
  horizontalSpacing = cantonWidth / horizontalStars;
  verticalSpacing = cantonHeight / verticalStars;
  for (var i = 0; i < population; i++) {
    x = (0.5 + (i % horizontalStars)) * horizontalSpacing;
    y = (0.5 + Math.floor(i / horizontalStars)) * verticalSpacing;
    stars.push([x, y]);
  }
  drawStars();
  updateOutputText();
}

function adjustStars(stepSize, maxSteps, numberOfPoints) {
  $('#stepsRemaining').text(maxSteps + ' steps remaining');
  points = randomPoints(numberOfPoints);
  mostIsolatedPoint = 0;
  distanceToNearestStar = 0;
  for (var i = 0; i < numberOfPoints; i++) {
    point = points[i];
    x = point[0];
    y = point[1];
    star = stars[nearestStar(x, y)];
    d = distance(x, y, star[0], star[1]);
    if (d > distanceToNearestStar) {
      distanceToNearestStar = d;
      mostIsolatedPoint = i;
    }
  }
  point = points[mostIsolatedPoint];
  x = point[0];
  y = point[1];

  starToMove = nearestStar(x, y);

  star = stars[starToMove];
  separationX = x - star[0];
  separationY = y - star[1];
  if (separationX || separationY) {
    hypotenuse = distance(x, y, star[0], star[1]);
    currentStep = Math.min(stepSize, hypotenuse / 2);
    deltaX = currentStep * separationX / hypotenuse;
    deltaY = currentStep * separationY / hypotenuse;
    star[0] += deltaX;
    star[1] += deltaY;
    if (star[0] < 0) star[0] = 0;
    if (star[0] > cantonWidth) star[0] = cantonWidth;
    if (star[1] < 0) star[1] = 0;
    if (star[1] > cantonHeight) star[1] = cantonHeight;

    drawStars();
    updateOutputText();
  }

  if (maxSteps > 0) {
    timeoutId = setTimeout(adjustStars, 10, stepSize * 0.9992, maxSteps - 1, numberOfPoints);
  }
}

function updateOutputText() {
  starText = '';
  for (var i = 0; i < stars.length; i++) {
    starText += stars[i][0] + ', ' + stars[i][1] + '\n';
  }
  $('#coordinateList').text(starText);
}

function randomPoints(n) {
  pointsToReturn = [];
  for (i = 0; i < n; i++) {
    x = xorshift() * cantonWidth;
    y = xorshift() * cantonHeight;
    pointsToReturn.push([x, y]);
  }
  return pointsToReturn;
}

function xorshift() {
  rng_t = rng_x ^ (rng_x << 11);
  rng_x = rng_y;
  rng_y = rng_z;
  rng_z = rng_w;
  rng_w = rng_w ^ (rng_w >> 19) ^ rng_t ^ (rng_t >> 8);
  result = rng_w / 2147483648
  return result
}

function nearestStar(x, y) {
  var distances = [];
  for (var i = 0; i < stars.length; i++) {
    star = stars[i];
    distances.push(distance(x, y, star[0], star[1]));
  }
  minimum = Infinity;
  for (i = 0; i < distances.length; i++) {
    if (distances[i] < minimum) {
      minimum = distances[i];
      nearest = i;
    }
  }
  return nearest;
}

function distance(x1, y1, x2, y2) {
  var x = x2 - x1;
  var y = y2 - y1;
  return Math.sqrt(x * x + y * y);
}

function drawStars() {
  ctx.clearRect(0, 0, cantonWidth, cantonHeight);
  for (i = 0; i < stars.length; i++) {
    star = stars[i];
    x = star[0];
    y = star[1];
    drawStar(x, y);
  }
}

function drawStar(x, y) {
  ctx.beginPath();
  ctx.moveTo(x, y - starRadius);
  ctx.lineTo(x - 0.588 * starRadius, y + 0.809 * starRadius);
  ctx.lineTo(x + 0.951 * starRadius, y - 0.309 * starRadius);
  ctx.lineTo(x - 0.951 * starRadius, y - 0.309 * starRadius);
  ctx.lineTo(x + 0.588 * starRadius, y + 0.809 * starRadius);
  ctx.fill();
}
canvas {
  margin: 0;
  border: medium solid gray;
  background-color: blue;
}

<input id='stars' onchange='resetStars()' type='number' value='13' min='13' max='50' maxlength='2' step='1'>stars

<input id='width' onchange='resizeCanvas()' type='number' value='494' min='1' max='500' maxlength='3' step='any'>width

<input id='height' onchange='resizeCanvas()' type='number' value='350' min='1' max='500' maxlength='3' step='any'>height

<button type='button' onclick='resetStars()'>Reset Stars</button>
<button type='button' onclick='arrange()'>Arrange Stars</button>
<button type='button' onclick='stop()'>Stop</button>
<textarea id='stepsRemaining' rows='1' readonly></textarea>

<canvas id='canton' width='494' height='350'></canvas>

<textarea id='coordinateList' rows='50' cols='40' readonly></textarea>

Output for 50 stars
(width = 1.4, height = 1.0)
Mean distance estimated at 0.0655106697162357.
Coordinates:
0.028377044205135808, 0.2128159150679491
0.10116766857540277, 0.05156676609341312
0.2903566419069437, 0.07216263690037035
0.49154061258041604, 0.004436102736309105
0.6930026352073071, 0.07060477929576484
1.0988644764108417, 0.022979778480838074
1.1735677936511582, 0.18600858289592742
1.3056806950504931, 0.062239869036660435
0.3967626880807638, 0.24483447327177033
0.27004118129346155, 0.40467589936498805
0.4996665039421278, 0.13023282430440133
0.5148978532656602, 0.6161298793146592
0.5907056537744844, 0.2614323599301046
0.8853042432872087, 0.048123917861564044
0.7753680330575412, 0.22938793622044834
1.365432954694329, 0.2355377720528128
0.1985172068244217, 0.23551298706793927
0.4477558465270544, 0.4170264112485973
0.6084424566752479, 0.7764909501169484
0.6099528761580699, 0.4395002434593519
0.9506038166406011, 0.34903243854585914
1.1898331497634231, 0.5756784243472182
1.0933574395540542, 0.46422120794648786
1.1516574254138159, 0.2930213338333888
0.07646053006349718, 0.40665000611360175
0.0634456093015551, 0.5853189455014883
0.3470036636019768, 0.5938838331082922
0.7591083341283029, 0.4005456925638841
0.9745306853981277, 0.184624209972443
1.3552011948311598, 0.549607060691302
1.3334000268566828, 0.7410204535471169
1.2990417572304487, 0.39571229988825735
0.05853941030364222, 0.7734808757471414
0.19396697551982484, 0.5678753467094985
0.7103231124251072, 0.5955041661956884
0.6168410756137566, 0.948561537739087
0.8967624790188228, 0.5368666961690878
0.9751229155529001, 0.8323724819557795
0.9987127931392165, 0.652902038374714
1.3231032600971289, 0.9164326184290812
0.20785221980162555, 0.7566700629874374
0.3987967842137651, 0.7678025218448816
0.44395949605458546, 0.9137553802571048
0.775611700149756, 0.9029717946067138
0.806442448003616, 0.7328147396477286
0.9481952441521928, 0.9872963855418118
1.1528689317425114, 0.9346775634274639
1.1651295140721658, 0.7591158327925681
0.09316709042512515, 0.934205211493484
0.2769325337580081, 0.9341145493466471

After running your animation with various numbers of stars, it seems like it has a tendency to put stars close to the edges of the box.  However, not knowing the true optimum arrangement, I can't tell whether this is a bug or a feature.

@dan04 nor me - I have an idea of why it happens though. The stars near the edge are too close to it for there to be a significant probability of them moving towards it (stars mostly move towards the most isolated points, not points nearby). But they can still move towards the edge indirectly, by alternating between moving towards two distant points near the edge, resulting in a zigzag path. I suspect this means that it is necessary to have stars near the edges, but I'm looking forward to seeing another approach to see if that shares the bug/feature...

@dan04 my second answer seems to show that the stars don't need to be as near to the edges as I thought, and gives better results than my first answer. Working directly with the mean rather than indirectly through the maximum turns out to be more effective.

Here's a simple example.  It always arranges the stars into a rectangular grid, and optimizes it by choosing the factorization in which the grid cells are as close to square as possible.  It works great when the number of stars has a divisor close to its square root, and pessimally when the number of stars is prime.
from __future__ import division
import math
import sys

def divisors(n):
    """
    Return all divisors of n (including n itself) as a set.
    """
    result = {1, n}
    # Use +2 instead of +1 to allow for floating-point error.
    for i in range(2, int(math.sqrt(n)) + 2):
        if n % i == 0:
            result.add(i)
            result.add(n // i)
    return result

def squareness(width, height):
    """
    Given the dimensions of a rectangle, return a value between 0 and 1
    (1 iff width == height) measuring how close it is to being a square.
    """
    if width and height:
        return min(width / height, height / width)
    else:
        return 0.0

def star_grid(num_stars, width, height):
    """
    Return the factors (x, y) of num_stars that optimize the mean
    distance to the nearest star.
    """
    best_squareness = 0.0
    best_dimensions = (None, None)
    for nx in divisors(num_stars):
        ny = num_stars // nx
        sq = squareness(width / nx, height / ny)
        if sq > best_squareness:
            best_squareness = sq
            best_dimensions = (nx, ny)
    return best_dimensions

def star_coords(num_stars, width, height):
    """
    Return a list of (x, y) coordinates for the stars.
    """
    nx, ny = star_grid(num_stars, width, height)
    for ix in range(nx):
        x = (ix + 0.5) * width / nx
        for iy in range(ny):
            y = (iy + 0.5) * height / ny
            yield (x, y)

def _main(argv=sys.argv):
    num_stars = int(argv[1])
    width = float(argv[2])
    height = float(argv[3])
    for coord in star_coords(num_stars, width, height):
        print('%g,%g' % coord)

if __name__ == '__main__':
    _main()

Output for 50 stars
(width = 1.4, height = 1.0)
A 10×5 rectangle.
0.07,0.1
0.07,0.3
0.07,0.5
0.07,0.7
0.07,0.9
0.21,0.1
0.21,0.3
0.21,0.5
0.21,0.7
0.21,0.9
0.35,0.1
0.35,0.3
0.35,0.5
0.35,0.7
0.35,0.9
0.49,0.1
0.49,0.3
0.49,0.5
0.49,0.7
0.49,0.9
0.63,0.1
0.63,0.3
0.63,0.5
0.63,0.7
0.63,0.9
0.77,0.1
0.77,0.3
0.77,0.5
0.77,0.7
0.77,0.9
0.91,0.1
0.91,0.3
0.91,0.5
0.91,0.7
0.91,0.9
1.05,0.1
1.05,0.3
1.05,0.5
1.05,0.7
1.05,0.9
1.19,0.1
1.19,0.3
1.19,0.5
1.19,0.7
1.19,0.9
1.33,0.1
1.33,0.3
1.33,0.5
1.33,0.7
1.33,0.9

Javascript - move a star randomly if mean distance is reduced
(with an animation of the process)
This doesn't give such a busy animation as my first answer, having long periods with no movement as potential rearrangements are tested and rejected. However, the final result has a lower mean distance, so this method is an improvement.
The approach is still very simple:

Choose a star at random
Move it a random distance in a random direction
If the mean distance is reduced, keep the new position

This process is repeated a large number of times, gradually decreasing the amount by which the stars are moved. The random choice of distance to move is biased towards smaller distances, so progress is in small alterations interspersed with the occasional larger jump. Each step takes longer than in my first answer, as measuring the mean distance is a slow process requiring sampling the entire canton.
As required by the question, this does not use the built in random function, instead using xorshift.
Much of the code covers set up and animation - the part that applies the algorithm is the function adjustStars.
Code
You can watch the process in progress in the Stack Snippet below.

stars = [];
timeoutId = 0;

resetRandomNumberGenerator();

function resetRandomNumberGenerator() {
  rng_x = 114; // Numbers for the random number generator.
  rng_y = 342;
  rng_z = 982;
  rng_w = 443;
}

$(document).ready(function() {
  c = document.getElementById('canton');
  ctx = c.getContext('2d');
  resizeCanvas();
});

function stop() {
  clearTimeout(timeoutId);
}

function arrange() {
  clearTimeout(timeoutId);
  resetStars();
  resetRandomNumberGenerator();
  maxStepSize = Math.min(cantonWidth, cantonHeight) / 16;
  adjustStars(maxStepSize, 7000, 15000);
}

function resizeCanvas() {
  cantonWidth = parseFloat($('#width').val());
  cantonHeight = parseFloat($('#height').val());
  starRadius = cantonHeight / 20;
  document.getElementById('canton').width = cantonWidth;
  document.getElementById('canton').height = cantonHeight;
  ctx.fillStyle = 'white';
  resetStars();
}

function resetStars() {
  stop();
  stars = [];
  population = parseInt($('#stars').val(), 10);
  shortSide = Math.floor(Math.sqrt(population));
  longSide = Math.ceil(population / shortSide);
  if (cantonWidth < cantonHeight) {
    horizontalStars = shortSide;
    verticalStars = longSide;
  } else {
    horizontalStars = longSide;
    verticalStars = shortSide;
  }
  horizontalSpacing = cantonWidth / horizontalStars;
  verticalSpacing = cantonHeight / verticalStars;
  for (var i = 0; i < population; i++) {
    x = (0.5 + (i % horizontalStars)) * horizontalSpacing;
    y = (0.5 + Math.floor(i / horizontalStars)) * verticalSpacing;
    stars.push([x, y]);
  }
  drawStars();
  updateOutputText();
}

function adjustStars(stepSize, maxSteps, numberOfPoints) {
  $('#stepsRemaining').text(maxSteps + ' steps remaining');
  var points = randomPoints(numberOfPoints);
  currentMean = meanDistance(stars, points);
  potentialStars = shiftedStars(stepSize);
  potentialMean = meanDistance(potentialStars, points);
  if (potentialMean < currentMean) {
    stars = potentialStars;
  }
  drawStars();
  updateOutputText();

  if (maxSteps > 0) {
    timeoutId = setTimeout(adjustStars, 10, stepSize * 0.999, maxSteps - 1, numberOfPoints);
  }
}

function shiftedStars(stepSize) {
  shifted = [];
  chosenOne = Math.floor(xorshift() * stars.length);
  for (i = 0; i < stars.length; i++) {
    star = stars[i];
    x = star[0];
    y = star[1];
    if (i === chosenOne) {
      for (n = 0; n < 10; n++) {
        x += xorshift() * stepSize;
        x -= xorshift() * stepSize;
        y += xorshift() * stepSize;
        y -= xorshift() * stepSize;
      }
      if (x < 0) x = 0;
      if (x > cantonWidth) x = cantonWidth;
      if (y < 0) y = 0;
      if (y > cantonHeight) y = cantonHeight;
    }
    shifted.push([x, y]);
  }
  return shifted;
}

function meanDistance(arrayOfStars, arrayOfPoints) {
  var totalDistance = 0;
  for (i = 0; i < arrayOfPoints.length; i++) {
    point = arrayOfPoints[i];
    x = point[0];
    y = point[1];
    totalDistance += nearestStarDistance(x, y, arrayOfStars);
  }
  return totalDistance / arrayOfPoints.length;
}

function randomPoints(numberOfPoints) {
  var arrayOfPoints = [];
  for (i = 0; i < numberOfPoints; i++) {
    x = xorshift() * cantonWidth;
    y = xorshift() * cantonHeight;
    arrayOfPoints.push([x, y]);
  }
  return arrayOfPoints;
}

function updateOutputText() {
  starText = '';
  for (var i = 0; i < stars.length; i++) {
    starText += stars[i][0] + ', ' + stars[i][1] + '\n';
  }
  $('#coordinateList').text(starText);
}

function xorshift() {
  rng_t = rng_x ^ (rng_x << 11);
  rng_x = rng_y;
  rng_y = rng_z;
  rng_z = rng_w;
  rng_w = rng_w ^ (rng_w >> 19) ^ rng_t ^ (rng_t >> 8);
  result = rng_w / 2147483648
  return result
}

function nearestStarDistance(x, y, starsToUse) {
  var distances = [];
  for (var i = 0; i < stars.length; i++) {
    star = starsToUse[i];
    distances.push(distance(x, y, star[0], star[1]));
  }
  minimum = Infinity;
  for (i = 0; i < distances.length; i++) {
    if (distances[i] < minimum) {
      minimum = distances[i];
    }
  }
  return minimum;
}

function distance(x1, y1, x2, y2) {
  var x = x2 - x1;
  var y = y2 - y1;
  return Math.sqrt(x * x + y * y);
}

function drawStars() {
  ctx.clearRect(0, 0, cantonWidth, cantonHeight);
  for (i = 0; i < stars.length; i++) {
    star = stars[i];
    x = star[0];
    y = star[1];
    drawStar(x, y);
  }
}

function drawStar(x, y) {
  ctx.beginPath();
  ctx.moveTo(x, y - starRadius);
  ctx.lineTo(x - 0.588 * starRadius, y + 0.809 * starRadius);
  ctx.lineTo(x + 0.951 * starRadius, y - 0.309 * starRadius);
  ctx.lineTo(x - 0.951 * starRadius, y - 0.309 * starRadius);
  ctx.lineTo(x + 0.588 * starRadius, y + 0.809 * starRadius);
  ctx.fill();
}
canvas {
  margin: 0;
  border: medium solid gray;
  background-color: blue;
}

<input id='stars' onchange='resetStars()' type='number' value='13' min='13' max='50' maxlength='2' step='1'>stars

<input id='width' onchange='resizeCanvas()' type='number' value='494' min='1' max='500' maxlength='3' step='any'>width

<input id='height' onchange='resizeCanvas()' type='number' value='350' min='1' max='500' maxlength='3' step='any'>height

<button type='button' onclick='resetStars()'>Reset Stars</button>
<button type='button' onclick='arrange()'>Arrange Stars</button>
<button type='button' onclick='stop()'>Stop</button>
<textarea id='stepsRemaining' rows='1' readonly></textarea>

<canvas id='canton' width='494' height='350'></canvas>

<textarea id='coordinateList' rows='50' cols='40' readonly></textarea>

Output for 50 stars
(width = 1.4, height = 1.0)
Mean distance estimated at 0.06402754713808706.
Coordinates:
0.08147037630270487, 0.07571240182553095
0.24516777356538358, 0.0803538189052793
0.431021735247462, 0.07821284835132788
0.6001163609128221, 0.08278495286739646
0.7668077034213632, 0.0821321119375313
0.941333266969696, 0.08040530195264808
1.1229190363750599, 0.07255685332834291
1.3074771164489858, 0.07681674948141588
0.09227450444336446, 0.2257047798057907
0.33559513774978766, 0.20668611954667682
0.5182463448452704, 0.23841239342827816
0.6630614113293541, 0.26097114328053417
0.821886619004045, 0.23577904321258844
1.012597304977012, 0.23308200382761057
1.174938874706673, 0.22593017096601203
1.3285181935709358, 0.24024108928169902
0.0746772556909648, 0.3920030109869904
0.23006559905554042, 0.3204287339854068
0.4086004105498357, 0.3507788129168045
0.5669847710831315, 0.4371913211100495
0.7399474422203116, 0.41599441829489137
0.9099913571857917, 0.36933063808924294
1.1170137101288482, 0.3905679602615213
1.3037811235560612, 0.3979526346564911
0.09290206345982034, 0.5678420747594305
0.23463227399157258, 0.47552307265325633
0.4042403660145938, 0.5030345851947539
0.6611151741402685, 0.5918138006294138
0.8237963249937061, 0.5663224022272697
0.9812774216782155, 0.5032518469083094
1.146386501309064, 0.570255729516661
1.3185563715676663, 0.5571870810112576
0.07541940949872694, 0.7356649763259809
0.2877585652075202, 0.6321535875762999
0.4952646673275116, 0.6343336480073624
0.6965646728710738, 0.9178076185211137
0.7903485281657828, 0.7508031981325222
0.9774998621426763, 0.6683301268754337
1.1539480102558823, 0.7513836972857155
1.3177199931376755, 0.7245296168327016
0.22215183098388988, 0.7769843436963862
0.4048364942297627, 0.7779653803681718
0.5021290208205218, 0.9254525763987298
0.6058821167972933, 0.7683130432395833
0.8777330967719849, 0.9201076171801651
0.9894820530574747, 0.8172934111543102
1.1143371956097312, 0.9265012354173626
1.3045771339439551, 0.9069856484512913
0.0930066325438706, 0.9157592790749175
0.2959676633891297, 0.9251379492518523