Trova la somma dei primi n numeri gonfiabili


19

Terminologia

Un numero crescente è uno in cui ogni cifra è maggiore o uguale a tutte le cifre alla sua sinistra (es. 12239)

Un numero decrescente è quello in cui ogni cifra è inferiore o uguale a tutte le cifre a sinistra di essa (es. 95531)

Un numero rimbalzante è qualsiasi numero che non aumenta o diminuisce. Poiché ciò richiede almeno 3 cifre, il primo numero rimbalzante è 101

L'obiettivo

Dato un numero intero n maggiore o uguale a 1, trova la somma dei primi n numeri rimbalzanti

Regole

  • Questo è il codice golf, quindi vince la risposta con il minor numero di byte
  • Se la tua lingua ha limiti sulla dimensione dei numeri interi (es. 2 ^ 32-1) n sarà abbastanza piccolo da contenere la somma nell'intero
  • L'input può essere qualsiasi forma ragionevole (stdin, file, parametro della riga di comando, numero intero, stringa, ecc.)
  • L'output può essere qualsiasi forma ragionevole (stdout, file, elemento utente grafico che visualizza il numero, ecc.)

Casi test

1 > 101
10 > 1065
44701 > 1096472981

3
Non sono sicuro di aver compreso le tue restrizioni. Posso sorti numeri e verificare se sono uguali al numero originale? Sta usando un built-in ( sort), ma non è strettamente un built-in per verificare se sta aumentando. Controlla i requisiti del programma Non osservabile e Do X senza Y sul nostro post Meta "Cose da evitare".
AdmBorkBork,

5
Ciao, benvenuto in PPCG! Anche se questo è un bel primo post (+1), ho alcuni piccoli suggerimenti: Nessun builtin che controlla se un numero sta aumentando può essere usato , Nessun builtin che controlla se una stringa sta aumentando lessicograficamente può essere usato (non consentendo built-in) è una cosa da evitare quando si scrivono sfide ; abbiamo un Sandbox per le sfide proposte , in cui puoi condividere la tua idea di post prima
dell'invio

Ho aggiornato le restrizioni per abbinare meglio la categoria "Eccezioni" del link che hai pubblicato
media il

4
Non vedo ancora il punto di avere una tale limitazione in primo luogo. Certo, sta a te decidere se mantenerlo o meno, ma proibire gli incorporati è in genere una cattiva pratica. Se ritieni che la sfida sia banalizzata dai built-in, dovresti notare che limitarli semplicemente non rende più interessante la risoluzione del compito, ma piuttosto aggiunge una piastra di caldaia. Potresti prendere in considerazione la rimozione di tale restrizione? (a proposito, questo rientra ancora nel Do X senza Y ) Altrimenti, l'idea mi piace parecchio, e non vorrei che una restrizione leggermente soggettiva togliesse il compito effettivo.
Mr. Xcoder,

10
Ho comunque rimosso la restrizione, poiché è chiaro che è più divertente per la comunità in quel modo, e mi fiderò delle linee guida e delle migliori pratiche qui che assicurano che le sfide siano della migliore qualità
media il

Risposte:


8

Gelatina , 10 8 byte

ṢeṚƬ¬µ#S

Provalo online!

Come funziona

ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the 
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.

4
Il +1 ṚƬè estremamente pulito ...
Mr. Xcoder il

6

Pyth , 10 byte

s.f!SI#_B`

Provalo qui!

Come funziona?

sf! SI # _B` - Programma completo. Prende un numero intero Q da STDIN e restituisce STDOUT.
 .f - Trova i primi numeri interi positivi Q che soddisfano una determinata condizione.
   ! SI # _B - La condizione. Restituisce vero solo per numeri rimbalzanti.
       _B` - Lancia il numero su una stringa e biforcalo (accoppilo) con il suo rovescio.
      # - Filtro-mantieni quelli ...
     I - Che sono invarianti sotto ...
    S - Ordinamento.
           - Per chiarire, I (invariante) è un operatore Pyth che accetta due input, a 
             funzione e un valore e controlla se la funzione (valore) == valore, quindi
             tecnicamente questo non è un built-in.
   ! - Logico no. L'elenco vuoto viene mappato su true, altri valori su false.
s - Somma.

4

K (ngn / k) , 37 byte

{+/x{{(a~&\a)|a~|\a:10\x}(1+)/x+1}\0}

Provalo online!

{ } è una funzione con argomento x

x{ }\0vale la {}su 0 xvolte, preservando i risultati intermedi

(1+) è la funzione successiva

{ }(1+)/x+1applica la funzione successore a partire da x+1fino a quando il valore {}restituisce true

10\x sono le cifre decimali di x

a: assegnato a a

|\ è la scansione massima (massimi parziali) di a

&\ analogamente, è la scansione minima

a~|\anon aaccoppiare il suo max-scan?

| o

a~&\a la sua scansione minima?

+/ somma


4

JavaScript (ES6), 77 byte

f=(i,n=0,k,p)=>i&&([...n+''].map(x=>k|=x<p|2*(p<(p=x)))|k>2&&i--&&n)+f(i,n+1)

Provalo online!

Commentate

f = (                     // f = recursive function taking:
  i,                      //   i = number of bouncy numbers to find
  n = 0,                  //   n = current value
  k,                      //   k = bitmask to flag increasing/decreasing sequences
  p                       //   p = previous value while iterating over the digits
) =>                      //
  i && (                  // if there's still at least one number to find:
    [...n + '']           //   turn n into a string and split it
    .map(x =>             //   for each digit x in n:
      k |=                //     update k:
        x < p |           //       set bit #0 if x is less than the previous digit
        2 * (p < (p = x)) //       set bit #1 if x is greater than the previous digit
                          //       and update p
    )                     //   end of map()
    | k > 2               //   if both bits are set (n is bouncy):
    && i--                //     decrement i
    && n                  //     and add n to the total
  ) + f(i, n + 1)         //   add the result of a recursive call with n + 1

3

Python 2, 110 92 89 byte

n=input()
x=s=0
while n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1
print s

Provalo online

Questa funzione determina se un numero è rimbalzante:

lambda x:{-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]))

Puoi confrontare direttamente i personaggi. In effetti, la comprensione impostata può diventare set(map(cmp,`x`[:-1],`x`[1:])).
Jakob,

@Jakob Grazie. Ho sempre dimenticato che puoi usare in mapquel modo.
mbomb007,

1
x=s=0\nwhile n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1salva 3 byte
Mr. Xcoder il


3

Retina , 93 byte

K`:
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(#*).*
:$1#;$.($1#
)`\d
*_;
)`:(#+).*
$1:$1
\G#

Provalo online!Spiegazione:

K`:

Inizializza s=i=0. ( sè il numero di #s prima del :,i il numero di #s dopo.)

"$+"{
...
)`

Ripetere n tempi.

/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)`

Ripeti mentre i non è rimbalzante.

:(#*).*
:$1#;$.($1#

Incremento i e crea una copia in decimale.

\d
*_;

Converti le cifre della copia in unario. Il test di rimbalzo utilizza la copia unaria, quindi funziona solo una voltai è stato incrementato almeno una volta.

:(#+).*
$1:$1

Aggiungi ias ed eliminare la copia delle cifre unari, in modo che per il prossimo passo del ciclo interno il test bounciness non riesce e iviene incrementato almeno una volta.

\G#

Convertire s in decimale.

La versione a 121 byte viene calcolata in decimali, quindi potrebbe funzionare con valori maggiori di n:

K`0:0
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(\d+).*
:$.($1*__);$.($1*__)
)+`;\d
;$&*_;
)`\d+:(\d+).*
$.(*_$1*):$1
:.*

Provalo online! Spiegazione:

K`0:0

Inizializza s=i=0.

"$+"{
...
)`

Ripeti in tempi.

/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)

Ripeti finchéi non è rimbalzante.

:(\d+).*
:$.($1*__);$.($1*__)

Incrementa ie crea una copia.

+`;\d
;$&*_;

Converti le cifre della copia in unario. Il test di rimbalzo utilizza la copia unaria, quindi funziona solo una volta chei è stato incrementato almeno una volta.

\d+:(\d+).*
$.(*_$1*):$1

Aggiungi ials ed eliminare la copia delle cifre unari, in modo che per il prossimo passo del ciclo interno il test bounciness non riesce e iviene incrementato almeno una volta.

:.*

Elimina i.


3

05AB1E , 12 byte

µN{‚Nå_iNO¼

Provalo online!

Spiegazione

µ              # loop over increasing N until counter equals input
     Nå_i      # if N is not in
 N{‚          # the pair of N sorted and N sorted and reversed
         NO    # sum N with the rest of the stack
           ¼   # and increment the counter

3

Java 8, 114 112 byte

n->{int i=0,s=0;for(;n>0;++i)s+=(""+i).matches("0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*")?0:--n*0+i;return s;}

Utilizza un'espressione regolare per verificare se il numero aumenta o diminuisce. Provalo online qui .

Ungolfed:

n -> { // lambda
    int i = 0, // the next number to check for bounciness
        s = 0; // the sum of all bouncy numbers so far
    for(; n > 0; ++i) // iterate until we have summed n bouncy numbers, check a new number each iteration
        s += ("" + i) // convert to a String
             .matches("0*1*2*3*4*5*6*7*8*9*" // if it's not an increasing  number ...
             + "|9*8*7*6*5*4*3*2*1*0*") ? 0 // ... and it's not a decreasing number ...
             : --n*0 // ... we have found another bouncy number ...
               + i; // ... add it to the total.
    return s; // return the sum
}

2

Python 2, 250 byte

n=input()
a=0
b=0
s=0
while a<n:
    v=str(b)
    h=len(v)
    g=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]>=v[f-1]]
    d=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]<=v[f-1]]
    if len(g)!=h-1 and len(d)!=h-1:
       a+=1
       s+=b
    b+=1
print s

Benvenuto! Potresti voler visualizzare questa pagina per Suggerimenti per il golf a Python
mbomb007,

1
Suggerisco di usare ;per mettere quante più istruzioni possibili su una singola riga, rimuovendo gli spazi bianchi e definendo una funzione per le 2 lunghe righe molto simili, in modo da poter riutilizzare parte del codice. Inoltre, puoi fare a=b=s=0e len(g)!=h-1!=len(d).
mbomb007,

Grazie per i suggerimenti Devo andare adesso. ma ci lavorerò più tardi.
Hashbrowns,


0

Rosso , 108 byte

func[n][i: s: 0 until[t: form i
if(t > u: sort copy t)and(t < reverse u)[s: s + i n: n - 1]i: i + 1
0 = n]s]

Provalo online!

Più leggibile:

f: func [ n ] [
    i: s: 0
    until [
       t: form i  
       if ( t > u: sort copy t ) and ( t < reverse u ) [
            s: s + i
            n: n - 1
       ]
       i: i + 1
       0 = n
    ]
    s
]

Una buona opportunità da usare form- form iè 5 byte più breve dito-string i


0

MATL , 31 30 byte

l9`tVdZS&*0<a?wQtG>?.]y]QT]xvs

Provalo online!

l       % Initialize counter to 1
9       % First value to check for being bouncy
`       % Start do-while loop
  tV    % duplicate the current number and convert to string
        % (let's use the iteration where the number is 1411)
        % stack: [1, 1411, '1411']
  d     % compute differences between the characters
        %  For non-bouncy numbers, this would be either all 
        %  positive values and 0, or all negative values and 0
        % stack: [1, 1411, [3 -3 0]]
  ZS    % keep only the signs of those differences
        % stack: [1, 1411, [1 -1 0]]
  &*    % multiply that array by its own transpose, so that
        %  each value is multiplied by every other value
        %  for non-bouncy numbers, all products will be >=0
        %  since it would have had only all -1s or all 1 (other than 0s)
        % stack: [1, 1411, [1 -1  0
                            -1  1 0
                            0  0  0]]
  0<a?  % if any value in the matrix is less than 0
    wQ    % switch the counter to top, increment it
          % stack: [1411, 2]
    tG>?  % duplicate it, check if it's gotten greater than the input limit
      .]    % if so, break out of loop
  y]    % else, duplicate bouncy number from inside stack,
        %  keeping a copy to be used for summing later
        % stack: [1411, 2, 1411]
  QT    % increment number, push True to continue loop
]     % loop end marker
x     % if we've broken out of loop, remove counter from stack
v     % concatenate the bouncy numbers we've collected in stack and 
s     % sum them

0

R , 96 byte

function(n){while(n){y=diff(T%/%10^(0:log10(T))%%10);g=any(y<0)&any(y>0);F=F+T*g;n=n-g;T=T+1};F}

Provalo online!

Spiegazione :

while(n){                         # while n > 0

        T%/%10^(0:log10(T))%%10   # split T into digits(T==TRUE==1 at the 1st loop)
y=diff(                         ) # compute the diff of digits i.e. digits[i] - digits[i+1]

g=any(y<0)&any(y>0)               # if at least one of the diff is < 0 and 
                                  # at least one is > 0 then T is "bouncy"

F=F+T*g                           # if bouncy increment F (F==FALSE==0 at the 1st loop)

n=n-g                             # decrement n by 1 if bouncy

T=T+1}                            # increment T by 1 and loop

F}                                # return F

0

Rubino (123 byte)

o=0
x=["0"]
while n>0 do x=(x.join.to_i+1).to_s.split('')
(x.sort!=x&&x.sort!=x.reverse ? (n-=1;o+=x.join.to_i):'')
end
p o

Mi sembra abbastanza brutto. Il rimbalzo è definito in questo bloccox.sort!=x&&x.sort!=x.reverse



0

C (gcc), 104 byte

f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}

Provalo online qui .

Ungolfed:

f(n, // function: return type and type of arguments defaults to int;
     // abusing extra arguments to declare variables
  i,   // number currently being checked for bounciness
  s,   // sum of the bouncy numbers
  j,   // copy of i to be used for checking bounciness in a loop
  p,   // used for investigating the last digit of j
  b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
    for(i = s = 0; // check numbers from zero up; initial sum is zero
        n; // continue until we have n bouncy numbers
        s += b ? 0 // not bouncy, no change to the sum
        : i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
        ++i) // either way, move to the next number
        for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
        // bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
            p = j % 10, // get the last digit
            j /= 10, // truncate one digit from the right
            b &= // adjust bounciness:
                 (p -= j % 10) // compare current digit to the next
                 < 0 ? // not an increasing number, clear second to least significant bit
                 : p ? 2 // not a decreasing number, clear least significant bit
                 : b; // keep it the same
    n = s; // gcc shortcut for return s
}

Suggerisci u+=!y?--b,o:0,++oinvece di u+=y?0:o+0*--b,++o, ;y&=(c-=n%10)<0?:c?2:y)c=n%10,n/=10;anziché;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;
ceilingcat il
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.