Intermediate Algorithm Scripting

Sum All Numbers in a Range

將某範圍的數加總起來

我最一開始的想法

function sumAll(arr) {
  var result=0;  

  min = Math.min.apply(null,arr);
  max = Math.max.apply(null,arr);

  for(i=min; i<=max; i++){
      result = result + i;
  }

  console.log(result);
  return result;
}

sumAll([1, 100]);

官方答案是用公式解 XD

function sumAll(arr) {
  max=Math.max(arr[0],arr[1]);
  min=Math.min(arr[0],arr[1]);
  return (max+min)*(max-min+1)/2;
}

Diff Two Arrays

抓出兩個陣列中,沒有重複的值

function diffArray(arr1, arr2) {
    var newArr = [];
    // Same, same; but different.

    // filter
    var newarr1 = arr1.filter(function(x){
        if(arr2.indexOf(x) === -1){
            return true;
        } else {
            return false;
        }
    });
    // console.log(newarr1)

    var newarr2 = arr2.filter(function(x){
        if(arr1.indexOf(x) === -1){
            return true;
        } else {
            return false;
        }
    });
    // console.log(newarr2)


    // concat
    newArr = newarr1.concat(newarr2);


    // Check
    console.log(newArr);
    return newArr;
  }

  diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

有趣的解法

function diffArray(a, b){
 c = a.concat(b)
 d = [];
var diffarr = c.filter(function(c1){
       if (a.indexOf(c1) === -1 || b.indexOf(c1) === -1){
               d.push(c1);
       }
    });
    return d;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Roman Numeral Converter

阿拉伯數字轉羅馬數字 覺得頭暈

function convertToRoman(num) {

    // var something
    var M, D, C, L, X, V, I;
    var Rarr = [M, D, C, L, X, V, I];
    var RSarr = ["M", "D", "C", "L", "X", "V", "I"];
    var Rarrnum = [1000, 500, 100, 50, 10, 5, 1];

    // get remainder array
    var Rresult = divide(num);
    console.log(Rresult);

    function divide(num) {
        var temp = num;

        for (i = 0; i < Rarr.length; i++) {
            Rarr[i] = Math.floor(temp / Rarrnum[i]);
            temp = temp % Rarrnum[i];
        }

        return Rarr;
    }


    // get roman number
    var end = join(Rresult);
    console.log(end);

    function join(Rresult) {
        var result = "";
        for (i = 0; i < Rresult.length; i = i + 2) {

            // ex: 9 = IX
            if (Rresult[i - 1] === 1 && Rresult[i] === 4) {
                result = result + RSarr[i] + RSarr[i - 2];
            }

            // ex: 4 = IV
            else if (Rresult[i - 1] === 0 && Rresult[i] === 4) {
                result = result + RSarr[i] + RSarr[i - 1];
            }

            // ex: 7 = VII
            else if (Rresult[i - 1] === 1) {
                result = result + RSarr[i - 1];
                for (j = 0; j < Rresult[i]; j++) {
                    result = result + RSarr[i];
                }
            }

            // ex: 2 = II
            else {
                for (j = 0; j < Rresult[i]; j++) {
                    result = result + RSarr[i];
                }
            }
        }
        return result;
    }
    return end;


}

convertToRoman(1004);

其他,先把4,9的組合列出來

function convert(num) {

    var Rarr = ["M", "CM","D", "CD", "C", "XC","L", "XL",  "X", "IX", "V", "IV", "I"];
    var Rarrnum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
    var str = "";

    for(i=0; i<Rarr.length; i++){

        while(Rarrnum[i] <= num ){
            str = str + Rarr[i];
            num = num - Rarrnum[i];
        }

    }

    console.log(str);
    return str;

   }

   convert(3249);

Wherefore art thou

function whatIsInAName(collection, source) {
    // What's in a name?
    var arr = "";
    // Only change code below this line

    // source 的所有 key
    var keys2 = Object.keys(source);    

    for(i=0; i<collection.length; i++){
        for(j=0; j<keys2.length; j++){
            result = collection[i].hasOwnProperty(keys2[j]);

        }

    }
    a = keys2[0];



    // Only change code above this line
    console.log();
    return arr;
  }

  whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

今天的成果

function whatIsInAName(collection, source) {
    // What's in a name?
    var arr = [];
    // Only change code below this line


    // source 的所有 key
    var keys2 = Object.keys(source);
    console.log(keys2.length);

    var fitCount = [];


    for(i=0; i<collection.length; i++){

        fitCount[i] = 0;

        // 紀錄 collection[i] 中有多少與 source 相同的 key value 對 
        for (var Skey in source){
            if(collection[i].hasOwnProperty(Skey) && collection[i][Skey]===source[Skey]){
                console.log("i="+i+", key="+Skey+", value="+collection[i][Skey]);
                fitCount[i] = fitCount[i] + 1; 
            }
        }

        // 如果 fitCount[i] 與 source 的長度相同,就把 fitCount[i] 放進 arr
        if(fitCount[i] == keys2.length){
            arr.push(collection[i]);
        }
    }

    // Only change code above this line
    console.log(arr);
    return arr;
  }

  whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 });

用 filter 實做

function where(collection, source) {
    var arr = [];
    // What's in a name?

    arr = collection.filter(function(obj){

        var fitCount = 0;
        for (var key in source){
            if(obj[key] == source[key]){
                fitCount += 1;
            }
        }

        return fitCount == Object.keys(source).length;

    });

    console.log(arr);
    return arr;
  }

  where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 });

節錄一個詭異的解法 (很多解法我都摸不著頭緒)

function whatIsInAName(collection, source) {
  // What's in a name?  
  return collection
    .filter((obj) => JSON.stringify(Object.assign(JSON.parse(JSON.stringify(obj)), source)) === JSON.stringify(obj));
}

Search and Replace

用 after 取代 before,但首字大小寫要相同

function myReplace(str, before, after) {

    // If "before" first alphabet is Upper
    var isUpper = /[A-Z]/.test(before[0]);
    console.log(isUpper);

    // If "before" first alphabet is Upper, then change after first alphabet to Upper
    if ( isUpper ){
        var afterArr = after.split("");
        afterArr[0] = afterArr[0].toUpperCase();
        after = afterArr.join("");
    }

    // Use "after" replace "before"
    str = str.replace(before, after);

    console.log(str);
    return str;
  }

  myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

簡化了幾個部份

function myReplace(str, before, after) {

    // If "before" first alphabet is Upper
    var isUpper = /[A-Z]/.test(before[0]);
    console.log(isUpper);

    // If "before" first alphabet is Upper, then change after first alphabet to Upper
    if ( isUpper ){
        after = after[0].toUpperCase() + after.slice(1);
    }

    // Use "after" replace "before"
    str = str.replace(new RegExp(before, "g"), after);

    console.log(str);
    return str;
  }

  myReplace("He is Sleeping on the Sleeping couch", "Sleeping", "sitting")

Pig Latin

我的解法

function translatePigLatin(str) {

    var isVowel = /^[aeiou]/.test(str);
    var newStr;

    if (isVowel) {
        //+way
        newStr = str + "way";
    } else {
        // first consonant + ay

        var muYin = ["a", "e", "i", "o", "u"];
        var muYinIndex = new Array(str.length);

        muYinIndex = muYin.map(function(item) {
            return str.indexOf(item);
        });

        minIndexArray = muYinIndex.filter(function(item) {
            return item > -1
        });

        minIndex = Math.min.apply(Math, minIndexArray);

        newStr = str.slice(minIndex) + str.slice(0, minIndex) + "ay";
    }

    console.log(newStr);
    return newStr;
}

translatePigLatin("glove");

依照我的流程,可以化約為這個語法

function translatePigLatin(str) {
  var vowel = /[(a/e/i/o/u)]/igm;
  var consonant = /[^(a/e/i/o/u)]/igm;
  var v =  str.search(vowel);
  var c =  str.search(consonant);
    return v > c ?  str.slice(v) + str.substr(c, v) + "ay" : str + "way";
}

完全用 replace

function translatePigLatin(str) {
  return str
    .replace(/^([aeiouy])(.*)/, '$1$2way')
    .replace(/^([^aeiouy]+)(.*)/, '$2$1ay');
}

// test here
translatePigLatin("consonant");

DNA Pairing

我的解法

function pairElement(str) {

    var arr = str.split("");
    var newArr = [];

    function switchATCH(ATCG){
        switch( ATCG ){
            case "A":
                newArr.push(["A", "T"]);
                break;
            case "T":
                newArr.push(["T", "A"]);
                break;
            case "C":
                newArr.push(["C", "G"]);
                break;
            case "G":
                newArr.push(["G","C"]);
                break;    
        }
    }

    arr.map(function(item){
        switchATCH(item);
    });


    console.log(newArr);
    return newArr;
  }

  pairElement("ATCG");

討論區的一個解法

function pairElement(str) {
  var pairs = {
    "A": ["A", "T"],
    "T": ["T", "A"],
    "C": ["C", "G"],
    "G": ["G", "C"]
  };

  return str.split("").map(function(elem) {
    return pairs[elem];
  });

別人更簡短的版本

function pairElement(str) {  
  return str.split("").map(function (x) {
    switch (x) {
      case "G":
       return ["G","C"];       
      case "C":   
       return ["C","G"];        
      case "T":
       return ["T","A"];       
      case "A":
       return ["A","T"];       
    }    
  });
}

之後的解法

function pair(str) {

    var obj = {
        "A": ["A", "T"],
        "T": ["T", "A"],
        "C": ["C", "G"],
        "G": ["G", "C"]
    }

    var newArr = str.split("").map(function(key){
        return obj[key];
    });

    console.log(newArr);
    return newArr;
  }

  pair("GCG");

Missing letters

自己想的

function fearNotLetter(str) {
  var char;
  var charNum;

  for (i = 0; i < str.split("").length; i++) {
    if (str.charCodeAt(i) - str.charCodeAt(i - 1) == 2) {
      charNum = str.charCodeAt(i) - 1;
      char = String.fromCharCode(charNum);
    }
  }

  console.log(char);
  return char;
}

fearNotLetter("abce"); // d

可以抓出所有缺少的字

function fearNotLetter(str) {
  var allChars = '';
  var notChars = new RegExp('[^'+str+']','g');

  for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)
    allChars += String.fromCharCode(str[0].charCodeAt(0) + i);

  return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}

// test here
fearNotLetter("abce");

Boo who

自己想的

function booWho(bool) {
  // What is the new fad diet for ghost developers? The Boolean.

  if(bool===true || bool===false){
    return true;
  } else{
    return false;
  }

}

booWho(null);

解答

function booWho(bool) {
  return typeof bool === 'boolean';
}

// test here
booWho(null);

Sorted Union

自己想的

function uniteUnique(arr) {

  var newArr = arguments[0];

  for(i=1; i<arguments.length; i++){
    for(j=0; j<arguments[i].length; j++){
      var numIndex = arguments[0].indexOf(arguments[i][j]);
      if(numIndex<0){
        newArr.push(arguments[i][j]);
      }
    }
  }

  console.log(newArr);
  return newArr;
}

uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]);

ES6新的函式,有點像集合的概念,在 set 中重複的值會被刪除

//jshint esversion:6

function uniteUnique(arr) {

  //make an array out of arguments and flatten it (using the spread operator)
  const args = [].concat(...arguments);

  // create a Set
  return [...new Set(args)];
}

// test here
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

Convert HTML Entities

自己想的

function convertHTML(str) {
  // &colon;&rpar;

  var newStr = str;
  var obj = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;"
  };

  for ( var key in obj){
    newStr = newStr.replace(new RegExp(key, "g"), obj[key]);    
  }

  console.log(newStr);
  return newStr;
}

convertHTML("Hamburgers < Pizza < Tacos");

答案一

function convertHTML(str) {
  // Use Object Lookup to declare as many HTML entities as needed.
  var htmlEntities = {
    '&':'&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '\"':'&quot;',
    '\'':"&apos;"
  };
  //Use map function to return a filtered str with all entities changed automatically.
  return str.split('').map(function(entity){
    return htmlEntities[entity] || entity;
  }).join('');
}

// test here
convertHTML("Dolce & Gabbana");

答案二

function convertHTML(str) {

 function repEnt(ent){
  switch(ent){
    case "&":
      return "&amp;";
    case "<":
      return "&lt;"; 
    case ">":
      return "&gt;";
    case '"':
      return '&quot;';
    case "'":
      return "&apos;";  
    }
 }
  str = str.replace( /[&<>"']/g, repEnt ); 
  return str;
}

convertHTML("Dolce & Gabbana");

答案三

function convertHTML(str) {
  var entities = { '&': '&amp;', '<':'&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;'}
  return str.replace(/[&<>"']/g, function(match) {
    return entities[match]
  } )
}

Spinal Tap Case

function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins

  var newStr;

  newStr = str.match(/[A-Z][a-z]*/g);
  // newStr = newStr.replace(/[_-\s]/gi, "-");


  console.log(newStr);
  return newStr;
}

spinalCase('Teletubbies say Eh-oh');

Last updated

Was this helpful?