js、html字符串转矩阵2025-01-01

代码如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>文字字符串转矩阵</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <style>
        body {
            display: flex;
        }

        #inputCode {
            width: 45%;
        }

        .runButton {
            width: 8%;
            padding: 10px;
        }

        #result {
            width: 45%;
            padding: 10px;
            height: 500px;
            overflow-y: auto;
        }
    </style>
</head>

<body>
    <textarea id="inputCode"></textarea>
    <button class="runButton" id="runButton">转</button>
    <pre id="result"></pre>

    <script>
        /**
        * TextProcessor 类,用于处理文本相关操作
        */
        class TextProcessor {
            /**
             * 从每一行中删除尾随空格
             * @param {string} text - 要处理的文本
             * @returns {string} - 处理后的文本
             */
            static removeTrailingWhitespace(text) {
                // 将文本按换行符分割为行数组
                let lines = text.split('\n');
                // 使用 map 方法对每行进行处理,删除尾随空格
                let processedLines = lines.map(line => line.replace(/\s+$/, ''));
                // 将处理后的行数组重新组合为文本
                return processedLines.join('\n');
            }

            /**
             * 从文本中删除空行
             * @param {string} text - 要处理的文本
             * @returns {string} - 处理后的文本
             */
            static removeBlankLines(text) {
                // 将文本按换行符分割为行数组
                let lines = text.split('\n');
                // 使用 filter 方法筛选出非空行
                let nonBlankLines = lines.filter(line => line.trim().length > 0);
                // 将非空行数组重新组合为文本
                return nonBlankLines.join('\n');
            }

            /**
             * 综合处理文本,先删除行尾空白符,再删除空行
             * @param {string} text - 要处理的文本
             * @returns {string} - 最终处理后的文本
             */
            static processText(text) {
                // 先调用 removeTrailingWhitespace 方法删除行尾空白符
                let textWithoutTrailingWhitespace = this.removeTrailingWhitespace(text);
                // 再调用 removeBlankLines 方法删除空行
                return this.removeBlankLines(textWithoutTrailingWhitespace);
            }
        }

        /**
         * StringMatrixCreator 类,用于处理字符串相关操作
         */
        class StringMatrixCreator {
            /**
             * 构造函数,目前为空
             */
            constructor() { }

            /**
             * 计算字符串中的行数
             * @param {string} str - 输入的字符串
             * @returns {number} - 行数
             * @throws {Error} - 如果输入不是字符串,抛出错误
             */
            countLines(str) {
                if (typeof str !== 'string') {
                    throw new Error('输入必须是字符串');
                }
                return str.split('\n').length;
            }

            /**
             * 找出字符串中最长的行
             * @param {string} str - 输入的字符串
             * @returns {string} - 最长的行
             * @throws {Error} - 如果输入不是字符串,抛出错误
             */
            findLongestLine(str) {
                if (typeof str !== 'string') {
                    throw new Error('输入必须是字符串');
                }
                const lines = str.split('\n');
                let maxLength = 0;
                let longestLine = '';
                for (const line of lines) {
                    if (line.length > maxLength) {
                        maxLength = line.length;
                        longestLine = line;
                    }
                }
                return longestLine;
            }

            /**
             * 根据输入字符串创建矩阵
             * @param {string} str - 输入的字符串
             * @returns {string[]} - 表示矩阵的字符串数组
             * @throws {Error} - 如果输入不是字符串,抛出错误
             */
            createMatrix(str) {
                if (typeof str !== 'string') {
                    throw new Error('输入必须是字符串');
                }
                const numLines = this.countLines(str);
                console.log('确定行数:', numLines);
                const longestLine = this.findLongestLine(str);
                const colCount = longestLine.length;
                console.log('确定列数:', colCount);
                const matrix = [];
                const lines = str.split('\n');
                for (const line of lines) {
                    const paddingLength = colCount - line.length;
                    const paddedLine = line + '※'.repeat(paddingLength);
                    matrix.push(paddedLine);
                }
                return matrix;
            }
        }


        document.getElementById('runButton').addEventListener('click', () => {


            try {
                const creator = new StringMatrixCreator();
                const outputDiv = document.getElementById('result');
                const inputString = document.getElementById('inputCode').value;

                let processedMultiLineText = TextProcessor.processText(inputString);
                console.log('处理后的文本:');
                console.log(processedMultiLineText);
                //console.log('转为矩阵后:');
                const mymatrix = creator.createMatrix(processedMultiLineText);



                // 输出矩阵的行数和列数
                const rows = mymatrix.length;
                const cols = mymatrix[0] ? mymatrix[0].length : 0;
                console.log(`实际矩阵行数列数: ${rows},  ${cols}`);


                const validator = new MatrixValidator(mymatrix);
                const isReal = validator.isRealMatrix();
                console.log(`矩阵是否为实矩阵: ${isReal}`);

                // 逆时针旋转90°
                const matrix2 = transposeAndReorderMatrix(mymatrix);
                // 遍历并打印转置和重新排序后的矩阵的每一行
                matrix2.forEach(row => {
                    console.log(`[${row.join(',')}]`)
                });



                // 将矩阵内容输出到 outputDiv
                outputDiv.innerHTML = mymatrix.map(row => `${row}`).join('\n');
            } catch (error) {
                console.error(error.message);
            }
        });

        class MatrixValidator {
            constructor(mymatrix) {
                this.mymatrix = mymatrix;
            }

            //定义:如果矩阵的每个元素都是非空字符串,也不是空白符,就称这个矩阵为“实矩阵”。

            isRealMatrix() {
                for (let row of this.mymatrix) {
                    for (let element of row) {
                        if (typeof element !== 'string' || element.trim() === '') {
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        /**
         * 函数用于对给定的矩阵进行转置和列的逆序排列。看起来像是被逆时针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
        }
    </script>
</body>

</html>

运行结果:


测试结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容