codefreecamp-Basic Algorithm Scripting

本文介绍了一系列JavaScript编程技巧,包括回文检查、查找最长单词、标题化句子等实用功能的实现方式,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Check for Palindromes  
    function palindrome(str) {
        var s,s1;
        s=s1=str.replace(/[\s,.(\)\\/\-_]/g,"").toLowerCase();

        var arr=s1.split("").reverse().join("");
        // Good luck!
        console.log(s1);
        if(arr==s)
            return true;
        else
            return false;
    }
    palindrome(eye);
//Find the Longest Word in a String 
    function findLongestWord(str) {
        var arr=[];
        var _=str.split(" ");
        for(var i=0;i<_.length;i++){
            arr.push(_[i].length);
        }
        console.log(arr);
        return Math.max.apply(null,arr);
    }

    findLongestWord("The quick brown fox jumped over the lazy dog");
//Title Case a Sentence 
    function titleCase(str) {
        var arr=str.split(" ");
        console.log(arr);

        arr=arr.map(function(x){
            return x.toLowerCase().replace(/()/,function(v){
                return v.toUpperCase();});
        });
        return arr.join(" ");
    }

    titleCase("I'm a little tea pot");
 //Return Largest Numbers in Arrays
 //右边大数组中包含了4个小数组,分别找到每个小数组中的最大值,然后把它们串联起来,形成一个新数组
    function largestOfFour(arr) {
        // You can do this!
        var _=[];
        for(var i=0;i<arr.length;i++){
            _.push(Math.max.apply(null,arr[i]));
        }
        return _;
    }

    largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//Confirm the Ending
    function confirmEnding(str, target) {
        // "Never give up and good luck will find you."
        // -- Falcor
        var len=target.length;
        if(target==str.substr(-len)){
            return true;
        }else{
            return false;
        }
    }

    confirmEnding("Bastian", "n");
//Repeat a string repeat a string
    function repeat(str, num) {
        // repeat after me
        var s=str;
        var s1="";
        if(num>=0){
            for(var i=0;i<num;i++){
                s1+=s;
            }
            return s1;
        }else{
            return "";

        }
    }

    repeat("abc", 3);
//Truncate a string  
    function truncate(str, num) {
        // Clear out that junk in your trunk
        var s=str;
        var len=str.length;
        if(len>num){
            if(num>3){
                s=str.slice(0,num-3)+"...";
            }else{
                s=str.slice(0,num)+"...";
            }
        }else{
            console.log(s);
            return s;
        }

        return s;
    }

    truncate("A-tisket a-tasket A green and yellow basket", 11);
//Chunky Monkey  数组切割
    function chunk(arr, size) {
        // Break it up
        var count=arr.length%size == 0 ? arr.length / size : Math.floor(arr.length / size) +1;
        var _arr=[];
        for(var i=0;i<count;i++){
            _arr.push(arr.slice(size*i,size*(i+1)));
        }
        console.log(_arr);
        return _arr;
    }

    chunk(["a", "b", "c", "d"], 2);
//Slasher Flick  截断数组,返回截断后的数组
    function slasher(arr, howMany) {
        // it doesn't always pay to be first

        var newArr=arr;
        if(howMany>0){
            newArr.splice(0,howMany);//splice改变了原数组,现在结果是[3],返回的是[1,2]
            return newArr;
        }else
            return newArr;
    }

    slasher([1, 2, 3], 2);
//Mutations   如果数组第一个字符串元素包含了第二个字符串元素的所有字符,函数返回true。
    function mutation(arr) {
        var s1=arr[0].toLowerCase();
        var s2=arr[1].toLowerCase();
        for(var i=0;i<s2.length;i++){
            if(s1.indexOf(s2[i])<0)
            {return false;}
        }
        return true;
    }

    mutation(["hello", "hey"]);
    mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])
//Falsy Bouncer  删除数组中所有假值
    function bouncer(arr) {
        // Don't show a false ID to this bouncer.
        return arr.filter(function(x){  
            return Boolean(x);
        });
    }
     bouncer([7, "ate", "", false, 9]);
//Seek and Destroy  第一个参数是待摧毁的数组,其余的参数是待摧毁的值。
// [].slice.call(arguments)
    function destroyer(arr) {
        // Remove all the values
        var _=arguments[0];
        var arg=[];
        for(var j=1;j<arguments.length;j++){
            arg.push(arguments[j]);
        }
        for(var i=0;i<arg.length;i++){
            _=_.filter(function(f){
                return f!=arg[i];
            });
        }
        return _;
    }

    destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//Where do I belong  先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引

    function where(arr, num) {
        // Find my place in this sorted array.
        var _=arr;
        _.push(num);
        return _.sort(function(a,b){return a-b;}).indexOf(num);
    }

    where([40, 60], 50);
//Caesars Cipher 。。。。。。。。。。。。。。

    function rot13(str) { // LBH QVQ VG!
        var s=str.split("");
        s=s.map(function(x){
            var code=x.charCodeAt();
            if(code>=65&&code<=90){
                if(code<=77){
                    return String.fromCharCode(code+13);
                }else{
                    return String.fromCharCode(12-(90-code)+65);
                }
            }
            return x;
        });
        return s.join("");
    }

    // Change the inputs below to test
    rot13("SERR PBQR PNZC");
### Nguyen-Stern Algorithm Explanation The Nguyen-Stern algorithm is a cryptographic method designed to forge signatures under certain conditions, particularly targeting hash functions with specific vulnerabilities. This algorithm exploits the birthday paradox to find collisions in short-message hashes[^1]. In essence, this approach allows an attacker to generate two different messages that produce the same hash output when processed through a vulnerable hash function. The core principle relies on creating numerous pairs of messages until a pair producing identical hash outputs can be found. For practical application scenarios, the algorithm has been demonstrated against various signature schemes where it could potentially exploit weaknesses within underlying hash mechanisms used during signing processes[^2]. ### Implementation Considerations Implementing the Nguyen-Stern attack involves several key steps focused around generating message pairs efficiently while checking for collision occurrences: ```python import hashlib from itertools import combinations def nguyen_stern_attack(hash_function='sha1', rounds=1000): """Demonstrates a simplified version of the Nguyen-Stern attack.""" def create_message_pair(i): m1 = f'Message A {i}'.encode() m2 = f'Message B {i}'.encode() return (m1, m2) seen_hashes = {} for i in range(rounds): msg_a, msg_b = create_message_pair(i) hsa = getattr(hashlib, hash_function)(msg_a).hexdigest() hsb = getattr(hashlib, hash_function)(msg_b).hexdigest() if hsa == hsb: print(f"Collision detected between:\n{msg_a.decode()}\nand\n{msg_b.decode()}") # Store hashes for later comparison if hsa not in seen_hashes: seen_hashes[hsa] = msg_a elif hsb not in seen_hashes: seen_hashes[hsb] = msg_b # Check all previously stored hashes against new ones for ha, hb in combinations(seen_hashes.values(), 2): if getattr(hashlib, hash_function)(ha).hexdigest() == getattr(hashlib, hash_function)(hb).hexdigest(): print(f"Found collision after storing more hashes.\nBetween:\n{ha.decode()}\nand\n{hb.decode()}") nguyen_stern_attack('md5') ``` This code snippet provides a basic simulation of how one might attempt to implement aspects of the Nguyen-Stern attack using Python's `hashlib` library. Note that real-world applications would require significantly greater complexity and computational resources than what is shown here[^3]. --related questions-- 1. What are some common defenses against attacks like those enabled by the Nguyen-Stern algorithm? 2. How do modern hashing algorithms mitigate risks associated with collision-based attacks such as Nguyen-Stern? 3. Can you provide examples of other famous cryptanalysis techniques similar to or inspired by the principles behind Nguyen-Stern? 4. In which types of systems or protocols was the vulnerability exploited by Nguyen-Stern most prevalent historically? [^1]: Description about exploiting birthdays paradox. [^2]: Practical implications discussed regarding digital signatures. [^3]: Simplified example provided demonstrating concept.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值