j - 是否有一种惯用的方式在 J 中对角打印向量(列表)或字符串?
问题描述
如果我有一个列表 a=:i.5,可以这样打印(对角线):
0
1
2
3
4
或者对于像'enigmatic'这样的字符串,可以生成'x'模式吗?
e e
n n
i i
g g
m
a a
t t
i i
c c
(此处发布的 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");
}
}
我猜#(长度)。您可以像这样垂直打印(在 J 中):
>/. 'hello'
h
e
l
l
o
提前致谢!
解决方案
一个相当惯用的观点是,
用空格填充每个数字,形成一个矩阵,然后shape $
适当地形成矩阵:
y =: '012345'
z =: #y
c =: '_' NB. fill character
(z,z)$,(c#~z),~"_ 0 y
0_____
_1____
__2___
___3__
____4_
_____5
要获得另一个对角线,您可以简单地使用 reflect |.
:
m
0_____
_1____
__2___
___3__
____4_
_____5
|."1 m
_____0
____1_
___2__
__3___
_4____
5_____
同样,您可以创建索引矩阵:
]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
然后将每个元素放置到位:
6 6 $ ,(ii + |."1 ii) { '_enigma'
e____e
_n__n_
__ii__
__gg__
_m__m_
a____a
推荐阅读
- javascript - Ajax Post 和检索多个变量
- hide - 在 Sugarcrm 中为所有用户隐藏产品目录标准小面板
- django - 在 Django 中加入超过 2 个表
- php - wp_login_form 隐藏重定向值
- python - peewee 非空约束失败,将 _id 添加到类
- android - Android:如何在变量中添加 5 次并获得它们的总秒数
- java - Java中的HTTP Post请求处理程序
- unity3d - 有没有办法统一覆盖动画过渡检查器窗口?
- sql - 检查列值以填充配置单元中的多个列
- node.js - 如何在 Node.js 中确定客户端操作系统