function knapsack($n, $content) { global $weight; global $value; global $solution; if ($n == 0 || $content == 0) { return 0; } else { for ($i = $n - 1; $i >= 0; $i--) { if ($weight[$i] > $content) { $solution[$i] = 0; return knapsack($n - 1, $content); } else { if ($value[$i] + knapsack($n - 1, $content - $weight[$i]) > knapsack($n - 1, $content)) { $solution[$i] = 1; return $value[$i] + knapsack($n - 1, $content - $weight[$i]); } else { $solution[$i] = 0; return knapsack($n - 1, $content); } } } } }
$x[$j] = 1; $c -= $p[$j]; } else { // se for maior que a capacidade eu divido a capacidade pelo peso do item para saber o quanto cabe. $x[$j] = $c / $p[$j]; $c = 0; // após isso mochila não cabe mais nada. } } return $x; // retorno o array de valores dos itens } $items = $_POST['items']; $weight = $_POST['weights']; $values = $_POST['values']; $capacity = $_POST['weightBag']; $result = knapsack($weight, $values, sizeof($values), $capacity); # Exibe o Resultado echo "<table class='table table-hover'>"; echo "<thead><tr><th>Item</th><th>Valor</th><th>Peso</th><th>Porcentagem</th></tr></thead>"; $totalVal = $totalWt = $total = 0; echo "<tbody>"; foreach ($result as $key => $f) { $totalVal += $values[$key]; $totalWt += $weight[$key]; $total += $values[$key] * $f; echo "<tr><td>" . $items[$key] . "</td><td>" . $values[$key] . "</td><td>" . $weight[$key] . "</td><td>" . $f * 100 . "%</td></tr>"; } echo "<tr><td align=right><b>Total</b></td><td>" . $totalVal . "</td><td>" . $totalWt . "</td><td>" . $total . " ( Valor * Porcentagem )</td></tr>"; echo "</tbody>"; echo "</table><hr>";
/** * Создание кампании на основе данных из XML-файла * */ private function create_campaign($campaign_type) { $this->load->model('campaigns'); $this->load->model('groups'); $this->load->model('ads'); $this->load->model('schedule'); $this->load->model('entity'); $this->load->model('payment_gateways'); if ('cpm_flatrate' == $campaign_type) { $this->load->model('sites_channels'); } $current_balance = (double) $this->entity->ballance($this->user_id); $campaign_cost = $this->new_campaign->get_campaign_cost(); if ($campaign_cost > $current_balance) { return "You can not create a new campaign, because you have insufficient funds in the account. Make a deposit and then try again."; } $camp_info = $this->new_campaign->get_name_date(); $campaign_id = $this->campaigns->create(array('name' => $camp_info['name'], 'id_entity_advertiser' => $this->user_id, 'id_campaign_type' => $campaign_type)); $targeting_id = $this->new_campaign->get_targeting(); $targeting_id_temp = $this->new_campaign->get_targeting(true); $this->targeting_groups->copy($targeting_id_temp, $targeting_id); $this->targeting_groups->set_status($targeting_id, 'active'); $this->targeting_groups->cancel($this->user_id, $this->role, $targeting_id_temp); $targeting_type = $this->new_campaign->get_targeting_type(); $this->campaigns->update($campaign_id, array('targeting_type' => $targeting_type, 'id_targeting_group' => $targeting_id)); $schedule = $this->new_campaign->get_schedule(); if ($schedule->schedule_is_set) { $this->campaigns->set_schedule($campaign_id, $this->schedule->set($schedule->schedule)); } else { $this->campaigns->set_schedule($campaign_id, NULL); } //добавление группы в созданную кампанию $group_id = $this->groups->add($campaign_id, $this->new_campaign->get_group_name()); if ('cpm_flatrate' == $campaign_type) { //добавление каналов/сайтов в кампанию $sites_channels_list = $this->new_campaign->get_sites_channels(array('status' => 'new')); $added_group_sites_channels = $this->groups->add_sites_channels($group_id, $sites_channels_list); //добавили новые сайты-каналы в группу $current_balance = (double) $this->entity->ballance($this->user_id); $current_bonus = (double) $this->entity->bonus($this->user_id); $campaign_cost = $this->new_campaign->get_campaign_cost(); //Списание средств за добавленные каналы if ($current_balance + $current_bonus >= $campaign_cost) { foreach ($sites_channels_list as $id_site_channel => $site_channel_info) { $this->sites_channels->renew($added_group_sites_channels[$id_site_channel], false, $site_channel_info['ad_type'], $site_channel_info['id_program']); } } else { //Задача о рюкзаке $this->load->helper("knapsack"); $items_costs = $this->new_campaign->get_campaign_detailed_cost(); $sites_channels_to_pay = knapsack($items_costs, $current_balance); //Списание средств за доступные адвертайзеру программы if (count($sites_channels_to_pay) > 0) { foreach ($sites_channels_to_pay as $arr_index) { $site_channel_info = $items_costs[$arr_index]; $this->sites_channels->renew($added_group_sites_channels[$site_channel_info['id_site_channel']], false, $site_channel_info['ad_type'], $site_channel_info['id_program']); } } } } //добавление объявлений в группу $ads_list = $this->new_campaign->get_ads_list(); foreach ($ads_list as $ad) { if ('text' == $ad->ad_type) { $this->ads->add($group_id, array('title' => (string) $ad->title, 'description1' => (string) $ad->description1, 'description2' => (string) $ad->description2, 'display_url' => (string) $ad->display_url, 'destination_url' => (string) $ad->destination_url, 'destination_protocol' => (string) $ad->destination_protocol), 'text'); } else { $this->ads->add($group_id, array('title' => (string) $ad->title, 'id_image' => (string) $ad->image_id, 'id_dimension' => (string) $ad->id_dimension, 'display_url' => (string) $ad->display_url, 'destination_url' => (string) $ad->destination_url, 'destination_protocol' => (string) $ad->destination_protocol), 'image'); } } $this->new_campaign->free_storage($this->id_xml); $this->session->unset_userdata('id_xml'); return $campaign_id; }
public function _save($id, $fields) { if (count($this->new_campaign->get_sites_channels(array('status' => 'old'))) + count($this->new_campaign->get_sites_channels(array('status' => 'new'))) == 0) { return ''; } $cost = $this->new_campaign->get_sites_channels_new_cost(); $ballance = $this->entity->ballance($this->user_id); if ($cost > $ballance) { return ''; } $this->new_campaign->set_daily_impressions($fields['daily_impressions']); $this->new_campaign->save_data(); $payment_trouble_flag = false; if ($this->input->post('form_type') == 'save') { if (0 == $fields['daily_impressions']) { $this->groups->set_frequency_coup($this->id_group, NULL); } else { $this->groups->set_frequency_coup($this->id_group, $fields['daily_impressions']); } //Удаление старых сайтов-каналов в случае необходимости $xml_sites_channels = $this->new_campaign->get_sites_channels(array('status' => 'old')); $mysql_sites_channels = $this->groups->get_site_channels($this->id_group); $sites_channels_to_delete = array(); foreach ($mysql_sites_channels as $site_channel_info) { if (!array_key_exists($site_channel_info['id_site_channel'], $xml_sites_channels)) { $sites_channels_to_delete[] = $site_channel_info['id_site_channel']; } } if (count($sites_channels_to_delete) > 0) { $this->groups->del_sites_channels($this->id_group, $sites_channels_to_delete); } //добавление новых сайтов-каналов $xml_sites_channels = $this->new_campaign->get_sites_channels(array('status' => 'new')); if (count($xml_sites_channels) > 0) { $this->load->model('entity'); $this->load->model('sites_channels'); $added_group_sites_channels = $this->groups->add_sites_channels($this->id_group, $xml_sites_channels); $campaign_cost = $this->new_campaign->get_campaign_cost(); $current_balance = $this->entity->ballance($this->user_id); if ($current_balance >= $campaign_cost) { foreach ($xml_sites_channels as $id_site_channel => $site_channel_info) { $payment_trouble_flag |= in_array($this->sites_channels->renew($added_group_sites_channels[$id_site_channel], false, $site_channel_info['ad_type'], $site_channel_info['id_program']), array(2, 3)); } } else { $this->load->helper("knapsack"); //Оплата доступных добавленных сайтов-каналов $items_costs = $this->new_campaign->get_campaign_detailed_cost(); $sites_channels_to_pay = knapsack($items_costs, $current_balance); //Списание средств за доступные адвертайзеру программы if (count($sites_channels_to_pay) > 0) { foreach ($sites_channels_to_pay as $arr_index) { $site_channel_info = $items_costs[$arr_index]; $payment_trouble_flag |= in_array($this->sites_channels->renew($added_group_sites_channels[$site_channel_info['id_site_channel']], false, $site_channel_info['ad_type'], $site_channel_info['id_program']), array(2, 3)); } } } } } $this->new_campaign->free_storage($this->id_xml); $this->session->unset_userdata('id_xml'); }
/** * автоматически оплачивает сайты/каналы пользователя исходя из имеющихся наличных средств * * @param integer $id_entity уникальный код учетной записи пользователя * @return integer количество оплаченных сайтов/каналов */ public function autopay($id_entity) { $CI =& get_instance(); $CI->load->helper('knapsack'); $CI->load->model('entity', '', TRUE); $res = $this->db->select('gsc.id_group_site_channel, ad_type, cost_text, cost_image')->from('group_site_channels gsc')->join('groups g', 'gsc.id_group=g.id_group')->join('campaigns c', 'g.id_campaign=c.id_campaign')->where('id_entity_advertiser', $id_entity)->where('gsc.status', 'unpaid')->get(); $prg_list = array(); $index = 1; foreach ($res->result() as $row) { $prg_list[$index]['id_group_site_channel'] = $row->id_group_site_channel; $adTypes = explode(',', $row->ad_type); if (in_array('image', $adTypes)) { $prg_list[$index]['cost'] = $row->cost_image; } else { if (in_array('text', $adTypes)) { $prg_list[$index]['cost'] = $row->cost_text; } } $index++; } $balance = $CI->entity->ballance($id_entity); $pay_list = knapsack($prg_list, $balance); $payed = 0; foreach ($pay_list as $ind) { $r = $this->renew($prg_list[$ind]['id_group_site_channel'], FALSE); if ($r == self::SUCCESS) { $payed++; } } return $payed; }