Ascesa, sequenza, ascesa


19

Abbiamo una sequenza strettamente crescente di numeri interi non negativi, come:

12 11 10

Aspettare! Questa sequenza non è strettamente crescente, vero? Bene, i numeri sono scritti in basi diverse. La base minima possibile è 2, la più grande è 10.

Il compito è indovinare le basi per ogni numero scritto, in modo che:

  • la sequenza è in costante aumento,
  • la somma delle basi è massimizzata.

Ad esempio, la soluzione per l'esempio sarà:

6 8 10

perché sotto queste basi la sequenza diventa 8 9 10decimale - una sequenza strettamente crescente, e non siamo in grado di trovare basi per le quali la sequenza rimane strettamente crescente e la cui somma è maggiore di 6+8+10.

A causa della seconda limitazione, una soluzione 3 5 7non è soddisfacente: nonostante il fatto che la sequenza diventi al di 5 6 7sotto di tali basi, dobbiamo massimizzare la somma delle basi, e 3+5+7 < 6+8+10.

Se in assenza di basi 2<=b<=10è possibile che le serie siano in forte aumento, ad esempio:

102 10000 10

singolo

0

dovrebbe essere prodotto.

La sequenza di input può essere passata nel modo più conveniente per la tua soluzione (input standard / parametri della riga di comando / argomenti della funzione ...).


1
È 1 3 5una sequenza crescente? Che dire 1 7 22? (nella base 10)
Maniglia della porta

Sì, 1 3 5e 1 7 22stanno entrambi salendo sotto la base 10. Quindi, la soluzione per entrambi i casi è 10 10 10, perché dobbiamo massimizzare la somma delle basi assicurando che la sequenza aumenti quando l'n-esimo numero viene interpretato come scritto nella base uguale a n -th termine di soluzione.
pawel.boczarski,

2
@Dennis Sì, intendo una sequenza strettamente crescente. 1 1 1o 3 3 4non si stanno alzando.
pawel.boczarski,

3
Se i commenti indicano che la domanda è suscettibile di interpretazioni errate, non limitarti a rispondere nei commenti. Modifica la domanda in modo che gli altri non perdano tempo a scrivere risposte che la interpretino in modo diverso.
Peter Taylor,

3
E in tema di ambiguità, uno dei commenti sulla mia risposta afferma che dovremmo presumere che i numeri siano scritti in forma canonica nella data base. In tal caso, correggi la frase " La base minima possibile è 2 " in qualcosa del tipo " La base minima possibile è una maggiore del valore della cifra più grande ".
Peter Taylor,

Risposte:


13

Pyth, 31 30 29 byte

e+0f.x!sgM.:iVczdT2ZosN^STlcz

1 byte grazie a @Jakube.

Dimostrazione. Collaudare l'imbragatura.

L'ingresso è dato su STDIN, spazio separato. Se è consentito l'input separato da newline, posso accorciare il programma di 2 byte.

Spiegazione:

e+0f.x!sgM.:iVczdT2ZosN^STlcz
                                  Implicit: z = input(), T = 10, Z = 0, d = ' '
                        ST        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                          lcz     len(z.split())
                       ^          All combinations w/replacement of that length.
                    osN           Order by increasing sum.
   f                              Filter on
              czd                 z.split(' ')
            iV   T                Vectorize the "Convert to base" operation over 
                                  the integers as strings and the base sequence.
          .:      2               Take length 2 subsequences.
        gM                        Map the >= operation over them.
      !s                          Sum and logically negate.
    .x             Z              If that throws an error, returns 0 (e.g. reject)
 +0                               Prepend a 0, in case no sequences are found.
e                                 Take the end of the list.

Includere 1nell'elenco di possibili basi è sicuro perché i, che utilizza il intbuiltin di Python , non consente 1come base e quindi genera sempre un errore, che viene intercettato e filtrato.


9

CJam, 43 byte

0B,2>ea,m*{:+~}${ea::~_2$.b__Q|$=*@.b=}=p];

Legge gli argomenti della riga di comando e stampa un array.

Provalo online nell'interprete CJam .

Esempi

$ cjam rise.cjam 12 11 10
[6 8 10]
$ cjam rise.cjam 19 18 17
0

Come funziona

0       e# Push a 0 (default return value).
B,2>    e# Push [0 ... 10] and remove the first two elements.
ea,     e# Push the number of command-line arguments (n).
m*      e# Cartesian power. Pushes all vectors of {2 ... 10}^n.
{:+~}$  e# Sort by the negated sums.
{       e# Find; for each vector V in {2 ... 10}^n:
  ea::~ e#   Evaluate each character of each command-line argument.
  _2$   e#   Copy the results and V.
  .b    e#   Vectorized base conversion (list to integer).
  __    e#   Push two copies.
  Q|$   e#   Deduplicate and sort the last copy.
  =     e#   Compare it to the first. Pushes 1/0 if equal/unequal.
  *     e#   Repeat the original result of .b that many times.
  @.b   e#   Vectorized base conversion (integer to list).
  =     e#   Compare the result to the modified command-line arguments.
        e#   Equality makes sure that the base was greater than all digits.
}=      e# If pushed 1, push V and break.
p       e# Print. Either prints the last V or 0 if none matched.
];      e# Clear the stack to avoid implicitly printing the 0 (if still present).

6

Julia, 176 156 145 118 109 99 97 byte

A->try p=NaN;flipud(map(i->(k=11;t=p;while t<=(p=parseint("$i",k-=1))end;k),flipud(A)))catch;0end

Ungolfed:

function anonfunc(i)
  # Start with k=11 so that it evaluates to 10 on first while iteration
  k=11
  # set t to the previous value of p
  # Note: p here gets held over between iterations within the map
  t=p
  # Iterate through, dropping k by 1 and evaluating the integer in
  # base k and stopping if the value drops below t
  # Note: "p=" expression inside conditional to ensure k-=1 is evaluated
  # at least once (to make NaN work as desired)
  while t<=(p=parseint("$i",k-=1))
  end
  # if it dropped below t, return the base, k to be the corresponding
  # element in the map
  return k
end

function f(A)
  # Using try/catch to return 0 if no acceptable base found
  try
    # This is a trick to make sure the comparison in the while loop
    # evaluates to false on the first use of it (last value in A)
    p=NaN
    # Apply anonfunc to each element of A, starting with the last element
    # and store the result in S
    S=map(anonfunc,flipud(A))
    # S is backwards, so flip it and return it
    return flipud(S)
  catch
    # Will throw to here if parseint fails with the base due to having
    # a digit not acceptable in the base
    return 0
  end
end

Utilizzato con un input di array 1d. Se la funzione è assegnata a c, allora si chiamerebbe c([12,11,10])e sarebbe in uscita [6,8,10].

Nota: avevo usato dec(i)all'interno del comando parseint, ma poiché iè un nome di variabile a carattere singolo e non ho bisogno di accedere a un componente, ho usato "$i"per ottenere lo stesso risultato.


Hai dei buoni trucchi qui. Bel lavoro.
Alex A.

Questo codice sembra controllare le basi per una sequenza strettamente decrescente nell'ordinario ordine di lettura da sinistra a destra.
pawel.boczarski il

@ pawel.boczarski - Non sono sicuro di cosa intendi, ma se lo desideri, posso fornire alcuni esempi di ciò che genera per determinati input. Ad esempio, se si assegna alla funzione il nome c, quindi gli c([12,11,10])output [6,8,10], che sono le basi richieste.
Glen O

@GlenO Oh, capisco. Ho usato il vettore riga [12 11 10]invece di [12,11,10]e ciò ha dato l'effetto indesiderato.
pawel.boczarski,

@ pawel.boczarski - ah, capisco. Sì, se vuoi che funzioni con i vettori di riga, dovrai sostituire "flipud" con "fliplr", nel qual caso restituirà un vettore di riga delle basi.
Glen O

5

Julia, 259 204 183 byte

Ho salvato un mucchio con l'aiuto di Glen O.

A->(M(x)=maxabs(digits(x))+1:10;S=[];X={};for i=M(A[1]),j=M(A[2]),k=M(A[3]) s=map(parseint,map(dec,A),[i,j,k]);all(diff(s).>0)&&(S=[S,sum(s)];X=[X,{[i,j,k]}])end;X==[]?0:X[indmax(S)])

Ungolfed + spiegazione:

function f(A)
    # Define a function to obtain the smallest possible base range
    M(x) = (maxabs(digits(x)) + 1):10

    # Define container arrays for the sums and bases
    S = []
    X = {}

    # Loop over all possible bases for each of the elements
    for i = M(A[1]), j = M(A[2]), k = M(A[3])
        # Parse each element of the input as a string
        # in the given base
        s = map(parseint, map(dec, A), [i,j,k])

        # Push the sum and bases if s is rising
        if all(diff(s) .> 0)
            S = [S, sum(s)]
            X = [X, {[i,j,k]}]
        end
    end

    # If X is empty, return 0, otherwise return the bases
    isempty(X) ? 0 : X[indmax(S)]
end

OK, un po 'di golf da fare ... usa "repr" invece di "string" nel comando map, funzioneranno allo stesso modo in questo contesto e salveranno due byte. E possiamo salvarne un po 'di più usando un operatore infix per il parseint scrivendo "\ = parseint" e quindi usando x [1] \ i anziché p (x [1], i) - un altro byte nel "\" parte, quindi salvando tre per ogni utilizzo di p per un risparmio netto di 8 byte. Un altro byte salvato sostituendo "massimo (cifre (x)) con massimo (cifre (x) ...)"
Glen O

Per un risparmio più grande, unisci i cicli for - usa for i=M(A[1]):10,j=M(A[2]):10,k=M(A[3]):10 <code here>end;, risparmiando otto per i due end;secondi rilasciati e otto per sostituire "for" con ,.
Glen O

In realtà, possiamo fare ancora meglio per la parte del parseint. Elimina completamente la ridenominazione del parseint e utilizzalo s=map(parseint,x,[i,j,k]), risparmiando 18 byte rispetto alla soluzione originale e 10 rispetto al mio precedente miglioramento suggerito. E piuttosto che s==sort(unique(s))usare all(diff(s).>0)per salvare altri 3 byte.
Glen O

C'è sicuramente altro che si può fare, ma lo lascerò a te e proverò invece a trovare il mio approccio.
Glen O

Correzione minore: ho suggerito di utilizzare max (...) anziché massimo ... ma mentre salva un byte, non riesce per i valori di input a una cifra, quindi è necessario utilizzare il massimo.
Glen O

4

CJam (39 byte)

{Afb:X,9,2f+m*{X\.b__$_&=*},{:+}$0\+W=}

Questa è una funzione anonima che accetta l'input come un array di numeri decimali nello stack e lascia l'output come array o come numero intero 0nello stack. Demo online .


Inoltre, questo sembra ordinare in base alla somma degli interi risultanti anziché delle basi e ha lo stesso problema della mia revisione precedente ( 19non può essere un numero di base 9).
Dennis,

1
Hmm. La domanda sembra aver bisogno di qualche miglioramento.
Peter Taylor,

@PeterTaylor Pah, scuse;)
Decadimento beta

2

Python 2 (147 byte)

def x(s):
 q=int;c=10;o=q(s[-1])+1;l=[]
 for i in map(str,s)[::-1]:
    n=q(i,c)
    while o<=n:
        c-=1;n=q(i,c)
        if 3>c:return 0
    l=[c]+l;o=n
 return l

Chiamare la funzione xcon un elenco di ints.

Esempio:

print x([12,11,10])

stampe

[6, 8, 10]
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.