the burglar's tool.

Start your word games and stuff in here for people to take part and have fun with.
1 post Page 1 of 1
Contributors
User avatar
benji_19994
VIP - Donator
VIP - Donator
Posts: 156
Joined: Mon Apr 16, 2012 3:13 pm

the burglar's tool.
benji_19994
Imagine you are a burglar. Your backpack can carry 7 kilogram of items. You break into a house and have to decide which items to take with you as you can not carry all of them. Every item has a weight and has a value. Your objective is to get as much value as possible while not carrying more than 7 kilogram of weight.

item value weight
statue 7 5
bracelet 3 4
gloves 2 3
diadem 8 3
necklace 5 2
gem 4 1

Write a program that solves this problem for you.
Post code, language used and answer to the problem (items you take).

Alright get going guys



This is my code: It's written in php Rollover to view spoiler

Code: Select all
<?php
$arr = array(array("statue",7,5),array("bracelet",7,5),array("gloves",2,3),array("diadem",8,3),array("necklace",5,2),array("gem",4,1));
//array of items and their corresponding values and weights respectively
$ctr = 0;
//The following nested loop will check for the highest value with combos of any 2 items taken together
for($i = 0 ; $i <= 5 ; $i++)
{
    for($j = 0 ; $j <= 5 ; $j++)
    {
        if(($i != $j) && (($arr[$i][2]+$arr[$j][2])<=7))//Checking if the same item is selected more than once in the combo and the weight should be <=7
        {
            $combos[$ctr]['item'] = $arr[$i][0]." & ".$arr[$j][0];
            $combos[$ctr]['value'] = $arr[$i][1]+$arr[$j][1];
            $ctr++;
        }
    }
}
//The following nested loop will check for the highest value with combos of any 3 items taken together
for($i = 0 ; $i <= 5 ; $i++)
{
    for($j = 0 ; $j <= 5 ; $j++)
    {
        for($k = 0 ; $k <= 5 ; $k++)
        {
            if(($i != $j) && ($i != $k) && ($k != $j) && (($arr[$i][2]+$arr[$j][2]+$arr[$k][2])<=7))//Checking if the same item is selected more than once in the combo and the weight should be <=7
            {
                $combos[$ctr]['item'] = $arr[$i][0]." & ".$arr[$j][0]." & ".$arr[$k][0];
                $combos[$ctr]['value'] = $arr[$i][1]+$arr[$j][1]+$arr[$k][1];
                $ctr++;
            }
        }
    }
}
$highestval = 0;
$flag = 0;
for($x = 0 ; $x < $ctr ; $x++)
{
    if($combos[$x]['value'] > $highestval)
    {
        $highestval = $combos[$x]['value'];
        $flag = $x;
    }
}
echo "The items with highest value would be : ".$combos[$flag]['item']." and their combined value is : ".$highestval;
?>
[/spoiler]
1 post Page 1 of 1
Return to “Game Room”