Stampa tutti i numeri da -100 a 100 che contengono una determinata cifra


38

Fornito un numero compreso tra 0 e 9 (incluso), la funzione / subroutine deve stampare tutti i numeri tra -100 e 100 (incluso) che contengono la cifra specificata.

Per esempio:

Input: 9
Output: -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99

Regole:

  • Non è possibile utilizzare stringhe (in qualunque modo siano rappresentate nella lingua scelta) o array di caratteri. (Tranne per stampare la risposta sulla console.)
  • Non è possibile utilizzare le matrici.

punteggio:

Punteggio = lunghezza della subroutine / funzione (gli spazi bianchi non verranno conteggiati)

Vince la risposta con il punteggio più basso.

Gli spazi bianchi NON verranno conteggiati. Si prega di formattare correttamente il codice!

Alcune risposte utilizzano espressioni regolari, che potrebbero violare la regola delle stringhe, come sottolineato da alcuni membri. Queste risposte non saranno accettate.

Si prega di testare il codice con 0prima di pubblicare.


2
L'output fornito è errato o poco chiaro. Dove sono -98 ... -91 e 91 ... 98?
Oberon,

27
Una risposta per gli spazi bianchi segnerà 0. Sei sicuro di volerlo fare?
pastebin.com slash 0mr8spkT

3
È consentito l'uso di regex? Lavorare con regex significa lavorare con le stringhe. Allo stesso modo, lavorare con liste / collezioni (e strutture simili) equivale a lavorare con le matrici. La risposta di @wallywest qui usa regex. Questa è la cosa che non mi piace delle domande quando provano a vietare l'uso di stringhe e / o array. Le persone trovano modi alternativi di usarli. E se una risposta si attua davvero correttamente, non ottiene tutti i voti che dovrebbe solo perché sembra complicata.
microbian

2
"Gli spazi bianchi NON verranno conteggiati. Per favore formatta il tuo codice correttamente!" non è un ottimo modo per farlo, poiché gli spazi bianchi in diverse lingue hanno un significato diverso. Più spesso, è solo "pubblica anche una versione non leggibile / leggibile".
Bob

2
@ace Ho creato una risposta negli spazi bianchi (ci sono volute 4 ore di duro lavoro con questo). penso che segna zero, giusto?
Victor Stafusa,

Risposte:


75

Spazio bianco, 834 caratteri (0 se si sottrae spazi bianchi)

Usato questo interprete per testarlo.

Mi ci sono volute circa 4 ore di duro lavoro e orribili debug per creare. Ma è fatto!

   	    	 
   	    	 
	
	    	    	 
			   		    
	  			    	    		
  			   		
		    	     	
   
		    	    	 
			
	  	  	 		
   	    	 
			   	
	  	
	  	  	 		

   	   	  
   	    		
			 
    		  	  
	  	
	  	   	 	
 
   		
	  

		 	   			
  		
	  

   	   			
 
    	    	 
			
	  	  	   
   	 	 
	 	    	    	 
				  	
	  	  	  	

   	  	   
   	 	 
	 		   	    	 
				  	
	  	  	  	

 
 	  	 	 

   	  	  	
   	     	
			
	  	   		 
   	     
	
  
   	   		 
   	     	
   	
		    	    		
				
 	
   	  	 	 
   	    		
   	    		
			   	
	   		 
 
 	   	  

   	   	 	
   	    	 
			
	  	  		  
   	    	 
			   	
	  	
	  	  		  




   	  	 		
  			  	  
	
 	   	     
	
  
 
 	   	  

   	  		  
   	     
	
     		  	  
	
 	


EDIT : testo selezionabile fornito con trucchi HTML. Se lo copi e lo incolli da qui in un altro posto, controlla se hai ottenuto esattamente [space][tab][linefeed][linefeed][linefeed]alla fine con 100 o 101 righe (a seconda se il tuo editor conta o meno una nuova riga se l'ultima termina con un'alimentazione di riga).

Nel caso in cui non sia possibile utilizzarlo in questo modo, considerando spazio come S, avanzamento riga Le tabulazione Te linee di interruzione dopo le L, eccolo qui:

SSSTSSSSTSL
SSSTSSSSTSL
TL
TSSSSTSSSSTSL
TTTSSSTTSSSSL
TSSTTTSSSSTSSSSTTL
SSTTTSSSTTL
TTSSSSTSSSSSTL
SSSL
TTSSSSTSSSSTSL
TTTL
TSSTSSTSTTL
SSSTSSSSTSL
TTTSSSTL
TSSTL
TSSTSSTSTTL
L
SSSTSSSTSSL
SSSTSSSSTTL
TTTSL
SSSSTTSSTSSL
TSSTL
TSSTSSSTSTL
SL
SSSTTL
TSSL
L
TTSTSSSTTTL
SSTTL
TSSL
L
SSSTSSSTTTL
SL
SSSSTSSSSTSL
TTTL
TSSTSSTSSSL
SSSTSTSL
TSTSSSSTSSSSTSL
TTTTSSTL
TSSTSSTSSTL
L
SSSTSSTSSSL
SSSTSTSL
TSTTSSSTSSSSTSL
TTTTSSTL
TSSTSSTSSTL
L
SL
STSSTSTSL
L
SSSTSSTSSTL
SSSTSSSSSTL
TTTL
TSSTSSSTTSL
SSSTSSSSSL
TL
SSL
SSSTSSSTTSL
SSSTSSSSSTL
SSSTL
TTSSSSTSSSSTTL
TTTTL
STL
SSSTSSTSTSL
SSSTSSSSTTL
SSSTSSSSTTL
TTTSSSTL
TSSSTTSL
SL
STSSSTSSL
L
SSSTSSSTSTL
SSSTSSSSTSL
TTTL
TSSTSSTTSSL
SSSTSSSSTSL
TTTSSSTL
TSSTL
TSSTSSTTSSL
L
L
L
L
SSSTSSTSTTL
SSTTTSSTSSL
TL
STSSSTSSSSSL
TL
SSL
SL
STSSSTSSL
L
SSSTSSTTSSL
SSSTSSSSSL
TL
SSSSSTTSSTSSL
TL
STL
L
L

32
+1 sfruttando "0 se sottrai spazi bianchi"
Jwosty

12
Haha, ho imparato una lezione. : P
duci9y,

2
@Cruncher La lingua è ben definita e del tutto inequivocabile . Per la tua domanda particolare: un numero è una serie di spazi e tabulazioni, che rappresenta il numero in binario (spazio = 0, tab = 1, formato binario big-endian) e termina con una nuova riga. Quindi sai che un numero finisce quando raggiungi una nuova riga.
Tim S.

1
Ho imparato Whitespace oggi. codegolf.stackexchange.com/a/23216/17886
duci9y

7
Interpreto "Gli spazi bianchi NON verranno conteggiati." significa che questa risposta non è valida. ;) +1
Tim Seguine

24

Bash + utils - 20

seq -100 100|grep 9

O 21 byte se in uno script

seq -100 100|grep $1

Per eseguire lo script:

sh myscript 9

4
grepnon è basho sh. È un'altra utility!
Devnull

devo essere d'accordo, non è puro shell / bash :)
Nik O'Lai

1
Vede una domanda. Ricorda la risposta. Vede esattamente la stessa risposta già pubblicata. Darn! +1
The Guy with The Hat

6
Penso che questo stia usando le stringhe.
David Conrad,

1
@DavidConrad Se lo guardi in questo modo, tutto usa le stringhe. La fonte del programma è una stringa. Il terminale utilizza stringhe. Ecc.
Colonnello Trentadue

9

JavaScript 133-1 = 132

Sicuramente non potrebbe esserci nulla di sbagliato in questa versione ora ...?

for(k=prompt(),c=console,j=-100;100>=j;j++)if(i=j,0==j&j==k)c.log(0);else for(;i;)if(h=i%10,h=0>h?-h:h,i=i/10|0,h==k){c.log(j);break}

PROMPT: 2
CONSOLE.LOG:
-92
-82
-72
-62
-52
-42
-32
-29
-28
-27
-26
-25
-24
-23
-22
-21
-20
-12
-2
 2
 12
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 32
 42
 52
 62
 72
 82
 92

CONTROL, using zero
PROMPT: 0
CONSOLE.LOG:
    -100
    -90
    -80
    -70
    -60
    -50
    -40
    -30
    -20
    -10
      0
     10
     20
     30
     40
     50
     60
     70
     80
     90
    100

1
Anche un po 'più breve: for(i=-100,r=prompt();101>i;i++)(i+'').match(r)&&console.log(i).
VisioN,

2
Mi piace questa risposta (+1), ma non usa implicitamente le stringhe?
Non che Charles

2
questo utilizza la conversione di stringa implicita
Claudiu

1
In realtà chaps, no non lo fa ... alert(RegExp(9).test(99))che si basa solo sui numeri, ritorna anche a truecausa del sistema di digitazione vagamente basato su JavaScript. Le funzioni funzionano con i numeri come se fossero stringhe ma sono ancora numeri ... Se si modifica il codice per leggerlo r=RegExp(x=+prompt());for(i=-100;101>i;i++)r.test(i)&&console.log(i);console.log(typeof(x));console.log(typeof(i))ed eseguirlo, il tipo finale di risposta mostrerebbe xei come numeri ... Ergo, non sto usando stringhe ...
WallyWest

2
La stampa @VoronoiPotato è anche una stringa op. Ma siamo ovviamente tenuti a farlo.
Tim Seguine,


6

Rubino: 92 caratteri

s=gets.to_i
$><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" "

Versione leggibile:

searchfor = gets.to_i
$><< (-100..100).select { |number|
  absnumber = number.abs
  loop {
    break "" if absnumber % 10 ==s
    break if 0 == absnumber /= 10
  }
} * " "

Esecuzione di esempio:

bash-4.2$ ruby -e 's=gets.to_i;$><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" "' <<< 9
-99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99

Prova:

bash-4.2$ for i in {0..9}; do diff -w <(ruby -e 's=gets.to_i;$><<(-100..100).select{|n|a=n.abs;loop{break""if a%10==s;break if 0==a/=10}}*" "' <<< $i) <(seq -100 100|grep $i|tr \\n \ ) > /dev/null; echo "$i : $?"; done
0 : 0
1 : 0
2 : 0
3 : 0
4 : 0
5 : 0
6 : 0
7 : 0
8 : 0
9 : 0

Fallisce il 0test.
duci9y

Ops. Hai ragione, @ duci9y. Corretto.
arte

6

K - 45 caratteri

Non vincere alcun premio, ma il golf K è sottorappresentato. K non diventa più carina con la spaziatura corretta, quindi lascerò questo così com'è, perché K diventa molto esigente su quale spazio bianco è importante e quale no.

{|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]}

Ha spiegato:

  • a:100-!201- Crea un elenco da 0 a 200 inclusi, quindi sottralo da 100. Ora abbiamo i numeri da -100 a 100 inclusi, ma all'indietro dalle specifiche della domanda. Possiamo sempre risolverlo in seguito, quindi per ora lo assegneremo solo a a.
  • _ _abs - Prendi la parola del valore assoluto di questi numeri, perché per qualunque motivo K la pensa _abs dovrebbe dare risultati in virgola mobile. Per fortuna, pavimentandoli li trasforma di nuovo in numeri interi.
  • 10_vs'- Espandi ogni ( ') numero intero come un numero di base 10 ( _vssta per "vettore dallo scalare"). Si noti che non è stato necessario utilizzare l'operatore Each 'sulle funzioni sopra perché operano su atomi.
  • @[...;100;0,]- Modifica l'elemento nel nostro elenco all'indice 100 (un elenco vuoto, che è il risultato dell'espansione di 0 nella base 10) dalla funzione 0,, che antepone uno zero in primo piano. Senza questa correzione, questa funzione fallirà sull'ingresso 0.
  • &x in'- Ora, restituisci gli indici ( &) dove xè una cifra in ( _in) ciascuno (' ) delle espansioni che abbiamo così accuratamente costruito sopra.
  • |a@- Infine, utilizzare questi indici per indicizzare ae invertire l'elenco nel giusto ordine.

L'uso è ovvio, anche se buona fortuna mettere le mani su un interprete K. (C'è un'implementazione open source su Github che puoi compilare.)

  {|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]} 0
-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
  {|a@&x _in'@[10_vs'_ _abs a:100-!201;100;0,]} 5
-95 -85 -75 -65 -59 -58 -57 -56 -55 -54 -53 -52 -51 -50 -45 -35 -25 -15 -5 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95

Mi chiedo se lingue come K abbiano usi produttivi al di fuori di scenari come questa domanda. Fanno?
duci9y

2
@ duci9y In realtà, K in particolare si è trovata un mercato di nicchia su Wall Street che gestisce transazioni ad alto volume e ad alta velocità, usando il suo software di database nativo KDB. Anche il parente stretto J trova impiego, sebbene più in contesti aziendali e accademici.
algoritmo

È fantastico! Ero convinto che le lingue esoteriche fossero solo per divertimento. Bello vedere che non è così.
duci9y,

La descrizione non dice "Non è possibile utilizzare le matrici"?
Omar,

6

bash 55 49 caratteri:

(senza contare gli spazi bianchi &&)

for i in {-100..100}
do
  [[ $i =~ $1 ]] && echo $i
done

Eseguendolo dicendo:

bash filename 9

produrrebbe:

-99
-98
-97
-96
-95
-94
-93
-92
-91
-90
-89
-79
-69
-59
-49
-39
-29
-19
-9
9
19
29
39
49
59
69
79
89
90
91
92
93
94
95
96
97
98
99

Puoi sostituire "&&" con "&&" per due punti extra. Inoltre conto un carattere in meno se lascio cadere la nuova riga finale.
Trauma digitale

1
Scratch that - Ho appena visto la nuova regola: "EDIT: gli spazi bianchi NON verranno conteggiati. Per favore formatta il tuo codice correttamente!" . Quindi immagino che riuscirai a contare tutti i personaggi non bianchi?
Trauma digitale

Quindi puoi convertire le ;s in newline e salvare 2 punti.
joeytwiddle

4

PHP 67 byte:

for($i=-100;$i<101;++$i)if(strpos($i,$_GET[n])!==!1)echo$i,PHP_EOL;

Sì, c'è una chiamata "strpos", ma sto usando solo numeri!

Ecco una versione 'ungolfed':

for($i=-100;$i<101;++$i)
{
    if(strpos($i,$_GET[n])!==false)
    {
        echo $i,PHP_EOL;
    }
}

Perché funzioni, puoi provarlo qui: http://writecodeonline.com/php/

Ricorda solo di aggiungere $_GET[n]='<number>';all'inizio del codice.

Oppure, su un server di lampada o XAMPP, è possibile creare una pagina e poi accedervi sul browser, con il parametro ?n=<number>dopo il nome del file.


1
Sembra una conversione di stringa implicita, che viola la regola senza stringhe.
VoronoiPotato

Non è colpa mia. Non ho fatto la lingua. Ho usato quello che ho. Inoltre, la conversione viene effettuata internamente. Non c'è nulla nel codice che tratta delle stringhe (tranne l'output).
Ismael Miguel,

Per come ho letto la regola, devi trattare i numeri in modo aritmetico. Trattarli come stringhe, da te o dalla lingua o dalla biblioteca, è vietato. Ma quasi tutti gli altri stanno evitando la regola in modo simile.
David Conrad,

Bene, tutti vogliono farlo nel modo più piccolo. E il più piccolo sta trattando i numeri come stringhe (internamente senza conversione implicita in stringa nel codice).
Ismael Miguel,

4

Mathematica 28

Mi dispiace, non ho potuto resistere.

:)

Le istruzioni sono: "Fornito un numero compreso tra 0 e 9 (incluso), la funzione / subroutine deve stampare tutti i numeri tra -100 e 100 (incluso) che contengono la cifra indicata."


Quanto segue stampa tutti questi numeri in ordine.

f@n_ :=Print/@Range[-100,100]

Come bonus speciale, stampa quei numeri nello stesso intervallo che non contengono la cifra data. :)


Ma questo non usa n come filtro
Murta

@Marta, Sì, ho sovvertito l'intento del puzzle (motivo per cui ho detto "Mi dispiace"), fornendo tecnicamente una risposta appropriata.
David

4

Il mio primo tentativo qui, quindi forse sto facendo alcune cose sbagliate, per favore scusatemi;)
Quindi, non ero sicuro di dover aggiungere l'intera classe o solo la logica all'interno.

Java - 199 caratteri

intx=System.in.read()-48;for(inti=-100;i<101;i++){if((i<10&&i==-x)||(i>-10&&i==x)||(i<-9&&((i/100==x&&i<-99)||i%10==-x||i/10==-x))||(i>9&&((i/100==x&&i>99)||i%10==x||i/10==x)))System.out.println(i);}

Ecco un modulo più leggibile:

int x = System.in.read() - 48;
for(int i = -100; i < 101; i++) {

    if((i < 10 && i == -x) || (i > -10 && i == x)
        || (i < -9 && ((i / 100 == x && i < -99 ) || i % 10 == -x || i / 10 == -x))
        || (i > 9 && ((i / 100 == x && i > 99) || i % 10 == x || i / 10 == x)))

        System.out.println(i);

}

Immagino che l'idea di base non fosse poi così male, ma aveva bisogno di troppe eccezioni, per risolvere finalmente tutti i casi ...: /


Siamo spiacenti, non funziona con 0:(
duci9y

Oh, certo, l'ultima aggiunta l'ho fatta incasinare. Codice aggiornato, quindi sono sceso al 199 ora. Grazie per la segnalazione!
Jochen Reinschlüssel,

Non me ne sono reso conto: D Troppa codifica in lingua madre nei giorni scorsi, credo;)
Jochen Reinschlüssel

Hai rimosso ogni singolo spazio nella tua versione compatta ... non causerebbe un errore? Esempio: i tuoi primi 4 personaggi: intx... non dovrebbe essere int x:?
SirPython,

4

C - 104 107 114 caratteri - 0 = 104 107 114

a,b;main(i){i=getchar()-48;for(a=-100;a<101;a++){for(b=a;a&&abs(a%10)!=i;a/=10);if(a|!i&!b)printf("%i ",b);a=b;}}

Ungolfed:

#include <stdio.h>

int a, b;

int main(int i) {
    i = getchar() - '0';
    for( a = -100 ; a < 101 ; a++ ) {
        for( b = a ; a && abs(a % 10) != i ; a /= 10 );
        if( a | !i & !b )
            printf("%i ", b);
        a = b;
    }
}

Bello. Potresti anche pubblicare una versione non modificata con spazi bianchi adeguati, per favore?
duci9y

@ duci9y L'ha aggiunto.
Oberon,

Questo non produrrà risultati fuori servizio? (Le specifiche sono state aggiornate per indicare che l'ordine conta.)
Gaffi

@Gaffi Bene allora. Modificherò il codice.
Oberon,

4
Non si nota che 0contiene 0.
ugoren,

3

R 87 93

Ecco un miglioramento:

a=scan();r=-100:100;s=abs(r);r[(!a&!r%%10)|a&(a==s%%10|a==floor(s/10)|a==floor(s/100))]

(Potenzialmente) Più leggibile, con note:

a=scan() # take user input of selected digit
r=-100:100 # define our scanning range
s=abs(r) # copy the range as the absolute value for proper floor() calculation
#r[<criteria>] is functionally the same as subset(r,<criteria>)
r[ # when any of the criteria below are met, use that value from the range
    (!a & !r%%10) # case when input is 0, !a is evaluated as "a when a<>0 == true"
    | a & # all other digits below
    a==s%%10
    |
    a==floor(s/10)
    |
    a==floor(s/100)
    ] # R does not require a print command, so this as-is will display the corresponding values

Perché nessuno spazio bianco?
duci9y

@ duci9y Perché nessuno è necessario. Formatterò per essere più leggibile e aggiungerò anche quello, solo per buona misura.
Gaffi,

Non funziona con 0.
duci9y

@ duci9y Non fallisce. Ho apportato una piccola modifica dal post originale (+2 caratteri), poiché il post originale DID ha avuto esito negativo 0. Hai provato con questa versione più recente? Sto usando R 3.0.1.
Gaffi,

@ duci9y Per essere chiari, intendevo dire che l'hai usato sulla versione più recente del mio codice . La mia versione di R dovrebbe essere abbastanza vicina alla versione più recente per non importare. Tuttavia, non ho provato affatto su nessuna versione 2. *.
Gaffi,

3

Prolog: 75

f(D) :-
  between(-100,100,N) ,
  number_chars(N,Ds) ,
  member(D,Ds) ,
  writeln(N) ,
  fail
  .

How do you call this? I saved it in a test.pl file, started swipl, entered consult('test') and then entered f(9). But it only returned false.
Martin Thoma

3

C answer in 98 characters

This is one of the sexiest things I've ever coded

main()
{
    int t=getchar()-48,i=100,j=-i;
    while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101  );
}

The older version, with 104 non-whitespace chars:

int main()
{
    int t=getchar()-48,i,j=-101;
    while(++j<101)
    {
        i=j<0?-j:j;
        while(i = t-i%10?i/10:!printf("%d\n",j));
    }
}

"Works for me" using GCC and CLANG.


Awesome! Welcome to Code Golf.
duci9y

2

GNU coreutils (44)

read N
seq -100 100 | grep $N | tr '\n' ' '
echo

where tr is used to convert newlines to spaces, and echo provides one final newline.

$ bash ./script
9
-99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99

This isn't much different from an existing answer.
devnull

2

Javascript 116

   a = 0
        for(i=-100;101>i;i++){
        m=Math
        f=m.floor
        j = m.abs(i)
        if((j>10&&f(j/10)==a)||j-f(j/10)*10==a||j/100==a){

             console.log(i)

        }
        }

2

J - 27 chars

All whitespace is safely removable, meaning 27 characters. Negative numbers in output will have _ for a negative sign: this is just the way J writes its negative numbers.

((e. 10 #.^:_1 |)"0 # ]) & (i: 100)

Explained:

  • V & (i: 100) - Bind (&) the set of numbers from -100 to 100 inclusive (i:100) as the right argument of the main verb (V). The single argument of the entire verb gets piped into the left side.
  • (U"0 # ]) - Use the result of the verb U over each number from the right argument ("0) to select (#) items from the right argument (]).
  • (e. 10 #.^:_1 |) - Given the digit to test for as the left argument and the number to check as the right argument, expand in base 10 (10 #.^:_1) the absolute value of the number (|), and check if the digit is an element of that expansion (e.).

Usage:

   ((e. 10 #.^:_1 |)"0 # ]) & (i: 100) 0
_100 _90 _80 _70 _60 _50 _40 _30 _20 _10 0 10 20 30 40 50 60 70 80 90 100
   ((e. 10 #.^:_1 |)"0 # ]) & (i: 100) 5
_95 _85 _75 _65 _59 _58 _57 _56 _55 _54 _53 _52 _51 _50 _45 _35 _25 _15 _5 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95

The underscore-for-negative convention in J always bothered me -- it wouldn't be so bad if it used a minus symbol in output (without messing with the format verb).
Desty

The underscore is J's unambiguous (and, I would argue, elegant and APLish) way of differentiating negative signs from the verb - Negate/Minus. K lets you use the negative sign "naturally" in numbers, and incidentally K came out an arcane syntactic clusterfuck. If it's really irking you, work in your choice of ;8!:1, '4.0'8!:2, or '-'I.@:=&'_'}":, costing 7, 11, and 16 chars respectively to make the resulting program a function instead of an expression, by my count.
algorithmshark

I know what it is, but it's a bit bothersome all the same when it comes to I/O. It'd be nicer if it produced minus signs by default when printing numbers, rather than printing underscores presumably in case someone wanted to eval the resulting string.
Desty

2

Groovy, 127

def x = args[0].toInteger()
for (k in -100..100)
    if (k == x)
        print " ${k}"
    else
        for (n = Math.abs(k); n > 0; n = (int) n / 10)
            if (n % 10 == x) {
                print " ${k}"
                break
            }

No strings (except to output the spaces between the numbers), no char arrays or other arrays, no regexes. Tested with 0. Output:

-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100


1
And I discovered a new language today. :)
duci9y

2

Javascript - 108

Not sure if existing javascript answer will be taken into consideration because it uses regex, so I created one without it:

for(x=+prompt(i=-100);i<101;i++)if((j=i<0?-i:i)&&j%10==x||((j/100==x||(0|j/10)==x)&&x)||j==x)console.log(i)

Can also be shortened to 101 if x variable is put directly, like:

for(x=5,i=-100;i<101;i++)if((j=i<0?-i:i)&&j%10==x||((j/100==x||(0|j/10)==x)&&x)||j==x)console.log(i)

It basically checks if absolute values of div or mod operations are equal to the digit (which also works for 100).


If x=1, this fails to print -100 or 100.
DocMax

Should be fixed now
Damir Kasipovic

1 works nicely, but now 0 prints 1, 2, 3... Sorry to be a troublemaker here.
DocMax

Well if you put x=0; it works ok, the problem was that prompt() returns string, so I added *1 and it hopefully should be ok now. THank you for your suggestions
Damir Kasipovic

1
parseInt(j/10) can be replaced with (0|j/10) which is both shorter and avoids the implicit strings. The (unavoidable) string-to-number conversion in prompt()*1 cannot be shortened as +prompt(). (Or shorter still, change the function to start for(x=+prompt(i=-100);....
DocMax

2

GW Basic: 107 characters excluding whitespace

1 input n
2 for i=-100 to 100
3 j=abs(i):a=j mod 10
4 if a=n then 8
5 b=j\10
6 if (b=n) and b then 8
7 if (b<10) or n<>1 then 9
8 print i
9 next

Using single digits for the line numbers helps and stripping the whitespace means there isn't really a need for having multiple statements on a line more than once to keep numbers reaching 10.


2

GROOVY, 71

f={z->
  _=10
  (-_*_.._*_).grep {
    a=it.abs()
    b=a%_==z
    a<_?b:b||(int)(a/_)%_==z
  }
}

println f(0)
println f(9)

Results in

[-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[-99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -79, -69, -59, -49, -39, -29, -19, -9, 9, 19, 29, 39, 49, 59, 69, 79, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

2

Javascript 96

Using bitwise or:

b=Math.abs;
a=prompt();
for(i=-100;i<101;)
    if(!(b(i++/10)^a && b(i%10)^a)||b(i)/a==100)  console.log(i)

2

Haskell, 86 75 (78 with necessary whitespaces)

f 0=[-100,-90..100]
f d=[b|b<-[-100..100],abs(b`quot`10)==d||abs(b`rem`10)==d]

Ungolfed:

f dig =
  if dig == 0
    then [-100, 90 .. 100]
    else [num | num <- [-100 .. 100], abs (num `quot` 10) == d || abs (num `rem` 10) == d]

If you use a two line definition with pattern matching, i.e. a 0=[-100.... and a d=[b|b<-.... you can get rid of the if then else and save a few bytes.
nimi

1

Python - 172 chars

def f(x,y,z):
    if x%10==y or (x>9 and x/10==y) or (x==100 and y==1):
        print z
def g(x,y):
    f(abs(x),y,x)
    if x<100:
        g(x+1,y)
def h(y):
    g(-100,y)

To test within Python:

>>> h(4)
-94
-84
-74
...
-49
-48
...

1

VBA 121

(no whitespace or Sub definition counted):

Sub t(d)
For n = -100 To 100
m = Abs(n)
o = o & IIf(d = 0, IIf(d = n Mod 10, " " & n, ""), IIf(d = n Or d = m Mod 10 Or d = Int(m / 10) Or d = Int(m / 100), " " & n, ""))
Next
MsgBox o
End Sub

Does this work with 0?
duci9y

@duci9y Yes. Specifically because: IIf(d = 0, IIf(d = n Mod 10, " " & n, "")
Gaffi

1

perl, 117 with non-meaningful whitespace chars removed

I think you were looking for something more like this. Reads from stdin, outputs one line per match. No regexps, arrays (or sets or hashes or anything else that is an array under the covers) or strings, implicit or otherwise, except the strings passed to print:

chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"

eg:

ski@anito:~$ echo 0 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"'
-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 

ski@anito:~$ echo 1 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"'
-100 -91 -81 -71 -61 -51 -41 -31 -21 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -1 1 10 11 12 13 14 15 16 17 18 19 21 31 41 51 61 71 81 91 100 

ski@anito:~$ echo 2 | perl -e 'chomp($x=<>); for($y=-100;$y<101;++$y) { $a=abs $y; print "$y " if $a % 10 == $x || $a > 9 && int( $a/10 ) == $x || $a==100 && $x==1}; print "\n"'
-92 -82 -72 -62 -52 -42 -32 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -12 -2 2 12 20 21 22 23 24 25 26 27 28 29 32 42 52 62 72 82 92 

1

F# 87 92 - 7

let f n = {-100..100}
|>Seq.filter(fun x->abs x%10=n||abs x/10=n&&n>0)
|>Seq.iter(printf"%d ")

added 5 chars because 0 wasn't handled correctly. (Single digit values would all be returned.)


1

This is my first time playing code golf. This looks pretty interesting. I can't win, but I tried and wanted to show what I could do.

Python: 104 (89 if I can mulligan the import) - if the results must be printed exactly as shown in the example

from math import *

def g(x):
    t = 10
    p = lambda i: x == i % t or i >= t and p(i / t)
    for i in range(-100, 101):
        if p(abs(i)):
            print i,
    print
# g(0)
# -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100

Python: 71 - if the output can be done outside the function and the only restriction for the output is that no violating numbers are printed

f = lambda x: [(-i, i) for i in range(101) for j in (10, 100) if i % j == x or i >= j and i / j == x]
# print f(0)
# [(0, 0), (0, 0), (-10, 10), (-20, 20), (-30, 30), (-40, 40), (-50, 50), (-60, 60), (-70, 70), (-80, 80), (-90, 90), (-100, 100), (-100, 100)]

1

JavaScript 125 char

Sorry for the several edits I've been having troubles doing this from my phone :)

function c(n,i){o=i||0;h=100;j=o-h;f=Math.abs(j);m=f/10|0;if((m==n&&m!=0)||n==f%10||f/h==n)console.log(j);if(o<h*2)c(n,o+1);}

1

Dogelang, 42 non-whitespace characters

f=n->for i in(-100..101)=>if n in str i=>print i

Same as my Python solution, just converted to dogelang.

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.