# 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 – Level River St Oct 29 '14 at 11:26
• @flawr I think it means odd, as in not an even number. – NinjaBearMonkey Oct 29 '14 at 14:28
• God I am stupid, I thought it was kind of an obscure computer scientist abbreviation=) – flawr Oct 29 '14 at 14:34
• @jpjacobs: Bytes, unless the question explicitly says otherwise. – Dennis Oct 29 '14 at 17:20
• Whole program or just a function? (real smart of me to answer first and make this question later...) – Rodolfo Dias Oct 29 '14 at 20:23

# 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 '14 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. – isaacg Oct 29 '14 at 20:20 • Vz is a neat trick: I didn't know that U<string> gave range(len(<string>)). – FryAmTheEggman Oct 29 '14 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. – isaacg Oct 29 '14 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. – Nit Oct 29 '14 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 '14 at 7:08 • @xnor: Found an even shorter condition. ;) – Falko Oct 29 '14 at 7:11 • Clever. You can still do L+~j though. – xnor Oct 29 '14 at 7:12 • @xnor: Ah, you're right. I always forget the +~ trick... – Falko Oct 29 '14 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 '14 at 7:20 ## 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) – FryAmTheEggman Oct 29 '14 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()"). – undergroundmonorail Oct 29 '14 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. – FryAmTheEggman Oct 29 '14 at 14:51 • Wow, even with Python 2 and print" ".join(a) your code is shorter (82) than mine. – Falko Oct 29 '14 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. – isaacg Oct 29 '14 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. – FryAmTheEggman Oct 29 '14 at 18:57 # Java - 168 A simple nested loop, there's nothing really special going on here. class C{public static void main(String[]a){int b=-1,c=a[0].length()-1,d;for(;b++<c;)for(d=-1;d++<c;)System.out.print((b==d|b==c-d?a[0].charAt(d):" ")+(c==d?"\n":""));}}  With line breaks: class C{ public static void main(String[]a){ int b=-1,c=a[0].length()-1,d; for(;b++<c;) for(d=-1;d++<c;) System.out.print( (b==d|b==c-d?a[0].charAt(d):" ")+ (c==d?"\n":"")); } }  # 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. – isaacg Oct 29 '14 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. – sampathsris Oct 30 '14 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. – Kasran Oct 30 '14 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. – Dennis Oct 30 '14 at 17:22
• Wow, shorter than mine and not even using ES6. +1 – Scimonster Oct 30 '14 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. – Dennis Oct 31 '14 at 1:06
• And can't you make it function(s) since you don't recurse? – Zacharý Jun 23 '17 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 '14 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. – Martin Ender Oct 29 '14 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 '14 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.) – marinus Oct 30 '14 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).  # 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  # R, 999893 89 bytes m=ifelse(diag(l<-length(w<-el(strsplit(scan(,''),'')))),w,' ') write(pmax(m,m[,l:1]),1,l)  Try it online! Line 1 reads input string, splits it into characters, stores its length and creates a matrix with the word on its main diagonal – letters of the word are superposed on an identity matrix (and repeated by default to match its length) and only those matching 1's are retained, others being replaced by spaces. Line 2 prints a matrix formed by elements of either the diagonal matrix or its horizontally mirrored version, whichever are greater. −2 + 1 = −1 byte thanks to JayCe −4 bytes thanks to Giuseppe • Sweet! And nice explanation.you can save 2 bytes – JayCe Aug 17 '18 at 13:42 • looking at he other answers and the question - It seems like the matrix should be larger (extra space) - the output should not be a square matrix.. – JayCe Aug 17 '18 at 13:54 • @JayCe Thanks for the 2 bytes! And thanks for the comment about formatting, you are probably right (although the rules could be more clear about this). Fortunately all it needed was putting a space into the separator while printing. – Robert Hacken Aug 17 '18 at 14:25 • 89 bytes using pmax and inlining some more assignments. – Giuseppe Nov 24 '18 at 18:27 • @Giuseppe Thanks! Sadly, still not enough to beat J.Doe's solution – Robert Hacken Nov 24 '18 at 23:21 ## 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++). – Beta Decay Oct 29 '14 at 9:34 • Also, I use this for my byte counting. – Beta Decay Oct 29 '14 at 9:36 • @BetaDecay Ah great, I must have overlooked those. And thanks for the link! – InvisiblePanda Oct 29 '14 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  # Jelly, 11 bytes LḶḤ⁶ẋ;"µ»ṚY  Try it online! # 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 '18 at 6:14 • -i-1 can be +~i – Jo King Aug 17 '18 at 6:24 ## C# 208 static void Main() { string s=Console.ReadLine(),t=""; int n=s.Length; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j)t+=s[i]; else if(i==n-j-1)t+=s[n-i-1]; t+=" "; } t+="\n"; } Console.WriteLine(t); }  • Save 11 precious characters with t+=i==j?s[i]:i==n-j-1?s[n-i-1]:"";. – sampathsris Oct 29 '14 at 11:22 • Can you remove those newlines? – Zacharý Jun 23 '17 at 12:53 ## GolfScript 46 (DEMO) :w,:l,{l,{.[.l(\-]2$?)!w@[=32]=}%\;''+' '*}%n*


No matter how long, there's always gotta be an answer in...

# Java - 289 234 bytes

public static void main(String[]a){int l=a.length-1,i=0,j;for(;i<=l;i++){for(j=0;j<=l;j++){if(j==i)System.out.print(a[i]);else if(i==l-j)System.out.print(a[j]);else System.out.print(" ");System.out.print(" ");}System.out.println();}}}


Ungolfed:

    class A {

public static void main(String[] a) {
int l = a.length - 1, i = 0, j;
for (; i <= l; i++) {
for (j=0; j <= l;j++) {
if (j == i)
System.out.print(a[i]);
else if (i == l-j)
System.out.print(a[j]);
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}


Output, lousily done, is:

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


Added the import java.util.Scanner inside the code because I never remember if the imports count towards the byte count... Damn, I really suck at this.

• Imports do count. This is partly because of Python's import-and-alias syntax: from math import floor as f which is a bit cheaty – user16402 Oct 29 '14 at 15:54
• You should be able to save a bunch of characters by combining all the System.out.print calls into one, using a couple of ternary operators. – DLosc Oct 30 '14 at 16:29
• @DLosc Could you give me a few examples? – Rodolfo Dias Oct 30 '14 at 18:28
• Yes, actually Geobits' answer is a perfect example--see the contents of the System.out.print call at the end. – DLosc Oct 31 '14 at 0:13
• @RodolfoDias Don't feel that way. My first few golfs in Java were terrible, and I can still normally shave a decent chunk off my "first revisions" if I look hard enough ;) – Geobits Oct 31 '14 at 13:28

# C# (192 / 170)

using System;class P{static void Main(){var s=Console.ReadLine();int x,y,l=s.Length;for(x=0;x<l;x++){for(y=0;y<l;y++)Console.Write(x==y||l-x==y+1?s.Substring(x,1):" ");Console.Write("\n");};}}


Or, as "Main() only":

static void Main(){var s=Console.ReadLine();int x,y,l=s.Length;for(x=0;x<l;x++){for(y=0;y<l;y++)Console.Write(x==y||l-x==y+1?s.Substring(x,1):" ");Console.Write("\n");};}


# QBasic, 91 bytes

INPUT w$l=LEN(w$)
FOR i=1TO l
c$=MID$(w$,i,1) LOCATE i+1,i*2 ?c$
LOCATE l-i+2,i*2
?c\$
NEXT


Loops through the input word and uses the LOCATE statement to place each letter (twice) on the screen.