codecamp

库存更新算法挑战

function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
    var arr=[];
    outer:for(let x of arr2){    //更新数组
      for(let y of arr1){
        if(x[1]==y[1]){
          y[0]+=x[0];
          continue outer;
        }
      }
      arr.push(x);   //arr2独有的放进arr
    }

    
    return arr.concat(arr1).sort(function(a,b){  //排序
      var index=0;
      var char_a,char_b;
      do{
        char_a=a[1].charCodeAt(index);
        char_b=b[1].charCodeAt(index);
        index++;
      }while( char_a==char_b );

      
      return char_a-char_b;
    });
}


// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];


var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];


updateInventory(curInv, newInv);

收银系统算法挑战
排列组合去重算法挑战
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

HTML5&CSS

JavaScript

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }