Is there an idiomatic way to print a vector(list) or a character string diagonally in J?

Viewed 119

if I have a list a=:i.5, can it be printed like this(diagonally):

0 
 1
  2
   3 
    4

or in the case of a string like 'enigmatic' can a 'x' pattern be generated?

e       e
 n     n
  i   i
   g g
    m
   a a
  t   t
 i     i
c       c

(C code is posted here for reference purpose only.)

    #include<stdio.h>
    #include<string.h>
    main()
    {
    int len, i, j;
    char str[100];
    printf("Enter a string with odd no. of characters to get X Pattern\n");
    gets(str);
    len = strlen(str);
    for(i = 0;i < len; i++)
    {
    for (j = 0; j<len; j++)
    if (i == j || i+j == len-1)   /* this is the condition for getting the 'x' shape */
   {
    printf("%c",str[i]);         /* print character at current string position */
    }
   else
   {
    printf(" ");
   }
  printf("\n");
    }
   }

I guess # (for length). You can print vertically like this (in J):

>/. 'hello'  
h
e
l
l
o

Thanks in advance!

2 Answers

A rather idiomatic view is to pad , each digit with spaces, form a matrix and then shape $ the matrix appropriately:

y =: '012345'
z =: #y
c =: '_'   NB. fill character
(z,z)$,(c#~z),~"_ 0 y

0_____
_1____
__2___
___3__
____4_
_____5

To get the other diagonal, you can simply use reflect |.:

m
  0_____
  _1____
  __2___
  ___3__
  ____4_
  _____5
|."1 m
  _____0
  ____1_
  ___2__
  __3___
  _4____
  5_____

Similarly, you may create index matrices:

   ]ii =: 6 6 $ ,(6#0),~"_ 0]>:i.6
1 0 0 0 0 0
0 2 0 0 0 0
0 0 3 0 0 0
0 0 0 4 0 0
0 0 0 0 5 0
0 0 0 0 0 6
   ]|."1 ii
0 0 0 0 0 1
0 0 0 0 2 0
0 0 0 3 0 0
0 0 4 0 0 0
0 5 0 0 0 0
6 0 0 0 0 0

and then put each element in place:

 6 6 $ ,(ii + |."1 ii) { '_enigma'
e____e
_n__n_
__ii__
__gg__
_m__m_
a____a

Maybe not as idiomatic, but another way that is bit more generic is to use monad }, as you can easily modify it to allow other patterns.

With two matrices to choose from:

    ] a=: ('_',: # #"0 1 ,.) 'enigma'
______
______
______
______
______
______

eeeeee
nnnnnn
iiiiii
gggggg
mmmmmm
aaaaaa

You can use a bitmap like:

    ]b=: (+|.) = i. # 'enigma'
1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

    b}a
e____e
_n__n_
__ii__
__gg__
_m__m_
a____a

} allows gerund form, so v1`v2} y is (v1 y)}(v2 y). As a tacit definition:

f=: ((+|.)@=@i.@#)`('_',: # #"0 1 ,.)}
f 'enigma'
Related