Restituisce ogni numero da un gruppo di numeri


11

La sfida

Il programma deve restituire tutti i numeri inclusi in un gruppo (virgola e trattino separati da sequenza) di numeri.

Regole

  • s è la stringa di sequenza;
  • tutti i numeri inclusi ssono positivi ;
  • numeri sempre aumenterà ;
  • i numeri non si ripeteranno mai
  • quando rispondi, mostra l'output di s="1,3-5,9,16,18-23"

Esempi

input(s)    outputs
-----------------
1           1
1,2         1,2
1-4         1,2,3,4
1-4,6       1,2,3,4,6
1-4,8-11    1,2,3,4,8,9,10,11

In bocca al lupo. =)


1
Avremo mai sequenze di input che non aumentano costantemente, ad esempio: 4-9,1-2o 1-3,9-6?
Matt,

1
O sovrapposti? L'output deve essere ordinato e non contenere duplicati?
Peter Taylor,

@Gareth Sì, questo è un codice-golf, quindi vota per la risposta più breve. Matt e Peter, ho modificato la domanda, per favore controlla. Grazie!
Berna Mariano,

Deve essere un programma completo e c'è una restrizione sul formato dell'output?
Brad Gilbert b2gills,

Risposte:


6

GolfScript (24 caratteri)

','/{~.,!{~)),>~}*}%','*

Per esempio

$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

In realtà ho quattro soluzioni a 24 caratteri, ma ho scelto questa perché non ha caratteri alfanumerici.

Come funziona

# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
    # This is executed for each of those strings in a map
    # So stack holds e.g. "1" or "3-5"

    # Evaluate the string.
    # If it's a single number, this puts the number on the stack.
    # Otherwise it's parsed as a positive number followed by a negative number.
    ~
    # Stack holds e.g. 1 or 3 -5
    # Duplicate the last element on the stack and make a list of that length.
    # If it's negative or zero, the list will be empty
    .,
    # Negate. An empty list => 1; a non-empty list => 0
    !
    # If the string was a single number "n", the stack now holds n 0
    # If the string was a range "m-n", the stack now holds m -n 1
    # The following block will be executed 0 times for "n" and once for "m-n"
    {
        # Here we rely on twos-complement numbers satisfying ~n = -n -1
        # Stack: m -n
        ~))
        # Stack: m -(-n)-1+2  =  m n+1
        ,
        # Stack: m [0 1 2 ... n]
        >
        # Stack: [m m+1 ... n]
        ~
        # Stack: m m+1 ... n
    }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output

Come puoi espandere 3-5 in 3,4,5 senza usare un singolo personaggio -?
Berna Mariano,

@BernaMariano, scusa, in qualche modo ho perso la tua domanda. Espanderò la risposta con una spiegazione dettagliata.
Peter Taylor,

7

Perl 25 26 25

$_ è la stringa di sequenza

s/-/../g;$_=join",",eval

Sessione di esempio:

[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

Aggiunto 1 carattere al conteggio dei personaggi per l' opzione (grazie Gareth, ..kinda).-n-p


Probabilmente ho sbagliato a contare il personaggio (con le opzioni della riga di comando). Sentiti libero di correggere il mio conteggio, per favore
Ardnew,

Seguendo la risposta a questa domanda su meta , devi solo aggiungere 1 carattere per l' nopzione.
Gareth,

Rimuovere -M5.010e lo scambio -eper-E
Brad Gilbert b2gills

4

golfscript, 46 45

Il mio primo programma di script di golf in assoluto, ha impiegato ore per essere completato.

{','/{'-'/{~}%.,1-{))+{,}/\-~}{~}if}%","*}:r; 

# call:
"1,3-5,9,16,18-23"r

# return:
1,3,4,5,9,16,18,19,20,21,22,23

Puoi provarlo su http://golfscript.apphb.com/

Il mio miglior tentativo di spiegare questa atrocità:

{...}:r;     # makes a function block ... and names it r

','/         # slices the top element of stack from each ','
             # so we get ["1" "3-5" "9" "16" "18-23"]

{...}%       # makes a function block ... and calls it for 
             # each element in the list

'-'/{~}%     # slices the list by '-' and evals each element 
             # from string to int. ["1"] becomes [1], 
             # ["3-5"] becomes [3 5]

.,1-         # adds the length of the list -1 on top of the stack
             # so for [1] the stack becomes [1] 0, for [3 5]
             # it becomes [3 5] 1

# next we add two function blocks, they, like the 0/1 just before
# are used by an if clause a tiny bit later. First block is for 
# lists that have a 1 on top of them, the latter for ones with 0.

# First block, we have something like [3 5]

))+          # pops the top element of the array, increments 
             # it and puts back. [3 6]

## It seems {...}%~ is same as {...}/
## this is why these two are not in the code any more

{,}%         # , makes a list from 0 to n-1, where n is the parameter
             # so we get [[0 1 2] [0 1 2 3 4 5]]

~            # Dumps the outer array, [0 1 2] [0 1 2 3 4 5]

\            # swaps the two arrays

-            # set complement [3 4 5]

~            # dumps the array, so the elements are left in the stack

# Second block, we have something like [16]

~            # just dumps the array, 16

# Blocks end

if           # takes the top three elements of the stack, evaluates the 
             # first (0 or 1), runs second if true (anything but 
             # [], "", 0 or {} ), otherwise the third.

","*         # joins an array with ","

modifica 1: ha cambiato l'ultimo {}% ~ in {} /, anche la mia descrizione era probabilmente errata.


2
+1, perché chiunque abbia fatto un programma in GolfScript se lo è guadagnato.
Gareth,

@Gareth Grazie. Per prima cosa ho pensato di farlo nel modo perl: cambiare - in ... e valutarlo. Quindi non sono riuscito a trovare alcun modo sano per costruire array quindi l'ho fatto. Sono sicuro che qualcuno troverà una soluzione di 20 caratteri con golfscript.
shiona,

Ne ho 24 al momento, quindi ne prenderò 20 come una sfida;) Tuttavia puoi salvarne alcuni abbastanza facilmente. Il problema richiede un programma, non una funzione, quindi puoi perdere l'iniziale {e il finale }:r;e puoi anche salvarne uno sostituendolo 1-con (. (Per inciso, IIRC è un trucco che mi mancava anche nel mio primo programma GolfScript)
Peter Taylor,

PS C'è una sottile differenza tra {...}%~e {...}/. Se stai accedendo a qualcosa di più in basso nello stack, integer $allora il primo è più semplice, perché non devi regolare il numero intero ogni volta per compensare ciò che stai lasciando nello stack.
Peter Taylor,

4

R , 44 byte

`-`=seq;eval(parse(t=c("c(",scan(,""),")")))

Provalo online!

Ridefinisci -nel senso seq(cioè :), circonda l'ingresso con c()e valuta l'espressione corrispondente.


3

K, 47

","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0

Caso di prova

k)","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0
1,3-5,9,16,18-23
"1,3,4,5,9,16,18,19,20,21,22,23"

","/:$,/{{x+!1+y-x}. 2#"J"$"-"\:x}'","\:0:0per 43 byte
streetster

3

Gelatina , 9 byte

⁾-ryṣ”,VF

Provalo online!

   y         Replace
⁾-r          hyphens with the letter r,
    ṣ”,      split on commas,
       V     evaluate every element,
        F    and flatten.

L'intervallo diade rprende due argomenti su entrambi i lati e produce un intervallo inclusivo tra di loro.


2

J, 53 43 41 39 38 caratteri

;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1

Accetta input dalla tastiera:

   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1-4,8-11
1 2 3 4 8 9 10 11

Output per il test case richiesto:

   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1,3-5,9,16,18-23
1 3 4 5 9 16 18 19 20 21 22 23

2

Hassium , 173 byte

Questo è stato piuttosto lungo e potrebbe non essere in competizione poiché c'è un finale, alla fine.

 func main(){p="1,2,3,5-8".split(",")for(c=0;c<p.length;c++){e=p[c]if(e.contains("-")){p=e.split("-")for(x=p[0].toInt();x<=p[1].toInt()print(x++ +",")){}}else print(e+",")}}

Corri online e vedi espanso qui



1

Python 2.7, 147 138 byte

z, f = input (). split ( ''), []
per i in z:
 x = i.split ( '-')
 se len (x)> 1: f + = range (int (x [0]), int (x [1]) + 1)
 altro: f + = [int (x [0])]
print str (f) [1: -1]

Uso:

>>> python nums.py
"1,3-5,9,16,18-23"
1, 3, 4, 5, 9, 16, 18, 19, 20, 21, 22, 23

Non è il miglior programma ...


1
Benvenuti in PPCG. Penso che puoi abbreviare la tua risposta usando 1 spazio per i rientri.
intrepidcoder il

Grazie @intrepidcoder, non sapevo che avresti potuto usare singoli rientri di spazio.
Alex,

1

MATLAB, 47 byte

disp(eval(['[',strrep(input(''),'-',':'),']']))

Questo frammento legge un input di stringa dalla finestra di comando, sostituisce "-" con ":", aggiunge parentesi quadre alla stringa e quindi la valuta, in modo che l'input venga espanso in una matrice completa di numeri.

Esempio di input:

'1,3-5,9,16,18-23'

Esempio di output:

1     3     4     5     9    16    18    19    20    21    22    23

Credo che questo output sia consentito, poiché la sfida dice solo che tutti i numeri in un gruppo dovrebbero essere visualizzati.


l'output separato da virgole sarebbe più bello, anche se posso vedere un modello separato da 5 spazi , per me è fantastico :)
BernaMariano,


1

PowerShell, 79 71 byte

('('+($args[0]-replace'-','..'-replace',','),(')+')'|iex|%{$_})-join','

Provalo online!

La parte interna cambia "1,5-9,12" in un formato "(1), (5..9), (12)" che PowerShell comprende, quindi esegue quello con iex, che crea una matrice di array. Quindi scorrere attraverso ciascun array interno, quindi infine unire tutti gli elementi dell'array esterno

Prende in prestito il codice dalla mia risposta "Aiutami a gestire il mio tempo"

uso

PS C:\Tools\Scripts\golfing> .\return-each-number-from-a-group-of-numbers.ps1 '1,3-5,9,16,18-23'
1,3,4,5,9,16,18,19,20,21,22,23

-8 byte grazie alla Veskah



1

K (oK) , 40 31 byte

Soluzione

,/{{x+!1+y-x}. 2#.:'"-"\x}'","\

Provalo online!

Spiegazione:

Gestito più golf mentre si aggiungeva la spiegazione ...

,/{{x+!1+y-x}. 2#.:'"-"\x}'","\ / the solution
                           ","\ / split input on ","
  {                      }'     / apply lambda to each
                    "-"\x       / split x on "-"
                 .:'            / value (.:) each (')
               2#               / 2 take (dupe if only 1 element)
   {        }.                  / diadic lambda, 2 args x and y
         y-x                    / y subtract x
       1+                       / add 1
      !                         / range 0..n
    x+                          / add x
,/                              / flatten

0

Clojure, 110 byte

#(clojure.string/join","(for[s(.split %",")[a b][(map read-string(.split s"-"))]r(if b(range a(inc b))[a])]r))

Gestire le stringhe non è molto divertente :(


0

Python 2 , 112 byte

Risposta abbastanza semplice e diretta.

L=[]
for s in input().split(','):
 if'-'in s:a,b=map(int,s.split('-'));L+=range(a,b+1)
 else:L+=[int(s)]
print L

Provalo online!



0

Japt , 12 byte

q, c@OvXr-'ò

Provalo


Puoi sostituirlo c@con £?
Oliver,

@Oliver, in quanto è una vecchia sfida che non specifica il suo formato I / O, ho sbagliato dal lato della cautela, prendendo l'input come stringa delimitata da virgole e emettendolo come un array appiattito. Normalmente, però, sì, avrei specificato l'input come una matrice di stringhe, l'output come una matrice multidimensionale e appena usato £al posto dei primi 5 byte.
Shaggy,

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.