You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionknapsackDynamic(): boolean{conststart: number=newDate().getTime()constvalues: number[]=[0, ...this.items.map((item)=>item.value)]constweights: number[]=[0, ...this.items.map((item)=>item.size)]constN: number=this.items.lengthletM: any[]=this.arrayGen(this.bagSize,N)letkeepArr: any[]=this.arrayGen(this.bagSize,N)for(leti=1;i<=N;i++){for(letj=0;j<=this.bagSize;j++){if(weights[i]>j){// не можем добавить, т.к. вес большеM[i][j]=M[i-1][j]keepArr[i][j]=0// не можем сохранить этот предмет}else{constvalueIfLeft=M[i-1][j]constvalueIfTaken=M[i-1][j-weights[i]]+values[i]if(valueIfTaken>=valueIfLeft){// максимизируем значениеM[i][j]=valueIfTakenkeepArr[i][j]=1// берём данные предмет}else{M[i][j]=valueIfLeftkeepArr[i][j]=0}}}}letkeptElements: number[]=[]leteleKey: number=this.bagSizefor(leti=N;i>0;i--){if(keepArr[i][eleKey]==1){keptElements.push(i-1)eleKey-=weights[i]}}this.executionTime.push(newDate().getTime()-start)for(constelofthis.items){el.select=false}this.selectedItems=[]this.selectedValue=0this.selectedSize=0for(constelofkeptElements){this.items[el].select=truethis.selectedValue+=this.items[el].valuethis.selectedSize+=this.items[el].sizethis.selectedItems.push({index: el,name: this.items[el].name,value: this.items[el].value,size: this.items[el].size})}returntrue}functionarrayGen(bagSize: number,N: number)=>{letM=newArray(bagSize+1)M[0]=newArray(bagSize+1).fill(0)for(leti=1;i<=N;i++){M[i]=newArray(bagSize)}returnM}