Skip to content

Instantly share code, notes, and snippets.

@seocam
Last active April 4, 2019 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seocam/4a371aaec5cadaf18e296abf538bd456 to your computer and use it in GitHub Desktop.
Save seocam/4a371aaec5cadaf18e296abf538bd456 to your computer and use it in GitHub Desktop.
let iters = 0;
function greedyThief(items, n){
iters = 0
const new_items = [...items]
const sorted_items = new_items.sort((a, b) => {
const w_diff = b.weight - a.weight
if (w_diff === 0) {
return b.price - a.price
}
return w_diff
})
console.log(sorted_items, n)
const result = greedyBacktracking(sorted_items, [], {value: 0, weight: 0}, n, [], 0)[0]
console.log(iters)
return result
}
function greedyBacktracking(items, pkg, pkgAttrs, n, bestPkg, bestPkgValue) {
iters++;
for(let i=0; i < items.length; i++) {
let item = items[i]
if ((pkgAttrs.weight + item.weight) > n) {
/*console.log('item:', item)
console.log('pkg:', pkg)
console.log('items:', items)
console.log('-------------------------')*/
break
}
const new_items = items.slice(0, i).concat(items.slice(i+1))
pkg.push(item)
pkgAttrs.value += item.price
pkgAttrs.weight += item.weight
/*console.log('pkg: ',pkg)
console.log('pkgAttrs: ', pkgAttrs)
console.log('bestPkgValue: ', bestPkgValue)*/
if (pkgAttrs.value > bestPkgValue) {
//console.log('troquei')
bestPkg = [...pkg]
bestPkgValue = pkgAttrs.value
} else {
//console.log('nopz')
}
//console.log('-------------------------')
const [a, b] = greedyBacktracking(new_items, pkg, pkgAttrs, n, bestPkg, bestPkgValue)
bestPkg = a
bestPkgValue = b
pkg.pop()
pkgAttrs.value -= item.price
pkgAttrs.weight -= item.weight
}
//console.log(bestPkg)
return [bestPkg, bestPkgValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment