title: Random without Time-Basis

text:
# Question
Title: Random without Time-Basis
Computers do not out-of-nowhere create random numbers without basis, as most likely, time is the universal basis of randomness.

I want you to create a code that creates random numbers with these rules:

* Time is not allowed to be the basis, at any point of the program.
* Predefined random/pseudo-random functions are not allowed.
* Numbers generated can be within any range. *Well at least two different integers :D*
* Numbers are echoed.

# Answer
# JavaScript

That was fun!

```
arr = []
index = 0

function init(seed) {
    index = 0
    arr[0] = seed
    for (var i = 1; i < 624; i ++) {
        arr[i] = (1812433253 * (arr[i-1] ^ (arr[i-1] >>> 30)) + i) | 0
    }
 }

function getNumber() {
    if (index == 0) generateNumbers()

    var y = arr[index]
    y ^= (y >>> 11)
    y ^= ((y << 7) & 2636928640)
    y ^= ((y << 15) & 4022730752)
    y ^= (y >>> 18)

    index = (index + 1) % 624
    return y
}

function generateNumbers() {
    for (var i = 0; i < 624; i ++) {
        var y = (arr[i] & 0x80000000) + (arr[(i+1) % 624] & 0x7fffffff)
        arr[i] = arr[(i + 397) % 624] ^ (y >>> 1)
        if (y % 2 != 0) arr[i] ^= 2567483615
    }
}

// let's get our seed now from the SE API
var x = new XMLHttpRequest()
x.open('GET', 'http://api.stackexchange.com/2.2/answers?pagesize=10&order=desc&sort=activity&site=stackoverflow&filter=!Sri2UzKb5mTfr.XgjE', false)
x.send(null)
// we've got the answer data, now just add up all the numbers.
// only 4 digits at a time to prevent too big of a number.
var seed = 0
var numbers = x.responseText.match(/\d{0,4}/g)
for (var i = 0; i < numbers.length; i++) seed += +numbers[i]

init(seed)
for (var i = 0; i < 10; i++) console.log(getNumber())

```

I wrote up the Mersenne Twister in JS. Then, I realized I had to get a seed from somewhere.

So, I decided I would get it from the Stack Exchange API! (I could use `localStorage` and increment a counter, but that's no fun.) So, I grabbed the 10 most recently active answers, and then I just took every 4 or less consecutive digits in the response and added them up.

These seeds are always different, since Stack Overflow is constantly updating (and my quota keeps going down!) The numbers include answer IDs, question IDs, scores, up/downvote counts, owner rep/IDs, and the wrapper data (quota and such). On one run I got `256845`, then `270495`, and then `256048`, etc....

This logs 10 random 32-bit two's-complement numbers to the console. Sample output:

```
247701962
-601555287
1363363842
-1184801866
1761791937
-163544156
2021774189
2140443959
1764173996
-1176627822

```
> 6 votes

# Answer
# **C**

Compile with the -pthread flag (or whatever your compiler uses).

```
#include <stdio.h>
#include <pthread.h>

#define m (unsigned long)2147483647
#define q (unsigned long)127773
#define a (unsigned int)16807
#define r (unsigned int)2836

static unsigned long seed;
pthread_t t[20];
int lo, hi, done;

void *pseudorandom(void *id)
{
    while(done)
    {
        int test;
        hi = seed/q;
        lo = seed%q;
        test = a * lo - r * hi;
        if (test > 0) seed = test;
        else seed = test + m;
    }
}

main()
{
     int i;
     seed = 54321;
     done = 1;

     for(i = 0; i < 20; i++)
     {
          pthread_create(&(t[i]), NULL, &pseudorandom, NULL);
     }

     for (i = 0; i < 10; i++)
     {
          printf("%lu\n", seed);
     }

     done = 0;
}

```

I'm not sure if this qualifies or not based on the "time is not allowed" standard, because it is basically using the scheduler as the source of entropy by intentionally ignoring thread safety. It works by using a fairly basic psuedo-random function (Lehmer random number generator) with a hard coded initial seed. It then starts 20 threads that all run the Lehmer calculation with a shared set of variables.

Seems to work fairly well, here are a couple of consecutive runs:

```
comintern ~ $ ./a.out
821551271
198866223
670412515
4292256
561301260
1256197345
959764614
874838892
1375885882
1788849800
comintern ~ $ ./a.out
2067099631
953349057
1736873858
267798474
941322622
564797842
157852857
1263164394
399068484
2077423336

```

**EDIT:** Gave this a little more thought and realized that this isn't time based at all. Even with a completely deterministic scheduler, the entropy isn't coming from the time slices - it is coming from the loading of all the running processes on the system.

**EDIT 2** After taking some inspiration from @Quincunx posting a bell curve, I dumped 12MB of randomness into a file and uploaded it to CAcert. It failed all of the diehard tests, but clocked a respectable 7.999573 out of 8 on the ENT test (only *Potentially* deterministic). Curiously, doubling the thread count made it worse.
> 5 votes

# Answer
# Java

```
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @author Quincunx
 */
public class NoTimeRandom extends Random {

    private AtomicLong seed;

    public NoTimeRandom() {
        byte[] ba = (new String[0].toString() + new String[0].toString()
                + new String[0].toString() + new String[0].toString()
                + new String[0].toString() + new String[0].toString()).getBytes();
        int seed1 = 1;
        for (byte b : ba) {
            seed1 += b;
        }

        ba = (new String[0].toString() + new String[0].toString()
                + new String[0].toString() + new String[0].toString()
                + new String[0].toString() + new String[0].toString()).getBytes();
        long seed2 = 1;
        for (byte b : ba) {
            seed2 += b;
        }

        seed = new AtomicLong(seed1 ^ seed2);
    }

    @Override
    protected int next(int bits) {
        long oldseed, newseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            newseed = (oldseed * 25214903917L + 11) & 281474976710655L;
        } while (!seed.compareAndSet(oldseed, newseed));

        return (int) (newseed >>> (48 - bits));
    }

    public static void main(String[] args) {
        Random r = new NoTimeRandom();

        for (int i = 0; i < 5; i++) {
            System.out.println(r.nextInt());
        }
    }

}

```

The magic is in the `public NoTimeRandom()`. Arrays cast to strings can confuse new programmers, as the numbers are random. Sample (for `char[]`: `[C@4a8e91eb`). The `next` method is copied from `java.util.Random`.

Sample output:

```
134277366
467041052
-555611140
-1741034686
1420784423

```

---

Let's test the effectiveness of this rng:

In my answer to *Approximate a Bell Curve*, the data generation I used depends on a good rng. Let's run it with this as the rng. Output:

Just as I thought. This is a pretty lousy rng.
> 5 votes

# Answer
# C

It generates a random number in the 0-255 range by taking the seed from https://stackoverflow.com/questions using `wget`.

```
#include <stdio.h>
main()
{
    FILE *file;
    unsigned char c,x;
    system("wget -O - https://stackoverflow.com/questions > quest.html");
    file = fopen ("quest.html", "r");
    while(c=fgetc(file) != EOF) x+=c;
    fclose(file);
    printf("%d",x);
}

```

Sample run:

```
C:\Users\izabera>random
--2014-03-02 16:15:28--  https://stackoverflow.com/questions
Resolving stackoverflow.com... 198.252.206.140
Connecting to stackoverflow.com|198.252.206.140|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 85775 (84K) [text/html]
Saving to: `STDOUT'

100%[======================================>] 85,775      40.3K/s   in 2.1s

2014-03-02 16:15:31 (40.3 KB/s) - `-' saved [85775/85775]

15 /* <=================== THIS IS THE RANDOM NUMBER */
C:\Users\izabera>random
--2014-03-02 16:15:36--  https://stackoverflow.com/questions
Resolving stackoverflow.com... 198.252.206.140
Connecting to stackoverflow.com|198.252.206.140|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 85836 (84K) [text/html]
Saving to: `STDOUT'

100%[======================================>] 85,836      50.0K/s   in 1.7s

2014-03-02 16:15:38 (50.0 KB/s) - `-' saved [85836/85836]

76
C:\Users\izabera>random
--2014-03-02 16:15:56--  https://stackoverflow.com/questions
Resolving stackoverflow.com... 198.252.206.140
Connecting to stackoverflow.com|198.252.206.140|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 85244 (83K) [text/html]
Saving to: `STDOUT'

100%[======================================>] 85,244      36.0K/s   in 2.3s

2014-03-02 16:15:59 (36.0 KB/s) - `-' saved [85244/85244]

144

```
> 4 votes

# Answer
# C++

```
#include<iostream>
int main()
{
    int *ptr=new int,i=0;
    for(;i<5;i++)
    {
        std::cout<<*(ptr+i)<<'\n';
    }
    return 0;
}

```

### output

any 5 random numbers

three samples
> 2 votes

# Answer
**Javascript**
Generating random with user mouse move

```
var ranArr=[];
var random=0;
var first=second=0;
function generateR(event) {
ranArr.push(parseFloat(event.clientX+document.body.scrollLeft))
ranArr.push(parseFloat(event.clientY+document.body.scrollTop));
var len=ranArr.length;

for(var i=0;i<len;i++) {
    if(i<len/2) {

    first+=ranArr[i];
    } else {
    second += ranArr[i];
    }
}
third = second/first;
third = third+"";
console.log(third.substr(5));
}
document.onmousemove=function(event){generateR(event)};

```

Last five copied data:
9637090187003
7828470680762
6045869361238
4220720695015
2422653391073
> 2 votes

# Answer
# perl

What's all this rubbish with getting seeds over the internet? Sounds like cheating to me ;-) I prefer to give my seed to a cryptographic hash function instead, and give output in the range 0 to 2^160-1 like so:

```
use Digest::SHA1 qw(sha1);
use bigint;
sub r {
  $_ = \3;
  /^.*x([0-9a-f]+).$/;
  hex((unpack "H*", sha1 "some_salt".$1.$$)[0])
}
print join " ", r'

```

Anytime you have entropy of uncertain quality, a way to distribute it more regularly (but not increase its quality!) is to pipe it into the likes of SHA1 or MD5 or so, as I've done here. For pre-hash seeds, I've used pid and the address of a random reference. You could of course add other inputs for more entropy, eg on x86 you can use TSC - (but inlining assembly code in perl is a bit of a bear, so I skipped it).

If you want to have different output than the guy on the next computer over, simply adjust "some\_salt" to be a string of your liking. Or leave it out altogether if you are a minimalist =)
> 2 votes

# Answer
# Java

My solution abuses `hashCode()` method of `Object` class.

```
class G22640 {
    static class Rand {
        public int nextInt() {
            return new Object().hashCode();
        }
    }

    public static void main(String args[]) {
        Rand r = new Rand();
        for (int i = 0; i < 10; i++) {
            System.out.println(r.nextInt());
        }
    }
}

```

Sample output:

```
31859448
22101035
11593610
4580332
25736626
32157998
3804398
32440180
19905449
2772678

```

---

Motivated by other answer's demonstrating the randomness of the solution, I changed my solution to return the middle 16 bits of the `int` returned by `Object.hashCode()`.

```
import java.io.*;

class G22640 {
    static class Rand {
        public short nextShort() {
            return (short) ((new Object().hashCode() >> 8) & 0xFFFF);
        }
    }

    public static void main(String args[]) throws IOException {
        Rand r = new Rand();

        for (int i = 0; i < 10; i++) {
            System.out.println(r.nextShort());
        }

        // generateToFile("random_22640.txt");
    }

    private static void generateToFile(String fileName) throws IOException {
        Rand r = new Rand();
        BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(fileName));

        for (int i = 0; i < 10000000; i++) {
            int a = r.nextShort();
            for (int j = 0; j < 2; j++) {
                o.write(a & 0xFF);
                a >>= 8;
            }
        }

        o.flush();
        o.close();
    }
}

```

I generated a 19 MB file (consisting of 107 `short`) and submit it to CACert. Here is the screenshot of the result (it has been edited to look nice, but the numbers are left as it is):

I was surprised at the result, since it clocks 7.999991 at Entropy test and passes (?) all 7 Diehard tests.
> 2 votes

# Answer
**Bash, range: ints between 0 and 1**

```
echo -n & echo "$! % 2" | bc

```
> 1 votes

# Answer
**Ruby**

Unfortunately Mac only. We use `sox` to pull bytes from the microphone (as a string, ahem...), reverse it to get the status header on the end (\*cough\*), chop it up, chop off the header, take the MD5 of the chunks, ditch the non-numeric chars from the hash, add the remaining largish integers together, stick a `0.` on the front, convert to a float, done.

Generates floats of varying length on the interval `0..1`.

```
require 'open3'
require 'digest'

class InsecureRandom
  def self.random_number
    n = self.get_bytes
    .map! { |r| Digest::MD5.hexdigest(r) }
    .map! { |r| r.gsub(/[a-z]/, '') }
    .map!(&:to_i)
    .reduce(0,:+)

    "0.#{n}".to_f
  end

  private
  def self.get_bytes
    Open3.popen3('sox -d -q -e unsigned-integer -p') do |_, stdout, _|
      stdout.read(20000).reverse.split('\\').to_a.take(20)
    end
  end
end

randomish = Array.new(20) { InsecureRandom.random_number }
puts randomish
# >> 0.2333530765409607
# >> 0.17754047429753905
# >> 0.936039801228352
# >> 0.2781141892158962
# >> 0.6243140263525706
# >> 0.1583419168189452
# >> 0.2173713056635174
# >> 0.930577106355
# >> 0.11215268787922089
# >> 0.13292311877287152
# >> 0.14791818448435443
# >> 0.4864648362730452
# >> 0.5133193113765809
# >> 0.3076637743531015
# >> 0.16060112015793476
# >> 0.7294970251624926
# >> 0.18945368886946876
# >> 0.9970215825154781
# >> 0.13775531752383308
# >> 0.5794383903900283

```
> 1 votes

# Answer
**C**

Generating random using process ID.

```
#include <unistd.h>
#include <stdio.h>

int     main(void)
{
    int out;
    out *= out *= out = getpid();
    printf("%d\n", out % 1024);
    return (0);
}

```

Sample output :

```
-767
0
769
-1008
337
-768
369
-752
-415
0
-863
784
-463
256
657

```
> 1 votes

# Answer
# SPIN

If this was , i would win!

```
byte a
?a@

```
> 1 votes

# Answer
# python

Python's conciseness never ceases to amaze. Since using imgur's random image is not valid apparently, I've used a great source of randomness: stackoverflow's chat!

```
   import urllib.request

def getrand():
    req = urllib.request.Request("http://chat.stackoverflow.com/")
    response = urllib.request.urlopen(req)
    the_page = str(response.read())

    x = 1
    for char in the_page:
        x = (3*x + ord(char) + 1)%2**32

    print(x)

```

5 trials:

```
3258789746
1899058937
3811869909
274739242
1292809118

```

Not truly random but then again none of these are.
> 0 votes

# Answer
# perl

I saw a lot of answers which made HTTP requests, which seems wasteful to me because under the covers there are random numbers being passed about on the wire. So I decided to write some code to swipe one at a lower level:

```
use IO::Socket::INET;
print ((sockaddr_in(getsockname(IO::Socket::INET->new(
    PeerAddr => "google.com", PeerPort => 80, Proto => "tcp"
))))[0]);

```

Gives random ports in the range 0..65535, theoretically. In practice, there are a number of ports you will never see, so the distribution is far from perfect. But it is, AFAICT the minimal amount of work you can do to get some entropy from a remote host that has a port open.

PS - Error handling is left as an exercise to the reader ;-)
> 0 votes

# Answer
# C

```
// alternating two pure-RNG inspired by http://xkcd.com/221/
int getRandomNumber()
{
   static int dice_roll = 0;
   dice_roll++;
   if ((dice_roll % 2) == 1)
   {
      return 4;
   }
   else
   {
      return 5;
   }
}

int main(int argc, char **argv)
{
    printf("%d\n%d\n", getRandomNumber(), getRandomNumber())
    return 0;
}

```
> 0 votes

---
Tags: popularity-contest
---


# Question
Title: Implementing bool() without any conditionals
Title says it all. Given some input, turn it into a boolean value (0 or 1), without using conditional statements (e.x. `== > < <= >= != ~=`), or any function which uses conditional statements within its implementation, such as `if`, `while` and `for`. Your program must work with floating points, although you get more if it works with other items.

A general rule for determining whether `bool(item)` is False is if the item is empty (`''` is an empty string, `[]` is an empty list.), or if the function used to turn an item of one type into another is given no input (in Python, `str()` returns `''`, `list()` returns `[]`.)

Here are (some of) the different valid types. Your program is considered to work with one type if it works with one item in the following lists:

* Integers, floating points, doubles, longs
* Strings
* Lists, tuples, arrays (bytearrays)
* Dictionaries
* Functions
* Objects/Classes

Program score will be calculated like this: `[# of characters]-(50*[# of types])`. The program with the smallest score wins the challenge.

# Answer
> 8 votes
# Python - 122 chars - 50\*13 types = -528

```
def b(x=False):
 try:return[False][x]
 except IndexError:return True
 except:
  try:return b(len(x))
  except:return True

```

Works for the following built-in types (as listed in §3.2 The standard type hierarchy)

1. NotImplemented
2. Ellipsis
3. int
4. long
5. bool
6. string
7. unicode
8. tuple
9. list
10. bytearray
11. set
12. frozenset
13. dict

# Answer
> 2 votes
# JavaScript, -278

```
function bool(_,$){try{$=_.length;$._;_=$}catch(_){}return 1-isNaN(_/_)}

```

Doesn’t use any boolean operators! If global leaking and input is okay, then it’s even shorter, at 65 characters:

```
bool=eval.bind(0,'try{$=_.length;$._;_=$}catch(_){}1-isNaN(_/_)')

```

Works for anything with a `length` and all primitive types and their object wrappers.

Now you've added a list of things that count as types, but what kind of function or class should evaluate to `false`? This one treats functions that take no arguments as `false` \- does that count? What about classes? What does that mean?

# Answer
> 2 votes
# MMIX (8 bytes assembled)

Assembly language has no statements.

```
bool    ZSNZ $0,$0,1
        POP  1,0

```

# Answer
> 0 votes
### Scala(152 characters)

```
implicit def?(a:Any)={val f=false;a match{case 0=>f;case null=>f;case ""=>f;case ()=>f;case None=>f;case x:Iterable[_]=>x.exists(_=>true)case _=>true}}

```

Sample inputs:

```
scala> if(0) true else false
res0: Boolean = false

scala> if(0.0) true else false
res1: Boolean = false

scala> if(1) true else false
res2: Boolean = true

scala> if(()) true else false
res3: Boolean = false

scala> if(List()) true else false
res4: Boolean = false

scala> if(List(1)) true else false
res5: Boolean = true

scala> if(Set()) true else false
res6: Boolean = false

scala> if("") true else false
res7: Boolean = false

scala> if(Map()) true else false
res8: Boolean = false

scala> if(None) true else false
res9: Boolean = false

scala> class X
defined class X

scala> if(new X()) true else false
res10: Boolean = true

```

# Answer
> 0 votes
## **GoRuby, 19 - 50\*(number of types in Ruby)**

```
def bool(o)
   [1,[o].fle.j.sz].mi
end

```

Returns 0 if the passed object converts to the empty string, 1 otherwise. Of course, Ruby doesn't treat 0 as false, so this isn't a very *useful* function...in fact, `bool(bool(x))` is always 1. Objects that do convert to 0 include `nil`,`false`,`[]`, and lists containing only objects that convert to 0.

# Answer
> 0 votes
# Python 85 chars - 50\*20 types = -915 points

```
def b(x=False):
 try:return b(len(x))
 except:return{0:False,None:False}.get(x,True)

```

So it works for all types in the six categories in the question. The score is therefore 85 - 50\*6 = -215, or am I wrong?

Here is also my test code:

```
class Test(object):
  def __init__(self):
    pass

for x in [None, NotImplemented, Ellipsis,
    0,1,0L,1L,False,True,0.0,1.0,0.0j,1.0j,
    '','a',u'',u'a',
    (),(1,),[],[1],bytearray(),bytearray('31'),
    set(),set('ab'),frozenset(),frozenset('ab'),
    {},{'a':0},b, Test, Test.__init__,(a for a in 'a')]:
  print b(x), bool(x), type(x)

```

Think I've forgotten some types ;-)

```
b(x) bool(x) type(x)
False False <type 'NoneType'>
True True <type 'NotImplementedType'>
True True <type 'ellipsis'>
False False <type 'int'>
True True <type 'int'>
False False <type 'long'>
True True <type 'long'>
False False <type 'bool'>
True True <type 'bool'>
False False <type 'float'>
True True <type 'float'>
False False <type 'complex'>
True True <type 'complex'>
False False <type 'str'>
True True <type 'str'>
False False <type 'unicode'>
True True <type 'unicode'>
False False <type 'tuple'>
True True <type 'tuple'>
False False <type 'list'>
True True <type 'list'>
False False <type 'bytearray'>
True True <type 'bytearray'>
False False <type 'set'>
True True <type 'set'>
False False <type 'frozenset'>
True True <type 'frozenset'>
False False <type 'dict'>
True True <type 'dict'>
True True <type 'function'>
True True <type 'type'>
True True <type 'instancemethod'>
True True <type 'generator'>

```

# Answer
> 0 votes
# Bash

Bash only does integer arithmetic of numbers stored in strings. So this isn't really a proper answer as there are no floats. But I thought this was an interesting integer-only solution:

```
$ bool () { echo $(( (($1 * $1) + 2) % (($1 * $1) + 1) )); }
$ for i in {-5..5}; do bool $i; done
1
1
1
1
1
0
1
1
1
1
1
$

```

# Answer
> -2 votes
## Perl, 5 char

```
1-!$x

```

Works for integers, floating-point values, strings, and C. Although in Perl, these are all the same type.

---
Tags: code-challenge
---


title: Brainf**k Debugger

text:
# Question
Title: Brainf**k Debugger
Your challenge is to take input like this (a Hello World program):

```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

```

And output a prompt (which will be `"> "`):

```
>

```

The user can then enter anything at the prompt. Your simple debugger must have these commands:

* `S` \- step

+ Output the current location (see `L`) after stepping.
    + `S(a positive integer)` \- step that many spaces
* `L` \- location

+ The term "location" always refers to where you are in the program (i.e., the instruction pointer).
    + Formatted like this:

    ```
      v
    +++++++[>+++++++<-]>.

    ```

    This means that the current location of the program is at the third `+`.
* `G(an integer)` \- go to

+ This means keep stepping until you get to that location. If you reach the end of the program and you haven't gotten there, simply exit the program.
    + A negative integer means that many characters from the end. Yes, this means that `-0` is different than `0`, and `-1` is the second to last character.
    + Don't output anything for this command.
* `D` \- dump array

+ Formatted like `1, 2, 3, 4, 5`
    + If the array is `1, 2, 3, 0, 0, 0, 0, 0, ...`, only output `1, 2, 3`.
    + `D(a positive integer) (a positive integer)` \- dump all array items between those two positions (inclusive)
* `(a positive integer)` \- output the item currently at that array position
* `P` \- output the index of the BF pointer (the thing you change with `>` and `<`).

When the program requests input, show the prompt `"I> "`. (You may input one character at a time.)

When it outputs something, show `"O> " + (the output)`. Multiple outputs between commands must be chained together (i.e. you can't do `> G-0 O> H O> e O> l O> l O> o ...`, it has to be `> G-0 O> Hello, World!`).

Output "Done" and exit once you reach the end of the program.

---

Sample run:

```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
> S
1
> S
2
> S2
4
> S0
4
> L
    v
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
> D
4
> 0
4
> D10 15
0, 0, 0, 0, 0, 0
> G-0
O> Hello, World!
Done

```

Sample run showing stepping through loops and the `P` instruction (calculates `3*2+1`)

```
+++[>++<-]>+
> S3
3
> L
   v
+++[>++<-]>+
> S3
6
> L
      v
+++[>++<-]>+
> P
1
> S3
9
> L
         v
+++[>++<-]>+
> S
3
> L
   v
+++[>++<-]>+
> D
2, 2
>

```

Sample run showing I/O

```
>+[>,---------------------------------]<[<]>[>.]
> G37
I> H
I> e
I> l
I> l
I> o
I> !
> D
0, 39, 68, 75, 75, 78
> G-0
O> 'DKKN
Done

```

---

This is , so the shortest code will win.

# Answer
# PHP - 1008

```
<?php
$_=trim(fread(STDIN,1e5));$z=$p=0;$t=$l=[];$q='';function s(){global$p,$t,$l,$_,$q,$z;switch($_[$z++]){case'>':$p++;break;case'<':$p--;break;case'+':@$t[$p]++;break;case'-':@$t[$p]--;break;case'.':$q.=chr($t[$p]);break;case',':echo"I>";$t[$p]=ord(trim(fread(STDIN,2)));break;case'[':$l[]=$z;if(!isset($t[$p])||$t[$p]==0){$c=1;while($c>0){$b=$_[$z++];if($b=='[')$c++;elseif($b==']')$c--;}array_pop($l);}break;case']':$z=array_pop($l)-1;break;}if($z==strlen($_)){if($q)echo'O>'.$q."\n";die("Done\n");}}for(;;){echo">";$c=trim(fread(STDIN,1e5));$g=strlen($c);switch($c[0]){case'L':echo str_repeat(' ',$z)."v\n".$_."\n";break;case'D':if($g)$x=$t;else{list($a,$b)=explode(' ',substr($c,1));$x=array_slice($t,$a-1,$b);}echo implode(', ',$x)."\n";break;case'S':if($g)s();for($i=0;$i<substr($c,1);$i++)s();echo $z."\n";break;case'G':if($c[1]=='-')$x=strlen($_)-substr($c,2);else$x=substr($c,1);while($z!=$x)s();break;case'P':echo$p."\n";default:if(is_numeric($c))echo$t[$c]."\n";}if($q)echo'O>'.$q."\n";$q='';}

```

The output for cells that were never written is slightly different:

```
[timwolla@/data/workspace/php/PCG]php pcg-22585.php
+
>D15 20

>

```

Large version:

```
<?php
$_=trim(fread(STDIN,1024));
$z=$p=0;
$t=$l=[];
$q='';

function step() {
    global $p, $t,$l,$_,$q,$z;
    switch ($_[$z++]){
        case '>':
            $p++;
        break;
        case '<':
            $p--;
        break;
        case '+':
            @$t[$p]++;
        break;
        case '-':
            @$t[$p]--;
        break;
        case '.':
            $q.=chr($t[$p]);
        break;
        case ',':
            echo "I>";
            $t[$p] = ord(trim(fread(STDIN, 2)));
        break;
        case '[':
            $l[] = $z;
            if (!isset($t[$p]) || $t[$p] == 0) {
                $counter = 1;
                while ($counter > 0) {
                    $char = $_[$z++];
                    if ($char == '[') $counter++;
                    else if ($char == ']') $counter--;
                }
                array_pop($l);
            }
        break;
        case ']':
            $z = array_pop($l)-1;
        break;
    }
    if($z==strlen($_)) {
        if ($q) echo 'O>'.$q."\n";
        die("Done\n");
    }
}

for(;;){
    echo ">";
    $c=trim(fread(STDIN,100));
    switch ($c[0]) {
        case 'L':
            echo str_repeat(' ', $z)."v\n".$_."\n";
        break;
        case 'D':
            if(strlen($c) == 1)$x=$t;
            else {
                list($a,$b)=explode(' ',substr($c,1));
                $x=array_slice($t,$a-1,$b);
            }
            echo implode(', ', $x)."\n";
        break;
        case 'S':
            if(strlen($c)==1)step();
            for($i=0;$i<substr($c,1);$i++)step();
            echo $z."\n";
        break;
        case 'G':
            if($c[1]=='-')$x=strlen($_)-substr($c,2);
            else $x=substr($c,1);
            while ($z!=$x)step();
        break;
        case 'P':
            echo $p."\n";
        default:
            if(is_numeric($c)) echo $t[$c]."\n";
    }
    if ($q) {
        echo 'O>'.$q."\n";
        $q='';
    }
}

```
> 3 votes

---
Tags: code-golf, brainfuck
---


# Question
Title: Create an n to the d tic tac toe win-checker
Create the shortest program to check who has won in an nd tic tac toe game.

Your program should work when `n` (width) and `d` (dimension number) are in these ranges:

```
n∈[3,6]∩ℕ  ie a number from this list: 3,4,5,6
d∈[2,5]∩ℕ  ie a number from this list: 2,3,4,5

```

`n = 3; d = 2` (32 ie 3 by 3):

```
[][][]
[][][]
[][][]

```

`n = 3; d = 3` (33 ie 3 by 3 by 3):

```
[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

```

`n = 6; d = 2` (62 ie 6 by 6):

```
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]

```

And so on.

**Winning** (If you've played enough multi-dimensional tic tac toe, this is the same.)

In order for there to be a win, one player must have all the adjacent squares along a line. That is, that player must have `n` moves on a line to be a winner.

Adjacent:

* each tile is a point; for example (0,0,0,0,0) is a point in `d=5`
* adjacent tiles are tiles such they are both points on the same unit d-cube. In other words, the Chebyshev distance between the tiles is 1.
* in other words, if a point `p` is adjacent to a point `q`, then every coordinate in `p`s corresponding coordinate in `q` differs from it by no more than one. Additionally, at least on coordinate pair differs by exactly one.

Lines:

* Lines are defined by vectors and a tile. A line is each tile hit by the equation: `p<sub>0</sub> + t`<`some vector with the same number of coordinates as p<sub>0</sub>`>``

**Input**:

Input will be to STDIN. The first line of input will be two numbers, `n` and `d` in the form `n,d`.

After this will be a line consisting of coordinates specifying the moves that have been done. Coordinates will be listed in the form: `1,1;2,2;3,3`. The upper left corner is the origin ( 0,0 for 2D). In the general case, this list will be like `1,2,...,1,4;4,0,...,6,0;...` where the first number represents left-right-ness, the second up-down-ness, the third through the 3rd dimension, etc. Note that the first coordinate is `X`s first turn, the second is `O`s first turn, ....

The input will be followed by a newline.

**Output**:

Output will be to STDOUT. Simply indicate who won if someone won, or if it is a tie. If it is neither a tie nor a win, don't output anything.

Additionally, indicate if there is a move clash, that is, if there are at least two moves in the same location.

If there was a win/draw before the input ended, your program can do whatever it wants.

**Test cases** (anyone want to suggest any more?):

Input:

```
4,3
0,0,0;1,1,1;1,0,1;2,0,2;0,0,1;2,0,0;2,0,1;3,0,2;3,0,1

```

Example Output:

```
X wins

```

Another possible output (requires explanation):

```
1

```

# Answer
Python, 745 578 Characters

```
import sys
x=[]
o=[]
t=1
b=","
k=map
def m(c):
 m=x if t else o
 c=k(int,c.split(b))
 if c in o+x:
  print b
  sys.exit()
 m.append(c)
 r=0
 for p in m:
  r=w(p,m)
 return r
def w(p,m):
 for q in m:
  d=max(k(lambda x,y:abs(x-y),p,q))
  if d==u:
   if e(p,q,m):
    return 1
 return 0
def e(p,q,m):
 v=k(lambda p,q:(p-q)/u,q,p)
 l=p
 for i in range(1,n):
  y=k(lambda j,h:j+h,l,v)
  if y not in m:
   return 0
  l=y
 if not l==q:
  return 0
 return 1
q=sys.stdin.readline
d=q()
v=q()
z=d.split(b)
(n,d)=k(int,z)
a=v.split(";")
u=n-1
for c in a:
 r=m(c)
 if r:
  print t
 t=not t

```

I made some changes and shrank it down quite a bit. Note that a return of True means that x has won, False means y won, and , means that an invalid move was made.
> 3 votes

# Answer
# Not an answer - Java

I was curious to see how many different ways there were to win for a given n,d so I wrote this code to list them all.

```
import java.util.*;

public class MultiDTTT {
    static Set<Win> wins = new HashSet<Win>();
    static final int d = 3;
    static final int n = 3;
    static final char maxChar = (char)(n-1) + '0';

    public static void main(String[] args) throws Exception {
        String pad = "";
        for(int i=0; i<d; i++) pad = pad + "0";
        for(int i=0; i<Math.pow(n,d); i++) {
            String s = Integer.toString(i,n);
            s = pad.substring(s.length()) + s;
            buildWin(s,"",0);
        }
        System.out.println(wins.size());
        for(Win w : wins) System.out.println(w.toString());
    }

    static void buildWin(String s, String p,int i) {
        if(i<d) {
            if(s.charAt(i) == '0') {
                buildWin(s,p+"u",i+1);
                buildWin(s,p+"s",i+1);
            }
            else if(s.charAt(i) == maxChar) {
                buildWin(s,p+"d",i+1);
                buildWin(s,p+"s",i+1);
            }
            else {
                buildWin(s,p+"s",i+1);
            }
        }
        else {
            if(p.contains("u") || p.contains("d")) wins.add(new Win(s,p));
        }
    }

    static class Win {
        String start;
        String pattern;
        Set<String> list = new HashSet<String>();

        Win(String s, String p) {
            start = s;
            pattern = p;
            char[] sc = s.toCharArray();
            for(int i=0; i<n; i++) {
                list.add(new String(sc));
                for(int j=0; j<d; j++) {
                    switch (p.charAt(j)) {
                        case 'u':
                            sc[j]++;
                            break;
                        case 'd':
                            sc[j]--;
                            break;
                        case 's':
                            break;
                    }
                }
            }
        }

        public String toString() {
            String s = ""; //start + ", " + pattern + "\n    ";
            for(String ss : list) s = s + ss + " ";
            return s;
        }

        public boolean equals(Object x) {
            return (x instanceof Win) && this.list.equals(((Win)x).list);
        }
        public int hashCode(){
            return list.hashCode();
        }
    }
}

```

I hand-tested it on n,d = 2..3,2..3 and it appears to work… after that the number of possible ways to win grows quickly as shown below:

```
n       1       2       3       4       5       6
d
1       1       1       1       1       1       1
2       1       6       8       10      12      14
3       1       28      49      76      109     148
4       1       120     272     520     888     1400
5       1       496     1441    3376    6841    12496
6       1       2016    7448    21280   51012   107744

```

Having generated all wining sets, I could extend the program to check the given input against winning sets but, of course, that method would never win the golf. So I was content to stop here - except it looked like I could find a closed-form solution for the number of ways to win as a function of n and d… It is Number of ways to win = 0.5( (n+2)^d - n^d).
> 3 votes

# Answer
# C++ 794 ~~849~~ chars

```
#include <algorithm>
#include <iostream>
#include <cmath>
#include <string>
#define _ return
#define Y int
#define Z(a) cout<<#a
#define W(a,b,c) for(a=c;a++<b;)
using namespace std;Y n,d,A[5],P[6],T=1,x[7776]={},i,j,k,a,z,p=pow(n,d);char c;bool B;string s;Y K(){a=P[j];W(k,i,0)a/=n;_ a%n;}Y M(){j=0;z=K();W(j,n,1){if(K()!=z){_ 1;}}_ 0;}Y N(){W(j,n,0)if(K()!=n-1-j)_ 1;_ 0;}Y O(){W(j,n,0)if(K()!=j)_ 1;_ 0;}Y S(){z=0;W(i,d,0){z*=n;z+=A[i];}_ z;}Y C(){a=z=0;W(i,p,0){if(s[i]-'0'){P[z]=i;++z;if(a){if(x[i]!=a)_ 0;}else a=x[i];}}_ a;}Y L(){W(i,d,0)if(M()*N()*O())_ 0;_ 1;}Y main(){cin>>n>>c>>d;while(1){W(i,d,0)B=cin>>A[i]>>c;if(x[S()]){Z(!);_ 0;}x[S()]=T;T*=-1;if(!B)break;}W(i,p,0)i<n?s+="1":s+="0";do if(C()&&L()){C()==1?Z(X):Z(O);_ 0;}while(prev_permutation(s.begin(),s.end()));_ 0;}

```

Output is: "X" (X wins), "O" (O wins), or "!" (illegal move attempt).

This just maps the points into a linear array and checks all possible subsets of size n, first for being constant at X or O, and then for being in a line. To check for being in a line, the coordinates of the points in each subset are examined one at a time; they must each be either increasing from 0 to n-1, decreasing from n-1 to 0, or constant. The points are naturally ordered in the linear array, so it makes sense to call a coordinate increasing or decreasing for a given set of points.

Thanks to Howard for pointing out a serious mistake in the first version.

**In solidarity with Quincunx, I have to point out that it would be a travesty if a C++ answer wins**
> 2 votes

---
Tags: code-golf, tic-tac-toe
---


# Question
Title: Create a Fanatic bot for Stack Exchange sites
Your challenge today is to cheat at badges!

You will build a bot that will connect to a Stack Exchange site, log in as you, visit the /questions page, visit a question, and then visit 9 other questions in the "related" sidebar (because that seems sufficient to count as "activity," and I need to standardize on something).

This bot must go through this process once every day, without any input or actions from the user. It should be able to be left running, and the user should be able to never touch the computer, and the consecutive days count will still be incremented. After "visiting" the site, it must print "visited".

You will assume that the user is using the Stack Exchange-provided OpenID.

The input of the program will be the site URL, SE OpenID email, and SE OpenID password. For example:

```
https://stackoverflow.com/ doorknob@doorknob.doorknob password

```

You can input these however you would like.

Your program must work for a minimum of:

(Just to make sure it is universal.)

This is , so the shortest code in bytes will win!

# Answer
> 11 votes
# Ruby, 456 characters

```
require'mechanize'
s,*e=gets.split
a,o=Mechanize.new,'http://openid.stackexchange.com/'
a.agent.http.verify_mode=OpenSSL::SSL::VERIFY_NONE
l=a.get(o+'account/login').forms[0]
l.email,l.password=e
a.submit l,l.buttons[0]
g=a.get(s+'/users/login').forms.find{|f|f.action=='/users/authenticate'}
g.openid_identifier=o
a.submit g,g.buttons[-1]
loop{p=a.get s+'/questions'
10.times{p=p.links.find{|i|i.href=~/^\/questions\/\d/}.click}
puts'visited'
sleep 86400}

```

Ungolfed version:

```
require 'mechanize'

site, email, password = gets.split

agent = Mechanize.new
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE

login_form = agent.get('http://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'

site_login_form = agent.get(site + '/users/login').forms.find {|form| form.action == '/users/authenticate' }
site_login_form.openid_identifier = 'http://openid.stackexchange.com/'
agent.submit site_login_form, site_login_form.buttons.last
puts 'logged in to site'

loop {
    page = agent.get(site + '/questions')
    10.times do page = page.links.find{|link| link.href =~ /^\/questions\/\d/ }.click; end
    puts 'visited'
    sleep 60 * 60 * 24
}

```

---
Tags: code-golf
---


title: Shortest Port Scanner

text:
# Question
Title: Shortest Port Scanner
Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a Port Scanner)

Take input from command line arguments.

```
your-port-scanner host_ip startPort endPort

```

Assume, startPort \< endPort (and `endPort - startPort < 1000`)

**Output:** All the open ports between that range should space or comma seperated.

# Answer
## sh/netcat, 39

```
nc -vz $1 $2-$3 2>&1|cut -f3 -d\ |xargs

```

Netcat does the scanning and returns results in this form on standard error:

```
localhost [127.0.0.1] 22 (ssh) open
localhost [127.0.0.1] 25 (smtp) open

```

`cut` and `xargs` extract the port number and make a single line out of it.

Remind me to shut SMTP down on that node.
> 5 votes

# Answer
## Perl, 92

```
$_='use I;$h=shift;grep I->new("$h:$_"),shift..shift';
s/I/IO::Socket::INET/g;@_=eval;say"@_"

```

Perl 5.10 or later, run with `perl -E 'code here'`.

Uses regexes to compress that long `IO::Socket::INET`, then `eval`; final formatting done with array interpolation.

By request, a more detailed explanation. To ungolf, let's first respace:

```
$_ = << 'EOC';
  use I;
  $h = shift;
  grep I->new("$h:$_"), shift..shift;
EOC
s/I/IO::Socket::INET/g;
@_ = eval;
say "@_";

```

The line before the `eval` replaces all (two) occurences of 'I' with 'IO::Socket::INET', that's a standard Perl golfing trick to reduce the impact of unavoidable long identifiers. Naming a few of the temporaries, the code is then equivalent to this:

```
use IO::Socket::INET;
$h = shift;
$p1 = shift;
$p2 = shift;
@_ = grep IO::Socket::INET->new("$h:$_"), ($p1 .. $p2);
say "@_";

```

In a nutshell: read host and port range arguments from the command line; attempt a connection to all of them in sequence (`IO::Socket::INET->new()`); keep a list of those who succeeded (`grep`); display the result nicely (`say`).
> 3 votes

# Answer
# Ruby - 85

```
require"socket"
h,p,e=$*
p.upto(e){|p|begin
TCPSocket.new h,p
$><<"#{p} "
rescue
end}

```
> 2 votes

# Answer
# sh/nmap/GNU grep/xargs - 36

```
nmap -p$2-$3 $1|grep -Po '^\d+'|xargs

```

Follows input and output specs:

```
$ sh 1109.sh 127.0.0.1 1 80
22 25 80

```
> 1 votes

# Answer
## Perl, 178

I'm new to Perl, any advice on shortening is appreciated!

```
use IO::Socket::INET;for($x=$ARGV[1];$x<$ARGV[2]+1;$x++){if(fork()){if($sock=new IO::Socket::INET(PeerAddr=>$ARGV[0],PeerPort=>$x,Proto=>'tcp')){print"$x ";}close($sock);exit;}}

```
> 1 votes

# Answer
# BASH - 105

In pure BASH (i.e no nmap or netcat).

```
exec 2>&- && exec 2<> /dev/null
for p in $(seq $2 $3); do
    > /dev/tcp/$1/$p &&
    echo -n "$p "
done

```

When using with an address other than localhost the timeout is quite long (in the order of minutes) when encountering a closed port so some sort of timeout/alarm function would be required in all likelihood.
> 1 votes

# Answer
# PHP - 70

```
<?for(list(,$h,$p,$e)=$argv;$p<=$e;++$p)@fsockopen($h,$p)&&print"$p ";

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Kind of meta: get the longest of the shortest answers
Your task - if you accept it - is to write a program which helps understanding my proposal on meta by calculating the winner of a competition. Of course, answers to this question will be treated as proposed, so your program (if correct) can calculate whether your answer will become the accepted answer.

## Rules

* The program reads a file with multiple lines of the following format (see example below): \[Language\] TAB \[NumberOfCharacters\] TAB \[LinkToAnswer\]
* The file name is passed as an argument to your program or the file is redirected to standard input of your program. It's your choice, please mention the method when giving the answer
* It's expected that the input format is correct. There's no need for error handling.
* The number of characters is positive. Your program must handle lengths up to 65535. 64k should be enough for everybody :-)
* The program outputs those lines on standard output which meet the idea of the meta proposal, that is
    + the shortest code of a particular programming language wins (reduction phase)
    + the longest code among all programming languages wins (sorting phase)
    + in case of a draw, all answers with the same length shall be printed
* The order of the output is not important
* Although the longest code wins, this is not . Your code must be as short as possible for your programming language.
* Answers on seldom programming languages which are not attempting to shorten the code deserve a downvote, because they try to bypass the intention of this kind of question. If there's only one answer for a specific programming language, it would be considered as a winner candidate, so you could start blowing its code.

Example input file (separated by single tabs if there should be an issue with formatting):

```
GolfScript  34  http://short.url/answer/ags
GolfScript  42  http://short.url/answer/gsq
C#  210 http://short.url/answer/cs2
Java    208 http://short.url/answer/jav
C#  208 http://short.url/answer/poi
J   23  http://short.url/answer/jsh
Ruby    67  http://short.url/answer/rub
C#  208 http://short.url/answer/yac
GolfScript  210 http://short.url/answer/210

```

Expected output (order is not important):

```
C#  208 http://short.url/answer/poi
C#  208 http://short.url/answer/yac
Java    208 http://short.url/answer/jav

```

## Update

Some programs rely on the fact that there is a single maximum (like the C# 210 character program). Derived from reality, someone can also write a GolfScript program with 210 characters. The output would remain the same. I have added such a GolfScript to the input.

## Update 2

As suggested I have retagged (still code-golf as well) and the deadline is **2014-03-06** (which looks like an arbitrary date, but I'll be back to Germany from travelling then).

## Final results

I decided to vote like the following:

* Answers where the number of characters cannot be confirmed get a comment to explain the count.
* Answers which can easily be reduced get a comment, an edit suggestion and go into the result with the lower count value. (Hopefully I have seen that in advance).
* Answers which do not compile get a downvote. (Quite a hard task as it turns out).
* Answers which are not golfed get a downvote (as described in the rules already).
* Answers which produce expected output get an upvote. Due to some answers which do not work as expected, I use 4 different input files and check against the expected result.

Finally, the winner is determined by providing the qualifying answers table as input to my reference program (plus double checking the result manually). If my own answer would be the winning one, I'd exclude it from the list. In case of several winners, I would have to pick only one. Therefore, some bonuses can be earned:

* answers which accept more input than expected (e.g. outside the defined ranges)
* answers which use a clever idea of making it short

I have taken a snapshot of the answers on 6th of March 2014, 19:45 UTC+1. The analysis is ongoing. Checking all the answers is harder than expected...

# Answer
# Java - 556

```
import java.util.*;class G{public static void main(String[]x){TreeMap<?,TreeMap>m=new TreeMap();try{Scanner s=new Scanner(System.in);for(;;){String[]a=s.nextLine().split("\t");a(new Long(a[1]),a(a[0],m)).put(a[2],a);}}catch(Exception e){}TreeMap<?,Map<?,String[]>>n=new TreeMap();for(TreeMap o:m.values())a(o.firstEntry().getKey(),n).putAll((Map)o.firstEntry().getValue());for(String[]o:n.lastEntry().getValue().values())System.out.println(o[0]+"\t"+o[1]+"\t"+o[2]);}static<T>Map a(T t,Map m){if(m.get(t)==null)m.put(t,new TreeMap());return(Map)m.get(t);}}

```

Program will read from STDIN.

```
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

class G {
    public static void main(String[] x) {
        TreeMap<?, TreeMap> m = new TreeMap();
        try {
            Scanner s = new Scanner(System.in);
            for (; ; ) {
                String[] a = s.nextLine().split("\t");
                a(new Long(a[1]), a(a[0], m)).put(a[2], a);
            }
        } catch (Exception e) {
        }
        TreeMap<?, Map<?, String[]>> n = new TreeMap();
        for (TreeMap o : m.values())
            a(o.firstEntry().getKey(), n).putAll((Map) o.firstEntry().getValue());
        for (String[] o : n.lastEntry().getValue().values())
            System.out.println(o[0] + "\t" + o[1] + "\t" + o[2]);
    }

    static <T> Map a(T t, Map m) {
        if (m.get(t) == null)
            m.put(t, new TreeMap());
        return (Map) m.get(t);
    }
}

```
1. Programm will read line by line until an exception occours (either `ArrayIndexOutOfBoundsException` when a blank line is encountered or `NoSuchElementException` if input ends without trailing new line). Each line read is added to the `TreeMap m`, which could have been defined as `TreeMap<String, TreeMap<Long, TreeMap<String,String[]>>>` (left-to-right: language, code-size, URL, input).
2. Then a result-`TreeSet<Long, TreeSet<String, String[]>> n` (left-to-right: code-size, URL, input) is build where the contents of every languages `firstEntry()` are aggregated.
3. `lastEntry()` of the aggregated `TreeMap` contains our result - we only need to print it.

Try on ideone.com (switched last two lines of input to show that all lines are read)
> 2 votes

# Answer
## Perl, 195 bytes

```
while(<>){/(\S+)\t(\d+)\t(.+)/;push@{$a{$1}},$3if$2==$l{$1};$l{$1}=$2,$a{$1}=[$3]if $2<($l{$1}//65536)}$m=(sort{$b<=>$a}values%l)[0];map{$l=$_;map{print"$l\t$m\t$_\n"if$l{$l}==$m}@{$a{$l}}}keys%l

```

Input is expected in STDIN, result is written to STDOUT:

```
C#      208     http://short.url/answer/poi
C#      208     http://short.url/answer/yac
Java    208     http://short.url/answer/jav

```

## Ungolfed version

```
#!/usr/bin/env perl
use strict;
$^W=1;

# hash %language remembers the minimum count for a language
# %language: <language> => <minimum count>
my %language;
# hash %array remembers the URLs for the minimum count of the language
# %array: <language> => [<url>, <url>, ....]
my %array;

while(<>){
    # parse input line (no error checking)
    /(\S+)\t(\d+)\t(.+)/;
    my ($lang, $count, $url) = ($1, $2, $3);
    # add URL, if the count is the current minimum for the language
    if ($count == ($language{$lang}//0)) {
    # better, but longer version:
    # if (defined $language{$lang} and $count == $language{$lang}) {
        push @{$array{$lang}}, $url;
    }
    # create a new entry for the language, if there is a new minimum
    if ($count < ($language{$lang}//65536)) {
    # better, but longer version:
    # if (not defined $language{$lang} or $count < $language{$lang}) {
        $language{$lang} = $count;
        $array{$lang} = [$url];
    }
}

# Sort the minimal values in numerical descending order and
# get the first entry as maximum.
my $maximum = (sort { $b <=> $a } values %language)[0];

# Loop over all URLs of minimal answers for the language,
# but print only the entries for the languages with the largest
# minima.
foreach my $lang (keys %language) {
    foreach my $url (@{$array{$lang}}) {
        if ($language{$lang} == $maximum) {
            print "$lang\t$maximum\t$url\n";
        }
    }
}
__END__

```
> 2 votes

# Answer
## Python ~~378~~ ~~377~~ 372

```
import sys
d=__import__("collections").defaultdict(list)
o={}
x=int
n="\n"
for i,l,u in[a.split()for a in sys.stdin.read().strip().split(n)]:d[i]+=[(l,u)]
for e,b in d.items():o[e]=[i for i in b if i[0]==str(min([x(i[0])for i in b]))]
print("".join(n.join("\t".join([u,s[0],s[1]])for s in y if x(s[0])==max(x(i[0][0])for i in o.values()))+n for u,y in o.items()).strip())

```

Input on the stdin:

```
C:\Users\gcq\Documents\python>type m.txt | python test.py
C#      208     http://short.url/answer/poi
C#      208     http://short.url/answer/yac
Java    208     http://short.url/answer/jav

```

And this is what i had before starting to compress it down, at 551 chars:

```
from collections import defaultdict
import sys
d = defaultdict(list)

for language, length, url in [a.split() for a in sys.stdin.read().strip().split("\n")]:
    d[language].append((length, url))

o = {}
for language, data in d.items():
    winval = data[0][0]
    for i in data:
        if int(i[0]) < int(winval):
            winval = i[0]
    o[language] = [i for i in data if i[0] == winval]

maxlen = max(int(i[0][0]) for i in o.values())

for language, dataa in o.items():
    for data in dataa:
        if int(data[0]) == maxlen:
            print("\t".join([language, data[0], data[1]]))

```
> 2 votes

# Answer
# dg - 286 281 260 251 218 bytes

```
import '/sys'
d=dict!
for(a,b,c)in(map str.split$(sys.stdin.read!).splitlines!)=>d!!a=(d.get a list!)+(list'(int b,c))
for(i,l)in(d.items!)=>for(s,u)in l=>s==(max$map(i->fst$min i)d.values!)=>print$i+' '+(str s)+' '+u

```

Example:

```
$ cat langs.txt | dg langs.dg
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav

```

**Ungolfed** version:

```
import '/sys'

s = sys.stdin.read!
d = dict!
# convert the string into a list of tuples (name, score, url)
u = map str.split $ s.splitlines!
# add all the values to the dict (converting the score to an integer)
for (a, b, c) in u =>
  d!!a = (d.get a list!) + (list' (int b, c))
# computes the maximum value amongst the mins
m = max $ map (i -> fst $ min i) d.values!
for (i, l) in (d.items!) =>
  for (s, u) in l =>
    # if the score equals the maximum then print all the line
    s == m => print $ i + ' ' + (str s) + ' ' + u  # actually here .format()
                                                   # would be better

```

**Q: What the heck is dg?**
**A:** A programming language that compiles to CPython bytecode, much like Scala compiles to JVM's. That essentially means that dg is an alternative syntax for Python 3. It allows you to use all of the existing libraries, too.

More info here (even a tutorial!): https://pyos.github.io/dg
> 2 votes

# Answer
# C# - 628

Here's a longer alternative of yours that uses `DataTable`:

```
using Microsoft.VisualBasic.FileIO;namespace System{using T=Data.DataTable;using R=Data.DataRow;using V=Data.DataView;using C=Data.DataColumn;class p{static void Main(string[] a){var I=typeof(Int32);T t=new T();t.Columns.AddRange(new[]{new C("a"),new C("b",I),new C("c"),new C("d",I)});var f=new TextFieldParser(a[0]);f.SetDelimiters("\t");while(!f.EndOfData){var r=t.NewRow();r.ItemArray=f.ReadFields();t.Rows.Add(r);}foreach(R r in t.Rows){r[3]=t.Compute("min(b)","a='"+r[0]+"'");}V v=new V(t);T s=v.ToTable();foreach(R r in s.Select("b='"+t.Compute("max(d)","")+"'")){Console.WriteLine(String.Join("\t",r[0],r[1],r[2]));}}}}

```

I originally thought I may have gained slight code reduction from using max/min with `DataTable`, but the types required to build the `DataTable` (rows/columns/view) add a lot of length, unfortunately. I'm new to code golfing so maybe somebody would be able to reduce it further. Still a fun challenge.
> 1 votes

# Answer
# Rebol - 314

```
d: map[]foreach r read/lines to-file system/script/args[r: split r tab p: take r r/1: to-integer r/1 r/2: reduce[r/2]either none? d/:p[repend d[p r]][case[d/:p/1 > r/1[d/:p: r]d/:p/1 = r/1[append d/:p/2 r/2]]]]l: 0 foreach[k v]d[l: max l v/1]foreach[k v]d[if l = v/1[foreach n v/2[print rejoin[k tab v/1 tab n]]]]

```

## un-golfed

```
d: map []

foreach r read/lines to-file system/script/args [
    r: split r tab
    p: take r
    r/1: to-integer r/1
    r/2: reduce [r/2]
    either none? d/:p [repend d [p r]] [
        case [
            d/:p/1 > r/1 [d/:p: r]
            d/:p/1 = r/1 [append d/:p/2 r/2]
        ]
    ]
]

l: 0 foreach [k v] d [l: max l v/1]
foreach [k v] d [
    if l = v/1 [
        foreach n v/2 [print rejoin [k tab v/1 tab n]]
    ]
]

```

Usage example:

```
$ rebol script.reb data.txt
C#    208   http://short.url/answer/poi
C#    208   http://short.url/answer/yac
Java  208   http://short.url/answer/jav

```
> 1 votes

# Answer
## C# - 515

Expects a file name as argument

```
using System.Collections.Generic;namespace N{using S=SortedList<int,T>;class T:List<string>{static void Main(string[]a){var d=new Dictionary<string,S>();int n,m=0;T w=new T();foreach(var l in System.IO.File.ReadAllLines(a[0])){var p=(a=l.Split('\t'))[0];n=int.Parse(a[1]);if(!d.ContainsKey(p))d.Add(p,new S());if(!d[p].ContainsKey(n))d[p].Add(n,new T());d[p][n].Add(l);}foreach(var e in d){n=e.Value.Keys[0];if(n==m)w.AddRange(e.Value[n]);if(n>m)w=e.Value[m=n];}foreach(var e in w)System.Console.WriteLine(e);}}}

```

First I designed my C# program to be straight forward, because I wanted to have a kind of reference program. But then I decided to also jump into contest myself and golfed it. This is one of the earlier versions of the code + some comments:

```
// N: namespace
// P: Program
// S: type definition: sorted dictionary
// a: arguments
// d: data container
// r: lines read from text file
// l: single line from r
// t: tabbed part of l after splitting
// p: programming language name
// n: character count
// m: maximum character count
// w: list of winners
// e: entry in data container
// c: winner candidate
using System.Collections.Generic;
namespace N
{
    using S = SortedList<int, P>;
    public class P : List<string>
    {
        public static void Main(string[] a)
        {
            var r = System.IO.File.ReadAllLines(a[0]);
            // Make it a data structure
            var d = new Dictionary<string, S>();
            foreach (var l in r)
            {
                var t = l.Split('\t');
                var p = t[0];
                var n = int.Parse(t[1]);
                if (!d.ContainsKey(p)) d.Add(p, new S());
                if (!d[p].ContainsKey(n)) d[p].Add(n, new P());
                d[p][n].Add(l);
            }
            // Get the maximum values
            var m = 0;
            P w = null;
            foreach (var e in d)
            {
                foreach (var s in e.Value.Keys)
                {
                    if (s > m)
                    {
                        w = e.Value[s];
                        m = s;
                    }
                    else if (s == m)
                    {
                        w.AddRange(e.Value[s]);
                    }
                    break; // Break here to get the shortest solution per language
                }
            }
            // Print everything on console
            foreach (var e in w)
            {
                System.Console.WriteLine(e);
            }
        }
    }
}

```
> 0 votes

# Answer
# C# - ~~460~~ 359

After realizing how bulky my `DataTable` solution was, I created the following example using Linq. It uses the same methodology as my previous solution.

## Golfed

```
namespace System{using Linq;using IO;class p{static void Main(string[]i){var l=(from f in File.ReadAllLines(i[0])let s=f.Split('\t')select new Tuple<string,int,string>(s[0],Convert.ToInt16(s[1]),f)).ToList();foreach(var f in l.Where(a=>a.Item2==l.Where(b=>b.Item1==l.Single(c=>c.Item2==l.Max(d=>d.Item2)).Item1).Min(e=>e.Item2)))Console.WriteLine(f.Item3);}}}

```

## Ungolfed

```
namespace System
{
    using Linq;
    using IO;
    class p
    {
        static void Main(string[]i)
        {
            var l=(from f in File.ReadAllLines(i[0])
                   let s=f.Split('\t')
                   select new Tuple<string, int, string>(s[0],Convert.ToInt16(s[1]),f)).ToList();
            foreach(var f in l.
                Where(a=>a.Item2==l.
                    Where(b=>b.Item1==l.
                        Single(c=>c.Item2==l.
                            Max(d=>d.Item2)).Item1).
                                Min(e=>e.Item2)))
            Console.WriteLine(f.Item3);
        }
    }
}

```

I'm still fairly new to Linq so I'm almost positive those expressions can be reduced further.

From your question, it's not clear if there is a single maximum length solution. For my answers I've used the assumption that there is a single maximum point (ie. if there was a GolfScript maximum of 210 as well, it may fail based on the Single maximum record returned). Heiko's solution would have the same issue. To fix this, we would have to add another step that contained a list of tied maxima to check minima for each language.
> 0 votes

# Answer
# C++ - 535

Will only output the answers tied for longest position after selecting only the shortest answers of each language as potential winners.

```
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){

    string s;
    vector<string>l;
    vector<int>v;
    vector<string>u;
    cin>>s;

    ifstream i(s.c_str());

    do{
        int n;
        i>>s;
        if(i.eof())break;
        l.push_back(s);
        i>>n;
        v.push_back(n);
        i>>s;
        u.push_back(s);
    }while(1);

    for(int i=0;i<l.size();i++){
        for(int j=0;j<l.size();j++){
            if(l[j]==l[i]){
                if(v[i]>v[j])l[i]="";
                else if(v[i]<v[j])l[j]="";
            }
        }
    }
    int n=0;
    for(int i=0;i<v.size();i++)
        if(n<v[i]&l[i]!="")n=v[i];

    for(int i=0;i<v.size();i++)
        if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;
}

```

Golfed (not as unreadable as some languages):

```
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){string s;vector<string>l;vector<int>v;vector<string>u;cin>>s;ifstream i(s.c_str());do{int n;i>>s;if(i.eof())break;l.push_back(s);i>>n;v.push_back(n);i>>s;u.push_back(s);}while(1);for(int i=0;i<l.size();i++)for(int j=0;j<l.size();j++)if(l[j]==l[i]){if(v[i]>v[j])l[i]="";else if(v[i]<v[j])l[j]="";}int n=0;for(int i=0;i<v.size();i++)if(n<v[i]&l[i]!="")n=v[i];for(int i=0;i<v.size();i++)if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;}

```
> 0 votes

---
Tags: code-challenge
---


# Question
Title: Shortest code to make a Too-low --- Too-high game
You have to make a game Too-low --- Too-high (TLTH) in shortest code (in bytes)

## Game rules:

1. Computer will choose a random number out of integer range (-32768..32767).
2. Now you will think of a number and input it.
3. The computer will tell if your number is lower (`TOO LOW`) or higher (`TOO HIGH`) than the chosen number.
4. When you guess the number, the computer should display `Congrats! You found the number!`.

## Code Rules:

1. Do not use the characters `T`, `O`, `L`, `W`, `H`, `I` and `G` (neither lowercase nor uppercase) in string or character literals.
For instance:

```
tolower(T);  // Acceptable
cout<<"T";   // Unacceptable
char ch='T'; // Unacceptable

```
2. **Remove 300 bytes** if your code can display the game rules before starting the game.
3. **Remove 50 bytes** if your code can count number of turns and display number of turns taken in the end of game like this:

```
"Congrats! You found the number in n turns!"

```

where n is number of turns taken, instead of

```
"Congrats! You found the number!"

```
4. **Remove 25 bytes** from your score if your code can tell user that the number you input is out of integer range.
For example:

```
Enter the number: 40000
Sorry! This number is out of range
Please Enter the number again:

```
5. **Remove 25 bytes** If your code takes the random number not from any built-in random function.
6. **Remove 10 bytes** If your code display "congrats" in color (pick any color except default white).

## Submission Rules:

1. Add a heading with your language name and score with all bounty calculation and its explanation.
2. Post your golfed and ungolfed code.

## Winner

1. The answer with **least bytes** wins.
2. If there is a tie, the answer with the more votes wins.
3. The winner will be chosen after 5 days.

**EDIT**:Please show your code's output.
**EDIT-2**: You can ignore Rule-1 for Rules-2,3 & 4 in Code Rules

Best Of Luck :\]

# Answer
> 2 votes
# JavaScript (-210 points (`190` bytes - `300` *(for the rules)* \- `50` *(for the number of guesses)* \- `25` *(for not using any built-in random number source)* \- `25` *(for telling you if the input is out of the range of a signed `16`-bit integer)*):

## Golfed:

```
alert('Guess number',n=(m=2<<15)/2-new Date%m);for(z=0;a=+prompt(++z);)alert(a>m|a<1-m?m+'-'+-~-m:a==n?'Great! You found the number in '+z+' turns':atob('VE9P\x47E'+(a>n?'hJR0g=':'xPVw==')))

```

## Full code (nicely formatted):

```
var max = 2 << 15;
var random = max/2 - new Date%max;
var counter = 0;

while (1) {
    var guess = +prompt();

    ++counter;

    if (guess > max | guess < -~-max) {
        alert(-~-max + '-' + max); // Shows that the range is between -32767 and 32768
    } else if (guess > random) {
        alert('TOO HIGH');
    } else if (guess < random) {
        alert('TOO LOW');
    } else if (guess == random) {
        alert('Congrats! You found the number in ' + counter + ' turns');
        break;
    }
}

```

## Output:

```
ALERT:  Guess number
PROMPT: 5
ALERT:  TOO LOW
PROMPT: 20000
ALERT:  TOO LOW
PROMPT: 30000
ALERT:  TOO HIGH
PROMPT: 25000
ALERT:  TOO HIGH
PROMPT: 22500
ALERT:  TOO HIGH
PROMPT: 21000
ALERT:  TOO HIGH
PROMPT: 20500
ALERT:  TOO HIGH
PROMPT: 20200
ALERT:  TOO LOW
PROMPT: 20400
ALERT:  TOO LOW
PROMPT: 20450
ALERT:  TOO LOW
PROMPT: 20475
ALERT:  TOO HIGH
PROMPT: 20460
ALERT:  TOO LOW
PROMPT: 20468
ALERT:  TOO HIGH
PROMPT: 20464
ALERT:  TOO LOW
PROMPT: 20466
ALERT:  TOO LOW
PROMPT: 34000
ALERT:  -32767-32768
PROMPT: 20467
ALERT:  Great! You found the number in 17 turns!
PROMPT: (nothing)

```

# Answer
> 20 votes
# Perl 5.10+: ~~159~~ 144 bytes − 350 = −206 points

```
say"Guess 16 bit signed number";$==32767-rand 65536;say(TOO.$",$_<0?LOW:HIGH)while++$i,$_=<>-$=;say"Congrats! You found the number in $i turns!"

```

**Edit 2:** With the recent rules change that allows me to use any string literal for the "congrats" message, I can save 15 bytes from my original 159-byte solution. There's nothing particularly novel or interesting about the new code above as compared to the old code (I just got rid of the `p` function, and call `say` directly instead), so the remainder of this post will describe the original code, shown below:

```
sub p{say join$",@_}p Guess,16,bit,signed,number;$==32767-rand 65536;p(TOO,$_<0?LOW:HIGH)while++$i,$_=<>-$=;p Congrats."!",You,found,the,number,in,$i,turns."!"

```

Yeah, I'm abusing the hell out of rule 1. Who needs strings, when you can have barewords? ;-)

Run with `perl -M5.010` to enable the Perl 5.10+ `say` feature (or replace the body of the `p` function with `print join$",@_,$/` for an extra cost of 5 bytes).

Bonus scores:

* −300 points: "display the game rules before starting the game"
* −50 points: "display number of turns taken in the end of game"

The code contains *no* string literals in a strict sense, so I'd say that rule 1 is, technically, not violated. The trick is that, in Perl, without `use strict`, any identifier that doesn't correspond to a known language keyword or subroutine will simple evaluate to its own name. The function `p` then simply takes a list of words and prints them out, separated by spaces.

Example play-through:

```
Guess 16 bit signed number
0
TOO HIGH
-10000
TOO LOW
-5000
TOO HIGH
-7500
TOO LOW
-6250
TOO HIGH
-6875
TOO LOW
-6553
TOO HIGH
-6700
TOO HIGH
-6790
TOO LOW
-6745
TOO HIGH
-6767
TOO LOW
-6756
TOO HIGH
-6761
Congrats! You found the number in 13 turns!

```

**Edit:** Oh, right, the rules say I need to post an un-golfed version of the code too, so here it goes. Technically, it's "de-golfed", since I usually compose my code golf programs in more or less fully golfed form from the beginning, and it can sometimes be tricky to remove all the "golfy" optimizations without fundamentally changing how some parts of the program work. Still, I've at least tried to add whitespace, comments and more meaningful function / variable names:

```
sub output {
    # print all arguments separated by spaces, plus a newline:
    # (in the golfed code, I use the special variable $" instead of " " for a space)
    say join " ", @_;
}

# print the rules:
output Guess, 16, bit, signed, number;

# choose a random number between -32768 and 32767 inclusive:
# (in the golfed version, using the special variable $= allows
# the int() to be left out, since $= can only take integer values)
$number = int( 32767 - rand 65536 );

# loop until the input equals the chosen number, printing "TOO LOW / HIGH":
# (the loop ends when $diff == 0, since 0 is false in Perl)
output (TOO, $diff < 0 ? LOW : HIGH) while ++$count, $diff = (<> - $number);

# print congratulations, including the loop count:
output Congrats."!", You, found, the, number, in, $count, turns."!";

```

---

**Ps.** As an alternative, if just using barewords instead of strings feels too cheaty for you, here's a 182-byte solution that doesn't use the letters `TOLWHIG` *even in barewords* (but does use them in a transliteration operator). It still gets the same bonuses, for a total score of **182 − 350 = −168 points**:

```
sub t{pop=~y/kpqvxyz/tolwhig/r}say"Guess 16 bit signed number";$==32767-rand 65536;say uc t"kpp ".($_<0?qpv:xyzx)while++$n,$_=<>-$=;say t"Cpnzraks! Ypu fpund kxe number yn $n kurns!"

```

The output looks exactly the same as above. Per the (original) rules, I do use the letters `t` and `i` in printing the rules, since it's allowed; eliminating even those uses would only cost two extra bytes, though. Conversely, making all the output uppercase (which, based on comments above, seems to be allowed) would let me save three bytes.

# Answer
> 15 votes
# Python 2: -80 points (270-300-50)

```
print"WhileURong(USayNumbr;ISayBigrOrSmalr)"
import random
r=random.randint(-32768,32767)
g=i=1
while g:g=cmp(input(),r);print("C\x6fn\x67ra\x74s! Y\x6fu f\x6fund \x74\x68e number \x69n %d \x74urns!"%i,"\x54\x4f\x4f \x48\x49\x47\x48","\x54\x4f\x4f \x4c\x4f\x57")[g];i+=1

```

Score is 270 characters, minus 300 for showing the instructions, minus 50 for showing the number of guesses in the "congrats!" string, for a total of negative 80 points.

Ungolfed version of the loop, with unescaped strings:

```
while g:
    g=cmp(input(),r)
    print ("Congrats! You found the number in %d turns!"%i,
           "TOO HIGH",
           "TOO LOW")[g]
    i+=1

```

The built-in `cmp` function returns 0 if the values are equal, -1 if the first is smaller and 1 if the first is bigger. I use the value to index a tuple of strings, and then again as the exit condition of the loop. Indexing a sequence with a negative index (like -1) counts from the end of the sequence, rather than from the start.

I was sorely tempted to skip the imports and just use `4` as my random number, as per XKCD 221 (would that qualify for the -25 character bonus?).

Example run (complete with an error, where I can't do negative math):

```
WhileURong(USayNumbr;ISayBigrOrSmalr)
0
TOO HIGH
-16000
TOO LOW
-8000
TOO HIGH
-12000
TOO HIGH
-14000
TOO LOW
-13000
TOO HIGH
-13500
TOO HIGH
-13750
TOO LOW
-13625
TOO HIGH
-13712
TOO LOW
-13660
TOO HIGH
-13640
TOO HIGH
-13685
TOO HIGH
-13700
TOO LOW
-13695
TOO LOW
-13690
TOO LOW
-13687
Congrats! You found the number in 17 turns!

```

# Answer
> 13 votes
# JavaScript 293, -300 (rules) - 50 (turns display) - 25 (range warning) - 25 (no random function) = -107 (new score)

`r=new Date%65536+~(z=32767);n=x="";for((A=alert)("\107uess my number, \111 \147\151ve feedback");(x=prompt())!=r;A(0>(x-~z^x-z)?"\164\157\157 "+(x>r?"\150\151\147\150":"\154\157\167"):"Ran\147e: "+~z+" - "+z))n++;A("C\157n\147ra\164s! Y\157u f\157und \164\150e number \151n "+ ++n+"\164urns!")`

I'd claim that by RGB conventions that black is a color, but that would be kinda cheating...

Oh, and might I add, no breaking rule #1, either!

Output in a series of alerts and prompts

```
ALERT: Guess my number, I give feedback
PROMPT: 0
ALERT: too low
PROMPT: 16000
ALERT: too low
PROMPT: 24000
ALERT: too low
PROMPT: 28000
ALERT: too high
PROMPT: 26000
ALERT: too high
PROMPT: 25000
ALERT: too low
PROMPT: 25500
ALERT: too high
PROMPT: 25250
ALERT: too low
PROMPT: 25375
ALERT: too high
PROMPT: 25310
ALERT: too low
PROMPT: 25342
ALERT: too low
PROMPT: 25358
ALERT: too low
PROMPT: 25366
ALERT: too high
PROMPT: 25362
ALERT: too high
PROMPT: 25360
ALERT: too high
PROMPT: 25359
ALERT: Congrats! You found the number in 16 turns!

```

Ungolfed code:

```
r = (new Date)%65536+~(z=32767); //Generates random number in range based off date's milliseconds... I'd use epoch, but I need to conserve
n=x=""; // Sets count and input to blank, these change as time goes on
// The line below sets up a call for `alert`, provides the initial rules, and subsequent loops compares the prompt with the number, as well as sets up "too", "high",  "low" and "out of range" message strings, and provides the feedback
for((A=alert)("\107uess my number, \111 \147\151ve feedback");(x=prompt())!=r;A(0>(x-~z^x-z)?"\164\157\157 "+(x>r?"\150\151\147\150":"\154\157\167"):"Ran\147e: "+~z+" - "+z))
{
    n++; // adds one to count providing the number isn't guessed yet
}
alert("C\157n\147ra\164s! Y\157u f\157und \164\150e number \151n "+ ++n+" \164urns!") // Congratulates the player, and displays the correct number of turns taken

```

# Answer
> 7 votes
## Javascript, 324 bytes, score -76

\[Updated due to rule changes\]

* 324 bytes
* -300 for showing the rules
* -50 for showing the turns when the user wins
* -25 for telling the user when he inputs a number outside the range
* -25 for not using built-in random (updated)

Total score: -76

Golfed:

```
function q(y){return y.replace(/./g,function(x){h=x.charCodeAt(0);return String.fromCharCode(h>32&h<58?h+32:h)})}d=o=32768;alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");for(a=1,n=new Date%(2*o)-o;d-n;a++)d=+prompt(a),alert(d>=o|d<-o?"BAD":d<n?q("4// ,/7"):d>n?q("4// ()'("):"Congrats! You found the number in "+a+" turns!")

```

Lets ungolf this mess.

First, properly idented (but this is still not very good with obfuscated code):

```
function q(y) {
  return y.replace(/./g, function(x) {
    h = x.charCodeAt(0);
    return String.fromCharCode(h > 32 & h < 58 ? h + 32 : h)
  })
}

d = o = 32768;
alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");

for (a = 1, n = new Date % (2 * o) - o; d - n; a++)
  d = +prompt(), alert(d >= o | d < -o ? "BAD" : d < n ? q("4// ,/7") : d > n ? q("4// ()'(") : "Congrats! You found the number in " + a + " turns!")

```

Second, renaming identifiers:

```
function unencrypt(encrypted) {
  return encrypted.replace(/./g, function(character) {
    charCode = character.charCodeAt(0);
    return String.fromCharCode(charCode > 32 & charCode < 58 ? charCode + 32 : charCode)
  })
}

guess = limit = 32768;
alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");

for (tries = 1, randomNumber = new Date % (2 * o) - o; guess - randomNumber; tries++)
  guess = +prompt(),
  alert(guess >= limit | guess < -limit ? "BAD" : guess < randomNumber ? unencrypt("4// ,/7") : guess > randomNumber ? q("4// ()'(") : "Congrats! You found the number in " + tries + " turns!")

```

So the unencrypt function gets all characters between ASCII 33 (`!`) and ASCII 58 (`:`) and adds 32, converting them in characters in the range `A-Z`.

Lets ungolf the code more by unecrypting all the strings:

```
guess = limit = 32768;
alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");

for (tries = 1, randomNumber = new Date % (2 * o) - o; guess - randomNumber; tries++)
  guess = +prompt(),
  alert(guess >= limit | guess < -limit ? "BAD" : guess < randomNumber ? "TOO LOW" : guess > randomNumber ? "TOO HIGH" : "Congrats! You found the number in " + tries + " turns!")

```

And finally lets move some instructions to other places, replace the long ternary chain with ifs and elses, join concatenating strings, and simplify the math, to increase the readability:

```
guess = 32768;
alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");

randomNumber = new Date % 65536 - 32768;

for (tries = 1; guess - randomNumber; tries++) {
  guess = +prompt(); // The preceding + is a golfing trick to convert string to number.
  if (guess > 32767 | guess < -32768) {
    alert("BAD");
  } else if (guess < randomNumber) {
    alert("TOO LOW");
  } else if (guess > randomNumber) {
    alert("TOO HIGH");
  } else {
    alert("Congrats! You found the number in " + tries + " turns!");
  }
}

```

Sample:

```
ALERT:  WhileURong(USayNumbr;ISayBigrOrSmalr)
PROMPT: 5
ALERT:  TOO LOW
PROMPT: 20000
ALERT:  TOO LOW
PROMPT: 30000
ALERT:  TOO HIGH
PROMPT: 25000
ALERT:  TOO HIGH
PROMPT: 22500
ALERT:  TOO HIGH
PROMPT: 21000
ALERT:  TOO HIGH
PROMPT: 20500
ALERT:  TOO HIGH
PROMPT: 20200
ALERT:  TOO LOW
PROMPT: 20400
ALERT:  TOO LOW
PROMPT: 20450
ALERT:  TOO LOW
PROMPT: 20475
ALERT:  TOO HIGH
PROMPT: 20460
ALERT:  TOO LOW
PROMPT: 20468
ALERT:  TOO HIGH
PROMPT: 20464
ALERT:  TOO LOW
PROMPT: 20466
ALERT:  TOO LOW
PROMPT: 20467
ALERT:  Congrats! You found the number in 16 turns!"

```

# Answer
> 7 votes
# C - 272 characters - 300 - 50 - 25 = -103

* -300 for displaying the rules;
* -50 for telling the player the number of turns;
* -25 for not using a standard RNG library.

Golfed code:

```
main(i){short a,c=i=0,b=time(0);for(a=b;b--;a=(a*233)+4594);b=a;puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");while(1){i++;scanf("%hi",&a);if(a==b){printf("Congrats! You found the number in %i turns!",i);break;}for(c=0;c^9;c++)putchar(c[a<b?"kff7cfn7!":"kff7_`^_!"]-23);}}

```

Ungolfed:

```
int main(int i) {
    short a,
          b = time(0),
          c = i = 0;

    for( a = b ; b-- ; a = (a * 233) + 4594);
    b = a;

    puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");

    while(1) {
        i++;
        scanf("%hi", &a);
        if(a == b) {
            printf("Congrats! You found the number in %i turns!", i);
            break;
        }
        for( c = 0 ; c ^ 9 ; c++ )
            putchar(c[ a < b ? "kff7cfn7!" : "kff7_`^_!" ] - 23);
    }
}

```

Output:

# Answer
> 5 votes
# C: 237 - 300 - 50 - 25 - 25 - 10: -173 points

-300 for the rules, -50 for showing the number of guesses, -25 for not using any built-in random number generator, -25 for the out of range message and -10 for colouring the congrats message.

```
int s[3]={542068564},g,n;main(r){for(r=(short)&r,puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");n++,scanf("%d",&g),s[1]=g<r?5721932:1212631368,g^r;puts(g^(short)g?"OOR":s));printf("\033[31mCongrats! You found the number in %d turns!",n);}

```

Ungolfed:

```
int s[3]={542068564},g,n;

main(r){
        for(
                r=(short)&r,
                puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");

                n++,
                scanf("%d",&g),
                s[1]=g<r?5721932:1212631368,
                g^r;

                puts(g^(short)g?"OOR":s)
        );

        printf("\033[31mCongrats! You found the number in %d turns!",n);
}

```

Example run:

```
WhileURong(USayNumbr;ISayBigrOrSmalr)
-32769
OOR
32768
OOR
0
TOO HIGH
-16384
TOO HIGH
-24576
TOO HIGH
-28672
TOO LOW
-26624
TOO LOW
-25600
TOO HIGH
-26112
TOO LOW
-25856
TOO LOW
-25728
TOO LOW
-25664
TOO HIGH
-25696
TOO HIGH
-25712
TOO LOW
-25704
Congrats! You found the number in 15 turns!

```

The last line shows up as red.

# Answer
> 4 votes
## C#: -30 points

* 345 bytes
* -300 for showing the rules
* -50 for showing the turns when the user wins
* -25 for telling the user when he inputs a number outside the range

**Golfed**:

```
int l=-32768,h=32767,n=new Random().Next(l,h),t=0,g=h+1;Console.Write("WhileURong(USayNumbr;ISayBigrOrSmalr)\n");while(n!=g){g=Convert.ToInt32(Console.ReadLine());Console.WriteLine(g==n?"C\x6fn\x67ra\x74s! Y\x6fu f\x6fund \x74\x68\x65 number in {0} \x74urns!":g<l||g>h?"BAD":g<n?"\x54\x4f\x4f \x4c\x4f\x57":"\x54\x4f\x4f \x48\x49\x47\x48",++t);}

```

To run it, put it in a file (code.cs) and run with scriptcs on the command line: `scriptcs code.cs`.

**Ungolfed**: Expanded variable names into something easier to understand, and changed hex letters into real letters.

```
int low = -32768,
    high = 32767,
    number = new Random().Next(low, high),
    turns = 0,
    guess = h+1;
Console.Write("WhileURong(USayNumbr;ISayBigrOrSmalr)\n");  // instructions
while (number != guess)
{
    guess = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(
      guess == number                                     // if you got it right
        ? "Congrats! You found the number in {0} turns!"  // give the victory speech
        : guess < low || guess > high                     // if out of range
          ? "BAD"                                         // let them know
          : guess < number                                // if guess is low
            ? "TOO LOW"                                   // tell them low
            : "TOO HIGH"                                  // otherwise tell them high
      , ++turns                                           // preincrement turns, add to output
    );
}

```

Sample output available here.

# Answer
> 4 votes
# bash, -137

### Score

273 (bytes) - 300 (rules) - 50 (count tries) - 25 (OOF warning) - 25 (custom PRNG) - 10 (color)

# Golfed version

```
IFS=# a=(`<$0`)
c=65536
y=$[10#`date +%N`%c]
e(){ echo -e ${a[$1]/z/$z};}
e 7
while read x
do((z++,x+=c/2,i=3+(x>y),x==y))&&break
((x<0||x>c-1))&&i=6
e $i
done
e 5
#TOO LOW#TOO HIGH#\e[32mCongrats! You found the number in z turns!#OOR#Guess my number. I'll say HIGH or LOW.

```

Note that the last line is a comment, so it contains no string or character literals.

### Ungolfed version

```
MYNUMBER=$[10#$(date +%N) % 65536 - 32768]
echo "Guess my number. I'll say HIGH or LOW."

while true; do
    read YOURGUESS
    GUESSES=$((GUESSES + 1))

    if ((YOURGUESS == MYNUMBER)); then
        break
    elif ((YOURGUESS < -32768 || YOURGUESS > 32767)); then
        echo OOR
    elif ((YOURGUESS < MYNUMBER)); then
        echo "TOO LOW"
    else
        echo "TOO HIGH"
    fi
done

echo -e "\e[32mYou found the number in $GUESSES turns!"

```

### Sample output

```
$ ./tlth
Guess my number. I'll say HIGH or LOW.
-32769
OOR
32768
OOR
0
TOO LOW
16384
TOO HIGH
8192
TOO HIGH
4096
TOO HIGH
2048
TOO HIGH
1024
TOO HIGH
512
TOO HIGH
256
TOO HIGH
128
TOO HIGH
64
TOO HIGH
32
TOO LOW
48
TOO HIGH
40
TOO LOW
44
TOO HIGH
42
Congrats! You found the number in 17 turns!

```

The last line is printed in green.

# Answer
> 2 votes
# C++ 505 + (-300-50-25-25) = 105

-300 : Instructions
-50 : Showing number of turns
-25 : Not using random function
-25 : warning user about input out of range

### GOLFED

```
#include<iostream>
#include<stdlib.h>
using namespace std;int main(){short int a,i=0,*r=new short int;int b=0;a=*r;char t[]={84,79,79,' ','\0'},l[]={76,79,87,'\n','\0'},h[]={72,73,71,72,'\n','\0'};cout<<"WhileURong(USayNumbr;ISayBigrOrSmalr)\n";while(a!=b){cin>>b;if(b<-32768||b>32767){cout<<"Sorry! the number is out of range please enter the number again\n";continue;}i++;if(b<a){cout<<'\n'<<t<<l;}if(b>a){cout<<'\n'<<t<<h;}if(a==b){cout<<"Congrats!You found the number in "<<i<<" turns!";}}return 0;}

```

### UNGOLFED

```
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    short int a,i=0,*r=new short int;
    int b=0;
    a=*r;
    char t[]={84,79,79,' ','\0'},l[]={76,79,87,'\n','\0'},h[]={72,73,71,72,'\n','\0'};
    cout<<"WhileURong(USayNumbr;ISayBigrOrSmalr)\n";
    while(a!=b)
    {
        cin>>b;
        if(b<-32768||b>32767)
        {
            cout<<"Sorry! the number is out of range please enter the number again\n";
            continue;
        }
        i++;
        if(b<a)
        {
            cout<<'\n'<<t<<l;
        }
        if(b>a)
        {
        cout<<'\n'<<t<<h;
        }
    if( a==b)
    {

            cout<<"Congrats!You found the number in "<<i<<" turns!";
        }
    }
    return 0;
}

```

### OUTPUT

# Answer
> 2 votes
# C, 183-300-25=-142

183 bytes -300 for the rules -25 for not using a random library

```
main(){short g,n=time(0)*(time(0)&1?1:-1);puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");while(g^n)scanf("%d",&g),puts(g>n?"TOO HIGH":g<n?"TOO LOW":"Congrats! You found the number!");}

```

ungolfed version:

```
main(){
    short g,n=time(0)*(time(0)&1?:-1);
    puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");
    while(g^n)
        scanf("%d",&g),
        puts(g>n?"TOO HIGH":g<n?"TOO LOW":"Congrats! You found the number!");
}

```

sample run:

```
WhileURong(USayNumbr;ISayBigrOrSmalr)
40
TOO HIGH
20
TOO HIGH
1
TOO HIGH
0
TOO HIGH
-20
TOO HIGH
-200
TOO HIGH
-2000
TOO HIGH
-20000
TOO LOW
-10000
TOO LOW
-5000
TOO LOW
-3000
TOO HIGH
-4000
TOO LOW
-3500
TOO HIGH
-3700
TOO HIGH
-3900
TOO HIGH
-3950
TOO HIGH
-3970
TOO LOW
-3960
Congrats! You found the number!

```

# Answer
> 2 votes
# J - 190 char -300 -50 = -160 pts

```
'Congrats, you found the number in ',' turns!',~":1>:@]^:(]`(1[2:1!:2~a.{~71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>)@.*@-[:".1!:1@1:)^:_~32767-?2^16['WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2

```

Explanation (recall that J is read from right to left):

* `'WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2` \- Print the rules.
* `32767-?2^16[` \- Toss the return value, and then generate a random number between 0 and 2^16-1 inclusive. Then, adjust it to the range -32768..32767 by subtracting it from 32767.
* `1>:@]^:(...)^:_~` \- The `x u^:v^:_ y` pattern is kinda like a while loop. `x` stays constant, and `y` gets mutated with every execution of `u`. This continues until either `x v y` returns 0 or `x u y` results in no change to `y`. The `~` swaps the two arguments, so that `x` will be the random number and `y` will begin at 1. Our `u` is `>:@]`, which increments this 1 and returns it, so it acts as a counter and the `x u y` termination condition can never occur.
* `[:".1!:1@1:` \- Take the counter, and ignore its value, using the number 1 instead (`1:`). Read in a line of input (`1!:1`) from the keyboard (file handle 1) and execute it (`".`). This allows J, whose negative sign is normally `_`, to take numbers in the form `-n` (evaluates as negation applied to the number `n`).
* `]`(...)@.*@-` \- Take the difference of the random number from before and the guess (`-`). Now, we select the next action depending on whether this difference is zero (`@.*`). If it is, return (`]``) that 0 as the result for `x v y`, so that execution terminates, and the whole while loop returns the counter. Else...
* `71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>` \- Return the array `5 8 16` if the number is negative, and `1 2 0 1` if it is positive. Then prepend `13 8 8 _39` and add 71 to everything, so we have either `84 79 79 32 76 79 87` or `84 79 79 32 72 73 71 72`.
* `1[2:1!:2~a.{~` \- Turn these numbers to ASCII characters by indexing the alphabet `a.` with them. Then print them out with `1!:2` (using file handle 2) and return 1 as the result of `x v y`.
* `'Congrats, you found the number in ',' turns!',~":` \- When the loop finishes, it returns the counter. Convert it to a string with `":` and put it in between the strings `'Congrats, you found the number in '` and `' turns!'`.

Sample output:

```
   'Congrats, you found the number in ',' turns!',~":1>:@]^:(]`(1[2:1!:2~a.{~71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>)@.*@-[:".1!:1@1:)^:_~32767-?2^16['WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2
WhileURong(USayNumbr;ISayBigrOrSmalr)
0
TOO HIGH
-20000
TOO LOW
-10000
TOO LOW
-5000
TOO HIGH
-7500
TOO HIGH
-8750
TOO HIGH
-9000
TOO HIGH
-9500
TOO LOW
-9250
TOO HIGH
-9375
TOO HIGH
-9450
TOO LOW
-9400
TOO HIGH
-9425
TOO HIGH
-9437
TOO LOW
-9431
TOO LOW
-9428
TOO HIGH
-9430
TOO LOW
-9429
Congrats, you found the number in 18 turns!

```

# Answer
> 2 votes
# JavaScript -40

335 - 300 (rules) - 50 (count turns) - 25 (out of range)

Not gonna win but a fun way to get the letters I think.

### Golfed

```
!function T(O,L,W,H,I,G){a=T.toString();c=L.floor(65536*L.random())+H;O(W+G+" between "+H+" & "+I);k=(f=a[9]+(d=a[11])+d+" ")+(e=a[17])+a[19]+a[21]+e;l=f+a[13]+d+a[15];for(m=1;(n=prompt(W+G))!=c;m++)n<H||n>I?O("Out of range"):n>c?O(l):O(k);O("Congrats! You found the"+G+" in "+m+" turns!")}(alert,Math,"Guess a",-32768,32767," number")

```

### Ungolfed

```
!function T(O,L,W,H,I,G){
    fn = T.toString();
    random = L.floor(L.random() * 65536) + H;

    O(W + G + " between " + H + " & " + I);

    tooLow = (too = fn[9] + (o = fn[11]) + o + " ") + (h = fn[17]) + fn[19] + fn[21] + h;
    tooHigh = too + fn[13] + o + fn[15];

    for (n=1; (guess = prompt(W + G)) != random; n++) {
        if (guess < H || guess > I) {
            O("Out of range");
        } else if (guess > random) {
            O(tooHigh);
        } else {
            O(tooLow);
        }
    }

    O("Congrats! You found the" + G + " in " + n + " turns!");
}(alert, Math, "Guess a", -32768, 32767, " number")

```

### Sample output

```
(ALERT) Guess a number between -32768 & 32767
(PROMPT) Guess a number
9999999
(ALERT) Out of range
(PROMPT) Guess a number
0
(ALERT) TOO LOW
(PROMPT) Guess a number
8008
(ALERT) Congrats! You found the number in 3 turns!

```

# Answer
> 1 votes
## APL (Dyalog) (157 - 300 - 50 = -193)

(Yes, these count as bytes, the APL charset fits in a byte.)

I've claimed "display the game rules" and "count the number of turns".

```
G
n←32768-?65536
t←0
⎕←'Guess 16-bit signed number'
t+←1
→8/⍨n=g←⎕
⎕←⎕AV[(⌽⎕AV)⍳'×↑↑ ','○↑-' '∇⌊∘∇'⊃⍨1+n<g]
→4
⎕←'Congrats! You found the number in't'tries!'

```

Example run:

```
      G
Guess 16-bit signed number
⎕:
      0
TOO HIGH
⎕:
      -10000
TOO LOW
⎕:
      -5000
TOO LOW
⎕:
      -2500
TOO LOW
⎕:
      -1250
TOO HIGH
⎕:
      -1750
TOO LOW
⎕:
      -1500
TOO LOW
⎕:
      -1375
TOO LOW
⎕:
      -1300
TOO LOW
⎕:
      -1275
TOO LOW
⎕:
      -1265
TOO HIGH
⎕:
      -1270
TOO HIGH
⎕:
      -1273
 Congrats! You found the number in  13  tries!

```

Ungolfed:

```
GuessNumber;num;tries;guess;decode;too;low;high
decode←{⎕AV[(⌽⎕AV)⍳⍵]} ⍝ invert the character code, char 1 becomes char 255 etc.
num←32768-?65536 ⍝ select a random number
tries←0

⍝ strings for low/high
too←decode '×↑↑ '
low←decode '○↑-'
high←decode '∇⌊∘∇'

⎕←'Guess 16-bit signed number'

try:
  tries +← 1
  guess ← ⎕
  →(guess=num)/found
  ⍝ still here: number was wrong
  ⎕←too, (1+num<guess)⊃low high  ⍝ output appropriate word
  →try ⍝ try again
found:
  ⎕←'Congrats! You found the number in' tries 'tries!'

```

# Answer
> 1 votes
## Pogo: -95 (255 - 300 - 50)

```
method main:void
    print("Guess the number. You will be told if you are high or low.")
    declare(integer,n,0)
    declare(integer,i,0)
    declare(integer,j,0)
    random() i
    while j != i
        set(n+1) n
        print("Number?")
        getinput() j
        if j > i
            print("High")
        end
        else
            print("Low")
        end
    end
    print("Yay" n "turns")
end main

```

---

If the number is 10:

> Number?
>
> 5
>
> Low
>
> 8
>
> Low
>
> 12
>
> High
>
> 10
>
> Yay 4 turns

---

The character count is based on the code with all whitespace removed.

Note that Pogo is not a fake language. I created it and wrote a compiler and IDE for it here: https://github.com/nrubin29/Pogo

---
Tags: code-golf
---