31
\$\begingroup\$

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

39 Answers 39

13
\$\begingroup\$

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)))))
\$\endgroup\$
  • \$\begingroup\$ No bit complement in Pyth? \$\endgroup\$ – xnor Oct 29 '14 at 20:16
  • \$\begingroup\$ @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. \$\endgroup\$ – isaacg Oct 29 '14 at 20:20
  • \$\begingroup\$ Vz is a neat trick: I didn't know that U<string> gave range(len(<string>)). \$\endgroup\$ – FryAmTheEggman Oct 29 '14 at 20:21
  • \$\begingroup\$ 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. \$\endgroup\$ – isaacg Oct 29 '14 at 20:23
20
\$\begingroup\$

APL (37 35 34 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 
\$\endgroup\$
  • 7
    \$\begingroup\$ All of my upvotes belong to APL. \$\endgroup\$ – Nit Oct 29 '14 at 16:33
13
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ I was just writing the same thing. My one improvement is i in[j,L+~j]. \$\endgroup\$ – xnor Oct 29 '14 at 7:08
  • \$\begingroup\$ @xnor: Found an even shorter condition. ;) \$\endgroup\$ – Falko Oct 29 '14 at 7:11
  • \$\begingroup\$ Clever. You can still do L+~j though. \$\endgroup\$ – xnor Oct 29 '14 at 7:12
  • \$\begingroup\$ @xnor: Ah, you're right. I always forget the +~ trick... \$\endgroup\$ – Falko Oct 29 '14 at 7:16
  • \$\begingroup\$ 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.) \$\endgroup\$ – xnor Oct 29 '14 at 7:20
11
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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) \$\endgroup\$ – FryAmTheEggman Oct 29 '14 at 13:37
  • \$\begingroup\$ @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()"). \$\endgroup\$ – undergroundmonorail Oct 29 '14 at 14:48
  • \$\begingroup\$ @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. \$\endgroup\$ – FryAmTheEggman Oct 29 '14 at 14:51
  • \$\begingroup\$ Wow, even with Python 2 and print" ".join(a) your code is shorter (82) than mine. \$\endgroup\$ – Falko Oct 29 '14 at 16:19
  • \$\begingroup\$ @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. \$\endgroup\$ – isaacg Oct 29 '14 at 20:03
8
\$\begingroup\$

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                              ";
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – FryAmTheEggman Oct 29 '14 at 18:57
4
\$\begingroup\$

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":""));
    }
}
\$\endgroup\$
4
\$\begingroup\$

Pure Bash, 94 bytes

l=${#1}
for((;t<l*l;t++));{
((x=t%l))||echo
((x-t/l&&x+t/l+1-l))&&printf \ ||printf ${1:x:1}
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Too many t%l calculations. Save it on first use to a variable ((x=t%l)) then use the variable to reduce it to 94 characters. \$\endgroup\$ – manatwork Oct 29 '14 at 18:24
  • \$\begingroup\$ Ah yes, I had done this for x=t%l and y=t/l and it was longer... didn't cross my mind just to use x only \$\endgroup\$ – Digital Trauma Oct 29 '14 at 18:28
4
\$\begingroup\$

Ruby, 64

f=->w{x=w.size
x.times{|i|y=" "*x
y[i],y[~i]=w[i],w[~i]
puts y}}

Explanation

  • Input is taken as the argument to a lambda. It expects a String.
  • In a loop that loops trough every character in the word (n in total):
    • Create a String consisting of n spaces.
    • Replace the ith and n-ith (~i, thanks xnor) space with the ith and n-ith character of the input.
    • Print the line
\$\endgroup\$
  • 7
    \$\begingroup\$ Congratulations on posting the 25,000th answer! :) (Actually, I'm not 100% sure, this is the one, due to caching. But it was the latest answer, when I first saw "25,000 answers" in the site stats.) \$\endgroup\$ – Martin Ender Oct 29 '14 at 15:19
  • 2
    \$\begingroup\$ You can do -i-1 as the bit complement ~i. \$\endgroup\$ – xnor Oct 29 '14 at 20:05
  • \$\begingroup\$ That's very clever, thanks! \$\endgroup\$ – britishtea Oct 29 '14 at 20:48
  • 2
    \$\begingroup\$ With this approach, it actually seems to be beneficial to use stdin instead of a lambda: gets.size.times{|x|u=?\s*~/$/;u[x]=$_[x];u[~x]=$_[~x];puts u} (assumes input is not terminated by a newline, e.g. echo -n CODE-GOLF). One can then make additional use of .chars to save another character: x=0;gets.chars{|r|u=?\s*~/$/;u[x]=r;u[~x]=$_[-x+=1];puts u} \$\endgroup\$ – Ventero Oct 29 '14 at 23:46
4
\$\begingroup\$

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]
  alert(o)
}

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
\$\endgroup\$
  • 2
    \$\begingroup\$ This doesn't have enough horizontal spacing - there should be columns of all spaces between each column with letters. \$\endgroup\$ – isaacg Oct 29 '14 at 20:06
4
\$\begingroup\$

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.

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

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
\$\endgroup\$
  • \$\begingroup\$ This does not have enough horizontal spacing. \$\endgroup\$ – Dennis Oct 30 '14 at 17:22
  • 1
    \$\begingroup\$ Wow, shorter than mine and not even using ES6. +1 \$\endgroup\$ – Scimonster Oct 30 '14 at 19:30
  • \$\begingroup\$ 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. \$\endgroup\$ – Dennis Oct 31 '14 at 1:06
  • 1
    \$\begingroup\$ And can't you make it function(s) since you don't recurse? \$\endgroup\$ – Zacharý Jun 23 '17 at 12:54
3
\$\begingroup\$

CJam, 38 36 35 34 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.
                                  Each invocation of this block will start with grid coordinates
                                  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.

\$\endgroup\$
  • \$\begingroup\$ My dear CJam, you've just got beaten by APL. ^_^ \$\endgroup\$ – vaxquis Oct 29 '14 at 11:09
  • \$\begingroup\$ @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. \$\endgroup\$ – Martin Ender Oct 29 '14 at 11:13
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ – vaxquis Oct 29 '14 at 14:40
  • \$\begingroup\$ 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.) \$\endgroup\$ – marinus Oct 30 '14 at 9:42
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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).
\$\endgroup\$
3
\$\begingroup\$

Canvas, 5 bytes

\\:⇵n

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
\$\endgroup\$
3
\$\begingroup\$

R, 99 98 93 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

\$\endgroup\$
  • 1
    \$\begingroup\$ Sweet! And nice explanation.you can save 2 bytes \$\endgroup\$ – JayCe Aug 17 '18 at 13:42
  • 1
    \$\begingroup\$ 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.. \$\endgroup\$ – JayCe Aug 17 '18 at 13:54
  • \$\begingroup\$ @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. \$\endgroup\$ – Robert Hacken Aug 17 '18 at 14:25
  • \$\begingroup\$ 89 bytes using pmax and inlining some more assignments. \$\endgroup\$ – Giuseppe Nov 24 '18 at 18:27
  • \$\begingroup\$ @Giuseppe Thanks! Sadly, still not enough to beat J.Doe's solution \$\endgroup\$ – Robert Hacken Nov 24 '18 at 23:21
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You can save two bytes by removing the spaces in for(;i < l;i++). \$\endgroup\$ – Beta Decay Oct 29 '14 at 9:34
  • \$\begingroup\$ Also, I use this for my byte counting. \$\endgroup\$ – Beta Decay Oct 29 '14 at 9:36
  • \$\begingroup\$ @BetaDecay Ah great, I must have overlooked those. And thanks for the link! \$\endgroup\$ – InvisiblePanda Oct 29 '14 at 9:38
2
\$\begingroup\$

JavaScript (ES6) - 185 177 175 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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

C, 119

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

This might not be compiled as C++, thus I hope, I haven't violated rules:)

\$\endgroup\$
  • \$\begingroup\$ 1. The output is currently wrong. There should be a space between the letters. 2. i=0 and j=0 is not needed, since global variables are initialized to zero. 3. You can use main(l,v)char**v; instead of main(int l,char**v). 4. If you update i as i+=puts(""), you can get rid of the outer loop's curly brackets. \$\endgroup\$ – Dennis Oct 30 '14 at 17:19
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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 
\$\endgroup\$
2
\$\begingroup\$

PowerShell 118 102 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
\$\endgroup\$
2
\$\begingroup\$

Jelly, 11 bytes

LḶḤ⁶ẋ;"µ»ṚY

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ 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! \$\endgroup\$ – Jo King Aug 17 '18 at 6:14
  • \$\begingroup\$ -i-1 can be +~i \$\endgroup\$ – Jo King Aug 17 '18 at 6:24
1
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ Save 11 precious characters with t+=i==j?s[i]:i==n-j-1?s[n-i-1]:"";. \$\endgroup\$ – sampathsris Oct 29 '14 at 11:22
  • \$\begingroup\$ Can you remove those newlines? \$\endgroup\$ – Zacharý Jun 23 '17 at 12:53
1
\$\begingroup\$

GolfScript 46 (DEMO)

:w,:l,{l,{.[.l(\-]2$?)!w@[=32]=}%\;''+' '*}%n*
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ – user16402 Oct 29 '14 at 15:54
  • \$\begingroup\$ 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. \$\endgroup\$ – DLosc Oct 30 '14 at 16:29
  • \$\begingroup\$ @DLosc Could you give me a few examples? \$\endgroup\$ – Rodolfo Dias Oct 30 '14 at 18:28
  • 1
    \$\begingroup\$ Yes, actually Geobits' answer is a perfect example--see the contents of the System.out.print call at the end. \$\endgroup\$ – DLosc Oct 31 '14 at 0:13
  • 1
    \$\begingroup\$ @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 ;) \$\endgroup\$ – Geobits Oct 31 '14 at 13:28
1
\$\begingroup\$

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");};}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.