Elemento di stringa nell'indice specificato


13

Data una stringa se un numero non negativo ninferiore alla lunghezza di s, emette il carattere nella nposizione -th di s.

0-indicizzazione e 1-indicizzazione sono consentiti. Per 1-indicizzazione, nsarà positivo e minore o uguale alla lunghezza di s.

s sarà composto solo da caratteri stampabili.

È consentito qualsiasi input / output ragionevole. Si applicano scappatoie standard .

Testcase (indicizzazione 0):

n s        output
0 "abcde"  a
1 "abcde"  b
2 "a != b" !
3 "+-*/"   /
4 "314159" 5

Testcase (1-indicizzazione):

n s        output
1 "abcde"  a
2 "abcde"  b
3 "a != b" !
4 "+-*/"   /
5 "314159" 5

Questo è , quindi vince la risposta più breve in byte.


13
Ho declassato questo perché in realtà non è una sfida di programmazione o golf; tutto ciò che viene essenzialmente chiesto qui è quale lingua ha il più breve incorporato per il lavoro.
Shaggy,

15
@Shaggy Lo stesso per molte altre semplici sfide come aggiungere due numeri, verificare se un numero è primo o stampare "Ciao, mondo!". Mentre questi sono noiosi in molte lingue che possono farli fuori dagli schemi, possono essere sfide interessanti per linguaggi più primitivi che devono implementare la propria implementazione. Inoltre, qualcosa di più complicato di solito è troppo chiedere a quelle lingue, quindi è bello avere uno sbocco per loro. Se ti annoiano sfide insignificanti, prova a farlo in un linguaggio non banale.
Martin Ender,

Risposte:



7

Alice , 5 byte

I&IO@

Provalo online!

Come al solito è molto più breve se evitiamo la modalità Ordinale e utilizziamo un formato di input abissale. Qui, il punto di codice del primo carattere viene utilizzato come input per l'intero . Il resto dell'input è la stringa. L'indice è basato su 1.

Spiegazione

I   Read a character and push its code point.
&I  Read that many more characters and push them.
O   Output the last one we read.
@   Terminate the program.

abysmal- Pensavo che ce l'avessi fatta xD
Stephen

@StephenS Vuoi dire che ho proposto questo formato I / O su meta? Sì, l'ho fatto, ma soprattutto per le lingue che dovrebbero implementare il proprio parser / renderer intero decimale ogni volta che competono in una sfida con l'I / O numerico, quindi probabilmente li salteranno del tutto. Ma ha lo sfortunato effetto collaterale che in alcune lingue che possono leggere e scrivere decimali abbastanza facilmente è ancora più breve usare invece i punti di codice.
Martin Ender,

6

Python, 15 byte

str.__getitem__

o

lambda s,i:s[i]

Entrambi accettano 2 argomenti: la stringa e l'indice. 0-indicizzati.


Sono sorpreso che entrambi i metodi abbiano la stessa lunghezza.
Leaky Nun,

6

Haskell, 4 byte

(!!)

Indicizzazione basata su 0. Esempio di utilizzo: (!!) "Hello" 1-> 'e'.


5

Ottava, 10 byte

@(s,n)s(n)

Prende una stringa se un numero ncome input e restituisce il ncarattere th di s.


5

Retina , 28 20 19 byte

8 byte salvati grazie a @MartinEnder non usando i gruppi di bilanciamento

Salvato 1 byte grazie a @ mbomb007 usando ^.+invece di^\d+

^.+
$*
+`1¶.
¶
!1`.

Provalo online!

Il programma è indicizzato 0.


Passare \da .per salvare un byte.
mbomb007,

@ mbomb007 Grazie per la
segnalazione


3

Alice , 10 byte

/@!O?]&
 I

Provalo online!

Prevede la stringa sulla prima riga e l'indice in base 0 sulla seconda riga.

Spiegazione

Nonostante la sua ricchezza di incorporati, l'indicizzazione delle stringhe non esiste in Alice. Il motivo è che richiede sia un numero intero che un parametro stringa e tutti i comandi in Alice sono rigorosamente numeri interi o stringhe.

In generale, il modo principale per eseguire qualsiasi operazione su stringhe che richiedono o generano numeri interi è memorizzare la stringa sul nastro in modalità Ordinale, che è quindi possibile manipolare con numeri interi in modalità Cardinale.

/    Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces
     diagonally up and down through the program.
I    Read one line from STDIN and push it.
!    Store the string on the tape. This writes the character codes into consecutive
     tape cells starting at the tape head. (It also writes a -1 at the end as a
     terminator, but the tape is initialised to -1s anyway).

     The next few commands are junk that luckily doesn't affect the program:

?      Load the string from the tape and push it to the stack again.
&      Fold the next command over this string. That is, for each character
       in the string, push that character, then execute the command.
?      So we're folding "load" over the string itself. So if the string is "abc"
       we'll end up with "a" "abc" "b" "abc" "c" "abc" on the stack.
!      Store the top copy of "abc" on the tape (does nothing, because it's
       already there).

     Now the relevant part of the program continues.

I    Read another line from STDIN, i.e. the string representation of the index.
/    Reflect to W. Switch to Cardinal. The IP wraps to the last column.
&    Implicitly convert the string to the integer value it represents and
     repeat the next command that many times.
]    Move the tape head right that many cells. Note that Ordinal and Cardinal
     mode have separate tape heads, but they are initialised to the same cell.
?    Load the value from that cell, which is the code point of the character
     at the given index.
O    Print the corresponding character.
!    This discards or converts some of the strings on the stack and writes some
     value back to the tape, but it's irrelevant.
@    Terminate the program.

1
"Nonostante la sua ricchezza di incorporati, l'indicizzazione delle stringhe non esiste in Alice." > _>
Leaky Nun,

1
@LeakyNun Se pensi che sia un male, non c'è nemmeno un built-in per ottenere la lunghezza di una stringa. ;)
Martin Ender,



3

Brachylog , 2 byte

∋₎

Provalo online!

Spiegazione

unifica il suo output con un elemento dell'Input. Con come pedice, unificherà il suo output con il Ith elemento di S, con [S,I]come input.


3

Cubix , 8 byte

t@poIA//

Questa soluzione è 1 indicizzata. L'input deve essere composto prima da un numero, quindi da un separatore (che non è una cifra o una .) e quindi dalla stringa.

Provalo online!




2

SILOS , 43 byte

loadLine
readIO
a=256+i
a=get a
printChar a

Provalo online!

Abbastanza semplice.


SILOS è tornato \ o /
Leaky Nun

1
Sì, sto cercando di rispondere al maggior numero possibile di chiamate, inclusa la schermata di caricamento di Windows. Mi piace il punto in termini di output grafico e librerie, ma vorrei comunque sviluppare uno schema di compressione per cercare di renderlo competitivo. Essenzialmente, l'int [] che compila può essere generato leggendo un flusso di byte. @LeakyNun
Rohan Jhunjhunwala

2

BF , 9 byte

,[->,<]>.

L'indice viene preso tramite il codice carattere di un carattere (come l'invio di Alice). Successivamente, abbiamo la stringa.

Provalo online!

Il collegamento TIO utilizza un wrapper Bash e l'input può essere modificato nel file di intestazione (il motivo del wrapper è in modo che possiamo vedere i byte).


Legit TIO hacking: p
Leaky Nun

@LeakyNun Ho usato il wrapper per BF .
user41805,

1
Ho detto che è legittimo.
Leaky Nun,

C'è un modo per fare input in altre lingue TIO del genere? Ti piace SMBF?
mbomb007,

@ mbomb007 Dovresti essere in grado di farlo per altre lingue usando i loro wrapper. Ecco il wrapper per SMBF
user41805

2

JavaScript, 11 10 byte

s=>n=>s[n]

Utilizza l'indicizzazione basata su 0.

-1 byte grazie a @Leaky Nun

f=
s=>n=>s[n]
console.log(f("abcde")(0));
console.log(f("abcde")(1));
console.log(f("a != b")(2));
console.log(f("+-*/")(3));
console.log(f("314159")(4));


1
puoi usare il curry s=>i=>s[i]per salvare un byte
Leaky Nun,

1
Ogni volta che vedo le risposte in questo modo mi dà fastidio perché so che la versione C # è sempre un byte più lungo per il punto e virgola alla fine. E questo è davvero il caso qui
TheLethalCoder

2

> <> , 13 + 1 = 14 byte

+1 per la -vbandiera per ricevere input

:?!\i~1-
io;\

Grazie a @steenbergh per avermi informato del-v bandiera e avermi salvato 3 byte!

Immettere l'indice con l'argomento della riga di comando -v [index] (indicizzato 0) e immettere la stringa tramite stdin.

Provalo online!

Spiegazione

Lo stack inizia con l'indice in alto.
:lo duplica.
?ignora il carattere successivo se l'indice è 0. (Eliminandolo dallo stack)
Se è zero, \riflette la direzione in cui andare verso il basso. Quindi, si riflette a destra con il prossimo \. Si avvolge ed esegue iun personaggio, lo oinserisce e ;ferma l'esecuzione.
In caso contrario, !salta la prossima istruzione, quindi non scende.
i~inserisce un personaggio e lo scarta immediatamente.
1spinge 1.
-sottrae 1dall'indice, quindi un carattere nell'input viene consumato e l'indice viene diminuito. Il programma torna indietro a :.


1
C'è il -v <x>parametro della riga di comando, che inizializza lo stack da mantenere <x>all'avvio del programma. Provalo online
steenbergh,

2

Carota , 16 byte

$^//.{#}/S1//.$/

Provalo online!

Il formato di input è come tale:

string
index

E il programma è 1-indicizzato.

Spiegazione

Carrot ha diverse variabili globali, una per ogni tipo: string, float e array (altre che verranno implementate a breve). Il programma si avvia in modalità stringa, in cui tutti gli operatori influenzeranno la variabile di stringa globale. E io chiamo queste variabili "stack".

(Esempio di input: abcdef\n3)

$                          Get the first line of the input and set the stack-string to this value
^                          Exit caret-mode
                           stack-string = "abcdef"
/                          Operator (behaves differently depending on the argument)
 /.{#}/                     And the argument to this operator is a regex, so this program gets the matches of this regex into the stack-array
  .                          Any character
   {#}                       Pops a line from the input. So now this evaluates to # of any character where # is the second line of the input (in this case, 3)
                           stack-array = ["abc"]
                           And now we just need to get the last character in this string, but first
S1                         Join the array on the number 1 and set this to the stack-string. Because the array only contains one element, the number 1 does not appear in the stack-string.
                           stack-string = "abc"
/                          Operator; because the argument is a regex, this retrieves the matches of the regex:
 /.$/                       Get the last character in the string
                           stack-array = ["c"]

Ora questo restituisce un array di un elemento contenente una stringa di lunghezza uno, ma viene mostrato come una stringa nel sito Web.

Se volessimo davvero dare il risultato come una stringa, S","alla fine potremmo farlo facilmente , ma non importa perché l'output sembra sempre lo stesso sull'interprete.


1

Lotto, 32 byte

@set/ps=
@call echo(%%s:~%1,1%%

Legge sda STDIN e accetta ncome parametro della riga di comando.



1

Turtlèd , 9 byte

!?:[*l+].

Provalo online!

spiegazione:

Prima di tutto, Turtlèd è basato sulla griglia, con una cosa tartaruga. Ci sono celle a griglia che la tartaruga può spostare a sinistra, in alto, in basso e a destra e può scrivere cose sulle celle della griglia.

[the first grid cell the turtle starts on is marked with a *]
!         input the string into the string variable

 ?        input the number into the number variable

  :       this command takes the number variable and moves right that many.
          hence this moves right by the amount inputted

   [*  ]  this is an `until` loop. the * there means that `until` the turtle ends the loop
          on a grid cell with * written on it (that is, the first cell), it will execute
          the code inside again and again

     l+   the code inside the while loop. the `l` moves the turtle left, and the +
          increments the string pointer. the string pointer is used with the string var;
          when you want to write something from the string, you use `.`, which writes
          the pointed char. the pointed char is the n-th character of the string, n being
          the value of the string pointer. this code will execute until the l moves
          the turtle back on to the origin cell. since we moved right by the number
          inputted, this will increase the string pointer (which starts at 1)
          by the amount inputted.

       .  write the pointed char, which was dealt with in the previous comment.
          if 0 is inputted, turtle stayed on the origin square, and executed none
          of the loop, and turtle writes the first char of string input.
          if 1 is inputted, turtle moved one right, moved one left and incremented
          string pointer once, which means the second char is written. and so on.


          [the char of input has been written over the origin square]
          [implicitly the grid is outputted, which has spaces and blank lines taken out]
          [this is the requested char outputted, plus an unavoidable trailing newline
          due to how I made the interpreter. sue me]

1

Clojure, 3

nth

: P Cosa puoi fare quando c'è un built-in per questo? Funziona su elenchi, vettori, stringhe e sequenze. È O (1) o O (n), a seconda del tipo di dati utilizzato.


1

sed , 31 byte

:
/^1/{s:1 .: :;b}
s: (.).*:\1:

Provalo online!

Input: indice e stringa, separati da uno spazio. Indice in unario, ma a base zero.


1

Dyvil , 4 byte

_[_]

Crea una funzione anonima che accetta a Stringe an inte restituisce achar .

Uso:

let f: (String, int) -> char = _[_]
print f("abc", 1) // b


1

QBasic 4.5, 24 byte

INPUT a$,b:?MID$(a$,b,1)

Abbastanza diretto.



1

Mathematica, 18 byte

#~StringTake~{#2}&

Soluzione di base, ma purtroppo il nome della funzione è piuttosto lungo.


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.