지정된 인덱스에서 문자열의 요소


13

의 길이보다 작은 문자열 s과 음수가 아닌 숫자 를 지정하면의- 번째 위치에 문자를 출력하십시오 .nsns

0 인덱싱 및 1 인덱싱이 허용됩니다. 1- 인덱싱의 n경우 양수이고 길이보다 작거나 같습니다 s.

s 인쇄 가능한 문자로만 구성됩니다.

합리적인 입 / 출력이 허용됩니다. 표준 허점이 적용됩니다.

테스트 사례 (0- 인덱싱) :

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

테스트 사례 (1- 인덱싱) :

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

이것은 이므로 바이트 단위의 최단 답변이 이깁니다.


13
나는 이것이 실제로 프로그래밍이나 골프 도전이 아니기 때문에 이것을 하향 투표했다. 본질적으로 여기에서 요구되는 것은 작업에 가장 짧은 언어가 내장 된 언어입니다.
Shaggy

15
@Shaggy 두 숫자 추가, 숫자가 소수인지 테스트 또는 "Hello, World!"와 같은 다른 많은 간단한 도전과 동일합니다. 이것들은 즉시 사용할 수있는 많은 언어에서 지루하지만, 자신의 구현을 시작해야하는 더 원시적 인 언어에는 흥미로운 도전이 될 수 있습니다. 또한 복잡한 언어는 일반적으로 해당 언어를 요구하기에 너무 많으므로 해당 언어를 사용할 수있는 것이 좋습니다. 사소한 도전이 당신에게 도움이된다면 사소한 언어로 도전 해보십시오.
마틴 엔더

답변:



7

Alice , 5 바이트

I&IO@

온라인으로 사용해보십시오!

평소와 같이 서수 모드를 피하고 심연 입력 형식을 사용하면 훨씬 짧습니다. 여기서 첫 번째 문자의 코드 포인트는 정수 입력으로 사용됩니다 . 입력의 나머지 부분은 문자열입니다. 인덱스는 1부터 시작합니다.

설명

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-나는 당신이 그것을 xD로 만들었다 고 생각했습니다
Stephen

@StephenS 메타에서이 I / O 형식을 제안 했습니까? 예, 그러나 그랬지만 대부분 숫자 I / O로 도전 할 때마다 고유 한 10 진 정수 파서 / 렌더러를 구현해야하는 언어의 경우에는 대부분 생략 할 수 있습니다. 그러나 소수 언어를 쉽게 읽고 쓸 있는 일부 언어 에서는 코드 포인트를 사용하는 것이 여전히 짧다 는 불행한 부작용이 있습니다 .
마틴 엔더

6

파이썬, 15 바이트

str.__getitem__

또는

lambda s,i:s[i]

둘 다 문자열과 인덱스라는 두 가지 인수를 취합니다. 인덱스가 0입니다.


두 방법의 길이가 모두 놀랐습니다.
Leaky Nun

6

하스켈, 4 바이트

(!!)

0 기반 인덱싱 사용 예 : (!!) "Hello" 1-> 'e'.


5

옥타브, 10 바이트

@(s,n)s(n)

문자열 s과 숫자 n를 입력으로 받아서의 nth 문자를 리턴합니다 s.


5

망막 , 28 20 19 바이트

밸런싱 그룹을 사용하지 않고 @MartinEnder 덕분에 8 바이트 절약

@ mbomb007 덕분에 1 바이트를 ^.+대신 사용하여 저장했습니다.^\d+

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

온라인으로 사용해보십시오!

프로그램은 0 인덱스입니다.


변경 \d하는 .바이트를 저장합니다.
mbomb007

@ mbomb007 팁 주셔서 감사합니다 :)
user41805


3

Alice , 10 바이트

/@!O?]&
 I

온라인으로 사용해보십시오!

첫 번째 줄의 문자열과 두 번째 줄의 0 기반 인덱스를 예상합니다.

설명

풍부한 내장 기능에도 불구하고 문자열 인덱싱은 Alice에 존재하지 않습니다. 그 이유는 정수와 문자열 매개 변수가 모두 필요하고 Alice의 모든 명령은 정수에서 정수 또는 문자열에서 문자열까지이기 때문입니다.

일반적으로 정수를 필요로하거나 결과를 나타내는 문자열에 대한 작업을 수행하는 주요 방법은 문자열을 테이프에 서수 모드로 저장 한 다음 카디널 모드에서 정수로 조작 할 수 있습니다.

/    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
"풍부한 내장 기능에도 불구하고 Alice에는 문자열 색인이 없습니다." > _>
Leaky Nun

1
@LeakyNun 그것이 잘못되었다고 생각되면 문자열 길이를 얻을 수있는 내장 기능도 없습니다. ;)
Martin Ender







2

SILOS , 43 바이트

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

온라인으로 사용해보십시오!

충분히 간단합니다.


SILOS가 돌아 왔습니다 \ o /
Leaky Nun

1
네, 창 로딩 화면을 포함하여 가능한 한 많은 callenges에 응답하려고합니다. 그래픽 출력 및 라이브러리 측면에서 요점을 좋아하지만 여전히 경쟁력을 높이기 위해 압축 구성표를 개발하고 싶습니다. 본질적으로 컴파일 된 int []는 바이트 스트림을 읽어서 생성 할 수 있습니다. @LeakyNun
Rohan Jhunjhunwala

2

BF , 9 바이트

,[->,<]>.

인덱스는 char의 문자 코드를 통해 가져옵니다 (예 : Alice 제출). 그 다음에는 문자열이 있습니다.

온라인으로 사용해보십시오!

TIO 링크는 Bash 래퍼를 사용하며 헤더 파일에서 입력을 변경할 수 있습니다 (래퍼의 이유는 바이트를 볼 수 있도록하기위한 것입니다).


합법적 TIO 해킹 : p
수녀

@LeakyNun BF 래퍼를 사용했습니다 .
user41805

1
나는 그것이 합법적이라고 말했다.
Leaky Nun

그런 다른 TIO 언어로 입력하는 방법이 있습니까? SMBF처럼?
mbomb007

@ mbomb007 래퍼를 사용하여 다른 언어에서도 그렇게 할 수 있어야합니다. 다음은 SMBF
user41805

2

자바 스크립트, 11 10 바이트

s=>n=>s[n]

0 기반 인덱싱을 사용합니다.

@Leaky Nun 덕분에 -1 바이트

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
카레 s=>i=>s[i]를 사용하여 바이트를 절약 할 수 있습니다
Leaky Nun

1
C # 버전이 항상 세미 콜론의 경우 1 바이트 더 길다는 것을 알기 때문에 이와 같은 답변을 볼 때마다 짜증납니다. 그리고 그것은 실제로 여기에 있습니다
TheLethalCoder

2

> <> , 13 + 1 = 14 바이트

-v플래그를 입력하려면 +1

:?!\i~1-
io;\

플래그 에 대해 알려주고-v 3 바이트를 절약 한 @steenbergh 에게 감사드립니다 !

명령 행 인수 -v [index](0 색인)로 색인을 입력하고 stdin을 통해 문자열을 입력하십시오.

온라인으로 사용해보십시오!

설명

스택은 인덱스를 맨 위에서 시작합니다.
:그것을 복제합니다.
?인덱스가 0 인 경우 다음 문자를 무시합니다. (스택에서 빼기)
0이면 \아래로 이동할 방향을 반영합니다. 그런 다음 다음과 함께 오른쪽에 반영됩니다 \. 그것은 감싸고 i문자를 입력하고, o그것을 입력 하고 실행을 ;중단합니다.
그렇지 않으면 !다음 명령어를 건너 뛰므로 내려 가지 않습니다.
i~문자를 입력 한 다음 즉시 버립니다.
1푸시 1. 인덱스에서
-빼기 1때문에 입력의 한 문자가 소비되고 인덱스가 감소합니다. 프로그램이로 돌아갑니다 :.


1
프로그램 시작시 -v <x>보유 할 스택을 초기화 하는 명령 행 매개 변수가 있습니다 <x>. 온라인 사용해보기
steenbergh

2

당근 , 16 바이트

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

온라인으로 사용해보십시오!

입력 형식은 다음과 같습니다.

string
index

그리고 프로그램은 1 인덱스입니다.

설명

Carrot에는 문자열, 부동 및 배열 (곧 구현 될 다른 변수)에 대해 여러 글로벌 변수가 있습니다. 프로그램은 모든 연산자가 전역 문자열 변수에 영향을주는 문자열 모드에서 시작합니다. 그리고이 변수들을 "스택"이라고 부릅니다.

(실시 예 입력 : 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"]

이제 이것은 길이가 1 인 문자열을 포함하는 하나의 요소 배열을 반환하지만 웹 사이트에는 문자열로 표시됩니다.

실제로 결과를 문자열로 제공하려면 S","끝에 쉽게 할 수 있지만 출력기는 여전히 인터프리터에서 동일하게 보이기 때문에 중요하지 않습니다.


1

배치, 32 바이트

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

sSTDIN에서 읽고 n명령 행 매개 변수로 사용합니다.


1

GolfScript , 7 4 바이트

~1/=

온라인으로 사용해보십시오!

나는 GolfScript를 빨아들이므로 Martin Ender 의 도움 을 소중하게 생각합니다 .


필요가 없습니다 [.
마틴 엔더

그러나 일반적으로 문자열에서 문자를 원하면 코드 포인트를 다시 변환하는 대신 문자열을 먼저 분할하면됩니다.~1/=
Martin Ender

@MartinEnder 그리고 그것은 당신이 앨리스를 이길 방법입니다 ...
Outgolfer Erik

1

Turtlèd , 9 바이트

!?:[*l+].

온라인으로 사용해보십시오!

설명:

우선, Turtlèd는 거북이 기반의 그리드 기반입니다. 거북이가 왼쪽, 위, 아래, 오른쪽으로 움직일 수있는 격자 셀이 있으며 격자 셀에 물건을 쓸 수 있습니다.

[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

클로저, 3

nth

: P 이것에 내장되어 있을 때 무엇을 할 수 있습니까? 이것은 목록, 벡터, 문자열 및 시퀀스에서 작동합니다. 사용 된 데이터 유형에 따라 O (1) 또는 O (n)입니다.



1

Dyvil , 4 바이트

_[_]

a String와 a를 사용 하고 a int를 반환 하는 익명 함수를 만듭니다 .char .

용법:

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




1

매스 매 티카, 18 바이트

#~StringTake~{#2}&

기본 솔루션이지만 불행히도 함수 이름은 매우 깁니다.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.