Interlace strings

34

0

Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"

Rules

  • The strings will only contain ASCII chars (32-126).
  • The strings will always be the same length, and will never be empty.
  • You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).
  • The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is , so the shortest code in bytes for each language wins.

ETHproductions

Posted 2016-10-31T20:42:51.723

Reputation: 47 880

11+1 for DrMcMoylex. :D – James – 2016-10-31T20:45:35.820

3"Dowrgnab" anagrams to "Downgrab" ( ͡° ͜ʖ ͡°) – Mama Fun Roll – 2016-11-01T03:44:40.237

You should point out explicitly that the "in either order" rule means swapping can begin from the first character or the second. – DLosc – 2016-11-02T05:08:49.037

@DrMcMoylex Take the code, golf example. If we swap starting from second character, we get: codf, gole. Starting from first character: gole, codf. – DLosc – 2016-11-03T05:17:40.997

Answers

14

Haskell, 37 bytes

l=(,):flip(,):l
(unzip.).zipWith3($)l

Zips the two strings, alternately swapping the characters, then unzips them.

A 37-byte recursive alternative:

(a:b)?(c:d)=a:d?b
e?_=e
a%b=(a?b,b?a)

xnor

Posted 2016-10-31T20:42:51.723

Reputation: 115 687

9

Python, 42 bytes with I/O golfing

def f(a,b):a[1::2],b[1::2]=b[1::2],a[1::2]

Swaps every other character of the two lists. Takes as input two lists of characters, and outputs by modifying them.

l=list('cat')
m=list('dog')    
print l,m

def f(a,b):a[1::2],b[1::2]=b[1::2],a[1::2]

f(l,m)
print l,m

gives

['c', 'a', 't'] ['d', 'o', 'g']
['c', 'o', 't'] ['d', 'a', 'g']

xnor

Posted 2016-10-31T20:42:51.723

Reputation: 115 687

1That's clever. Do you see the input/output formats as too flexible? – ETHproductions – 2016-10-31T22:57:31.697

@ETHproductions Not sure, it might be mostly Python-specific that lists are so much manipulable than strings. – xnor – 2016-11-01T01:29:03.917

8

Vim, 18, 17 bytes

qqyljvPkvPll@qq@q

Try it online!

This uses the V interpreter because of backwards compatibility. Input comes in this format:

string1
string2

Explanation:

 qq                 " Start recording in register 'q'
   yl               " Yank one letter
     j              " Move down a row
      vP            " Swap the yanked letter and the letter under the cursor
        k           " Move back up a row
         vP         " Swap the yanked letter and the letter under the cursor
           ll       " Move two letters to the right. This will throw an error once we're done
             @q     " Call macro 'q' recursively
               q    " Stop recording.
                @q  " Start the recursive loop

James

Posted 2016-10-31T20:42:51.723

Reputation: 54 537

Cut two letters by using x instead of yl and then jus P instead of second vP: lqqxjvPkPll@qq@q – Hauleth – 2016-11-02T15:19:16.697

@lukasz I had tried that initially, but for whatever reason, that runs it too many times and swaps the last letters when it shouldn't. I'll look into it some more though – James – 2016-11-02T15:21:06.207

1

@ŁukaszNiemier That link has the same code as I posted. Did you hit the [save] button? Either way, it's not working for me. The real reason why is because when you x the last character on the line, it moves your cursor to the left, messing up the placement of the swap.

– James – 2016-11-02T16:13:08.860

6

05AB1E, 11 10 bytes

øvyNFÀ}})ø

Try it online!

Explanation

input = ["code", "golf"] used as example.

ø             # zip strings into list of pairs
              # STACK: ['cg', 'oo', 'dl', 'ef']
 vy           # for each pair
   NFÀ        # rotate left index times
      }}      # end-if, end-loop
              # STACK: 'cg, 'oo', 'dl', 'fe'
        )ø    # wrap in list and zip
              # OUTPUT: ['codf', 'gole']

Emigna

Posted 2016-10-31T20:42:51.723

Reputation: 50 798

6

Haskell, 41 bytes

(a:b)#(c:d)=(a,c):d#b
_#_=[]
(unzip.).(#)

Returns a pair with the strings. Usage example: ( (unzip.).(#) ) "Hello," "world!"-> ("Hollo!","werld,").

Simple recursive approach: take the first char of each string as a pair and append a recursive call with the (rest of the) strings swapped. unzip makes a pair of lists out of the list of pairs.

nimi

Posted 2016-10-31T20:42:51.723

Reputation: 34 639

5

Perl, 48 bytes

Bytecount includes 47 bytes of code and -p flag.

say<>=~s%.\K(.)%"s/.{$-[0]}\\K(.)/$1/;\$1"%geer

Run with -p and -E flag. Expect each string on a different line :

perl -pE 'say<>=~s%.\K(.)%"s/.{$-[0]}\\K(.)/$1/;\$1"%geer' <<< "Hello
World"

Explanations :

-p : capture input in $_ and prints it at the end. (to get and print the first string)
<> : get a line of input. (to get the second string).
=~ : apply a regex to <> : s%%%geer, where thanks to r the modified string is returned (and then printed thanks to say).
The regex :
.\K(.) finds two characters, and will replace the second one with the result of the evaluation of this code "s/.{$-[0]}\\K(.)/$1/;\$1" :
The first part, s/.{$-[0]}\\K(.)/$1/ applies a regex to $_ : .{$-[0]} skips the first characters to get to the same point as the outer regex (since $-[0] contains the index of the first capture group, so in that case the index of the characters to substitute), and then we capture a char with (.) and replace it with the character of the outer regex ($1). And then we add $1 so the result of "s/.{$-[0]}\\K(.)/$1/;\$1" is the character we captured in the inner regex.
You may have noticed that $1 refer to the character we want to replace in both strings (so two different characters), so we play with /ee modifier of the regex which evaluates the right side of the regex twice : the first one will substitute only the $1 that isn't preceded by the \.

Dada

Posted 2016-10-31T20:42:51.723

Reputation: 8 279

5

Python, 55 bytes

lambda a,b:[(-~len(a)/2*s)[::len(a)+1]for s in a+b,b+a]

Slicing!

58 bytes:

def f(a,b):n=len(a);print[(s*n)[:n*n:n+1]for s in a+b,b+a]

64 bytes:

f=lambda a,b,s='',t='':a and f(b[1:],a[1:],s+a[0],t+b[0])or[s,t]

Recursively accumulates the characters of the two strings into s and t, and outputs the pair of them at the end. The alternation is done by switching the input strings each recursive call. Outputting a space-separated string was the same length:

lambda a,b,s='',t=' ':a and f(b[1:],a[1:],s+a[0],t+b[0])or s+t

This narrowly beat out a different recursive strategy of alternately taking characters from each string, with each of the two possible strings as the first one. (65 bytes)

g=lambda a,b:a and a[0]+g(b[1:],a[1:])
lambda a,b:(g(a,b),g(b,a))

xnor

Posted 2016-10-31T20:42:51.723

Reputation: 115 687

4

MATL, 11 10 9 8 bytes

Thanks to ETHproductions for 1 byte off!

"@X@YS&h

Input is a 2D array containing the two strings, such as: ['Halloween'; 'Challenge']. The output strings are in reverse order.

Try it online!

Explanation

        % Input 2D array implicitly
"       % For each column
  @     %   Push current column
  X@    %   Push iteration index, starting at 1
  YS    %   Circularly shift the column by that amount
  &h    %   Concatenate horizontally with (concatenated) previous columns
        % End implicitly
        % Display implicitly

Old version: 9 bytes

tZyP:1&YS

Explanation

        % Take input implicitly
t       % Duplicate 
        % STACK: ['Halloween'; 'Challenge'], ['Halloween'; 'Challenge']
Zy      % Size
        % STACK: ['Halloween'; 'Challenge'], [2 9]
P       % Flip array
        % STACK: ['Halloween'; 'Challenge'], [9 2]
:       % Range. Uses first element of the array as input
        % STACK: ['Halloween'; 'Challenge'], [1 2 3 4 5 6 7 8 9]
1&YS    % Circularly shift each column by those amounts respectively
        % STACK: [Caallwnee';'Hhlloeegn']
        % Display implicitly

Luis Mendo

Posted 2016-10-31T20:42:51.723

Reputation: 87 464

@ETHproductions Yes! Thank you! – Luis Mendo – 2016-10-31T22:12:05.240

4

Jelly, 9 8 6 bytes

Thanks to Dennis for saving 2 bytes!

Zṙ"J$Z

Uses the Jelly encoding.

Try it online!

Adnan

Posted 2016-10-31T20:42:51.723

Reputation: 41 965

You can use ṙ"J$ instead of Ėṙ@/€. Also, separating the string is not required, so you can drop the Y. – Dennis – 2016-10-31T23:47:48.517

@Dennis Ahh, that's neat. Thanks! :) – Adnan – 2016-11-01T15:26:10.030

4

Jelly, 5 bytes

żṚż¥/

Input is as separate arguments, output is concatenated.

Try it online! or verify all test cases.

How it works

żṚż¥/  Main link. Left argument: s (string). Right argument: t (string)

ż      Zipwith; yield the array of pairs of corresponding characters of s and t.
   ¥   Combine the two links to the left into a dyadic chain:
 Ṛ         Reverse the chain's left argument.
  ż        Zip the result with the chain's right argument.
    /  Reduce the return value of the initial ż by the quicklink Ṛż¥.

Dennis

Posted 2016-10-31T20:42:51.723

Reputation: 196 637

3

V, 12 bytes

lòyljvPkvPll

Try it online!

Nothing too interesting, just a direct port of my vim answer so I can compete with (but not beat) 05AB1E.

James

Posted 2016-10-31T20:42:51.723

Reputation: 54 537

3

Pyke, 9 bytes

,Fo2%I_(,

Try it here!

          - o = 0
,         -   transpose(input)
 F     (  -  for i in ^:
  o2%     -    (o++ %2)
     I_   -   if ^: i = reverse(i)
        , - transpose(^)

Blue

Posted 2016-10-31T20:42:51.723

Reputation: 26 661

3

JavaScript (ES6), 51 54

Edit 3 bytes saved thx @Neil

Function with array input/output

p=>p.map((w,i)=>w.replace(/./g,(c,j)=>p[i+j&1][j]))

I like this one more, but it's 55 (2 strings in input, array in output)

(a,b)=>[...a].reduce(([p,q],c,i)=>[q+c,p+b[i]],['',''])

Test

f=
p=>p.map((w,i)=>w.replace(/./g,(c,j)=>p[i+j&1][j]))

function go() {
  var a=A.value, b=B.value
  if (a.length == b.length)
    O.textContent = f([a,b]).join('\n')
  else
    O.textContent = '- different length -'
    
}

go()
<input id=A value='Hello,'><input id=B value='world!'>
<button onclick='go()'>go</button><pre id=O></pre>

edc65

Posted 2016-10-31T20:42:51.723

Reputation: 31 086

replace saves you 3 bytes: p=>p.map((w,i)=>w.replace(/./g,(c,j)=>a[i+j&1][j])). – Neil – 2016-11-01T00:56:39.320

2

Pyth, 8 bytes

C.e_FbkC

Try it online: Demonstration

Transposes the words, reverses each pair of letters 'current index'-times, transpose again.

Jakube

Posted 2016-10-31T20:42:51.723

Reputation: 21 462

2

JavaScript (ES6), 55 bytes

f=([c,...s],[d,...t],o="",p="")=>c?f(t,s,o+c,p+d):[o,p]

I wanted to do something clever with using regexp to replace alternate characters but that ended up taking 67 57 bytes:

a=>a.map((s,i)=>a[+!i].replace(/.(.?)/g,(_,c,j)=>s[j]+c))

Neil

Posted 2016-10-31T20:42:51.723

Reputation: 95 035

Nice. I had f=([a,...A],[b,...B])=>a?[a+f(B,A)[0],b+f(A,B)[0]]:[""] for the same length. – ETHproductions – 2016-10-31T22:49:42.687

I hoped to do a lot better, but no way, just 1 less. Time to post a non recursive answer – edc65 – 2016-10-31T23:05:05.543

@edc65 Nice idea to use map, it shaved 10 bytes off my regexp answer. Still too long though. – Neil – 2016-11-01T01:00:35.703

2

Java, 132 103 100 bytes

Thanks to Kevin Cruijssen for suggesting returning the array (among other improvements) and saving 29 bytes! Also Olivier Grégoire for 3 bytes!

char[]c(char[]s,int l){for(int o=l;o-->0;)if(o%2>0){char t=s[o];s[o]=s[l+o+1];s[l+o+1]=t;}return s;}

Called like this:

public static void main(String[] args) {
    System.out.println(c("Hello,world!".toCharArray(), 5)); // 5 is the length of each "String"
}

Output:

Hollo,werld!

Takes advantage of the fact that input can basically be formatted in any way (in this case, a single char array of Strings that are delimited by a comma), and pretty lenient output rules as well.

Hypino

Posted 2016-10-31T20:42:51.723

Reputation: 221

Hi, original input format you've got there. You can golf it some more though: char[]c(char[]s,int l){for(int o=l,t;o-->0;)if(l%2>0){t=s[l];s[l]=s[l+o+1];s[l+o+1]=(char)t;}return s;} (103 bytes) with the output being returned instead of printed directly. Example input: System.out.println(c("Hello,world!".toCharArray(), 5));; Example output: Hollo,werld!. – Kevin Cruijssen – 2016-11-01T09:01:56.373

True enough, I hadn't considered just returning the char array for some reason. That's great! – Hypino – 2016-11-01T15:26:34.860

The result should be Hollo!werld, and not Hollo,werld! (the punctuation is incorrect). I believe this can be fixed with a input value of 6 instead of 5. – Olivier Grégoire – 2016-11-02T14:28:24.983

Since you cast t to char, why don't you declare it in the for loop directly as a char? You'd spare a few bytes doing so. – Olivier Grégoire – 2016-11-02T14:34:06.243

Unfortunately you can't declare the char within the for-loop initializer, but you inspired me to check if declaring the char separately would be shorter than the cast and it indeed is by 1 byte. – Hypino – 2016-11-02T15:57:01.307

I didn't mean in the for loop initializer, but when you first use t: char t=s[l];. You don't use it elsewhere. For a concrete example, look at my own answer. – Olivier Grégoire – 2016-11-02T16:00:32.253

Ah okay I misunderstood you. You're right, that saves 3 bytes! – Hypino – 2016-11-02T16:06:06.190

Suggest s[o]^=s[l-~o];s[o]^=s[l-~o]^=s[o]; instead of char t=s[o];s[o]=s[l+o+1];s[l+o+1]=t; – ceilingcat – 2019-02-20T18:36:05.233

2

Perl, 40 bytes

Includes +1 for -n

Give strings as lines on STDIN

interlace.pl
hello
world
^D

interlace.pl

#!/usr/bin/perl -n
s/./${1&$.+pos}[pos]=$&/seg}{print@0,@1

Ton Hospel

Posted 2016-10-31T20:42:51.723

Reputation: 14 114

1

PowerShell v2+, 82 bytes

param($a,$b)$i=0;[char[]]$a|%{$c+=($_,$b[$i])[$i%2];$d+=($b[$i],$_)[$i++%2]};$c;$d

Still golfing... Nope. Can't seem to golf this down any without using a regex like other answers (boo on copying algorithms).

So we take $a and $b as strings, set index $i to 0, cast $a as a char-array, and send it through a loop |%{...}. Each iteration, we're string-concatenating onto $c and $d by indexing into an array-select (i.e., so it alternates back and forth). Then, we leave $c and $d on the pipeline, and output via implicit Write-Output happens at program completion.

AdmBorkBork

Posted 2016-10-31T20:42:51.723

Reputation: 41 581

1

PHP, 79 Bytes

for(;$i<=strlen(($a=$argv)[1]);$y.=$a[2-$i%2][$i++])echo$a[1+$i%2][+$i]??" $y";

Previous Version PHP, 82 Bytes

for(;$i<strlen(($a=$argv)[1]);$y.=$a[2-$i%2][$i++])$x.=$a[1+$i%2][$i];echo"$x $y";

Jörg Hülsermann

Posted 2016-10-31T20:42:51.723

Reputation: 13 026

for(...)echo$a[1+$i%2][$i];echo" $y"; (-2) – Titus – 2016-11-02T14:16:44.723

building off of Titus's comment for(;$i<=strlen(($a=$argv)[1]);$y.=$a[2-$i%2][$i++])echo$a[1+$i%2][$i]??" $y"; is a further -2, though it requires php 7 – user59178 – 2016-11-02T14:43:48.707

@user59178 nice but you need 1 Byte more – Jörg Hülsermann – 2016-11-02T15:04:28.197

do you? it works for me, you just get a Notice: String offset cast occurred in Command line code on line 1 – user59178 – 2016-11-02T18:02:13.957

@user59178 Yes to print the first letter of the first word – Jörg Hülsermann – 2016-11-02T18:31:08.573

as I say, it works fine for me, there are just 3 notices between that first letter and the rest of the output so if you don't have error reporting turned off it's easy to miss. – user59178 – 2016-11-03T09:02:21.043

@user59178 notices are still (and I guess always will be) turned off by default – Titus – 2016-11-05T12:03:49.270

1

C, 124 bytes

main(c,v)char**v;{char a[99],b[99];for(c=0;v[1][c]^0;++c){a[c]=v[1+c%2][c];b[c]=v[2-c%2][c];}a[c]=0;b[c]=0;puts(a);puts(b);}

Call with:

program.exe string1 string2

String length is limited to 98 characters.

Steadybox

Posted 2016-10-31T20:42:51.723

Reputation: 15 798

1

Octave, 64 61 bytes

@(x)reshape(x((t=1:end)+(2*mod(t,2)-1).*(mod(t-1,4)>1)),2,[])

Anonymous function that inputs a 2D char array with each string in a row, and produces the output in the same format.

Try it at Ideone.

Luis Mendo

Posted 2016-10-31T20:42:51.723

Reputation: 87 464

1

Racket 208 bytes

(let((sl string->list)(ls list->string)(r reverse))(let p((s(sl s))(t(sl t))(u'())(v'())(g #t))(if(null? s)
(list(ls(r u))(ls(r v)))(p(cdr s)(cdr t)(cons(car(if g s t))u)(cons(car(if g t s))v)(if g #f #t)))))

Ungolfed:

(define (f s t)
  (let ((sl string->list)                ; create short names of fns
        (ls list->string)
        (r reverse))
    (let loop ((s (sl s))                ; convert string to lists
               (t (sl t))
               (u '())                   ; create empty new lists
               (v '())
               (g #t))                   ; a boolean flag
      (if (null? s)                      ; if done, return new lists converted back to strings
          (list (ls (r u))
                (ls (r v)))
          (loop (rest s)
                (rest t)                 ; keep adding chars to new lists alternately
                (cons (first (if g s t)) u) 
                (cons (first (if g t s)) v)
                (if g #f #t))            ; alternate the boolean flag
          ))))

Testing:

(f "abcdef" "123456")

Output:

'("a2c4e6" "1b3d5f")

Above is recursive version.

Iterative version:

(let*((sl string->list)(ls list->string)(r reverse)(s(sl s))(t(sl t))(l'())(k'())(p(λ(a b g)(set! l(cons(if g a b)l))
(set! k(cons(if g b a)k)))))(for((i s)(j t)(n(in-naturals)))(p i j(if(= 0(modulo n 2)) #t #f)))(list(ls(r l))(ls(r k))))

Ungolfed:

(define (f s t)
  (let* ((sl string->list)              ; create short form of fn names
         (ls list->string)
         (r reverse)

         (s (sl s))                     ; convert strings to lists
         (t (sl t))

         (l '())                        ; create empty lists for new sequences
         (k '())

         (p (λ(a b g)                   ; fn to add chars to one or other list
              (set! l (cons (if g a b) l))
              (set! k (cons (if g b a) k)))))

    (for ((i s)(j t)(n (in-naturals)))  ; loop with both strings
          (p i j                        ; add to new lists alternately
             (if (= 0 (modulo n 2)) #t #f)))

    (list (ls (r l))                  ; convert reversed lists to strings
          (ls (r k)))))

rnso

Posted 2016-10-31T20:42:51.723

Reputation: 1 635

1

Lithp, 120 characters (+3 for -v1 flag)

Line split in 2 for readability:

#P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
     (js-bridge #C,J::(index (index P (& (+ I J) 1)) J))))))

Requires the -v1 flag to run.js as some functions are not yet part of the standard library.

Sample usage:

(
    (def f #P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
                (js-bridge #C,J::(index (index P (& (+ I J) 1)) J)))))))
    (print (f (list "Hello," "world!")))
)

This sort of highlights that I haven't spent enough time on the standard library. Having to use js-bridge/1 twice and the long regex form, as well as invoking map using invoke/* all contribute to this being much longer than it needs to be.

Time to work on my standard library more I think.

Andrakis

Posted 2016-10-31T20:42:51.723

Reputation: 361

1

C, 54 52 bytes

f(char*a,char*b,char*c){while(*c++=*a++,*c++=*b++);}

Assumes output c has already the desired length.

Usage:

main(){
 char a[]="123456";
 char b[]="abcdef";
 char c[sizeof(a)+sizeof(b)-1];
 f(a,b,c);
 puts(c);

}

If you insist on creating the output, here is a 91 bytes solution:

char*g(char*a,char*b){char*c=malloc(2*strlen(a)),*d=c;while(*c++=*a++,*c++=*b++);return d;}

Usage:

main(){
 char a[]="123456";
 char b[]="abcdef";
 puts(g(a,b));
}

Karl Napf

Posted 2016-10-31T20:42:51.723

Reputation: 4 131

0

C, 150 bytes

I used the typical omissions of header files and main()'s return type and return statement. It throws a warning, but compiles without issue. I also used a GCC-specific trick that allows array declarations with variable expressions.

The program expects the strings from the command line, and as such, the program should be run with ./a.out string1 string2.

main(int a,char**v){int x=strlen(v[1]);char s[x],t[x],c;strcpy(s,v[1]);strcpy(t,v[2]);for(a=0;a<x;++a)if(a%2)c=s[a],s[a]=t[a],t[a]=c;puts(s),puts(t);}

Or more legibly,

main(int a,char**v){
    int x=strlen(v[1]);
    char s[x],t[x],c;
    strcpy(s,v[1]);strcpy(t,v[2]);
    for(a=0;a<x;++a)
        if(a%2)c=s[a],s[a]=t[a],t[a]=c;
    puts(s),puts(t);
}

James Murphy

Posted 2016-10-31T20:42:51.723

Reputation: 267

0

Mathematica, 51 bytes

Takes input as an array of two arrays of characters, with output in the same format. The function simply constructs the new array using a (mod 2) operation.

Table[#[[Mod[j+i,2]+1,j]],{i,2},{j,Length@#[[1]]}]&

Greg Martin

Posted 2016-10-31T20:42:51.723

Reputation: 13 940

0

QBasic 4.5, 172 bytes

Ouch, this one gets painful with the ol' QBasic...

DEFSTR A-D:INPUT A,B
IF LEN(A)MOD 2=1 THEN A=A+" ":B=B+" "
FOR x=1 TO LEN(A) STEP 2
C=C+MID$(A,x,1)+MID$(B,x+1,1):D=D+MID$(B,x,1)+MID$(A,x+1,1):NEXT:?RTRIM$(C),RTRIM$(D)

Fun fact: Using DEFSTR saved more bytes than it cost because now I could use A instead of a$.

steenbergh

Posted 2016-10-31T20:42:51.723

Reputation: 7 772

0

QBIC, 112 bytes

QBIC can streamline a lot of the QBasic boilerplate, but the main MID$engine still needs to be done in QBasic because QBIC lacks a substring-function. Still, saves me 60 bytes.

;;_LA|~a%2=1|A=A+@ | B=B+C][1,a,2|X=X+$MID$(A$,b,1)+MID$(B$,b+1,1):Y$=Y$+MID$(B$,b,1)+MID$(A$,b+1,1)|]?_tX|,_tY|

steenbergh

Posted 2016-10-31T20:42:51.723

Reputation: 7 772

MIND$ => MIN$ in text. – Not that Charles – 2016-11-01T18:17:02.510

0

Java, 68 bytes

(a,b)->{for(int i=a.length;--i>0;){char t=a[--i];a[i]=b[i];b[i]=t;}}

Ungolfed and testing

import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiConsumer;

public class Main {

  static BiConsumer<char[], char[]> func = (left, right) -> {
      for (int i = left.length; --i > 0;) {
        char temp = left[--i];
        left[i] = right[i];
        right[i] = temp;
      }
    };

  public static void main(String[] args) {
    test("Hello,","world!", "Hollo!", "werld,");
    test("code", "golf", "codf", "gole");
    test("happy", "angry", "hnpry", "aagpy");
  }

  private static void test(String left, String right, String x, String y) {
    char[] leftChars = left.toCharArray();
    char[] rightChars = right.toCharArray();
    func.accept(leftChars, rightChars);
    Collection mixed = Arrays.asList(new String(leftChars), new String(rightChars));
    if (mixed.containsAll(Arrays.asList(x, y))) {
      System.out.println("OK");
    } else {
      System.out.printf("NOK: %s, %s -> %s%n", left, right, mixed);
    }
  }
}

Olivier Grégoire

Posted 2016-10-31T20:42:51.723

Reputation: 10 647

0

APL, 12

{↓(⍳⍴⊃⍵)⊖↑⍵}

Explanation: {...} defines a function, ⍵ is the right argument. The take (↑) creates a matrix out of the two strings, then rotates each column (⊖) n times, where n is the part in parenthesis (⍳⍴⊃⍵). That's defined as the iota of the length of the first argument. (Ex: length=5 ==> 1 2 3 4 5). So first column is rotated once, second twice (getting back to original positions), third column three times, etc...

Try it at tryapl.org

Moris Zucca

Posted 2016-10-31T20:42:51.723

Reputation: 1 519

0

Scala, 85 bytes

(_:String)zip(_:String)zip(Stream from 0)map{case(t,z)=>if(z%2==0)t else t.swap}unzip

take an anonymous string parameter, zip it with another string parameter, zip it with an stream of natural numbers, swap every second tuple of chars and unzip to get a tuple of sequences of chars

corvus_192

Posted 2016-10-31T20:42:51.723

Reputation: 1 889

0

Swift 3, 129 107 bytes

func c(n:inout[String],b:inout[String]){
for(j,c)in n.enumerated(){
if j&1<1{n[j]=b[j];b[j]=c}}
print(n,b)}

Original

The function receives two arrays of strings as parameters assuming both have same length, as follows:

c(n:["c", "o", "d", "e"],b:["g", "o", "l", "f"])

Produces following output

codf gole

Edit 1:

Get rid of the internal tuple and change the parameters of the function to be inout. Instead of string concatenation manipulate the parameters directly.

Example input:

var a:Array<String> = ["c", "o", "d", "e"]
var b:Array<String> = ["g", "o", "l", "f"]

c(n:&a,b:&b)

Ouput changed to be array of strings as in:

["g", "o", "l", "e"] ["c", "o", "d", "f"]

Otávio

Posted 2016-10-31T20:42:51.723

Reputation: 161