인터리브 문자열


30

영감. * 이전에이 문제를 겪지 않았다고 믿을 수 없습니다.

태스크

하나 이상의 인쇄 가능한 ASCII 문자열이 주어지면 각 문자열에서 하나의 문자를 주기적으로 문자가 없어 질 때까지 인터리브하십시오. 문자열에 다른 문자보다 문자가 부족한 경우 해당 문자열을 건너 뛰십시오.

SIMPLE 준다 SIMPLE

POLLS그리고 EPEES준다PEOPLELESS

LYES그리고 APRONS준다LAYPERSONS

ABCDEa c123 567제공Aa1B 2Cc3D E567

"\n$?*(빈 문자열) 및 ,(.)" (트레일 공간)은 ",\(n.$)?"* (트레일 공간)을 제공합니다.


* APL 솔루션이 더 짧습니다.


이것은 기본적으로 조옮김 작업이므로 매우 유사한 몇 가지 과제가 있었지만 정확히 동일한 과제는 없었습니다.
Martin Ender

7
CS HW에이 질문이 있습니다. 숙제 질문으로 닫을 수 있습니까? ; P
Downgoat

@EriktheOutgolfer 쿨! 나는 오늘 무언가를 배웠다.
Adám

답변:


23

젤리 , 1 바이트

Z

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

내장 된 "transpose"는 문자열 목록에 정확하게이 작업을 수행합니다.


궁금합니다. 짧은 문자열을 공백으로 채워야한다면 코드는 어떻게 생겼습니까?
Adám

2
그렇습니다 z⁶. z"왼쪽 조옮김, 오른쪽으로 패딩"입니다. 공간입니다.
Lynn

1
@ Adám Jelly는 목록에서 매우 잘 작동합니다. 내장 끝과 언어 구성 / 디자인은 어디에서 시작됩니까?
steenbergh

1
@Lynn In Jelly? Atoms 및 Quicks 목록의 모든 항목이 내장되어 있습니다.
Adám

2
@ Adám ;"(요소 별 연결)은 기본 제공없이 작업을 해결합니다.
Dennis

8

파이썬 2, 101 89 86 69 바이트

어떻게 든 이것을 람다로 가져올 수 있기를 바랍니다. 재귀 적으로 만들어서 단축시킵니다.조옮김이 더 짧기를 희망하기 때문에 이상적이지는 않지만 불행히도 (지금까지 내가 관리 한 것에서) 그렇지 않습니다.

f=lambda s:' '*any(s)and''.join(x[:1]for x in s)+f([x[1:]for x in s])

오래된 솔루션 :

w=input();o=''
while any(w):
 for i in range(len(w)):o+=w[i][:1];w[i]=w[i][1:]
print o

lambda s:''.join(''.join([c,''][c<' ']for c in x)for x in map(None,*[list(y)for y in s]))

w=input();o=''
while any(x>=' 'for x in w):
 for i in range(len(w)):o+=w[i][:1];w[i]=w[i][1:]
print o

바보 같은 느낌을 준 mathmandan 덕분에;) 저에게 많은 바이트를 저장했습니다! (구식 솔루션)


당신은 그냥 할 수 while any(w):없습니까? 빈 문자열은 파이썬에서 거짓입니다.
mathmandan

@mathmandan 당신 말이 맞아요, 내가 무슨 생각을했는지 모르겠어요 ..
Kade

문제 없습니다 :) 당신이 앞에 추가해야한다고 생각하는 것을 제외하고는 새로운 솔루션이 멋지게 보입니다 f=.
mathmandan

당신이 취할 수 []떠나, 재귀 호출의 오프 f(x[1:] for x in s)그것은 이러한 맥락에서 목록과 같은 역할을하는 발전기 이해, 만드는.
bioweasel 17



7

Pyth-3 바이트

매우 간단하고 나중에 모바일에서 확장 기능을 추가합니다.

s.T

테스트 스위트

s                         Join all the strings together
 .T                       Transpose, without chopping off overhang
  (Q implicit)

4
@Daniel 나도 학교에 있어요 : P
Maltysen

설명을 추가 할 계획이 있습니까?
John Dvorak

@JanDvorak은 지금 그것을하고 있습니다.
Maltysen

6

자바 스크립트 (ES6), 52 46 바이트

f=([[c,...s],...a])=>s+a?c+f(s+s?[...a,s]:a):c

입력을 문자열 배열로 취하고 단일 문자열로 출력합니다.

테스트 스 니펫

f=([[c,...s],...a])=>s+a?c+f(s+s?[...a,s]:a):c

g=a=>console.log("Input:",JSON.stringify(a),"Output:",JSON.stringify(f(a)))

g(["SIMPLE"])
g(["POLLS","EPEES"])
g(["LYES","APRONS"])
g(["ABCDE","a c","123 567"])
g(["\"\\n$?*",",(.)\" "]) // Backslash and quote are escaped, but in/output are correct


f=([[c,...s],...a])=>c?c+f([...a,s]):a+a&&f(a)
Neil

@ Neil 그것은 훌륭한 접근 방식입니다. 나는 내 자신의 :-)에서 6 바이트 골프 골프 관리
ETHproductions

6

하스켈, 33 바이트

import Data.List
concat.transpose

Ideone에서 사용해보십시오. 용법:

Prelude Data.List> concat.transpose$["ABCDE","a c","123 567"]
"Aa1B 2Cc3D E567"

내장 기능을 사용하지 않는 경우 : ( 38 34 바이트)

f[]=[]
f x=[h|h:_<-x]++f[t|_:t<-x]

Ideone에서 사용해보십시오. Zgarb 덕분에 4 바이트가 줄었습니다! 용법:

Prelude> f["ABCDE","a c","123 567"]
"Aa1B 2Cc3D E567"

1
대체 버전에서 모든 파렌을 제거 할 수 있습니다. 그래도 수입을 이길 수는 없습니다.
Zgarb

실제로 기본 사례가 필요합니까?
xnor

물론 기본 사례가 필요하지는 않습니다.
xnor

@xnor 또한 기본 케이스를 끝으로 옮기고 f a=a바이트를 저장하기 위해 바꿀 수 없습니다. 둘 다 []다른 유형을 가지고 있기 때문에 너무 가깝습니다.
Laikoni

5

C, 114 84 bytes

길이를 계산하지 않는 경우 -20 바이트

i,b;f(char**s){b=1;while(b){i=-1;b=0;while(s[++i]>0)if(*s[i])putchar(*s[i]++),++b;}}

문자 포인터 배열을 허용하고 마지막 항목이 널 포인터 여야합니다 (사용법 참조).

언 골프 및 사용법 :

i,b;f(char**s){
 b=1;
 while(b){
  i=-1;
  b=0;
  while(s[++i]>0)
   if(*s[i])
    putchar(*s[i]++),++b;
 }
}


int main(){
 char*a[]={ 
//  "POLLS","EPEES"
//  "LYES","APRONS"
 "ABCDE","a c","123 567"
 ,0};
 f(a);
 puts("");
}

Does the usage of printf/sprintf not allowed ? :D you would win quite some bytes.
Walfrat

@Walfrat Without printing directly I'd need to allocate a string, so how could this save anything.
Karl Napf

it was before your edit where you added the ++b and remove length compute, so yes can't work anymore.
Walfrat

@Walfrat Yes, but i had a malloc and return before and this was longer than just printing
Karl Napf

5

PHP, 68 67 bytes

for(;$f=!$k=$f;$i++)for(;y|$v=$argv[++$k];$f&=""==$c)echo$c=$v[$i];

Loops over command line arguments. Run with -r.

After the inner loop, $f is 1 when all strings are finished, 0 else (bitwise & casts ""==$c to int).
Next iteration of the outer loop: copy $f to $k (saves one byte from $k=0) and toggle $f:
When all strings are done, $f is now false and the loop gets broken.


Doesn't work with empty input strings. Take a look at the last testcase
aross

@aross: fixed. thanks.
Titus

4

Retina, 13 bytes

Byte count assumes ISO 8859-1 encoding.

O$#`.
$.%`
¶

Try it online!

Explanation

O$#`.
$.%`

This is based on the standard transposition technique in Retina. We sort (O) all non-linefeed characters (.), by ($#) the number of characters in front of them on the same line ($.%`), i.e. their horizontal position.

The second stage then simply removes linefeeds from the input.


4

Java, 19+155=174 160

String f(java.util.Queue<String> q){String s,r="";while(!q.isEmpty()){s=q.poll();r+=s.isEmpty()?"":s.charAt(0);if(s.length()>1)q.add(s.substring(1));}return r;}

Ungolfed:

  String f(java.util.Queue<String> q) {
    String s, r = "";
    while (!q.isEmpty()) {
      s = q.poll();
      r += s.isEmpty() ? "" : s.charAt(0);
      if (s.length() > 1) {
        q.add(s.substring(1));
      }
    }
    return r;
  }

Output:

SIMPLE

PEOPLELESS

LAYPERSONS

Aa1B 2Cc3D E567

",(n.$)?"* ​

First modification: merged string declaration to save some bytes. Removed import, it was used by the main() method (not shown here) that also needed LinkedList. It is fewer bytes to referece Queue directly.


initialize string s with string r can save few more
Syamesh K

I know it's been almost a year ago, but you can golf a few bytes: String f(java.util.Queue<String>q){String s,r="";for(;!q.isEmpty();r+=s.isEmpty()?"":s.charAt(0))if((s=q.poll()).length()>1)q.add(s.substring(1));return r;}
Kevin Cruijssen

3

PHP, 77 bytes

Golfed

function($a){for($d=1;$d!=$s;$i++){$d=$s;foreach($a as$v)$s.=$v[$i];}echo$s;}

Anonymous function that takes an array of strings.

I'm sure this could be golfed more, but it's early. On each iteration, we grab the i-th letter from each given string and append it to our final string, one at a time. PHP just throws warnings if we access bits of strings that don't exist, so that's fine. We only stop when no changes have been made after looping through all the strings once.

I feel like the usage of $d can be golfed more, but it's early. :P


How exactly do you put an array of strings in a single argument?
Titus

@Titus. Y'know, I never really thought about it. I just kinda assumed you could.
Xanderhall

3

Actually, 7 6 bytes

Golfing suggestions welcome! Try it online!

Edit: -1 byte thanks to Teal pelican.

a Z♂ΣΣ

Ungolfing

          Implicit input each string.
a         Invert the stack so that the strings are in the correct order.
<space>   Get the number of items on the stack, len(stack).
Z         Zip all len(stack) strings into one, transposing them.
♂Σ        sum() every transposed list of chars into strings.
Σ         sum() again to join the strings together.

Can you not remove the # to make it 6 bytes?
Teal pelican

@Tealpelican Welp, now I'm going to have to dig through all of my old Actually answers and see if I can't change Z♂#Σ to Z♂Σ in all of them. Thanks for the tip :D
Sherlock9

First time looking into the language, it looks so much fun! Glad I could help :))
Teal pelican

3

JavaScript (ES6), 46 bytes

f=([[c,...s],...a])=>c?c+f([...a,s]):a+a&&f(a)
<textarea oninput=o.textContent=f(this.value.split`\n`)></textarea><div id=o>



2

J, 13 bytes

({~/:)&;#\&.>

Try it online!

Based on the inspiration for this question.

Another way to do it takes 27 bytes but operates using transpose. Most of the bytes are to handle the automatically added zeroes from padding.

[:u:0<:@-.~[:,@|:(1+3&u:)&>

Explanation

({~/:)&;#\&.>  Input: list of boxed strings S
          &.>  For each boxed string x in S
        #\       Get the length of each prefix from shortest to longest
                 This forms the range [1, 2, ..., len(x)]
                 Rebox it
(    )         Operate on S and the prefix lengths
      &;         Raze both
   /:            Grade up the raze of the prefix lengths
 {~              Index into the raze of S using the grades
               Return

J's prohibiting mixed arrays really hurts you here. Try it in APL.
Adám

2

Bash + GNU utilities, 55

 eval paste `sed "s/.*/<(fold -1<<<'&')/g"`|tr -d \\n\\t

I/O via STDIN (line-separated) and STDOUT.

The sed formats each line to a bash process substitution. These are then evaled into paste to do the actual interleaving. tr then removes unnecessary newlines and tabs.

Ideone.


2

PHP, 63 bytes

Note: uses IBM-850 encoding

for(;$s^=1;$i++)for(;n|$w=$argv[++$$i];$s&=$x<~■)echo$x=$w[$i];

Run like this:

php -r 'for(;$s^=1;$i++)for(;n|$w=$argv[++$$i];$s&=$x<~■)echo$x=$w[$i];' "\"\n\$?*" "" ",(.)\" " 2>/dev/null;echo
> ",\(n.$)?"* 

Explanation

for(                       # Iterate over string index.
  ;
  $s ^= 1;                 # Continue until $s (stop iterating) is 1.
                           # Flip $s so each iteration starts with $s
                           # being 1.
  $i++                     # Increment string index.
)
  for(
    ;
    "n" | $w=$argv[++$$i]; # Iterate over all input strings. OR with "n"
                           # to allow for empty strings.
    $s &= $x<~■            # If last character printed was greater than
                           # \x0 (all printable chars), set $s to 0,
                           # causing the loop to continue.
  )
    echo $x = $w[$i];      # Print char $i of current string.

IBM-850?! Is that a natural encoding for PHP?
Adám

@Adám what do you mean by "natural"? PHP treats bytes in the range 128-255 as text, which is therefore interpreted as a constant. If the constant is undefined, it will be interpreted as a string. It's so I can do ~■ (negated binary 254) instead of "\x1" (binary 1).
aross

1
I see. It isn't that you actually need that codepage, you just need a 254 byte.
Adám

@Adám yes, the codepage just makes it a printable char which is a little less annoying.
aross

Great use of $$!
Titus

2

Python 3, 75 Bytes

I know the other Python one is shorter, but this is the first time I've used map ever in my life so I'm pretty proud of it

lambda n:''.join(i[k]for k in range(max(map(len,n)))for i in n if len(i)>k)

1

C, 75 71 bytes

Only limitation is the output length. Currently it's 99, but can be easily stretched to 999 (+1 byte).

i;main(a,b)char**b;{a--;for(;i<99;i++)*b[i%a+1]&&putchar(*b[i%a+1]++);}

Ungolfed:

i;
main( a, b )
char **b;
{
    a--;
    for( ; i < 99; i++ )
        *b[i % a + 1] && putchar( *b[i % a + 1]++ );
}

1

Oracle SQL, 195 bytes

    select listagg(b,'') within group(order by l,o) from(select substr(a,level,1) b,level l,o from i start with length(a)>0 connect by prior a=a and level<=length(a) and prior sys_guid() is not null)

Takes its input from a table named i with columns a (containing the string) and o (order of the string):

    create table i (a varchar2(4000), a integer)

Explanation:
We're exploiting CONNECT BY to break up the strings into each of the characters making them up. PRIOR SYS_GUID() being NOT NULL ensures we don't end up stuck in a loop.
We then concatenate the single characters with LISTAGG but we shuffle them around with an ORDER BY clause, ordering them first by their position in the original string and only then by the string they came from.

Not as short as the other answers but SQL isn't really meant as a string manipulation language :)


1

Python 2, 128 96

I was hoping not to have to use itertools

a=lambda a:"".join([i for i in reduce(lambda: b,c:b+c, map(None,*map(lambda m:list(m),a)) if i])

Ungolfed

 a=lambda a:                              #Start a lambda taking in a
    "".join(                              #Join the result together with empty string
        [i for i in reduce(               #For every item, apply the function and 'keep'
           lambda: b,c:b+c,               #Add lists from...
                map(None,*map(            #None = Identity function, over a map of...
                    lambda m:list(m), a)  #list made for mthe strings m
                   ) if i                 #truthy values only (otherwise the outer map will padd with None.
       ])

Would appreciate feedback/advice on improving this.
Pureferret


1

R, 73 bytes

for(i in 1:max(nchar(s<-scan(,""))))for(j in seq(s))cat(substr(s[j],i,i))

Try it online!

Explanation: very simple (but verbose), just loop through printing ith character of the jth string. Fortunately, substr returns an empty string if given an out-of-range input.


0

Python, 112 bytes

i=len(x)if len(x)>len(y) else len(y) h=0 a="" while h<i: if h<len(x) a+=x[h] if h<len(y): a += y[h] h+=1 print a

6
Your formatting is really messed up.. where do you even get x and y from?
Kade

0

Perl 5, 53 bytes

$i=0,map{push@{$a[$i++]},$_}/./g for<>;print@$_ for@a

Try it online!

Method

Creates a two dimensional array where the number of rows is equal to the length of the longest string and the maximum number of columns is equal to the number of strings. Then output each row of the array without spacing.


0

TXR Lisp, 20 bytes

(opip weave cat-str)

Run:

1> (opip weave cat-str)
#<intrinsic fun: 0 param + variadic>
2> [*1 "LYES" "APRONS"]
"LAYPERSONS"
3> [*1 "ABCDE" "a c" "" "123 567"]
"Aa1B 2Cc3D E567"
4> [*1 "\"\\n$?*" "" ",(.) "]
"\",\\(n.$)? *"

The weave function is lazy, so it returns a list, which is why we have to force the result to a string. Being lazy, it can weave infinite sequences. For instance, we can weave the even and odd natural numbers, which are themselves infinite lazy lists:

5> (take 20 (weave (range 2 : 2) (range 1 : 2)))
(2 1 4 3 6 5 8 7 10 9 12 11 14 13 16 15 18 17 20 19)

0

K (oK), 35 29 bytes

Solution:

{`c$r@&~^r:,/+(`i$x)[;!#,/x]}

Try it online!

Example:

> {`c$r@&~^r:,/+(`i$x)[;!#,/x]}("ABCDE";"a c";"123 567")
"Aa1B 2Cc3D E567"
> {`c$r@&~^r:,/+(`i$x)[;!#,/x]}("\n$?*";"";",(.)\" ")
"\n,$(?.*)\" "
> {`c$r@&~^r:,/+(`i$x)[;!#,/x]}("POLLS";"EPEES")
"PEOPLELESS"

Explanation:

Use 2nd-level indexing to pull out indices from 0 to max (length of flattened list) across all input lists. Any indexing beyond the bound of the sub-list will return a null. Flip (rotates 90), flatten, and then pull out the non-null results.

Notes:

  • I cast to integer (i$) so that we get useful nulls, as space () is considered null for a char list which means you cant tell nulls from valid spaces.
  • Also I couldnt get the TIO to work with input (worked fine in the oK repl) so the TIO link includes the "ABCDE"... example.

0

Jq 1.5, 49 bytes

map(explode)|transpose|map(map(values)[])|implode

Explanation

                      # example input:          ["LYES","APRONS"]
  map(explode)        # make list of ordinals   [[76,89,69,83],[65,80,82,79,78,83]]
| transpose           # zip lists               [[76,65],[89,80],[69,82],[83,79],[null,78],[null,83]]
| map(map(values)[])  # rm nulls and flatten    [76,65,89,80,69,82,83,79,78,83]
| implode             # convert back to string  "LAYPERSONS"

Sample Run

$ paste input <(jq -Mrc 'map(explode)|transpose|map(map(values)[])|implode' input)
["SIMPLE"]                  SIMPLE
["POLLS","EPEES"]           PEOPLELESS
["LYES","APRONS"]           LAYPERSONS
["ABCDE", "a c", "123 567"] Aa1B 2Cc3D E567
["\"\\n$?*", "", ",(.)\" "] ",\(n.$)?"* 

$ echo -n 'map(explode)|transpose|map(map(values)[])|implode' | wc -c
  49    

Try it online

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