[英]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):如果我有一个列表 a=:i.5,可以这样打印(对角线):
0
1
2
3
4
or in the case of a string like 'enigmatic' can a 'x' pattern be generated?或者对于像'enigmatic'这样的字符串,可以生成'x'模式吗?
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.) (此处发布的 C 代码仅供参考。)
#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):
您可以像这样垂直打印(在 J 中):
>/. 'hello'
h
e
l
l
o
Thanks in advance!提前致谢!
A rather idiomatic view is to pad ,
each digit with spaces, form a matrix and then shape $
the matrix appropriately:一个相当惯用的观点是用空格填充每个数字
,
形成一个矩阵,然后适当地shape $
矩阵:
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.也许不是惯用的,但另一种更通用的方法是使用 monad
}
,因为您可以轻松修改它以允许其他模式。
With two matrices to choose from:有两个矩阵可供选择:
] a=: ('_',: # #"0 1 ,.) 'enigma'
______
______
______
______
______
______
eeeeee
nnnnnn
iiiiii
gggggg
mmmmmm
aaaaaa
You can use a bitmap like:您可以使用 bitmap 像:
]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)
. }
允许动名词形式,所以v1`v2} y
是(v1 y)}(v2 y)
。 As a tacit definition:作为一个默认定义:
f=: ((+|.)@=@i.@#)`('_',: # #"0 1 ,.)}
f 'enigma'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.