10
\$\begingroup\$

Description

Create a fully working "Guess the number" game. The game is played by two players as follows:

  1. player one chooses a number (A) between 1 and N
  2. player two tries to guess A choosing a number (B) in the same range
  3. the first player responds "higher" if A > B, "lower" if A < B or "correct" if A = B.
  4. steps 2-3 are repeated I times or until "correct" is responded.
  5. If "correct" is heard, player two wins otherwise he loses.

Specs

Minimum specs for a valid entry:

  • user can play either as player one or player two.
  • computer plays the other role.
  • computer must really try to guess the number while playing as player two (so, guessing against the given data or ignoring the given data is cheating)
  • N = 100 or input by the user (your choice)
  • I = 5 or input by the user (your choice)
  • program must announce then winner at the end.
  • full human readable instructions of what to do in each step (e.g "Play as player one or player two?", "Enter another guess:", etc) - don't go nuts on this one; just keep it simple.

Winning conditions

In that order:

  1. Highest voted entry wins if it's at least 3 votes ahead of the second highest voted entry.
  2. Shortest entry wins.
\$\endgroup\$
6
  • \$\begingroup\$ I didn't explicitely read we needed an AI on that one. Could you confirm both players are human? \$\endgroup\$
    – J B
    Commented Feb 21, 2011 at 16:32
  • \$\begingroup\$ @JB: sorry about that :/ You do need an AI. I'm updating the question now... \$\endgroup\$
    – Eelvex
    Commented Feb 21, 2011 at 16:37
  • 2
    \$\begingroup\$ I think the instruction texts for each step should be given, otherwise it's hard to compare the answers. \$\endgroup\$
    – Joey
    Commented Feb 23, 2011 at 2:12
  • \$\begingroup\$ @Joey Definitely \$\endgroup\$ Commented Feb 23, 2011 at 14:59
  • \$\begingroup\$ Is user input validation important? \$\endgroup\$
    – zzzzBov
    Commented Mar 8, 2011 at 20:15

14 Answers 14

9
\$\begingroup\$

TRS-80 BASIC, 249 characters

I think this may be the first time I've submitted an answer to this site that I wrote before the site existed.

0 CLS:RANDOM:A=1:B=1E3:Q=RND(1E3):FORX=1TO8E9:PRINTA"-"B:INPUT"
 Guess";C:IFC<AORC>B,X=X-1:NEXTELSEIFC<QPRINT"Too low":A=C+1:NEXTELSEIFC>QPRINT"Too high":B=C-1:NEXTELSEPRINTC"is right!!
 It took you"X"tries.
":X=9E9:NEXT:FORX=0TO0:X=INKEY$="":NEXT:RUN

In fact, I wrote it before the worldwide web existed. Back in the 1980s, just as TRS-80s were becoming irrelevant.

This is an example of a "one-liner" — an attempt to fit the most interesting program you could into a single line of BASIC. It was my first one-liner, and not terribly impressive. (There were some amazing one-liners floating around out there.)

A line of TRS-80 BASIC was limited to 255 characters, minus a couple for overhead. Though you could sometimes exceed this, since the true limit was 255 bytes after tokenization — but the editor would also truncate a line that had over 255 characters before tokenization, and you needed to use tricks in the line editor in order to insert literal control characters like newlines into your strings.

And yes, to clarify, those line breaks in the listing are literal newline characters. (In order to get them in your code you needed to use the Change command while EDITing the line. A total pain, but worth it to replace eight or more characters for +CHR$(13) with one.)

Damn, I've been golfing for a long time.

\$\endgroup\$
6
\$\begingroup\$

C 397 Characters

N,H=99,L=0,c=0,w=1;main(){char s[9];puts("Play as player 1 or 2: ");scanf("%d",&N);if(N-1){getchar();do{N=rand()%(H-L)+L+1;printf("My guess: %d\n",N);gets(s);if(*s=='c'){w=2;break;}if(*s-'l')H=N-1;else L=N-1;c++;}while(c<5);}else{N=rand()%99+1;while(c<5){puts("Enter guess: ");scanf("%d",&H);if(H==N){puts("correct");break;}else puts(H>N?"higher":"lower");c++;}if(c==5)w=2;}printf("Winner %d",w);}

In a more readable form.

main()
{
        int i,N,H=100,L=0,c=0,w=1;
        char s[10];
        puts("Play as player 1 or 2: ");
        scanf("%d",&i);
        if(i-1)
        {
                getchar();
                do{
                        N=rand()%(H-L)+L+1;
                        printf("My guess: %d\n",N);
                        gets(s);
                        if(s[0]=='c')break;
                        else if(s[0]=='h')H=N-1;
                        else L=N-1;
                        c++;
                }while (c<5);
                if(c<5)w=2;
        }
        else
        {
                N=rand()%99+1;
                while (c<5)
                {
                        puts("Enter another guess: ");
                        scanf("%d",&H);
                        if(H==N){printf("correct\n");break;}
                        else if(H>N)printf("higher\n");
                        else printf("lower\n");
                        c++;
                }
                if(c==5)w=2;
        }
        printf("Winner %d",w);
}
\$\endgroup\$
3
  • \$\begingroup\$ @Joey Corrected Now. \$\endgroup\$
    – fR0DDY
    Commented Feb 24, 2011 at 9:07
  • \$\begingroup\$ well, i do not know complete C. But can you please explain how a program with variables with no type specifier compiles? \$\endgroup\$
    – MAKZ
    Commented Oct 28, 2014 at 7:41
  • \$\begingroup\$ Any variable with no specified type is an integer \$\endgroup\$
    – Ethiraric
    Commented Oct 28, 2014 at 8:00
4
\$\begingroup\$

C#:

Character count: With spaces: 575 No spaces: 464

    static void Main()
    {
        Action<object> w = s => Console.WriteLine(s);
        Func<object, byte> r = t => { w(t); var s = Console.ReadLine(); return Convert.ToByte(s); };
        var p = r("Player (1/2):");
        int N = 100, g, i = 0, c, d;
        var q = new List<int>(Enumerable.Range(0, N));
        Func<Guid> x = Guid.NewGuid;
        c = p == 1 ? r("Number:") : q.OrderBy(j => x()).First();
        m: i++;
        g = p == 2 ? r("Guess:") : q.OrderBy(j => x()).First();
        d = g < c ? -1 : (g > c ? 1 : 0);
        w(d == -1 ? "Higher" : (d == 1 ? "Lower" : "correct"));
        q = q.Where(n => d == -1 ? n > g : n < g).ToList();
        if(c != g && i < 5) goto m;
        r(g);
    }

Edit do while is now "Goto" (shiver)

\$\endgroup\$
3
\$\begingroup\$

Windows PowerShell, 289

nal ^ Read-Host
filter p{"Player $_ wins.";exit}
$p=1-(^ Player 1 or 2)
$n=($x=1)..($y=99)|random
if($p){$n=^ Enter number}1..5|%{if($p){'{0:"higher";"lower";"correct";2|p}'-f($n-(^ Guess))|iex}else{"Guessing, "+($g=$x..$y|random);@{104='$x=$g+1';108='$y=$g-1';99='2|p'}[+(^)[0]]|iex}}
1|p

History:

  • 2011-02-21 18:44 (620) Ungolfed.
  • 2011-02-21 19:15 (365) First round of golfing.
  • 2011-02-21 19:31 (359) Some inlining.
  • 2011-02-21 19:38 (340) Some strings shortened.
  • 2011-02-21 19:44 (339) whilefor
  • 2011-02-21 19:53 (331) Some duplicate strings pulled into variables.
  • 2011-02-21 19:53 (330) Another variable inlined.
  • 2011-02-21 19:53 (328) Optimized loop condition. Can't use a pipeline, though.
  • 2011-02-22 01:57 (326) else{if...}elseif – saves the braces.
  • 2011-02-22 12:42 (325) Moved plenty of stuff around, using a hashtable instead of the switch to avoid naming the loop. Now I can use just break and a pipeline, too. Winner announcement moved into a filter that uses exit so no break required, ever.
  • 2011-02-23 01:23 (308) Instead of an elseif chain for checking the guess I just use a format string with different values for negative, positive and zero values. Saves a lot.
  • 2011-02-23 02:16 (306) Using subtraction instead of equality.
  • 2011-03-12 02:27 (289) Reduced to the same level of rudimentary user interaction as the Ruby solution. Of course it's shorter then.
\$\endgroup\$
0
3
\$\begingroup\$

Good old plain C

#include <stdio.h>
#define x(s) puts(s)
main(){int c,i,l,h,g;srand(time(NULL));p:x("You want to guess (1) or should I (2)?");scanf("%d",&c);i=5;if(c==2){x("Think a number 1..100");h=100;l=1;goto t;}if(c==1){x("Guess a number 1..100");h=rand()%100+1;goto g;}return 0;t:if(!i--)goto u;printf("%d (1)higher (2)lower (3)correct",g=rand()%(h-l)+l);scanf("%d",&c);if(c==1)l=g;if(c==2)h=g;if(c==3)goto c;goto t;g:if (!i--)goto c;scanf("%d",&g);if(g>h)x("lower");if(g<h)x("higher");if(g==h){x("correct");goto u;}goto g;u:x("You win");goto p;c:x("I win");goto p;}
  • 23/11/2011 16:44:00 883 nice and cosy
  • 24/11/2011 09:38:00 616 fixed & shortened
  • 24/11/2011 11:52:00 555 shortened
\$\endgroup\$
1
  • 1
    \$\begingroup\$ you wrote this in the future? that's very clever!! \$\endgroup\$
    – mikera
    Commented Mar 8, 2011 at 21:44
3
\$\begingroup\$

JavaScript

New minified version (dropped var and reduced alert calls:

268 chars

function g(m){n=u(confirm('Player pick?'));function u(p){if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));alert(g<n?'higher':g>n?'lower':'correct')}}

To run call g(100);, self-execution is not counted, as it adds a variable number of characters (275 chars for g(100);).

original (somewhere around 600 chars including whitespace):

function guessTheNumber(m)
{
  var n = getNum(confirm('Player pick the number?')), g;
  
  function getNum(p)
  {
    var n;
    if (p)
    {
      do
      {
        n = parseInt(prompt('What number?'));
      } while(isNaN(n) || !n || n > m);
    }
    else
    {
      n = parseInt(Math.random() * m) + 1;
    }
    return n;
  }
  
  while(g!==n)
  {
    do
    {
      g = parseInt(prompt('Take a guess!'));
    } while(isNaN(g));
    if (g < n)
    {
      alert('higher');
    }
    else if (g > n)
    {
      alert('lower');
    }
    else
    {
      alert('correct!');
    }
  }
}

Minified (312):

function g(m){var g,n=u(confirm('Player pick?'));function u(p){var n;if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));if(g<n) alert('higher');else if(g>n) alert('lower');else alert('correct')}}
\$\endgroup\$
6
  • \$\begingroup\$ sorry, I didn't notice. Better put your latest code on the top. (Also, I can't get it to run properly :-/) \$\endgroup\$
    – Eelvex
    Commented Mar 11, 2011 at 20:27
  • \$\begingroup\$ @Eelvex: While you're trying to get that to run, my solution is shorter than the currently accepted again. And you should really specify the exact strings to be used when interacting with the user. Basically everything Magnus has done was to use more concise interaction which of course is shorter. \$\endgroup\$
    – Joey
    Commented Mar 12, 2011 at 1:31
  • \$\begingroup\$ Am I seeing that correctly and this program does not handle the case where the human is player 1 correctly? At least I don't see code for the AI to guess a number and the player to enter »higher«, »lower« or »correct« anywhere ... \$\endgroup\$
    – Joey
    Commented Mar 12, 2011 at 1:35
  • \$\begingroup\$ @Joey, I was under the impression that if a human player were to go first, they'd only have to pick a number. I guess I'm a bit foggy on why a human player would be choosing higher, lower, and correct \$\endgroup\$
    – zzzzBov
    Commented Mar 12, 2011 at 2:06
  • \$\begingroup\$ Just follow the instructions for players 1 and 2. One of them is a human, the other is a computer. There is no difference in protocol, though. Also the sentence »computer must really try to guess the number while playing as player two« very much implies that the computer has to guess a number. \$\endgroup\$
    – Joey
    Commented Mar 12, 2011 at 2:09
3
\$\begingroup\$

Python 2.7 334 335 327 314 300 Characters (My first time golfing)

(335) Forgot to escape newline.

(327) Removed redundant 100 for randint. Comparison of first character of response, instead of whole string.

(314) Updated printing who won.

(300) Changed when player was player 1: changed guessing of the number as computer

from random import*
i=input
s="Enter number:"
p=i("Player 1/2:")-1
h=100
N=(i(s),randint(1,h))[p]
b=l=0
for _ in[0]*5:
 exec("g=(h+l)/2;r=raw_input('Guessing '+`g`+':')[0];exec('h=g','l=g')[r=='l'];b=r=='c'","g=i(s);b=g==N;print(('higher','lower')[N<g],'correct')[b]")[p]
 if b:break
print 1+b,"won"
\$\endgroup\$
2
\$\begingroup\$

BASIC, 184

100 INPUT "P1 NUMBER? ";
200 FOR I%=1 TO 5
300 INPUT "P2 GUESS? ";G%
400 INPUT "P1 SENTENCE? ";S$
500 IF S$="CORRECT" THEN 800
600 NEXT I%
700 PRINT "WINNER 1":END
800 PRINT "WINNER 2"

Here's the no-AI version.

\$\endgroup\$
5
  • \$\begingroup\$ I realize this is an old answer, but I didn't know this back then and I just stumbled upon this - you could probably use shorter line numbers like 1, 2, 3, etc., or just assume something like QBASIC/FreeBASIC and omit them completely. \$\endgroup\$
    – user344
    Commented Apr 29, 2014 at 11:19
  • \$\begingroup\$ @nyuszika7h It's more of a popularity contest than code golf, I'd rather go for the more typical hundred-range numbers. \$\endgroup\$
    – J B
    Commented Apr 29, 2014 at 16:12
  • \$\begingroup\$ It is? Well, it's tagged code-golf. \$\endgroup\$
    – user344
    Commented Apr 29, 2014 at 16:32
  • \$\begingroup\$ With specific and explicit (and lousy, IMHO) winning conditions. \$\endgroup\$
    – J B
    Commented Apr 30, 2014 at 7:30
  • \$\begingroup\$ Oh right, I did see that but forgot it. \$\endgroup\$
    – user344
    Commented Apr 30, 2014 at 9:12
2
\$\begingroup\$

Lua 360 Chars

i=io.read p=print I=5 N=100 math.randomseed(os.time())r=math.random p"Play as player one or two?"o=i"*n">1 _=o and p("Input number between 1 and",N)n=o and i"*n"or r(I,N)l,u=1,N for k=1,I do p"Guess!"g=o and r(l,u)or i"*n"p("Guessed",g)if n==g then p"Correct"break elseif n>g then p"Higher"l=g else p"Lower"u=g end end p(o and"I"or"You",n==g and"Won"or"Loose")

Non-golfed version:

i=io.read
p=print
I=5
N=100
math.randomseed(os.time())      -- Make things less predictable
r=math.random                   
p"Play as player one or two?"
o=i"*n">1
_=o and p("Input number between 1 and",N) -- if one, ask for number
n=o and i"*n"or r(I,N)          -- get number from user or random
l,u=1,N                         -- boundaries for doing "smart" guessing
for k=1,I do
    p"Guess!"
    g=o and r(l,u)or i"*n"      -- get guess (random or input)
    p("Guessed",g)
    if n==g then p"Correct!"break -- break loop if guessed correctly
    elseif n>g then             -- if guess to low
    p"Higher"l=g else           -- print + update boundaries
    p"Lower"u=g end
end
p(o and"I"or"You",n==g and"Won"or"Loose") -- Determine outcome!
\$\endgroup\$
2
\$\begingroup\$

Javascript

This is about 800 characters, and includes your basic binary selection 'AI' for the computer player half. I could probably save a few characters if I got rid of all my vars but I don't like leaking variables even while code golfing. I also did a two step "Is this correct?"/"Is this higher?" thing with confirm pop-ups rather than giving a prompt pop-up and checking for "correct"/"higher"/"lower" though that could maybe also save some characters, I didn't really check.

Also, I only tested it on Firefox 4, so I don't know if some of the things I'm doing work consistently, particularly coalescing an invalid input, parsed as NaN, to a default value in my wp function.

function game(N, I) {
    var wa=function(a){window.alert(a)};
    var wc=function(s){return window.confirm(s)};
    var wp=function(s){return window.prompt(s)};
    var ri=function(s,d){return parseInt(wp(s),10)||d};
    var m=function(l,h){return Math.round((h+l)/2)};
    N = N || pd("Highest possible number?",100);
    I = I || pd("How many guesses?",5);
    var p = wc("Be player 2?");
    var s = [1,N];
    var a = p?Math.ceil(Math.random()*N):Math.min(N,Math.max(1,ri("Pick a number from 1 to " + N,1)));
    var w = 0;
    var g = 0;
    if(p) while(I--){while(!(g = ri("Guess:",0)));if(g==a){wa("correct");w=p+1;break;}else{wa(g<a?"higher":"lower")}}
    else while(I--){g = m(s[0],s[1]);if(wc("Is "+g+" correct?")) { w=p+1;break;} else if (wc("Is "+g+" higher?")){s=[s[0],g];}else{s=[g,s[1]];}}
    if(!w)w=!p+1;
    wa("Player " + w + " wins!");
}
game(100,5);
\$\endgroup\$
2
\$\begingroup\$

Java, 1886 chars

import java.io.*;import java.util.*;import java.util.regex.*;public class GuessGame {int L=1;int H=100;int G=5;int N;String HS="higher";String LS="lower";String CS="correct";public static void main(String[] args){if (args.length==2)new GuessGame(Integer.parseInt(args[0]),Integer.parseInt(args[1])).play();else if(args.length==0)new GuessGame(100,5).play();else System.out.println("usage GuessGame HighInteger NumberGuess");}GuessGame(int H,int G){this.H = H;this.G = G;}void play(){int pNum=getInt("Play As Player 1 or Player 2?","1|2");if(pNum==1)playP2();else playP1();System.out.println("The number was "+N);}int getInt(String pmpt,String val){BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));int i=0;Pattern p=Pattern.compile(val);boolean fnd=false;String ln="";try{while(!fnd){System.out.println(pmpt);ln=cin.readLine();Matcher m=p.matcher(ln);fnd=m.find();}i=Integer.parseInt(ln);} catch (Exception ex) {}return i;}String processGuess(int g){if(N>g)return HS;else if(N<g)return LS;else return CS;}void playP1(){N=new Random().nextInt(H);for(;G>0;G--){String rslt=processGuess(getInt("Player 2, enter your guess:","\\d?"));System.out.println(rslt);if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}void playP2() {N=getInt("Player 1, enter your number:", "\\d+");int max=H;int min=L;int nextGuess=min+(max-min)/2;for (;G>0;G--){System.out.println("Player 2, enter your guess:" + nextGuess);String rslt=processGuess(nextGuess);System.out.println(rslt);if(rslt.equals(HS)){min=nextGuess+1;nextGuess=fuzzify(nextGuess+(max-nextGuess)/2,min,max);}if (rslt.equals(LS)){max=nextGuess-1;nextGuess=fuzzify(nextGuess-(nextGuess-min)/2,min,max);}if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}int fuzzify(int i,int mn,int mx){int fz=new Random().nextInt(3);if(fz==1)return Math.max(mn,--i);if(fz==2)return Math.min(mx,++i);return i;}}

Non golfed version:

import java.io.*;
import java.util.*;
import java.util.regex.*;
public class GuessGame {
    int L = 1;
    int H = 100;
    int G = 5;
    int N;
    String HS = "higher";
    String LS = "lower";
    String CS = "correct";
    public static void main(String[] args) {
        if (args.length == 2)
            new GuessGame(Integer.parseInt(args[0]), Integer.parseInt(args[1])).play();
        else if (args.length == 0)
            new GuessGame(100, 5).play();
        else
            System.out.println("usage GuessGame HighInteger NumberGuess");
    }
    GuessGame(int H, int G) {
        this.H = H;
        this.G = G;
    }
    void play() {
        int pNum = getInt("Play As Player 1 or Player 2?","1|2");
        if (pNum == 1)
            playP2();
        else
            playP1();
        System.out.println("The number was " + N);
    }
    int getInt(String pmpt, String val) {
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        int i = 0;
        Pattern p = Pattern.compile(val);
        boolean fnd = false;
        String ln = "";
        try {
            while (!fnd) {
                System.out.println(pmpt);
                ln = cin.readLine();
                Matcher m = p.matcher(ln);
                fnd = m.find();
            }
            i = Integer.parseInt(ln);
        } catch (Exception ex) {}
        return i;
    }
    String processGuess(int g) {
        if (N > g)
            return HS;
        else if (N < g)
            return LS;
        else
            return CS;
    }
    void playP1() {
        N = new Random().nextInt(H);
        for (; G > 0; G--) {
            String rslt = processGuess(getInt("Player 2, enter your guess:", "\\d?"));
            System.out.println(rslt);
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    void playP2() {
        N = getInt("Player 1, enter your number:", "\\d+");
        int max = H;
        int min = L;
        int nextGuess = min + (max - min) / 2;
        for (; G > 0; G--) {
            System.out.println("Player 2, enter your guess:" + nextGuess);
            String rslt = processGuess(nextGuess);
            System.out.println(rslt);
            if (rslt.equals(HS)) {
                min = nextGuess + 1;
                nextGuess = fuzzify(nextGuess + (max - nextGuess) / 2, min, max);
            }
            if (rslt.equals(LS)) {
                max = nextGuess - 1;
                nextGuess = fuzzify(nextGuess - (nextGuess - min) / 2, min, max);
            }
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    int fuzzify(int i, int mn, int mx) {
        int fz = new Random().nextInt(3);
        if (fz == 1)
            return Math.max(mn, --i);
        if (fz == 2)
            return Math.min(mx, ++i);
        return i;
    }
}
\$\endgroup\$
8
  • \$\begingroup\$ First of all: That doesn't even compile, as Java has no multi-line strings. You cannot expect to break lines in the middle of a string and that to work. \$\endgroup\$
    – Joey
    Commented Mar 3, 2011 at 19:24
  • \$\begingroup\$ Ok, I stopped trying to make it look good on the screen and just pasted the single line. \$\endgroup\$ Commented Mar 3, 2011 at 20:38
  • 1
    \$\begingroup\$ Furthermore (savings in parentheses): The class can be named with a single letter (40). There is plenty of unnecessary whitespace in there (80). You can collapse declarations of multiple variables of the same type, e.g. int a=5,b=10 (34). You can name the arguments in the constructor different from the fields to avoid this. (10). You can eliminate L altogether since it always remains at 1 (4). You can leave out initialization of H and G which get set in the constructor anyway (6). You can use one-letter names for all variables and methods (235). \$\endgroup\$
    – Joey
    Commented Mar 3, 2011 at 20:41
  • \$\begingroup\$ True, but that would be totally unreadable. This is the point where I see code-golf really becomming code-bowling. But if I find some time, I'll polish it up tonight. \$\endgroup\$ Commented Mar 3, 2011 at 20:49
  • 1
    \$\begingroup\$ Correction for the previous figure: (272). You can rewrite fuzzify using the conditional operator (20). You can inline the BufferedReader in getInt (19). You can use String#matches to avoid the Pattern and Matcher in getInt (48). You can use the conditional operator in processGuess as well (30). I'm now down to 1360 instead of your initial 1953. \$\endgroup\$
    – Joey
    Commented Mar 3, 2011 at 21:08
2
\$\begingroup\$

Alarm Clock Radio, 5756 bits (2159 bytes)

Coming soon to an alarm clock near you! Newlines are for readability only. ASCII values are used occasionally in place of the literal numeric display on-screen. Fits specs. Uses defaults for A and I. On the first input, use NULL to be the guesser, otherwise you will set the number. PADSIZE MUST BE 4! CELLS MUST BE 7-BIT AND WRAP! Turing-complete! Outputs higher, lower, correct, you won, and you lost.

}+>,[,>>+++++++[>>>>>>>+++++++>+++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++]>>>>>>>++++++.>>>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++>+>>>>>>>]>+++.+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>+++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++.[+]+][++++[+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++>,[+[+++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++>++>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++.++++++++.[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>.+++++++++++++.[+
]+][++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++>+>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++.+++..++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++>+>>>>>>>]>+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>>>>>>>[+]>>>>>>>+++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++]]][>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++>+>>>>>>>]>+++.++[+++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+
+>>>>>>>]>.+++.++++.+.>>>>>>>[+]+][+++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++>+>>>>>>>]>+++.++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.]
\$\endgroup\$
1
\$\begingroup\$

Ruby 1.9 (298)

b=->f{puts "> "+f;gets}
a=->f{b[f].to_i}
q=a["Player 1 or 2?"]
i,j,g=100,1
n=q<2?a["Enter number:"]:rand(i)+j
5.times{q<2?(g=j+(i-j)/2
c=b["Guessing, #{g}"]
c[0]==?c?break: c[0]==?h?j=g :i=g):(
g=a["Guess:"]
puts g==n ?"correct":g<n ?"higher":"lower"
g==n&&break)}
puts "Player #{g==n ?2:1} won!"

Not very friendly instructions though.

\$\endgroup\$
2
  • \$\begingroup\$ Very nice! If only you had some randomization when AI is player 2... \$\endgroup\$
    – Eelvex
    Commented Mar 11, 2011 at 18:35
  • \$\begingroup\$ @Eelvex, beaten by 30 chars. \$\endgroup\$
    – zzzzBov
    Commented Mar 11, 2011 at 20:19
1
\$\begingroup\$

I felt the need to do Java some justice. :)

Java - 486 437 421 414

Golfed

import java.util.*;class GuessANumber{static<T>void p(T p){System.out.println(p);}static int i(){return new Scanner(System.in).nextInt();}public static void main(String[]a){int c,g,f=101,i=0;p("Pick (1) or guess (2)?");c=i();if(c==1)p("Pick a number (1-100)");g=c==1?i():new Random().nextInt(100);while(f!=g&&i++<5){p("Guess:");f=c==2?i():f>g?f/2:f+f/2;if(c==1)p(f);p(f>g?"lower":"higher");}if(f==g)p("correct");}}

Slightly Ungolfed

import java.util.*;

class a{
    
    static<T>void p(T p){
        System.out.println(p);
    }
    
    static int i(){
        return new Scanner(System.in).nextInt();
    }
    
    public static void main(String[]a){
        int c,g,f=101,i=0;
        p("Pick (1) or guess (2)?");
        c=i();
        if(c==1)p("Pick a number (1-100)");
        g=c==1?i():new Random().nextInt(100);
        while(f!=g&&i++<5){
            p("Guess:");
            f=c==2?i():f>g?f/2:f+f/2;
            if(c==1)p(f);
            p(f>g?"lower":"higher");
        }
        if(f==g)p("correct");
    }
}
\$\endgroup\$

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