js惨寿、html字符串轉(zhuǎn)矩陣2025-01-01

代碼如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>文字字符串轉(zhuǎn)矩陣</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">轉(zhuǎn)</button>
    <pre id="result"></pre>

    <script>
        /**
        * TextProcessor 類,用于處理文本相關(guān)操作
        */
        class TextProcessor {
            /**
             * 從每一行中刪除尾隨空格
             * @param {string} text - 要處理的文本
             * @returns {string} - 處理后的文本
             */
            static removeTrailingWhitespace(text) {
                // 將文本按換行符分割為行數(shù)組
                let lines = text.split('\n');
                // 使用 map 方法對(duì)每行進(jìn)行處理迹炼,刪除尾隨空格
                let processedLines = lines.map(line => line.replace(/\s+$/, ''));
                // 將處理后的行數(shù)組重新組合為文本
                return processedLines.join('\n');
            }

            /**
             * 從文本中刪除空行
             * @param {string} text - 要處理的文本
             * @returns {string} - 處理后的文本
             */
            static removeBlankLines(text) {
                // 將文本按換行符分割為行數(shù)組
                let lines = text.split('\n');
                // 使用 filter 方法篩選出非空行
                let nonBlankLines = lines.filter(line => line.trim().length > 0);
                // 將非空行數(shù)組重新組合為文本
                return nonBlankLines.join('\n');
            }

            /**
             * 綜合處理文本砸彬,先刪除行尾空白符,再刪除空行
             * @param {string} text - 要處理的文本
             * @returns {string} - 最終處理后的文本
             */
            static processText(text) {
                // 先調(diào)用 removeTrailingWhitespace 方法刪除行尾空白符
                let textWithoutTrailingWhitespace = this.removeTrailingWhitespace(text);
                // 再調(diào)用 removeBlankLines 方法刪除空行
                return this.removeBlankLines(textWithoutTrailingWhitespace);
            }
        }

        /**
         * StringMatrixCreator 類斯入,用于處理字符串相關(guān)操作
         */
        class StringMatrixCreator {
            /**
             * 構(gòu)造函數(shù)砂碉,目前為空
             */
            constructor() { }

            /**
             * 計(jì)算字符串中的行數(shù)
             * @param {string} str - 輸入的字符串
             * @returns {number} - 行數(shù)
             * @throws {Error} - 如果輸入不是字符串,拋出錯(cuò)誤
             */
            countLines(str) {
                if (typeof str !== 'string') {
                    throw new Error('輸入必須是字符串');
                }
                return str.split('\n').length;
            }

            /**
             * 找出字符串中最長(zhǎng)的行
             * @param {string} str - 輸入的字符串
             * @returns {string} - 最長(zhǎng)的行
             * @throws {Error} - 如果輸入不是字符串刻两,拋出錯(cuò)誤
             */
            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;
            }

            /**
             * 根據(jù)輸入字符串創(chuàng)建矩陣
             * @param {string} str - 輸入的字符串
             * @returns {string[]} - 表示矩陣的字符串?dāng)?shù)組
             * @throws {Error} - 如果輸入不是字符串增蹭,拋出錯(cuò)誤
             */
            createMatrix(str) {
                if (typeof str !== 'string') {
                    throw new Error('輸入必須是字符串');
                }
                const numLines = this.countLines(str);
                console.log('確定行數(shù):', numLines);
                const longestLine = this.findLongestLine(str);
                const colCount = longestLine.length;
                console.log('確定列數(shù):', 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('轉(zhuǎn)為矩陣后:');
                const mymatrix = creator.createMatrix(processedMultiLineText);



                // 輸出矩陣的行數(shù)和列數(shù)
                const rows = mymatrix.length;
                const cols = mymatrix[0] ? mymatrix[0].length : 0;
                console.log(`實(shí)際矩陣行數(shù)列數(shù): ${rows},  ${cols}`);


                const validator = new MatrixValidator(mymatrix);
                const isReal = validator.isRealMatrix();
                console.log(`矩陣是否為實(shí)矩陣: ${isReal}`);

                // 逆時(shí)針旋轉(zhuǎn)90°
                const matrix2 = transposeAndReorderMatrix(mymatrix);
                // 遍歷并打印轉(zhuǎn)置和重新排序后的矩陣的每一行
                matrix2.forEach(row => {
                    console.log(`[${row.join(',')}]`)
                });



                // 將矩陣內(nèi)容輸出到 outputDiv
                outputDiv.innerHTML = mymatrix.map(row => `${row}`).join('\n');
            } catch (error) {
                console.error(error.message);
            }
        });

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

            //定義:如果矩陣的每個(gè)元素都是非空字符串,也不是空白符磅摹,就稱這個(gè)矩陣為“實(shí)矩陣”滋迈。

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

        /**
         * 函數(shù)用于對(duì)給定的矩陣進(jìn)行轉(zhuǎn)置和列的逆序排列∑浚看起來(lái)像是被逆時(shí)針90°了杀怠。
         * @param matrix 
         * @returns 轉(zhuǎn)置后的矩陣
         */
        function transposeAndReorderMatrix(matrix) {
            // 獲取矩陣的行數(shù)
            const rows = matrix.length;
            // 獲取矩陣的列數(shù)
            const cols = matrix[0].length;
            const result = [];
            // 從最后一列開始倒序遍歷列
            for (let j = cols - 1; j >= 0; j--) {
                const newRow = [];
                // 遍歷每一行
                for (let i = 0; i < rows; i++) {
                    // 將原矩陣中對(duì)應(yīng)位置的元素添加到新行中
                    newRow.push(matrix[i][j])
                }
                // 將新行添加到結(jié)果數(shù)組中
                result.push(newRow)
            }
            // 返回結(jié)果矩陣
            return result
        }
    </script>
</body>

</html>

運(yùn)行結(jié)果:


測(cè)試結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末椰憋,一起剝皮案震驚了整個(gè)濱河市厅克,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌橙依,老刑警劉巖证舟,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異窗骑,居然都是意外死亡女责,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門创译,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)抵知,“玉大人,你說(shuō)我怎么就攤上這事∷⑾玻” “怎么了残制?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)掖疮。 經(jīng)常有香客問(wèn)我初茶,道長(zhǎng),這世上最難降的妖魔是什么浊闪? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任恼布,我火速辦了婚禮,結(jié)果婚禮上搁宾,老公的妹妹穿的比我還像新娘折汞。我一直安慰自己,他們只是感情好盖腿,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布字支。 她就那樣靜靜地躺著,像睡著了一般奸忽。 火紅的嫁衣襯著肌膚如雪堕伪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天栗菜,我揣著相機(jī)與錄音欠雌,去河邊找鬼。 笑死疙筹,一個(gè)胖子當(dāng)著我的面吹牛富俄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播而咆,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼霍比,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了暴备?” 一聲冷哼從身側(cè)響起悠瞬,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎涯捻,沒想到半個(gè)月后浅妆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡障癌,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年凌外,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涛浙。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡康辑,死狀恐怖摄欲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情疮薇,我是刑警寧澤蒿涎,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站惦辛,受9級(jí)特大地震影響劳秋,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜胖齐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一玻淑、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧呀伙,春花似錦补履、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至雨女,卻和暖如春谚攒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背氛堕。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工馏臭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人讼稚。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓括儒,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親锐想。 傳聞我的和親對(duì)象是個(gè)殘疾皇子帮寻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容