中间算法脚本 学习笔记

中间算法脚本 学习笔记
0

范围内数据求和

Sum All Numbers in a Range


function sumAll(arr) {
  var myArray=[];
  var myMax= Math.max.apply(null,arr);
  var myMin= Math.min.apply(null, arr);
  for(i=0;i<=myMax-myMin;i++)
    {
      myArray.push(myMin+i);
    }
  return  myArray.reduce((prev, curr) => prev + curr );
}
sumAll([5, 10]);

两个数组不同的元素组成新数组

Diff Two Arrays


function diff(arr1, arr2) {
  var newArr = [];
  newArr=arr1;
 newArr= newArr.concat(arr2);
var xnewArr= newArr.filter(function(val){
   return arr1.indexOf(val)<0||arr2.indexOf(val)<0;
 });
  return xnewArr;
}

diff(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

阿拉伯数字转为罗马数字

Roman Numeral Converter

function convert(num) {
 var str=num.toString();
  var result=[];
 var numArray=str.split('');
  var a=0,b=0,c=0,d=0;
  numArray.reverse();
  for(i=0;i<numArray.length;i++)
    {
     result.push(romanNum[i][numArray[i]]);
    }
 return result.reverse().join('');
}
var romanNum=[["","I","II","III","IV","V","VI","VII","VIII","IX"],
            ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
            ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
            ["","M","MM","MMM"]];
 
convert(3999);

遍历一个对象数组并返回一个包含相匹配的属性-值对的所有对象的数组

Where art thou

  1. 解法一

function where(collection, source) {
var arr = collection;
var result=[];
var myKeys= Object.keys(source);
arr.forEach(val=>{
myKeys.forEach(i=>{
if(val.hasOwnProperty(i))
{
if(val[i]===source[i])
if(result.indexOf(val)<0)
result.push(val);
}
else
{
result= result.filter(function(vval){return vval!==val;});
}
} );
});
return result;
}
where([{ “a”: 1, “b”: 2 }, { “a”: 1 }, { “a”: 1, “b”: 2, “c”: 2 }], { “a”: 1, “b”: 2 })

  1. 解法二 此处声明该解法来自于“ 酸菜有毒”的个人博客

function where(collection, source) {
var arr = [];
var keys = Object.keys(source);
arr = collection.filter(function(item){
for (var i = 0; i < keys.length; i++) {
if ( !item.hasOwnProperty(keys[i]) || item[keys[i]] !== source[keys[i]]) {
return false;
}
}
return true;
});
return arr;
}
where([{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], { last: “Capulet” });


字符串查找替换

Search and Replace

替换后字符的首字母大小写与原始字符保持一致

function myReplace(str, before, after) {
  var afterArray=after.split('');
 if(before.charAt(0)>='A'&&before.charAt(0)<='Z')
   after = after.replace(after[0],after[0].toUpperCase());
   //var regExp=new RegExp(before,"g"); 使用正则表达式替换
   //str= str.replace(regExp,after);
  return str.replace(before,after);//不使用正则表达式替换
  
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

把指定的字符串翻译成 pig latin

Pig Latin

function translate(str) {
  var i=0;  
  //查找元音字母首次出现的位置,并记录到i
  while(consonant[1].indexOf(str.charAt(i))>=0)
    {
      i++;      
    }
  if(i<=0)
    {
      str+="way";
    }
  else
    {
    //把第一次出现的元音字母之前的辅音/辅音丛移动到字符末尾,并添加“ay”
     str=str.substr(i,str.length-i)+str.substr(0,i)+"ay";
    }
  return str;
}
var consonant=[['a','e','i','u','o'],['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']];
translate("paragraphs");

找出缺失的字母

Missing letters

function fearNotLetter(str) {
  str=str.toLowerCase();
  var arrOld=[];
  var i=0;
  while(i<str.length)
    {
      arrOld.push(str.charCodeAt(i));
      i++;
    }
  var max= Math.max.apply(null,arrOld);
  var min= Math.min.apply(null,arrOld);
  var result;
  i=0;
 var arrNew=[];
  while(i<=max-min)
    {
      if(arrOld.indexOf(min+i)<0)
       arrNew.push(min+i);
      i++;
    }
  if(arrNew.length>0)
    result=String.fromCharCode(arrNew);
  return result;
}
fearNotLetter("aBce");

1赞