Search code examples
j

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


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!


Solution

  • 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'