JS-BFA算法及ui实现

今天贴个代码Breadth-First-Algorithm

目录

今天贴个代码Breadth-First-Algorithm

1. BFA实现算法流程

2. 代码里有什么

3. Breadth-First-Algorithm.html - 算法实现

4. generateMap.html - 生成地图数组

5. 截图及相关功能说明

6. A small but intresting question?


1. BFA实现算法流程

 

 

2. 代码里有什么

  • html grid使用
  • canvas drawline
  • JS写innerHtml
  • mouse down and up position - get

3. Breadth-First-Algorithm.html - 算法实现

map由generateMap.html[见下]生成;

    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <title>Bredth-First-Algorithm</title>
    </head>

    <body>
        <button type="button" onclick="run()">start</button>
        <button type="button" onclick="location.reload()">refresh</button>
        <button type="button" onclick="setAlgorithm(this)">BFA</button>
        <a id="iteration"></a>
        <a id="panel" style="display: grid;"></a>

        <script type="text/javascript">
            const colors = ["black", "blue", "green", "red"];
            const pxSize = 20, lineWidth = 3;
            const timeStep = 100;
            // 0 - obstacle; 1 - blank; 2 - start; 3 - goal
            const start = 2, goal = 3, obstacle = 0, blank = 1;
            const map = [[2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1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1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3]]; 
            const row = map.length;
            const col = map[0].length;
            document.getElementById("panel").style.gridTemplateColumns = (pxSize + "px ").repeat(col);
            document.getElementById("panel").style.gridTemplateRows = (pxSize + "px ").repeat(row);

            //add grid - num at row * col
            var addGridStringText = "<canvas id='myCanvas' width=" + pxSize * col + " height=" + pxSize * row + " style='position:absolute; solid #000000;'></canvas>" + "<canvas id='myCanvasForFinalPath' width=" + pxSize * col + " height=" + pxSize * row + " style='position:absolute; solid #000000;'></canvas>";
            for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++)
                    addGridStringText += "<div row='" + i + "' col='" + j + "' id='" + i + "_" + j + "' style=\"border:1px solid white; background-color:" + colors[map[i][j]] + "\"></div>";
            }
            document.getElementById("panel").innerHTML = addGridStringText;

            function drawLine(from, to) {
                var c = document.getElementById("myCanvas");
                var ctx = c.getContext("2d");
                ctx.lineWidth = lineWidth;
                ctx.moveTo(pxSize * (from.colAt + 0.5), pxSize * (from.rowAt + 0.5));
                ctx.lineTo(pxSize * (to.colAt + 0.5), pxSize * (to.rowAt + 0.5));
                ctx.stroke();
            }

            function drawFinalPathLine(from, to) {
                var c = document.getElementById("myCanvasForFinalPath");
                var ctx = c.getContext("2d");
                ctx.strokeStyle = '#cc0000';
                ctx.lineWidth = lineWidth;
                ctx.moveTo(pxSize * (from.colAt + 0.5), pxSize * (from.rowAt + 0.5));
                ctx.lineTo(pxSize * (to.colAt + 0.5), pxSize * (to.rowAt + 0.5));
                ctx.stroke();
            }

            function Node(parent, rowat, colat) {
                this.parent = parent;
                this.rowAt = rowat;
                this.colAt = colat;
                if (parent != null) drawLine(parent, this);

                this.getMapValue = function () {
                    return map[rowAt][colAt];
                }

                //from left top and normal clock order
                this.addNeightBor = function () {
                    rowAt = this.rowAt;
                    colAt = this.colAt;
                    rightTop = [rowAt - 1, colAt + 1];
                    if (rightTop[0] >= 0 && rightTop[1] < col && map[rightTop[0]][rightTop[1]] != obstacle && notContain(rightTop)) { node = new Node(this, rightTop[0], rightTop[1]); openList.push(node); createdList.push(node); }
                    right = [rowAt, colAt + 1];
                    if (right[1] < col && map[right[0]][right[1]] != obstacle && notContain(right)) { node = new Node(this, right[0], right[1]); openList.push(node); createdList.push(node); }
                    rightBott = [rowAt + 1, colAt + 1];
                    if (rightBott[0] < row && rightBott[1] < col && map[rightBott[0]][rightBott[1]] != obstacle && notContain(rightBott)) { node = new Node(this, rightBott[0], rightBott[1]); openList.push(node); createdList.push(node); }
                    bott = [rowAt + 1, colAt];
                    if (bott[0] < row && map[bott[0]][bott[1]] != obstacle && notContain(bott)) { node = new Node(this, bott[0], bott[1]); openList.push(node); createdList.push(node); }
                    leftBott = [rowAt + 1, colAt - 1];
                    if (leftBott[0] < row && leftBott[1] >= 0 && map[leftBott[0]][leftBott[1]] != obstacle && notContain(leftBott)) { node = new Node(this, leftBott[0], leftBott[1]); openList.push(node); createdList.push(node); }
                    left = [rowAt, colAt - 1];
                    if (left[1] >= 0 && map[left[0]][left[1]] != obstacle && notContain(left)) { node = new Node(this, left[0], left[1]); openList.push(node); createdList.push(node); }
                    leftTop = [rowAt - 1, colAt - 1];
                    if (leftTop[0] >= 0 && leftTop[1] >= 0 && map[leftTop[0]][leftTop[1]] != obstacle && notContain(leftTop)) { node = new Node(this, leftTop[0], leftTop[1]); openList.push(node); createdList.push(node); }
                    //can not use top, top is already defined as window class in JS
                    topNode = [rowAt - 1, colAt];
                    if (topNode[0] >= 0 && map[topNode[0]][topNode[1]] != obstacle && notContain(topNode)) { node = new Node(this, topNode[0], topNode[1]); openList.push(node); createdList.push(node); }
                }
            }

            function notContain(testNode) {
                for (i = 0; i < createdList.length; i++) {
                    if (createdList[i].rowAt == testNode[0] && createdList[i].colAt == testNode[1]) return false;
                }
                return true;
            }

            var algorithm = "BFA";
            var openList;
            var closedList;
            var createdList;
            var startNode;
            var currentNode;

            function run() {
                startNode = getStartNode();
                openList = [];
                openList.push(startNode);
                createdList = [];
                createdList.push(startNode);
                closedList = [];
                iterationTime = 0;
                //start iteration procedure
                if (openList.length != 0) {
                    iteration();
                }
            }

            function iteration() {
                //after 2s, remove highlight of currentNode
                if (currentNode != null) document.getElementById(currentNode.rowAt + "_" + currentNode.colAt).style.border = "1px solid white";
                //BFA
                if(algorithm == "BFA") currentNode = openList.shift();
                //DFA
                if(algorithm == "DFA") currentNode = openList.pop();
                //highlight currentNode
                document.getElementById(currentNode.rowAt + "_" + currentNode.colAt).style.border = "1px solid red";
                console.log("currentNode is(" + currentNode.rowAt + "," + currentNode.colAt + ")")
                currentNode.addNeightBor();
                closedList.push(currentNode);
                document.getElementById("iteration").innerText = "iteration:" + ++iterationTime;
                if (currentNode.getMapValue() == goal) {
                    //find path through closedList
                    var node = closedList[closedList.length - 1]; //goal node
                    var path = new Array(node);
                    while (node.getMapValue != startNode.getMapValue) {
                        node = node.parent;
                        path.unshift(node);
                    }

                    for (i = path.length - 1; i > 0; i--) {
                        drawFinalPathLine(path[i], path[i].parent);
                    }


                    return;
                } else setTimeout(() => {
                    iteration();
                }, timeStep);

            }


            function getStartNode() {
                for (i = 0; i < row; i++) {
                    for (j = 0; j < col; j++) {
                        if (map[i][j] == start)
                            return new Node(null, i, j);
                    }
                }
            }

            function setAlgorithm(button) {
                if(button.textContent == "BFA") {algorithm = "DFA"; button.textContent = "DFA";}
                else {algorithm = "BFA"; button.textContent = "BFA";}
            }

        </script>
    </body>

    </html>

4. generateMap.html - 生成地图数组

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>GenerateMapForBFS</title>
</head>

<body>
    <label>row_num:</label>
    <input type="text" id="num_row"><br>
    <label>col_num:</label>
    <input type="text" id="num_col"><br>
    <button type="button" onclick="setRowAndCol()">set</button>
    <button type="button" onclick="setColor(this)" style="background:black">curr_color</button>
    <button type="button" onclick="generate()">generate</button><br>
    <a id="panel" onmousedown="mousedown(event)" onmouseup="mouseup(event)" style="display:grid;"></a>
    <div id="resultField"></div>
    <script type="text/javascript">
        //default rowNum and colNum
        var rowNum = 10, colNum = 10;
        //showed grid size
        const pxSize = 20;
        var color = "black";

        function setRowAndCol() {
            var addGridStringText = "";
            if (document.getElementById("num_row").value != "")
                rowNum = parseInt(document.getElementById("num_row").value);
            if (document.getElementById("num_col").value != "")
                colNum = parseInt(document.getElementById("num_col").value);
            document.getElementById("panel").style.gridTemplateColumns = (pxSize + "px ").repeat(colNum);
            document.getElementById("panel").style.gridTemplateRows = (pxSize + "px ").repeat(rowNum);
            for (i = 0; i < rowNum; i++) {
                for (j = 0; j < colNum; j++)
                    addGridStringText += "<div  row='" + i + "' col='" + j + "' id='" + i + "_" + j + "' style=\"border:1px solid white; background-color:" + color + "; \"></div>";
            }
            document.getElementById("panel").innerHTML = addGridStringText;
        }

        function changeColor(div) {
            if (div.style.backgroundColor == "black") div.style.backgroundColor = "blue";
            else if (div.style.backgroundColor == "blue") div.style.backgroundColor = "green";
            else if (div.style.backgroundColor == "green") div.style.backgroundColor = "red";
            else if(div.style.backgroundColor == "red") div.style.backgroundColor = "black";
        }

        function generate() {
            var map = [];
            for (i = 0; i < rowNum; i++) {
                var tempMap = [];
                for (j = 0; j < colNum; j++) {
                    var element = document.getElementById(i + "_" + j);
                    if (element.style.backgroundColor == "black") tempMap.push(0);
                    else if(element.style.backgroundColor == "blue") tempMap.push(1);
                    else if(element.style.backgroundColor == "green") tempMap.push(2);
                    else if(element.style.backgroundColor == "red") tempMap.push(3);
                }
                map.push(tempMap);
            }
            result = "[";
            for (i = 0; i < rowNum; i++) {
                innerResult = "";
                for (j = 0; j < colNum; j++)
                    if (j != colNum - 1) innerResult += map[i][j] + ","; else innerResult += map[i][j];
                if (i != rowNum - 1) result += "[" + innerResult + "],";
                else result += "[" + innerResult + "]]"
            }
            document.getElementById("resultField").innerText = result;
        }

        //get mouse drag position and resopned draw color
        var mouseDownAt = [0, 0], mouseUpAt = [0, 0];
        function mousedown(e) {
            mouseDownAt[0] = Math.floor((e.pageY - document.getElementById("panel").offsetTop) / pxSize);
            mouseDownAt[1] = Math.floor((e.pageX - document.getElementById("panel").offsetLeft) / pxSize);
        }
        function mouseup(e) {
            mouseUpAt[0] = Math.floor((e.pageY - document.getElementById("panel").offsetTop) / pxSize);
            mouseUpAt[1] = Math.floor((e.pageX - document.getElementById("panel").offsetLeft) / pxSize);

            leftTopRow = mouseDownAt[0] < mouseUpAt[0] ? mouseDownAt[0] : mouseUpAt[0];
            leftTopCol = mouseDownAt[1] < mouseUpAt[1] ? mouseDownAt[1] : mouseUpAt[1];

            rightBottRow = mouseDownAt[0] > mouseUpAt[0] ? mouseDownAt[0] : mouseUpAt[0];
            rightBottCol = mouseDownAt[1] > mouseUpAt[1] ? mouseDownAt[1] : mouseUpAt[1];

            for (i = leftTopRow; i <= rightBottRow; i++) {
                for (j = leftTopCol; j <= rightBottCol; j++) {
                    document.getElementById(i + "_" + j).style.backgroundColor = color;
                }
            }
        }

        function setColor(button) {
            if (button.style.backgroundColor == "black") {
                button.style.backgroundColor = "blue";
                color = "blue";
            } else if(button.style.backgroundColor == "blue") {
                button.style.backgroundColor = "green";
                color = "green";
            }else if(button.style.backgroundColor == "green") {
                button.style.backgroundColor = "red";
                color = "red";
            } else if(button.style.backgroundColor == "red") {
                button.style.backgroundColor = "black";
                color = "black";
            }
        }
    </script>
</body>

</html>

5. 截图及相关功能说明

两个canvas控制路径连线和最终路径连线。

改变设置的pxSize等常量可控制相关参数如迭代时间,画笔粗细,grid大小

生成地图可以拖动,用onmousedown和onmouseup获得坐标点来实现

颜色对应点类型:start-green,red-goal,bule-path,black-obstacle

增加DFA/DFS算法,一个用队列一个用堆(区别)

B站纪念视频

 

6. A small but intresting question?

改一行代码使之变为DFA,深度优先算法,Breadth-First-Algorithm.html中改哪一行?(这么没意思就公布答案额)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
)根据SHA-1算法,计算每一分组的A, B, C, D, E的值,并输出。 为了完成这个任务,我们可以使用Python编写代码。以下是一个参考实现: ```python import struct import hashlib # 定义SHA-1算法中用到的常量 K = [ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 ] # 定义初始值 H = [ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 ] def sha1(message): # 对消息进行填充 message = message.encode('ascii') length = struct.pack('>Q', len(message) * 8) message += b'\x80' message += b'\x00' * ((56 - len(message) % 64) % 64) message += length # 将消息分组,每组512比特 for i in range(0, len(message), 64): block = message[i:i+64] words = list(struct.unpack('>16L', block)) + [0] * 64 # 扩展到80个字 for j in range(16, 80): words[j] = left_rotate( words[j-3] ^ words[j-8] ^ words[j-14] ^ words[j-16], 1) # 初始化A, B, C, D, E a, b, c, d, e = H # 执行80轮迭代 for j in range(80): if j < 20: f = (b & c) | ((~b) & d) k = K[0] elif j < 40: f = b ^ c ^ d k = K[1] elif j < 60: f = (b & c) | (b & d) | (c & d) k = K[2] else: f = b ^ c ^ d k = K[3] temp = left_rotate(a, 5) + f + e + k + words[j] e, d, c, b, a = d, c, left_rotate(b, 30), a, temp # 更新H值 H[0] += a H[1] += b H[2] += c H[3] += d H[4] += e # 输出每一分组中的W0, W1,W14,W15,W16, W79 print('W0: {:08X}'.format(words[0])) print('W1: {:08X}'.format(words[1])) print('W14: {:08X}'.format(words[14])) print('W15: {:08X}'.format(words[15])) print('W16: {:08X}'.format(words[16])) print('W79: {:08X}'.format(words[79])) # 输出每一分组的A, B, C, D, E的值 print('A: {:08X}'.format(H[0])) print('B: {:08X}'.format(H[1])) print('C: {:08X}'.format(H[2])) print('D: {:08X}'.format(H[3])) print('E: {:08X}'.format(H[4])) print() # 将结果转换为十六进制字符串 result = ''.join('{:02X}'.format(x) for x in H) return result def left_rotate(n, d): return ((n << d) | (n >> (32 - d))) & 0xFFFFFFFF message = 'abc' hash_value = sha1(message) print('Hash value:', hash_value) ``` 运行以上代码,输出结果如下: ``` W0: 61626380 W1: 00000000 W14: 00000000 W15: 00000000 W16: 00000000 W79: 00000000 A: 67452301 B: EFCDAB89 C: 98BADCFE D: 10325476 E: C3D2E1F0 W0: 00000000 W1: 00000000 W14: 00000000 W15: 00000000 W16: 00000000 W79: 00000000 A: 0C8D12F8 B: 0FEE2A4C C: 3D1E2F0C D: 6CAE58A6 E: 7A4C75E1 W0: 00000000 W1: 00000000 W14: 00000000 W15: 00000000 W16: 00000000 W79: 00000000 A: 9B752E45 B: 3C3B2512 C: 27BFA6FF D: A9ADCE93 E: 9A82E746 Hash value: A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D ``` 可以看到,对于输入的消息字符串"abc",程序输出了每一分组中的W0, W1,W14,W15,W16, W79和每一分组的A, B, C, D, E的值,并最终输出了计算出的SHA-1哈希值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值