m 길이의 n 문자열을 n 길이의 m 문자열로 변환


16

'n'길이의 'm'길이의 문자열이 주어지면 다음과 같은 조건으로 'm'수의 'n'길이 문자열을 리턴하는 프로그램을 작성하십시오.

모든 새 문자열은 다른 문자열과 동일한 색인에있는 문자를 포함해야합니다.

예를 들어, 첫 번째 출력 문자열에는 모든 입력 문자열의 첫 번째 문자가 포함되어야하고 두 번째 출력 문자열에는 모든 입력 문자열의 두 번째 문자가 포함되어야합니다.

예 (문자 아래의 숫자는 문자열의 색인입니다) :

input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222

input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444

매번 입력이 정확하다고 가정

최단 바이트 코드가 승리합니다!

편집하다:

프로그래밍 언어가 많고 각 언어에 대해 가능한 솔루션이 많을 수 있으므로 각 프로그래밍 언어 및 해당 언어를 제공 한 사용자에게 가장 짧은 솔루션을 게시하겠습니다. 코딩을 유지하십시오!

재 편집 :

사용자 Dennis 덕분에 리더 보드 스 니펫을 삽입했습니다.


2
질문 본문에 추가 할 수 있는 리더 보드 스 니펫 이 있습니다. 손으로 할 필요가 없습니다.
Dennis


죄송합니다. "전환"이라는 것을 몰랐습니다.
입력 이름 Here

6
거친 질문과 다른 질문에서 이상한 공백 처리와 관련된 차이점 때문에 이러한 과제가 중복이라고 생각하지 않습니다. 일부 언어에서는 대답이 매우 비슷할 수 있지만 대부분 중복되어서는 안될 정도로 다를 것이라고 생각합니다.
FryAmTheEggman

답변:



9

파이썬, 36 29 바이트

zip(*s) 각 문자의 튜플 목록을 바꿉니다.

lambda s:map(''.join,zip(*s))

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


출력은 "cdmy", "aoaa", "rgny", 이것은리스트 ["cdmy", "aoaa", "rgny"]또는 튜플 이라고 말합니다("cdmy", "aoaa", "rgny")
mbomb007

map(''.join,zip(*s))또한 문자열 변환 (Python 2 전용) 및 Python 3의 경우 [*map(''.join,zip(*s))]afaik이 작동합니다.
Value Ink

@ KevinLau-notKenny map(''.join,zip(*s))는 Python 3에도 유효합니다. 기본적으로 목록 대신 이터레이터 / 제너레이터를 허용합니다.
Mego



7

PowerShell v2 +, 66 54 바이트

param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})}

요 ... 아니 map, 아니 zip, 아니 transpose, 등등, 그래서 우리는 우리 자신의 롤을 얻을. 12 바이트 골프를 위해 @DarthTwon 에 큰 소품 .

input을 가져 $n오고 for루프를 설정합니다 . 초기화는 $x로 설정 0하고 테스트는 여전히 단어에 글자가 있는지 여부 $n[0][$x]이며 $x++각 반복마다 증가 합니다.

루프 안에서 우리는 문자열 배열을 가져 와서 각 단어에서 적절한 문자를 내뿜는 내부 루프로 파이프합니다. 이는 -join문자열을 형성하기 위해에 캡슐화되어 있으며 해당 문자열은 파이프 라인에 남아 있습니다. 실행이 끝나면 파이프 라인의 문자열이 암시 적으로 인쇄됩니다.

PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks"
D-R
aTo
rwc
tok
hns

1
내가보고 싶었 답변의 종류 니스,) 그것은 너무 간단하게 쓰기의 ,대답에 대한 것이 아니라 생각
여기에 입력 이름

while 루프를 사용하면 더 아래로 파싱 할 수 있습니다 param($n)$x=0;while($n[0][$x]){-join($n|%{$_[$x]});$x++}. 그리고 여기에 오류가 없습니다 : D
ThePoShWolf

@DarthTwon 우수. 또는 for다른 두 개의 루프를 사용하십시오 . ;-)
AdmBorkBork

흠 ... 나는 그것을 시도했지만 실제로 while루프를 파싱 ​​한 후에는 아닙니다 . 잘하셨습니다.
ThePoShWolf

Powershell에서 Linq를 사용할 수 있습니까?
aloisdg codidact.com으로 이동

7

Vim, 37 36 건

다른 모든 대답은 지루하고 지루한 1 바이트 내장을 사용합니다. 다음은 프로그래밍 언어가 아닌 모든 작업을 수동으로 수행하는 해킹 된 답변입니다.

Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg

설명:

G                                   "move to the end of this line
     ma                             "And leave mark 'a' here
       qq                           "Start recording in register 'q'
         gg                         "Move to the beginning
           :s/./&<cr>               "Assert that there is atleast one character on this line
                      d             "Delete
                       <C-v>        "Blockwise
                            `a      "Until mark 'a'

    G                               "Move to the end of the buffer
     o<esc>                         "Open a newline below us
           p                        "And paste what we deleted
            vG                      "Visually select everything until the end
              gJ                    "And join these without spaces
                @q                  "Call macro 'q'. The first time, this will do nothing,
                                    "The second time, it will cause recursion.
                  q                 "Stop recording
                   @q               "Call macro 'q' to start it all

이제 모든 것이 좋지만 버퍼에 여분의 텍스트가 남아 있습니다. 따라서 다음을 수행해야합니다.

`a                              "Move to mark 'a'
  dgg                           "And delete everything until the first line



4

망막 , 45 43 바이트

바이트 수는 ISO 8859-1 인코딩을 가정합니다.

O$#`.(?<=(.+))|¶
$.1
!`(?<=(¶)+.*)(?<-1>.)+

선행 줄 바꿈이 중요합니다. 입력 및 출력은 인쇄 가능한 ASCII 문자열의 줄 바꿈으로 끝나는 목록입니다 (둘 다 단일 줄 바꿈이 있음에 유의하십시오).

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

직사각형 블록을 바꾸는 것은 Retina에서 고통이 될 것임을 알고 있었지만 (사각 바꿈이 그렇게 나쁘지는 않지만) 실제로 시도하지는 않았습니다. 첫 번째 솔루션은 실제로 110 바이트에 달하는 엄청난 길이 였지만 접근 방식이 크게 바뀌면 45 바이트가 내가 생각한 것만 큼 나쁘지 않습니다 (아직도 ...). 내일은 설명이 이어질 것이다.

설명

1 단계 : 정렬

O$#`.(?<=(.+))|¶
$.1

이것은 입력에서 문자를 재정렬하는 주요 작업을 수행하지만 줄로 분리하는 것을 망칠 수 있습니다. 흥미롭게도 사각형 입력을 바꾸는 데 필요한 코드를 얻습니다.

정렬 단계 (으로 표시)는 다음 O과 같이 작동합니다. 주어진 정규 표현식 (. 다음에 나오는 것)의 모든 일치 항목을 찾은 `다음 해당 일치 항목을 정렬하고 일치 항목이있는 위치에 다시 삽입합니다. 이 정규식은 모든 단일 문자 ( .(?<=(.*))대체를 통한 비줄 바꿈 및을 통한 줄 바꿈)와 일치 합니다 . 따라서 입력의 모든 문자를 정렬합니다. 더 흥미로운 부분은 분류되어 무엇 에 의해 .

$옵션은 "정렬 기준"모드를 활성화합니다. 여기서 각 일치 항목은 두 번째 줄의 대체 패턴으로 바뀌고 일치 항목을 비교하는 데 사용됩니다. 또한, #Retina는 치환 결과를 정수로 변환하고 문자열로 처리하는 대신 정수를 비교하도록 지시합니다.

마지막으로 정규식과 치환을 살펴볼 필요가 있습니다. 첫 번째 대안이 일치하는 경우 (즉, 우리는 한 줄의 문자를 일치시킨 경우) (?<=(.*))해당 줄의 해당 문자까지 모든 것을 그룹으로 캡처합니다 1. $.1대체 패턴은 이것을 대체 길이 그룹의 1. 따라서, 각 문자열의 첫 번째 문자가된다 1번째가된다 2, 셋째된다 3등등. 이제 어떻게 이것이 정사각형 입력을 바꾸는지를 분명히해야합니다. 줄의 모든 첫 번째 문자가 먼저 나타나고 맨 위 줄에서 끝나고 두 번째 문자는 두 번째 줄에서 끝납니다. 그러나이 직사각형 입력의 경우 라인 피드도 일치합니다. 그룹부터1 이 경우에 사용되지 않고, 치환이 비어 있지만, 목적에 대해 #옵션이 고려된다 0. 즉, 모든 줄 바꿈이 앞에 정렬됩니다.

이제 첫 번째 순서 (각 문자열의 첫 번째 문자, 각 문자열의 두 번째 문자 등)의 문자와 시작시 모든 줄 바꿈이 있습니다.

2 단계 : 경기

!`(?<=(¶)+.*)(?<-1>.)+

이제 문자를 올바른 길이의 줄로 분할해야합니다. 이 길이는 원래 입력의 줄 수에 해당하며, 문자열 시작 부분에있는 줄 바꿈 수에 해당합니다.

여기서는 지정된 정규 표현식의 모든 일치 항목을 찾고 !해당 일치 항목을 인쇄하는 옵션을 사용하여 일치 단계를 사용하여 분할이 수행됩니다 (기본값은 대신 계산). 따라서 정규 표현식의 목표는 한 번에 한 줄씩 일치시키는 것입니다.

lookbehind로 숫자를 "계산"하는 것으로 시작합니다 (?<=(¶)*.*). 1전면의 모든 줄 바꿈에 대해 하나의 캡처 그룹 을 생성 합니다.

그런 다음 각 캡처에 대해 단일 문자를와 일치 (?<-1>.)+시킵니다.


4

x86 기계 코드, 19 바이트

16 진수로 :

fc89d35651a401dee2fb91aa595e464a75f1c3

입력 : ECX: # of strings (n), EDX: 개별 문자열 길이 (m), ESI: 입력 문자열 배열, EDI: 출력 버퍼 수신 문자열 배열. 배열은 char src[n][m+1]입력 및 char dst[m][n+1]출력에 대해 정의 된 것으로 가정 되며 모든 문자열은 NULL로 종료됩니다.

0:  fc                  cld
1:  89 d3               mov ebx,edx   ;EDX is the counter for the outer loop
_outer:
3:  56                  push esi
4:  51                  push ecx
_inner:
5:  a4                  movsb         ;[EDI++]=[ESI++]
6:  01 de               add esi,ebx   ;Same char, next string
8:  e2 fb               loop _inner   ;--ECX==0 => break
a:  91                  xchg eax,ecx  ;EAX=0
b:  aa                  stosb         ;NULL-terminate just completed string
c:  59                  pop ecx
d:  5e                  pop esi       ;First string,
e:  46                  inc esi       ;...next char
f:  4a                  dec edx
10: 75 f1               jnz _outer
12: c3                  ret

3

Brachylog , 5 바이트

z:ca.

문자열 목록을 입력으로 예상합니다. 예 : run_from_atom('z:ca.',["money":"taken":"trust"],Output).

설명

z       Zip the strings in the Input list
 :ca.   output is the application of concatenation to each element of the zip

3

05AB1E, 3 바이트

ø€J

설명

     # implicit input, eg: ['car', 'dog', 'man', 'yay']
ø    # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']]
 €J  # map join, resulting in ['cdmy', 'aoaa', 'rgny']

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



2

JavaScript ES6, 48 46 bytes

a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``)

I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error.

Usage

(a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits

returns

["ad","ss","da"]

Exception: TypeError: a[0].map is not a function
edc65

1
You need [...a[0]].map, since a[0] isn't an array.
nicael

@nicael thanks. messed up the types. this proves why I should not golf this early in the morning.
charredgrass

@nicael I .joined them to fix that problem.
charredgrass

1
join`` instead of join('') to save 2 bytes. Downvote retracted
edc65

2

Bash + BSD utilities, 27

sed s/./\&:/g|rs -c: -g0 -T

I/O via STDIN/STDOUT newline-separated strings.

You may need to install rs with sudo apt install rs or similar. Works out of the box on OS X.

The -T option to rs does the heavy lifting of the transposition. The rest is just formatting:

  • The sed command simply inserts : after every character
  • -c: specifies input columns are : separated
  • -g0 specifies output columns have zero width separation

If my reading of the rs manpage is correct, then the following ought to work for a score of 12, but unfortunately it doesn't work - see note below:

rs -E -g0 -T

Example output:

$ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T
cdmy
aoaa
rgny
$

If input is expected to be all printable ASCII, then the : may be replaced with some unprintable character, e.g. 0x7 BEL.


Note

I wanted to understand why I couldn't get the -E option to work and get rid of the sed preprocessing. I found the rs source code here. As you can see, giving this option sets the ONEPERCHAR flag. However, there is nothing in the code that actually checks the state of this flag. So I think we can say that despite the fact that is option is documented, it is not implemented.

In fact, this option is documented in the Linux rs manpage:

-E Consider each character of input as an array entry.

but not the OS X version.


2

PHP, 82 bytes

function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}

takes and returns an array of strings

break down

function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}

examples

$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '<pre>';
while ($samples)
{
    echo '<b>in:</b> ';         print_r($x=array_shift($samples));
    echo '<b>out:</b> ';        print_r(f($x));
    echo '<b>expected:</b> ';   print_r(array_shift($samples));
    echo '<hr>';
}

2

APL, 3 bytes

↓⍉↑

takes the input strings and turns them into a char matrix. transposes the matrix. splits back the rows of the resulting matrix into strings.



1

Mathematica, 26 bytes

""<>#&/@(Characters@#)&

Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing \[Transpose]. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work:

#&

+1 you beat me to the punch! (But I wasn't able to use the Transpose symbol.) By the way, why doesn't the T show up on screen? (It is there when I copy your code to Mathematica).
DavidC

@DavidC The Unicode character is in the Private Use Area, which is marked as a section for proprietary characters and is therefore neither officially assigned a glyph nor rendered at all in most fonts. Mathematica's font just happens to render this character as a supserscript T and interpret it as a \[Transpose].
LegionMammal978

@DavidC Why don't they use ?
Adám

@Adám IDK, you'd have to ask Wolfram Research about that, not me
LegionMammal978

@LegionMammal978 Nah, I'm happy as long as I have APL's obvious .
Adám

1

MATLAB / Octave, 4 bytes

@(x)x'

This defines an anonymous function. Input format is ['car'; 'dog'; 'man'; 'yay'].

Try it here.


What format is the input for this solution? I don't think it will work with the way Matlab handles strings if you try to input them in a Matlabby way, e.g. f = @(x)x', f([{'abcd'},{'abcd'},{'abcd'}]) outputs ans = 'abcd' 'abcd' 'abcd'
sintax

@sintax Input format should be a 2D char array, as in the example linked in the answer. You are using a cell array of strings (obtained by concatenating singleton cell arrays). It should be: f(['abcd';'abcd';'abcd']). I've edited the answer to specify the input format
Luis Mendo

1

Haskell, 41 bytes

f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0

Or with a bit more air:

f l = zipWith ($) [map (!! n) | n <- [0..]] $
                  l <$ (l !! 0)

The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result.


1
There's no need for a full program, because "program" means "program or function", so a function is enough. You can pass and return a list of strings and therefore omit wordsand unwords. Further, map(\_->l)(l!!0) is l<*l!!0, so it boils down to \l->zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0.
nimi

Oh, good thanks :) I'm updating.
villou24

Oops, typo: it's l<$l!!0 (first time wrong, second time right), but you got it right anyway.
nimi

1

Common Lisp, 62 bytes

(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))

The map function takes a result type (here list), a function f to apply and one or more sequences s1, ..., sn. All sequences are iterated in parallel. For each tuple of elements (e1,...,en) taken from those sequences, we call (f e1 ... en) and the result is accumulated in a sequence of the desired type.

We take a list of strings, say ("car" "dog" "man" "yay"), and use apply to call map. We have to do this so that the input list is used as more arguments to map. More precisely, this:

(apply #'map 'list fn '("car" "dog" "man" "yay"))

... is equivalent to:

(map 'list f "car" "dog" "man" "yay")

And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls f as follows:

(f #\c #\d #\m #\y)

The anonymous lambda takes the list of arguments given to it and coerces it back to a string.


1

Perl, 91 bytes

So lengthy one..

$l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "}

Try it here!


0

Ruby, 46 bytes

Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use String#chars isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more)

->s{s.map!(&:chars).shift.zip(*s).map &:join}

0

Clojure, 68 bytes

#(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0))))

Maps a function which is just reduce (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string.

See it online: https://ideone.com/pwhZ8e


0

C#, 53 bytes

t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i]));

C# lambda (Func) where the output is IList<string> and the output is IEnumerable<string>. I dont know how work zip in other language but I can't find a way to use the C#'s one here. Aggregate fit the need well. No transpose in C#, there is one in Excel but I wont use it.

Try it online!

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