原始的文字格式需要满足一定格式:
符合n排m列的格式,缺少的每个字,必须使用一个空格代替。
JavaScript代码如下:
/**
* 函数用于将输入的文本转换为一个二维字符矩阵
* 文字格式要符合n排m列的格式,缺一个字,必须使用一个空格代替
* @param text
* @returns matrix
*/
function mapChineseCharacters(text) {
// 将文本按空格分割后再用 '※' 连接,然后按换行符分割
const lines = text.split(' ').join('※').split('\n');
// 获取分割后的行数
const rows = lines.length;
// 获取第一行的长度作为列数
const cols = lines[0].length;
const result = [];
// 遍历每一行
for(let i = 0; i < rows; i++) {
const row = [];
// 遍历每一列
for(let j = 0; j < cols; j++) {
// 如果当前位置的字符未定义,打印错误信息
if(lines[i][j] === undefined) {
console.log('undefined!文字格式不符合要求')
}
// 将当前位置的字符添加到当前行的数组中
row.push(lines[i][j])
}
// 将当前行添加到结果数组中
result.push(row)
}
// 返回结果数组
return result
}
/**
* 函数用于对给定的矩阵进行转置和列的逆序排列。看起来像是被逆时针90°了。
* @param matrix
* @returns 转置后的矩阵
*/
function transposeAndReorderMatrix(matrix) {
// 获取矩阵的行数
const rows = matrix.length;
// 获取矩阵的列数
const cols = matrix[0].length;
const result = [];
// 从最后一列开始倒序遍历列
for(let j = cols - 1; j >= 0; j--) {
const newRow = [];
// 遍历每一行
for(let i = 0; i < rows; i++) {
// 将原矩阵中对应位置的元素添加到新行中
newRow.push(matrix[i][j])
}
// 将新行添加到结果数组中
result.push(newRow)
}
// 返回结果矩阵
return result
}
// 定义一个包含中文字符的文本
const text = `出戌大巳巳用喜
行时吉未时丑神
五日是时亦时东
鬼破日向吉天北
死凶午上出乙方
门酉时列行贵贵
同时五各宜人神
在截不方用上西
东路遇迎子吉南
南空申喜丑子方
方亡时神寅寅炷
勿不月贵卯卯香
向宜破神辰辰宜`;
// 调用 mapChineseCharacters 函数处理文本,并得到映射后的矩阵
const mappedMatrix = mapChineseCharacters(text);
// 对映射后的矩阵调用 transposeAndReorderMatrix 函数进行转置和重新排序
const matrix2 = transposeAndReorderMatrix(mappedMatrix);
// 遍历并打印映射后的矩阵的每一行
mappedMatrix.forEach(row => {
console.log(`[${row.join(',')}]`)
});
// 遍历并打印转置和重新排序后的矩阵的每一行
matrix2.forEach(row => {
console.log(`[${row.join(',')}]`)
});
运行结果:

运行结果