Codice più breve per creare un gioco troppo basso - troppo alto


20

Devi creare un gioco Troppo basso --- Troppo alto (TLTH) nel codice più breve (in byte)

Regole del gioco:

  1. Il computer sceglierà un numero casuale al di fuori dell'intervallo intero (-32768..32767).
  2. Ora penserai a un numero e lo inserirai.
  3. Il computer dirà se il numero è inferiore ( TOO LOW) o superiore ( TOO HIGH) rispetto al numero selezionato.
  4. Quando si indovina il numero, dovrebbe essere visualizzato il computer Congrats! You found the number!.

Regole del codice:

  1. Non utilizzare i caratteri T, O, L, W, H, Ie G(né minuscole né maiuscole) in stringhe di caratteri o letterali.
    Per esempio:

    tolower(T);  // Acceptable  
    cout<<"T";   // Unacceptable
    char ch='T'; // Unacceptable
    
  2. Rimuovi 300 byte se il tuo codice può visualizzare le regole del gioco prima di iniziare il gioco.

  3. Rimuovi 50 byte se il tuo codice può contare il numero di turni e visualizzare il numero di turni effettuati alla fine del gioco in questo modo:

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

    dove n è il numero di turni effettuati, anziché

    "Congrats! You found the number!"  
    
  4. Rimuovi 25 byte dal tuo punteggio se il tuo codice può dire all'utente che il numero inserito è al di fuori dell'intervallo intero.
    Per esempio:

    Enter the number: 40000  
    Sorry! This number is out of range
    Please Enter the number again:  
    
  5. Rimuovi 25 byte Se il tuo codice accetta il numero casuale non da alcuna funzione casuale incorporata.

  6. Rimuovi 10 byte Se il codice visualizza "complimenti" a colori (scegli qualsiasi colore tranne il bianco predefinito).

Regole di presentazione:

  1. Aggiungi un'intestazione con il nome della tua lingua e segna con tutto il calcolo della taglia e la sua spiegazione.

  2. Pubblica il tuo codice golf e non golf.

Vincitore

  1. Vince la risposta con meno byte .
  2. Se c'è un pareggio, vince la risposta con più voti.
  3. Il vincitore verrà scelto dopo 5 giorni.

EDIT : mostra l'output del tuo codice.
EDIT-2 : puoi ignorare la Regola-1 per le Regole-2,3 e 4 nelle Regole del codice

Buona fortuna :]


2
è una spiegazione valida delle regole del gioco? WhileURong(USayNumbr;ISayBigrOrSmalr)
John Dvorak,

1
Sulla base della tua descrizione del punteggio, non hai né un codice golf né un concorso di popolarità. È una sfida al codice (con un tiebreaker di popolarità). Dai un'occhiata al tag wiki. Ho proposto una modifica per contrassegnare la sfida in modo appropriato. ps - Jinx! @mniip
Jonathan Van Matre

1
@JonathanVanMatre per me la formulazione suona come code-golf , nonostante il pareggio.
mniip,

21
Inoltre, non mi piace particolarmente la regola di aiutare gli altri giocatori a migliorare la loro risposta. Nelle parole immortali di Andre the Giant in The Princess Bride, "Non è molto sportivo".
Jonathan Van Matre

1
Questa domanda è così. . . David H. Ahl
Michael Stern

Risposte:


2

JavaScript (-210 punti ( 190byte - 300 (per le regole) - 50 (per il numero di ipotesi) - 25 (per non usare alcuna fonte numerica casuale incorporata) - 25 (per dirti se l'input è fuori dall'intervallo di un segno 16-bit intero) ):

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==')))

Codice completo (ben formattato):

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;
    }
}

Produzione:

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)

@IlmariKaronen Scusa, ho fatto un errore. Ho aggiornato la mia risposta.
Spazzolino da denti

Grazie, ora funziona ... ma sembra che si rompa se immagino 0. :-( Inoltre, non dovrebbe esserci spazio in TOO LOW/ TOO HIGH?
Ilmari Karonen il

19

Perl 5.10+: 159 144 byte - 350 = −206 punti

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!"

Modifica 2: Con la recente modifica delle regole che mi consente di utilizzare qualsiasi stringa letterale per il messaggio "complimenti", posso salvare 15 byte dalla mia soluzione originale a 159 byte. Non c'è nulla di particolarmente nuovo o interessante nel nuovo codice sopra rispetto al vecchio codice (mi sono appena liberato della pfunzione e ho chiamato saydirettamente invece), quindi il resto di questo post descriverà il codice originale, mostrato di seguito:

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."!"

Sì, sto abusando della regola 1. Chi ha bisogno di stringhe, quando puoi avere delle password ? ;-)

Esegui con perl -M5.010per abilitare la sayfunzione Perl 5.10+ (o sostituire il corpo della pfunzione con print join$",@_,$/un costo aggiuntivo di 5 byte).

Punteggi bonus:

  • −300 punti: "visualizza le regole del gioco prima di iniziare il gioco"
  • −50 punti: "visualizza il numero di turni effettuati alla fine del gioco"

Il codice non contiene letterali stringa in senso stretto, quindi direi che la regola 1 non è tecnicamente violata. Il trucco è che, in Perl, senza use strict, nessun identificatore che non corrisponde a una parola chiave o subroutine di lingua nota valuterà semplicemente il proprio nome. La funzione pquindi prende semplicemente un elenco di parole e le stampa, separate da spazi.

Esempio di 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!

Modificare: Oh, giusto, le regole dicono che devo pubblicare anche una versione non giocata del codice, quindi eccola qui. Tecnicamente, è "de-golfed", poiché di solito compongo i miei programmi di golf di codice in forma più o meno completamente giocata a golf dall'inizio, e a volte può essere difficile rimuovere tutte le ottimizzazioni "golfy" senza cambiare radicalmente il modo in cui alcune parti del programma di lavoro. Tuttavia, ho almeno provato ad aggiungere spazi bianchi, commenti e nomi di funzioni / variabili più significativi:

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. In alternativa, se usare solo parole semplici invece di stringhe sembra troppo economico per te, ecco una soluzione da 182 byte che non usa le lettere TOLWHIG anche nelle parole nude (ma le usa in un operatore di traslitterazione). Ottiene ancora gli stessi bonus, per un punteggio totale di 182 - 350 = −168 punti :

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!"

L'output ha esattamente lo stesso aspetto di cui sopra. Per le regole (originali), io uso le lettere te inel stampare le regole, poiché è permesso; l'eliminazione anche di quegli usi costerebbe solo due byte extra. Al contrario, rendere tutto l'output in maiuscolo (che, sulla base dei commenti sopra, sembra essere consentito) mi consentirebbe di salvare tre byte.


Questa è una risposta simpatica e intelligente! +1 da me
Mukul Kumar

Ora che vedo questo mi chiedo se potrebbe essere battuto con Ruby 1.8 se prendi la penalità per def method_missing *args;args.join' ';end.
Kaya

Ti ho battuto con il buon vecchio JavaScript!
Spazzolino da denti

14

Python 2: -80 punti (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

Il punteggio è di 270 caratteri, meno 300 per mostrare le istruzioni, meno 50 per mostrare il numero di ipotesi nei "complimenti!" stringa, per un totale di 80 punti negativi.

Versione non golfizzata del loop, con stringhe senza escape:

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

La cmpfunzione integrata restituisce 0 se i valori sono uguali, -1 se il primo è più piccolo e 1 se il primo è più grande. Uso il valore per indicizzare una tupla di stringhe e poi di nuovo come condizione di uscita del ciclo. Indicizzare una sequenza con un indice negativo (come -1) conta dalla fine della sequenza, piuttosto che dall'inizio.

Sono stato fortemente tentato di saltare le importazioni e usarlo solo 4come mio numero casuale, come da XKCD 221 (sarebbe qualificato per il bonus di -25 caratteri?).

Esempio di esecuzione (completo di un errore, in cui non riesco a fare matematica negativa):

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!

Mostra l'output di esempio del codice.
Mukul Kumar

2
Questa regola del codice di rottura non è 1? WhileURong (USayNumbr; ISayBigrOrSmalr) contiene uno o più Os, Ls, Ws, Hs, Is e Gs.
Fors

@ Cruncher: non sono sicuro di cosa intendi, poiché il programma termina. Dopo aver ottenuto il valore giusto gè zero e il whileciclo termina.
Blckknght

@Blckknght oops, lettura veloce
Cruncher

@ForsYou can ignore Rule-1 for Rules-2,3 & 4 in Code Rules
Cruncher

13

JavaScript 293, -300 (regole) - 50 (visualizzazione giri) - 25 (avviso intervallo) - 25 (nessuna funzione casuale) = -107 (nuovo punteggio)

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!")

Direi che secondo le convenzioni RGB il nero è un colore, ma sarebbe un po 'barare ...

Oh, e potrei aggiungere, nessuna violazione della regola n. 1, neanche!

Output in una serie di avvisi e prompt

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!

Codice non golfato:

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

leggi attentamente le regole? bene devi pubblicare un codice ungolfed con un output
Mukul Kumar

@MukulKumar ordinato ...
WallyWest

Puoi salvare 4 aggiungendo il prefisso con la tua risposta A=alert;e sostituendo tutto alertcon A. E ancora uno se sposti l'avviso A(0>(x...dopo il punto e virgola prompt())!=r;)n++1.
DocMax

puoi cambiare il nome feedback if too high/lowche utilizza attualmente 84 caratteri in i give feedback(che richiederebbe solo \151 \147\151ve feedback24 caratteri per salvare 60 caratteri .
corsiKa

1
Potrei sbagliarmi, ma penso che tu possa spostare il n++ciclo da for in x=prompt(n++)per salvare dover fare + ++n+nell'allerta finale.
Salverebbe

7

Javascript, 324 byte, punteggio -76

[Aggiornato a causa di modifiche alle regole]

  • 324 byte
  • -300 per mostrare le regole
  • -50 per mostrare i turni quando l'utente vince
  • -25 per dire all'utente quando inserisce un numero al di fuori dell'intervallo
  • -25 per non usare casuale incorporato (aggiornato)

Punteggio totale: -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!")

Ungolf questo casino.

Innanzitutto, correttamente identificato (ma questo non è ancora molto buono con il codice offuscato):

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!")

In secondo luogo, rinominare gli identificatori:

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!")

Quindi la funzione non crittografata ottiene tutti i caratteri tra ASCII 33 ( !) e ASCII 58 ( :) e ne aggiunge 32, convertendoli in caratteri nell'intervallo A-Z.

Consente di annullare la registrazione del codice annullando la crittografia di tutte le stringhe:

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!")

E infine, consente di spostare alcune istruzioni in altri luoghi, sostituire la lunga catena ternaria con if ed elses, unire stringhe concatenanti e semplificare la matematica, per aumentare la leggibilità:

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!");
  }
}

Campione:

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!"

1
Mi piace davvero :)
Wolle Vanillebär Lutz

Mostra l'output di esempio del codice.
Mukul Kumar,

@MukulKumar. Fatto, l'output è stato aggiunto
Victor Stafusa il

7

C - 272 caratteri - 300-50 - 25 = -103

  • -300 per la visualizzazione delle regole;
  • -50 per comunicare al giocatore il numero di turni;
  • -25 per non usare una libreria RNG standard.

Codice golfizzato:

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);
    }
}

Produzione:

Produzione


Dov'è l'uscita?
Mukul Kumar

@IlmariKaronen, EDIT2. Inoltre, non prendo solo l'epoca.
Oberon

@Oberon pubblica anche l'output
Mukul Kumar

@MukulKumar, pubblicato.
Oberon,

5

C: 237 - 300 - 50 - 25 - 25 - 10: -173 punti

-300 per le regole, -50 per mostrare il numero di ipotesi, -25 per non usare alcun generatore di numeri casuali incorporato, -25 per il messaggio fuori portata e -10 per colorare il messaggio dei complimenti.

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);
}

Esempio di esecuzione:

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!

L'ultima riga viene visualizzata in rosso.


Bravo! Hai colpito tutti i doni !!!
Mukul Kumar,

4

bash, -137

Punto

273 (byte) - 300 (regole) - 50 (tentativi di conteggio) - 25 (avviso OOF) - 25 (PRNG personalizzato) - 10 (colore)

Versione golfizzata

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.

Nota che l'ultima riga è un commento, quindi non contiene valori letterali di stringhe o caratteri.

Versione Ungolfed

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!"

Uscita campione

$ ./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!

L'ultima riga è stampata in verde.


3

C #: -30 punti

  • 345 byte
  • -300 per mostrare le regole
  • -50 per mostrare i turni quando l'utente vince
  • -25 per dire all'utente quando inserisce un numero al di fuori dell'intervallo

Golfato :

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);}

Per eseguirlo, metterlo in un file (code.cs) e correre con scriptcs sulla riga di comando: scriptcs code.cs.

Ungolfed : nomi di variabili espansi in qualcosa di più facile da capire e cambiato lettere esadecimali in lettere reali.

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
    );
}

Uscita di esempio disponibile qui .


3
Ci scusiamo per raccontare questo, ma la regola stabilisce che " Non usare i caratteri T, O, L, W, H, Ie G(né minuscole né maiuscolo) in stringhe di caratteri o letterali. "
Victor Stafusa

Quindi basta sostituire T, O, L... con \x54, \x4F, \x4C... e stai bene.
bradipo

Grazie. Ho appena inserito le codifiche esadecimali per i caratteri applicabili in letterali stringa nella versione golfata e modificato il punteggio di conseguenza.
Yaakov Ellis

Mostra l'output di esempio del codice.
Mukul Kumar

@MukulKumar vedi qui per l'output. Ho anche apportato alcune piccole modifiche alla logica, risolto un problema.
Yaakov Ellis

2

C ++ 505 + (-300-50-25-25) = 105

-300: Istruzioni
-50: Visualizzazione del numero di giri
-25: Non utilizzo della funzione casuale
-25: avviso all'utente di input fuori 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;
}  

PRODUZIONE


Personalmente, non potevo fermarmi .. :)
Mukul Kumar

2

C, 183-300-25 = -142

183 byte -300 per le regole -25 per non usare una libreria casuale

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!");}

versione non golfata:

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!");
}

esempio di esecuzione:

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!

"TOO HIGH"ed "TOO LOW"entrambi contengono personaggi illegali TOLWHIGtolwhig.
Oberon,

Come fa "Complimenti! Hai trovato il numero!" e "WhileURong (USayNumbr; ISayBigrOrSmalr)".
Fors

@Per ma quelli sono ammessi (vedi EDIT2 ).
Oberon

Anzi lo sono! Per qualche motivo ho perso quella modifica.
Fors

@Oberon Quindi è TOO LOWconsentito anche da EDIT 2 ?
Spazzolino da denti

2

J - 190 caratteri -300 -50 = -160 punti

'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

Spiegazione (ricordare che J viene letto da destra a sinistra):

  • 'WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2 - Stampa le regole.
  • 32767-?2^16[- Lancia il valore restituito, quindi genera un numero casuale compreso tra 0 e 2 ^ 16-1 inclusi. Quindi, regolalo nell'intervallo -32768..32767 sottraendolo da 32767.
  • 1>:@]^:(...)^:_~- Il x u^:v^:_ ymodello è un po 'come un ciclo while. xrimane costante e yviene mutato ad ogni esecuzione di u. Questo continua fino a quando non x v yrestituisce 0 o non si x u yottiene alcuna modifica a y. Gli ~swap i due argomenti, in modo che xsarà il numero casuale e yavrà inizio alle 1. Il nostro uè >:@], che incrementa l'1 e lo restituisce, in modo che agisce come un contatore e la x u ycondizione di terminazione non potrà mai verificarsi.
  • [:".1!:1@1:- Prendi il contatore e ignora il suo valore, usando invece il numero 1 ( 1:). Leggere in una riga di input ( 1!:1) dalla tastiera (handle di file 1) ed eseguirlo ( ".). Ciò consente a J, il cui segno negativo è normalmente _, di assumere numeri nella forma -n(valuta come negazione applicata al numero n).
  • ]`(...)@.*@-- Prendi la differenza tra il numero casuale di prima e l'ipotesi ( -). Ora selezioniamo l'azione successiva a seconda che questa differenza sia zero ( @.*). In tal caso, restituire ( ]`) quello 0 come risultato x v y, in modo che l'esecuzione venga interrotta e l'intero ciclo while restituisce il contatore. Altro...
  • 71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>- Restituisce l'array 5 8 16se il numero è negativo e 1 2 0 1se è positivo. Quindi anteponi 13 8 8 _39e aggiungi 71 a tutto, quindi abbiamo 84 79 79 32 76 79 87o 84 79 79 32 72 73 71 72.
  • 1[2:1!:2~a.{~- Trasforma questi numeri in caratteri ASCII indicizzando l'alfabeto a.con loro. Quindi stamparli con 1!:2(usando l'handle del file 2) e restituire 1 come risultato di x v y.
  • 'Congrats, you found the number in ',' turns!',~":- Al termine del loop, restituisce il contatore. Convertilo in una stringa con ":e mettilo tra le stringhe 'Congrats, you found the number in 'e ' turns!'.

Uscita campione:

   '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!

2

JavaScript -40

335 - 300 (regole) - 50 (turni di conteggio) - 25 (fuori portata)

Non vincerò, ma un modo divertente per ottenere le lettere, penso.

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")

Uscita campione

(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!

1

APL (Dyalog) (157-300-50 = -193)

(Sì, contano come byte, il set di caratteri APL si inserisce in un byte.)

Ho affermato "mostra le regole del gioco" e "conta il numero di turni".

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!'

Esempio di esecuzione:

      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!'

1

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

Se il numero è 10:

Numero?

5

Basso

8

Basso

12

alto

10

Yay 4 turni


Il conteggio dei caratteri si basa sul codice con tutto lo spazio bianco rimosso.

Nota che Pogo non è un linguaggio falso. L'ho creato e ho scritto un compilatore e un IDE per questo qui: https://github.com/nrubin29/Pogo


Leggi EDIT e EDIT - 2
Mukul Kumar il

Aggiornato secondo le modifiche.
nrubin29,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.