# Character Cross

I was expecting to post something more complex as my first puzzle in PCG, but a particular, uh... homework question on Stack Overflow inspired me to post this. They want to:

print the following pattern for any given word that contains odd number of letters:

P           M
R       A
O   R
G
O   R
R       A
P           M


Notice that letters are a knight's move apart in the pattern you need to print. So, every other column is empty. -- (Thanks xnor for pointing this out.)

## Rules

1. Using C++ is prohibited. As I may link this question there.
2. You may use stdout, or any means of quickly outputting a string (e.g. alert() in JavaScript).
3. As always, shortest code wins.
• This is in the related posts on stack overflow: stackoverflow.com/q/5508110 Oct 29, 2014 at 11:26
• @flawr I think it means odd, as in not an even number. Oct 29, 2014 at 14:28
• God I am stupid, I thought it was kind of an obscure computer scientist abbreviation=) Oct 29, 2014 at 14:34
• @jpjacobs: Bytes, unless the question explicitly says otherwise. Oct 29, 2014 at 17:20
• Whole program or just a function? (real smart of me to answer first and make this question later...) Oct 29, 2014 at 20:23

## APL (373534 27)

↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞


It takes input from the keyboard, like so:

      ↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞
CODE-GOLF
C               F
O           L
D       O
E   G
-
E   G
D       O
O           L
C               F

• All of my upvotes belong to APL. Oct 29, 2014 at 16:33

# Python 2 - 94 90 89 88

s=input()
L=len(s)
R=range(L)
for i in R:print" ".join([s[j]," "][j!=i!=L+~j]for j in R)


Input:

"CODE-GOLF"


Output:

C               F
O           L
D       O
E   G
-
E   G
D       O
O           L
C               F

• I was just writing the same thing. My one improvement is i in[j,L+~j].
– xnor
Oct 29, 2014 at 7:08
• @xnor: Found an even shorter condition. ;) Oct 29, 2014 at 7:11
• Clever. You can still do L+~j though.
– xnor
Oct 29, 2014 at 7:12
• @xnor: Ah, you're right. I always forget the +~ trick... Oct 29, 2014 at 7:16
• Can you do for i in R:print" ".join([s[j]," "][j!=i!=L+~j]for j in R) to save a char? (I don't have access to Python 2 now to test.)
– xnor
Oct 29, 2014 at 7:20

# Pyth, 22

Vzjdm?@zd}N,dt-lzd\ Uz


Test:

$pyth -c 'Vzjdm?@zd}N,dt-lzd\ Uz' <<< "CODE-GOLF" C F O L D O E G - E G D O O L C F  Explanation: (Implicit) z = input() (Implicit) d = ' ' Vz for N in range(len(z)): jd print(d.join( m map(lambda d: ?@zd z[d] if }N N in ,dt-lzd (d,len(z)-d-1) else \ " ", Uz range(len(z)))))  • No bit complement in Pyth? – xnor Oct 29, 2014 at 20:16 • @xnor No, but it wouldn't help. Suppose ~ was bitwise not in Pyth. Then we could change t-lzd to +lz~d - still 5 characters. Oct 29, 2014 at 20:20 • Vz is a neat trick: I didn't know that U<string> gave range(len(<string>)). Oct 29, 2014 at 20:21 • Yeah, it's a nice feature. Works that way on lists too, but not tuples necessarily. EDIT: Oops, that's missing from the documentation. I'll add it. Sorry. Oct 29, 2014 at 20:23 ## Python 3: 75 chars s=input() i=n=len(s) while i:i-=1;a=[" "]*n;a[i]=s[i];a[~i]=s[~i];print(*a)  For line i, we start with a list of spaces and set the entries i from the front and back to be equal to the letters of the input string. Then, we print the result. Python strings are immutable, so a must be a list of characters instead. The list a must be initialized inside the loop or the modifications will carry over between loops. We use print(*a) to print each character in the list, space separated, which requires Python 3. The output lines are symmetrical, so we can have i count down rather than up using a while loop. >>> CODE-GOLF C F O L D O E G - E G D O O L C F  It also works for an even number of letters. >>> CODEGOLF C F O L D O E G E G D O O L C F  • Converting this to Pyth, I get VlzJ*]dlz=@JN@zN=@Jt_N@_zNjdJ which is 29 bytes... I guess I'll have to try something else to beat APL. Also, +1 for proof that Python 3 can out-golf Python 2 (sometimes) Oct 29, 2014 at 13:37 • @fry Python 3 usually out-golfs 2 in my experience. Even if nothing changes anywhere else, most challenges give one input and expect one output, and len("raw_input()") + len("print ") > len("input()") + len("print()"). Oct 29, 2014 at 14:48 • @undergroundmonorail Well, the trouble with that is that input() is also valid in python 2 (it just acts somewhat differently), so unless the input for the challenge is quite strict, python 2 will usually win out. Oct 29, 2014 at 14:51 • Wow, even with Python 2 and print" ".join(a) your code is shorter (82) than mine. Oct 29, 2014 at 16:19 • @FryAmTheEggman See my answer - it's an adaptation of the other python answer, and it's much shorter than APL. Pyth really doesn't like assigning to indexes, unfortunately. Oct 29, 2014 at 20:03 # CJam, 27 25 bytes l_,S*:Sf{W):W2$tW~@tS}zN*


Try it online.

### Example run

$cjam <(echo 'l_,S*:Sf{W):W2$tW~@tS}zN*') <<< CROSS; echo
C       S
R   S
O
R   S
C       S


As the example in the answer, each line has trailing whitespace.

### How it works

                             " N := '\n'; R := []; S = ' '; W := -1 ";
l                            " Q := input()                         ";
_,S*:S                      " S := len(Q) * S                      ";
f{            }       " for each C in Q:                     ";
"   T := S                             ";
W):W                "   W += 1                             ";
2$t " T[W] := C "; W~@t " T[~W] := C "; " R += [T] "; S " R += [S] "; z " R := zip(R) "; N* " R := N.join(R) "; " print R ";  • Sorry that this is basically a 'great answer!' comment, but I just had to say that it never, ever, would have occurred to me to build the box by columns instead of by rows. Oct 29, 2014 at 18:57 # Canvas, 5 bytes ＼＼：⇵ｎ  Try it here! Explanation: \ create a diagonal of the input \ create an even steeper diagonal of that :⇵ reverse a copy of it vertically n overlap the two  # Pure Bash, 94 bytes l=${#1}
for((;t<l*l;t++));{
((x=t%l))||echo

# JavaScript (E6) 101 95 129 136

Edit Wrong letter spacing. Fixed.
Edit Simpler and shorter using classic for loops
As a function, output via popup.

F=a=>{
for(l=a.length+1,i=s=o='';++i<l;s='\n')
for(j=0;++j<l;)
o+=s+((s=' ')+a)[j==i|i+j==l&&j]
}


Previous version using .map

F=a=>alert([...a].map((c,p)=>
--q<p
?B(q)+a[q]+B(p-q-1)+c
:B(p)+c+(p-q?B(q-p-1)+a[q]:'')
,B=n=>' '.repeat(n),q=a.length).join('\n'))


Test In FireFox/FireBug console

F('Java-Script')


Output

J                   t
a               p
v           i
a       r
-   c
S
-   c
a       r
v           i
a               p
J                   t

• This doesn't have enough horizontal spacing - there should be columns of all spaces between each column with letters. Oct 29, 2014 at 20:06

# Befunge-93, 68 71

:~:84*-!#@#v_\:2*\4+p1+
::+\4+g:!| >$1+0:>p1-:: 00+4\*2:\<>0p#:- ^#2g  You can test it here. It'll come up with an input dialog box on each pass through ~; enter your word one character at a time (it does say the input is 'klunky' after all), ending with a space. It won't print to the console; this wouldn't be Befunge without a hint of self-modification, after all! Instead it will modify its own grid to display the message. After it's done, the grid will look something like this:  ~:84*-!#@#v_\:2*\4+p1+ ::+\4+g:!| >$1+0:>p1-::
00+4\*2:\<>0p#:- ^#2g

c               f
o           l
d       o
e   g
-
e   g
d       o
o           l
c               f


(Note the noble sacrifice of the cell at (0,0), after we know the pointer won't go there anymore, for the purpose of storing a piece of data.)

It also works with inputs of even length. Note that, since Befunge-93 is limited to an 80x25 grid, the input size is limited to 21 characters if you run it in a Befunge-93 interpreter. Running it as Befunge-98 should remove this limit.

Edit - Now it works more along the lines of the intended output, at the expense of only three characters of length.

• Note that the letters are separated with a blank column. Letters are relatively in L shape. Oct 30, 2014 at 7:56
• Drats! That complicated things rather significantly. I think I can salvage this, but it'll add to the ending size... oh well. Oct 30, 2014 at 17:30

# Javascript 102 84 85

Edit: Had to fix spacing. Not so small anymore.

function p(s){for(i in s){o='';for(n in s)o+=(n==i?s[n]:n==s.length-1-i?s[n]:' ')+' ';console.log(o)}}

p('Thanks-Dennis')

T                       s
h                   i
a               n
n           n
k       e
s   D
-
s   D
k       e
n           n
a               n
h                   i
T                       s

• This does not have enough horizontal spacing. Oct 30, 2014 at 17:22
• Wow, shorter than mine and not even using ES6. +1 Oct 30, 2014 at 19:30
• Better, but the spacing is still wrong (look at the X). Also, unless the question says otherwise, you should write a program or a function. Snippets with hardcoded variables are generally frowned upon. Oct 31, 2014 at 1:06
• And can't you make it function(s) since you don't recurse? Jun 23, 2017 at 12:54

## CJam, 38363534 32 bytes

l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N}


Test it here. This reads the input word from STDIN. It also works for an even number of characters. This prints a trailing column of spaces, but I don't see anything in the rules against that.

Explanation

l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N}
l:I                              "Read input and store it in I.";
,                             "Get string length.";
,_                           "Turn into range and duplicate.";
f{                       } "Map block onto first range, with second range on the stack.";
f{                   }   "Map block onto second range, with first iterator in stack.
y and x on the stack (x on top).";
_2$= "Duplicate x, duplicate y, check for equality."; @2$+               "Pull up y, duplucate x, add,";
I,(=           "Check if that's one less than the string length.";
|          "Bitwise or between conditions.";
\         "Swap condition and x.";
I=       "Take x'th character from the string.";
S?     "Push a space and select character depending on condition.";
S    "Push another space.";
N  "Push a line feed.";


The contents of the stack are printed automatically at the end of the program.

• My dear CJam, you've just got beaten by APL. ^_^
– user18967
Oct 29, 2014 at 11:09
• @vaxquis I was surprised I was able to beat it twice in the first place. This problem seems much more suited to APL and co than to stack-based languages. Oct 29, 2014 at 11:13
• well, at least it's easier to write l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N} on a napkin than ↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞ ... chuckle
– user18967
Oct 29, 2014 at 14:40
• Well, someone else managed to beat me using CJam, and I can't make my program any shorter, so CJam did eventually beat me. (But Pyth gets the crown.) (That said, @vaxquis, APL is far easier to read than most of the other languages used on here, certainly once you know the 60 or so characters, and certainly when compared to Pyth or CJam or even J.) Oct 30, 2014 at 9:42

# C, 105

two slightly different ways of doing it.

c,i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;)putchar((c=v[1][i++])?i-1-j&&l-i-j?32:c:(i=0,j++,10));}

i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;i++)putchar((l-i)?i-j&&l-i-j-1?32:v[1][i]:(i=-1,j++,10));}


If you want to add extra spaces, replace putchar( with printf(" %c", for an extra 5 characters.

## J - 36 30 bytes:

Edit: 6 characters shorter, credits go to @algorithmshark .

(1j1#"1' '&,({~](*>.*&|.)=)#\)


eg:

   (1j1#"1' '&,({~](*>.*&|.)=)#\) 'Code-Golf'
C               f
o           l
d       o
e   G
-
e   G
d       o
o           l
C               f


Bonus: works with even length strings too:

   (1j1#"1' '&,({~](*>.*&|.)=)#\) 'CodeGolf'
C             f
o         l
d     o
e G
e G
d     o
o         l
C             f


# Prolog - 240 bytes

:-initialization m.
+[]. +[H|T]:-(H=' ';!),+T.
+[H|T]+I+X:-0=:=I,X=H;+T+(I-1)+X.
+L+I+C+S:-L=:=I;S=[D|E],+C+I+B,+C+(L-I-1)+B,+B+2*I+D,+L+(I+1)+C+E,+B,writef('%s\n',[B]).
-X:-get_char(C),(C='\n',X=[];X=[C|Y],-Y).
m:- -X,length(X,L),+L+0+_+X.


Invocation:

$echo "Code-Golf" | swipl -qf c.pl C f o l d o e G - e G d o o l C f  Readable: :- initialization(main). vars_to_spaces([]). vars_to_spaces([' '|T]) :- vars_to_spaces(T). vars_to_spaces([_|T]) :- vars_to_spaces(T). get_index([Head|_], Index, Result) :- 0 =:= Index, Result = Head. get_index([_|Tail], Index, Result) :- get_index(Tail, Index-1, Result). print_loop(Length, Index, Board, String) :- Length =:= Index; String = [FirstChar|RestString], get_index(Board, Index, Line), get_index(Board, Length-Index-1, Line), get_index(Line, 2*Index, FirstChar), print_loop(Length, Index+1, Board, RestString), vars_to_spaces(Line), writef('%s\n', [Line]). get_line(Line) :- get_char(C), ( C = '\n', Line = []; Line = [C|More], get_line(More)). main :- get_line(String), length(String, Length), print_loop(Length, 0, _, String).  # Jelly, 11 bytes LḶḤ⁶ẋ;"µ»ṚY  Try it online! # Powershell, 78 bytes +8 bytes thanks @streetster param($s)$s|% t*y|%{$r=,' '*$s.length;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}  Explaned test script: $f = {

param($s) # declare a parameter$s stores a word
$s|% t*y|%{ # split$s into chars https://codegolf.stackexchange.com/a/168174/80745
$r=,' '*$s.length   # create an array of spaces with length equal length of the word
$r[$i++]=$_ # set first char$r[-$i]=$s[-$i] # set last char$r-join' '          # join the array to string
}

}

&$f PROGRAM '' &$f sword
''
&$f uhm '' &$f o
''
&$f codegolf # It works with word that contains even number of letters  # Powershell, 70 bytes (if a word can be represented by an array of chars) +8 bytes thanks @streetster ($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}  Test script: $f = {

($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}

}

&$f P R O G R A M '' &$f s w o r d
''
&$f u h m '' &$f o
''
&$f c o d e g o l f # It works with word that contains even number of letters  Output for both cases: P M R A O R G O R R A P M s d w r o w r s d u m h u m o c f o l d o e g e g d o o l c f  • Since you can take input as a char-array (Meta post), that can save some bytes. Aug 20, 2018 at 13:21 • I'm not sure that the word in the rule print the following pattern for any given word that contains odd number of letters means an array of chars in a Powershell :) But I've updated post Aug 20, 2018 at 15:52 • Aren't you crossing the wrong way? – mkst Aug 21, 2018 at 7:16 • @streetster, you are best! I've updated the post. Aug 21, 2018 at 8:27 • Oof, +8 bytes - sorry! – mkst Aug 21, 2018 at 14:36 ## C# (214 212) (Certainly badly) Golfed version: using System;class A{static void Main(){char[]a,w=Console.ReadLine().ToCharArray();int l=w.Length,i=0;for(;i<l;i++){a=new string(' ',2*l-1).ToCharArray();a[2*i]=w[i];a[2*l-2*i-2]=w[l-i-1];Console.WriteLine(a);}}}  Ungolfed version: using System; class A { static void Main() { char[] a, w = Console.ReadLine().ToCharArray(); int l = w.Length, i = 0; for (; i < l; i++) { a = new string(' ', 2 * l - 1).ToCharArray(); a[2 * i] = w[i]; a[2 * l - 2 * i - 2] = w[l - i - 1]; Console.WriteLine(a); } } }  Any hints, tips, tricks or remarks are very welcome, as this is my first attempt at CodeGolf. I just wanted to try it, even though I know my C# byte length won't even come close to double the best solutions ;) And how do you guys count your bytes? I just posted the above into a Quick Watch window and did .Length. I could write a small program to count bytes for me, but I bet there is an easier way that I don't yet know. • You can save two bytes by removing the spaces in for(;i < l;i++). Oct 29, 2014 at 9:34 • Also, I use this for my byte counting. Oct 29, 2014 at 9:36 • @BetaDecay Ah great, I must have overlooked those. And thanks for the link! Oct 29, 2014 at 9:38 # JavaScript (ES6) - 185177175 170 bytes f=n=>{return s=' ',r='repeat',n=[...n],l=n.length,j=l/2-.5,[...h=n.slice(0,j).map((c,i)=>s[r](i)+c+s[r](l-2-(i*2))+' '+n[l-i-1]),s[r](j)+n[j],...h.reverse()].join('\n')}  Put this in the Firefox console and run as f('PROGRAM'): P M R A O R G O R R A P M  f("CODE-GOLF"): C F O L D O E G - E G D O O L C F  # Mathematica, 149 bytes FromCharacterCode@Flatten[Append[Riffle[#,32],10]&/@MapThread[Max,{#,Reverse@#,ConstantArray[32,Dimensions@#]},2]&@DiagonalMatrix@ToCharacterCode@#]&  Input passed as parameter to the function; function returns the output string. There is a trailing newline at the end of the output. Explanation: We create a diagonal matrix with the string, then we create a copy of it vertically flipped using Reverse@# to reverse the rows. Then we have a third matrix of the same dimensions containing only 32 (ascii space). We use MapThread to take the element-wise max of these 3 matrices. Finally, we Riffle spaces into each row, Append a newline at the end, and Flatten the result. # Perl - 90 It might be possible to squeeze some more characters out of this: ($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":" "for split//,($_ x y///c)


89 + 1 for -n.

Run with:

echo "program" | perl -nE'($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":"  "for split//,($_ x y///c)'  Output: p m r a o r g o r r a p m  ## T-SQL: 180 Taking the input from variable @i DECLARE @s VARCHAR(MAX)=REPLICATE(' ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A  This stuffs single characters in/decrementing from the start and end into a string of spaces. Test Result DECLARE @i VARCHAR(MAX)='Super Large' DECLARE @s VARCHAR(MAX)=REPLICATE(' ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A S e u g p r e a r L r L e a p r u g S e  # PowerShell 118102 97 ($x=[char[]]"$args")|%{$i++;$y=[char[]]" "*$x.Count;$y[$i-1]=$x[$i-1];$y[-$i]=$x[-$i];$y-join' '}  Outputs: PS C:\PowerShell> .\cross.ps1 SWORD S D W R O W R S D  # JavaScript (Node.js), 81 bytes f=s=>[...s].map((_,i,a)=>a.map((c,j)=>j==i|j==s.length+~i?c:' ').join ).join   EDIT: -1 Thanks Joe King. I didn't see the TIO gives preformatted direct paste for CG. Try it online! • btw, the excess code to execute the code in TIO can go in the program footer. This helps determine the correct byte count and use the automated PPCG answer format more smoothly. e.g. Try it online! – Jo King Aug 17, 2018 at 6:14 • -i-1 can be +~i – Jo King Aug 17, 2018 at 6:24 # Stax, 13 bytes â┤▼iS╙£≥»u5V╓  Run and debug it Unpacked, ungolfed, and commented, it looks like this. { begin block for mapping characters of input ]i^) left-pad each character to length (i+1) where i is the index m map using block r reverse the array; this produces the southwest-northeast diagonal m map using the rest of the program, implicitly output result i iteration index xi@ get the i'th character of the original input, where i is the iteration & assign element to array at index 0\ join with spaces  Run this one # R, 88 bytes n=ncol(m<-diag(u<-utf8ToInt(scan(,""))-32));diag(m[,n:1])=u;write(intToUtf8(m+32,T),1,n)  Try it online! • Nice! Like me, you can save 2 bytes by using pmax (originally Giuseppe's suggestion). Nov 24, 2018 at 23:10 • This won't work with length 1 input. Nov 24, 2018 at 23:28 # Canvas, 6 bytes ＼：↶ｎ ＊  Try it here! # Explanation ＼ Create a diagonal with the input ： Duplicate the diagonal ↶ Rotate left ｎ Simple overlap ＊ Insert spaces on every line  • There is already a 5-byte Canvas answer, but nice approach regardless! :) Apr 9, 2020 at 8:12 • I see, the built-in is ｎ... – user92069 Apr 9, 2020 at 8:38 # Zsh, 90 82 bytes Kudos to @pxeger for saving 8 bytes. for i ({1..$#1})(for z (${(s::)1}){((i==++j||j+i==$#1+1))||z=\
printf \$z\ }
echo)