Character Cross

31

3

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.

sampathsris

Posted 2014-10-29T06:41:22.000

Reputation: 391

Any restrictions around leading/trailing whitespace? – streetster – 2018-08-18T08:02:45.327

1@streetster No, none. Have a go at it :) – sampathsris – 2018-08-18T09:17:34.993

2

This is in the related posts on stack overflow: http://stackoverflow.com/q/5508110

– Level River St – 2014-10-29T11:26:21.277

What do you mean by ODD? – flawr – 2014-10-29T14:20:08.803

2@flawr I think it means odd, as in not an even number. – NinjaBearMonkey – 2014-10-29T14:28:53.957

31God I am stupid, I thought it was kind of an obscure computer scientist abbreviation=) – flawr – 2014-10-29T14:34:57.263

Is the shortest answer measured in bytes or characters? – jpjacobs – 2014-10-29T15:43:55.277

2@jpjacobs: Bytes, unless the question explicitly says otherwise. – Dennis – 2014-10-29T17:20:35.290

2Whole program or just a function? (real smart of me to answer first and make this question later...) – Rodolfo Dias – 2014-10-29T20:23:49.103

2Notice that letters are a knight's move apart in the pattern you need to print. So, every other column is empty. – xnor – 2014-10-30T00:59:58.590

1@krumia Congrats on posting a solid question as a first-time poster on PPCG! I hope you stick around. – xnor – 2014-10-31T01:07:18.003

@xnor That's not a knight's move, it's an elephant's move.

– Lily Chung – 2014-11-01T23:08:43.913

1I might be the first person in history to migrate a question here (although with some modifications). :D – sampathsris – 2014-11-01T23:47:33.720

Answers

13

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)))))

isaacg

Posted 2014-10-29T06:41:22.000

Reputation: 39 268

No bit complement in Pyth? – xnor – 2014-10-29T20:16:21.637

@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 – 2014-10-29T20:20:51.143

Vz is a neat trick: I didn't know that U<string> gave range(len(<string>)). – FryAmTheEggman – 2014-10-29T20:21:45.980

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 – 2014-10-29T20:23:56.790

20

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 

marinus

Posted 2014-10-29T06:41:22.000

Reputation: 30 224

7All of my upvotes belong to APL. – Nit – 2014-10-29T16:33:23.460

13

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

Falko

Posted 2014-10-29T06:41:22.000

Reputation: 5 307

I was just writing the same thing. My one improvement is i in[j,L+~j]. – xnor – 2014-10-29T07:08:51.460

@xnor: Found an even shorter condition. ;) – Falko – 2014-10-29T07:11:55.097

Clever. You can still do L+~j though. – xnor – 2014-10-29T07:12:43.243

@xnor: Ah, you're right. I always forget the +~ trick... – Falko – 2014-10-29T07:16:25.317

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 – 2014-10-29T07:20:55.690

@xnor: That's exactly what I thought of in that second! :) – Falko – 2014-10-29T07:22:16.303

11

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

xnor

Posted 2014-10-29T06:41:22.000

Reputation: 115 687

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 – 2014-10-29T13:37:53.580

@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 – 2014-10-29T14:48:10.713

@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 – 2014-10-29T14:51:41.787

Wow, even with Python 2 and print" ".join(a) your code is shorter (82) than mine. – Falko – 2014-10-29T16:19:53.860

@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 – 2014-10-29T20:03:17.640

8

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                              ";

Dennis

Posted 2014-10-29T06:41:22.000

Reputation: 196 637

1Sorry 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 – 2014-10-29T18:57:48.170

4

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

edc65

Posted 2014-10-29T06:41:22.000

Reputation: 31 086

2This doesn't have enough horizontal spacing - there should be columns of all spaces between each column with letters. – isaacg – 2014-10-29T20:06:52.660

4

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

britishtea

Posted 2014-10-29T06:41:22.000

Reputation: 1 189

7Congratulations 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.) – Martin Ender – 2014-10-29T15:19:19.463

2You can do -i-1 as the bit complement ~i. – xnor – 2014-10-29T20:05:47.730

That's very clever, thanks! – britishtea – 2014-10-29T20:48:25.120

2With 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} – Ventero – 2014-10-29T23:46:38.430

4

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":""));
    }
}

Geobits

Posted 2014-10-29T06:41:22.000

Reputation: 19 061

4

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}
}

Digital Trauma

Posted 2014-10-29T06:41:22.000

Reputation: 64 644

1Too 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. – manatwork – 2014-10-29T18:24:28.123

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 – Digital Trauma – 2014-10-29T18:28:56.853

4

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

Rip Leeb

Posted 2014-10-29T06:41:22.000

Reputation: 1 250

1And can't you make it function(s) since you don't recurse? – Zacharý – 2017-06-23T12:54:47.230

This does not have enough horizontal spacing. – Dennis – 2014-10-30T17:22:31.723

1

Wow, shorter than mine and not even using ES6. +1

– Scimonster – 2014-10-30T19:30:13.467

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 – 2014-10-31T01:06:30.377

4

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.

Kasran

Posted 2014-10-29T06:41:22.000

Reputation: 681

Note that the letters are separated with a blank column. Letters are relatively in L shape. – sampathsris – 2014-10-30T07:56:09.163

Drats! That complicated things rather significantly. I think I can salvage this, but it'll add to the ending size... oh well. – Kasran – 2014-10-30T17:30:34.563

3

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

Robert Hacken

Posted 2014-10-29T06:41:22.000

Reputation: 371

1

Sweet! And nice explanation.you can save 2 bytes

– JayCe – 2018-08-17T13:42:14.380

1looking 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 – 2018-08-17T13:54:02.770

@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 – 2018-08-17T14:25:04.870

89 bytes using pmax and inlining some more assignments. – Giuseppe – 2018-11-24T18:27:54.077

@Giuseppe Thanks! Sadly, still not enough to beat J.Doe's solution

– Robert Hacken – 2018-11-24T23:21:13.450

3

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

dzaima

Posted 2014-10-29T06:41:22.000

Reputation: 19 048

3

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.

Martin Ender

Posted 2014-10-29T06:41:22.000

Reputation: 184 808

My dear CJam, you've just got beaten by APL. ^_^ – None – 2014-10-29T11:09:08.937

@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 – 2014-10-29T11:13:10.627

2well, 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 – None – 2014-10-29T14:40:21.400

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 – 2014-10-30T09:42:26.157

3

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.

Level River St

Posted 2014-10-29T06:41:22.000

Reputation: 22 049

3

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

jpjacobs

Posted 2014-10-29T06:41:22.000

Reputation: 3 440

3

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).

kay - SE is evil

Posted 2014-10-29T06:41:22.000

Reputation: 230

2

Jelly, 11 bytes

LḶḤ⁶ẋ;"µ»ṚY

Try it online!

Erik the Outgolfer

Posted 2014-10-29T06:41:22.000

Reputation: 38 134

2

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!

user58120

Posted 2014-10-29T06:41:22.000

Reputation:

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 – 2018-08-17T06:14:32.203

-i-1 can be +~i – Jo King – 2018-08-17T06:24:16.847

2

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.

InvisiblePanda

Posted 2014-10-29T06:41:22.000

Reputation: 131

You can save two bytes by removing the spaces in for(;i < l;i++). – Beta Decay – 2014-10-29T09:34:14.340

Also, I use this for my byte counting.

– Beta Decay – 2014-10-29T09:36:14.343

@BetaDecay Ah great, I must have overlooked those. And thanks for the link! – InvisiblePanda – 2014-10-29T09:38:37.610

2

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

Scimonster

Posted 2014-10-29T06:41:22.000

Reputation: 2 905

http://codegolf.stackexchange.com/a/40594/26974 – sampathsris – 2014-10-29T10:39:23.023

I saw that one too. – Scimonster – 2014-10-29T10:40:33.210

2

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.

jcai

Posted 2014-10-29T06:41:22.000

Reputation: 973

2

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:)

V-X

Posted 2014-10-29T06:41:22.000

Reputation: 747

>

  • 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.
  • < – Dennis – 2014-10-30T17:19:55.537

    2

    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
    

    hmatt1

    Posted 2014-10-29T06:41:22.000

    Reputation: 3 356

    2

    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
    

    DarkAjax

    Posted 2014-10-29T06:41:22.000

    Reputation: 669

    2

    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 
    

    MickyT

    Posted 2014-10-29T06:41:22.000

    Reputation: 11 735

    1

    Charcoal, 9 7 17 10 bytes

    ↘S⟲OOLθUE¹
    

    +10 bytes because I missed the requirement of space-columns.
    -7 bytes thanks to @ASCII-only.

    Try it online (verbose) or try it only (pure).

    Challenges like this is why Charcoal was made.

    Explanation:

    Print the input-string in a down-right direction:

    Print(:DownRight, InputString());
    ↘S
    

    Rotate it 90 degree counterclockwise, and shift it up the length of the input-string amount of times with overlap:

    RotateOverlapOverlap(Length(q));
    ⟲OOLθ
    

    Put a space gap of size 1 between every column:

    Extend(1);
    UE¹
    

    Kevin Cruijssen

    Posted 2014-10-29T06:41:22.000

    Reputation: 67 575

    1It's not exactly diagonal. There should be an empty column between characters. – sampathsris – 2018-08-17T07:50:06.563

    1@Krumia Should be fixed now. – Kevin Cruijssen – 2018-08-17T08:09:49.783

    2

    @KevinCruijssen 10

    – ASCII-only – 2018-11-19T23:43:24.433

    @ASCII-only Thanks! Didn't knew about Extend, but it's just what was necessary here. – Kevin Cruijssen – 2018-11-20T07:36:30.617

    XD > try it only – ASCII-only – 2018-12-05T11:47:06.450

    @ASCII-only Ah oops, lol.. I'll just leave that in. ;p – Kevin Cruijssen – 2018-12-05T12:47:38.147

    1

    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
    

    mazzy

    Posted 2014-10-29T06:41:22.000

    Reputation: 4 832

    Since you can take input as a char-array (Meta post), that can save some bytes.

    – AdmBorkBork – 2018-08-20T13:21:30.237

    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 – mazzy – 2018-08-20T15:52:16.990

    1Aren't you crossing the wrong way? – streetster – 2018-08-21T07:16:17.777

    @streetster, you are best! I've updated the post. – mazzy – 2018-08-21T08:27:52.503

    1Oof, +8 bytes - sorry! – streetster – 2018-08-21T14:36:29.273

    But now the crossing is correct :) – mazzy – 2018-08-22T07:15:11.590

    1

    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.

    DLosc

    Posted 2014-10-29T06:41:22.000

    Reputation: 21 213

    1

    K (oK), 31 bytes

    Solution:

    `c$a||a:(2*#x)$(-1-2*!#x)$,:'x:
    

    Try it online!

    Explanation:

    Generate the diagonal, and or with the reverse of the diagonal

    `c$a||a:(2*#x)$(-1-2*!#x)$,:'x: / the solution
                                 x: / save input as x
                              ,:'   / enlist (,:) each-both (')
                             $      / pad (negative is right-pad)
                   (        )       / do this together
                          #x        / count (#) length of x
                         !          / range (!) 0..this count
                       2*           / double it
                    -1-             / subtract from -1
                  $                 / pad
            (    )                  / do this together
               #x                   / count (#) length of x
             2*                     / multiply by 2
          a:                        / save as a
         |                          / reverse (|) it
       a|                           / or (|) with a
    `c$                             / cast to characters                           
    

    streetster

    Posted 2014-10-29T06:41:22.000

    Reputation: 3 635

    1

    K4, 26 bytes

    Solution:

    a||a:(2*#x)$(-1-2*!#x)$$x:
    

    Explanation:

    Similar to my oK answer but a little shorter:

    a||a:(2*#x)$(-1-2*!#x)$$x: / the solution
                            x: / save input as x
                           $   / string ($) breaks into char lists
                          $    / cast ($)
                (        )     / do this together
                       #x      / count (#) length of x
                      !        / range (!) 0..this count
                    2*         / double it
                 -1-           / subtract from -1
               $               / pad
         (    )                / do this together
            #x                 / count (#) length of x
          2*                   / multiply by 2
       a:                      / save as a
      |                        / reverse (|) it
    a|                         / or (|) with a
    

    streetster

    Posted 2014-10-29T06:41:22.000

    Reputation: 3 635

    1

    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

    recursive

    Posted 2014-10-29T06:41:22.000

    Reputation: 8 616

    1

    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!

    J.Doe

    Posted 2014-10-29T06:41:22.000

    Reputation: 2 379

    Nice! Like me, you can save 2 bytes by using pmax (originally Giuseppe's suggestion).

    – Robert Hacken – 2018-11-24T23:10:16.080

    1This won't work with length 1 input. – Giuseppe – 2018-11-24T23:28:58.130

    1

    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);
    }
    

    bacchusbeale

    Posted 2014-10-29T06:41:22.000

    Reputation: 1 235

    Can you remove those newlines? – Zacharý – 2017-06-23T12:53:08.900

    Save 11 precious characters with t+=i==j?s[i]:i==n-j-1?s[n-i-1]:"";. – sampathsris – 2014-10-29T11:22:33.680

    1

    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.

    Rodolfo Dias

    Posted 2014-10-29T06:41:22.000

    Reputation: 3 940

    2Imports do count. This is partly because of Python's import-and-alias syntax: from math import floor as f which is a bit cheaty – None – 2014-10-29T15:54:07.987

    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 – 2014-10-30T16:29:11.663

    @DLosc Could you give me a few examples? – Rodolfo Dias – 2014-10-30T18:28:48.777

    1

    Yes, actually Geobits' answer is a perfect example--see the contents of the System.out.print call at the end.

    – DLosc – 2014-10-31T00:13:39.007

    See, replies like Geobits' make me feel like I know so little of Java. I was thinking about creating an empty String and appending to it the spaces and characters, using the System.out.println to output it only at the end. Oh well... – Rodolfo Dias – 2014-10-31T08:21:51.593

    1@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 – 2014-10-31T13:28:38.810

    1

    GolfScript 46 (DEMO)

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

    Cristian Lupascu

    Posted 2014-10-29T06:41:22.000

    Reputation: 8 369

    1

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

    RobIII

    Posted 2014-10-29T06:41:22.000

    Reputation: 397

    0

    PHP, 81 bytes

    for($k=strlen($s=$argn);$k;$t[2*$i]=$s[$i++],$t[2*--$k]=$s[$k],print"$t
    ")$t=" ";
    

    Run as pipe with -nR or try it online.

    Titus

    Posted 2014-10-29T06:41:22.000

    Reputation: 13 814

    -1

    C++:

    #include <iostream>
    #include <string>
    
    int main()
    {
        char a[] = {'P','R','O','G','R','A','M'};
        int length = sizeof(a)/sizeof(a[0]);
        int l = length - 1, i, j;
        for (i=0; i <= l; i++) {
            for (j=0; j <= l;j++) {
                if (j == i)
                    std::cout<<a[i];
                else if (i == l-j)
                    std::cout<<a[j];
                else
                    std::cout<<"s";
            }            
            std::cout<<"\n";
        }
    }
    

    user52864

    Posted 2014-10-29T06:41:22.000

    Reputation: 1

    2

    Welcome to PPCG! This is [tag:code-golf] which means that the goal is to solve the problem in as few bytes as code as possible. As per our help centre every answer should make a reasonable stab at the given winning criterion (within the limits of their language), which would mean at least removing unnecessary whitespace and using single-character variable names. You can always include a readable/"ungolfed" version in addition to the competitive one. Once you've done this, please also include the byte count of your code in the header.

    – Martin Ender – 2016-04-07T09:04:04.203

    And anyways, per the rules, using C++ is prohibited. – Zacharý – 2017-06-23T12:58:53.957