This code is working fine when the array length is 8 or 10 only. When we are checking this same code for more than 10 array length.it get loading not showing the results.
How do reduce my code. If you have algorithm please share. Please help me.
This program working flow:
$allowed_per_room_accommodation =[2,3,6,5,3,5,2,5,4];
$allowed_per_room_price =[10,30,60,40,30,50,20,60,80];
$search_accommodation = 10;
i am get subsets = [5,5],[5,3,2],[6,4],[6,2,2],[5,2,3],[3,2,5]
Show lowest price room and then equal of 10 accommodation; output like as [5,3,2];
<?php
$dp=array(array());
$GLOBALS['final']=[];
$GLOBALS['room_key']=[];
function display($v,$room_key)
{
$GLOBALS['final'][] = $v;
$GLOBALS['room_key'][] = $room_key;
}
function printSubsetsRec($arr, $i, $sum, $p,$dp,$room_key='')
{
// If we reached end and sum is non-zero. We print
// p[] only if arr[0] is equal to sun OR dp[0][sum]
// is true.
if ($i == 0 && $sum != 0 && $dp[0][$sum]) {
array_push($p,$arr[$i]);
array_push($room_key,$i);
display($p,$room_key);
return $p;
}
// If $sum becomes 0
if ($i == 0 && $sum == 0) {
display($p,$room_key);
return $p;
}
// If given sum can be achieved after ignoring
// current element.
if (isset($dp[$i-1][$sum])) {
// Create a new vector to store path
// if(!is_array(#$b))
// $b = array();
$b = $p;
printSubsetsRec($arr, $i-1, $sum, $b,$dp,$room_key);
}
// If given $sum can be achieved after considering
// current element.
if ($sum >= $arr[$i] && isset($dp[$i-1][$sum-$arr[$i]]))
{
if(!is_array($p))
$p = array();
if(!is_array($room_key))
$room_key = array();
array_push($p,$arr[$i]);
array_push($room_key,$i);
printSubsetsRec($arr, $i-1, $sum-$arr[$i], $p,$dp,$room_key);
}
}
// Prints all subsets of arr[0..n-1] with sum 0.
function printAllSubsets($arr, $n, $sum,$get=[])
{
if ($n == 0 || $sum < 0)
return;
// Sum 0 can always be achieved with 0 elements
// $dp = new bool*[$n];
$dp = array();
for ($i=0; $i<$n; ++$i)
{
// $dp[$i][$sum + 1]=true;
$dp[$i][0] = true;
}
// Sum arr[0] can be achieved with single element
if ($arr[0] <= $sum)
$dp[0][$arr[0]] = true;
// Fill rest of the entries in dp[][]
for ($i = 1; $i < $n; ++$i) {
for ($j = 0; $j < $sum + 1; ++$j) {
// echo $i.'d'.$j.'.ds';
$dp[$i][$j] = ($arr[$i] <= $j) ? (isset($dp[$i-1][$j])?$dp[$i-1][$j]:false) | (isset($dp[$i-1][$j-$arr[$i]])?($dp[$i-1][$j-$arr[$i]]):false) : (isset($dp[$i - 1][$j])?($dp[$i - 1][$j]):false);
}
}
if (isset($dp[$n-1][$sum]) == false) {
return "There are no subsets with";
}
$p;
printSubsetsRec($arr, $n-1, $sum, $p='',$dp);
}
$blockSize = array('2','3','6','5','3','5','2','5','4');
$blockvalue = array('10','30','60','40','30','50','20','60','80');
$blockname = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese");
$processSize = 10;
$m = count($blockSize);
$n = count($processSize);
// sum of sets in array
printAllSubsets($blockSize, $m, $processSize);
$final_subset_room = '';
$final_set_room_keys = '';
$final_set_room =[];
if($GLOBALS['room_key']){
foreach ($GLOBALS['room_key'] as $set_rooms_key => $set_rooms) {
$tot = 0;
foreach ($set_rooms as $set_rooms) {
$tot += $blockvalue[$set_rooms];
}
$final_set_room[$set_rooms_key] = $tot;
}
asort($final_set_room);
$final_set_room_first_key = key($final_set_room);
$final_all_room['set_room_keys'] = $GLOBALS['room_key'][$final_set_room_first_key];
$final_all_room_price['set_room_price'] = $final_set_room[$final_set_room_first_key];
}
if(isset($final_all_room_price)){
asort($final_all_room_price);
$final_all_room_first_key = key($final_all_room_price);
foreach ($final_all_room['set_room_keys'] as $key_room) {
echo $blockname[$key_room].'---'. $blockvalue[$key_room];
echo '<br>';
}
}
else
echo 'No Results';
?>
I'm assuming your task is, given a list rooms, each with the amount of people it can accommodate and the price, to accommodate 10 people (or any other quantity).
This problem is similar to 0-1 knapsack problem which is solvable in polynomial time. In knapsack problem one aims to maximize the price, here we aim to minimize it. Another thing that is different from classic knapsack problem is that full room cost is charged even if the room is not completely occupied. It may reduce the effectiveness of the algorithm proposed at Wikipedia. Anyway, the implementation isn't going to be straightforward if you have never worked with dynamic programming before.
If you want to know more, CLRS book on algorithms discusses dynamic programming in Chapter 15, and knapsack problem in Chapter 16. In the latter chapter they also prove that 0-1 knapsack problem doesn't have trivial greedy solution.
I am trying to make a text game in PHP but i have problem since i am programing in php for few days. I need to call function attack (I need $_mainAttack since it is combination of $_baseAttack and special attack) from defend function so i can calculate the health loss I have placed -5 just to see if it is working..
Also in health i need attack to be able to lower hp so i could calculate the hp loss. My do while loop is wrong and i need help to make it functional. I want when health goes lower than 0 to exit the loop. When it exits the loop it will print game over. I am stuck in endless loop and i have no idea how to fix this.
This is index.php:
<?php
include 'Duel.php';
$duel = new Duel();
$duel->attack();
$duel->defend();
?>
This is my class duel:
<?php
class Duel{
public $_maxHealth = 20;
public $_currentHealth;
public $_baseAttack, $_specialAttack, $_mainAttack;
public $_specialChance, $deflectChance;
public $_defense;
function __construct()
{
echo 'begining of attack <br/>';
}
function attack()
{
$_specialChance = rand(0, 20);
$_specialAttack = 0;
if ($_specialChance < 10) {
$_specialAttack = 0;
} elseif ($_specialChance < 15) {
$_specialAttack = (int) rand(0, 5);
} elseif ($_specialChance <= 20) {
$_specialAttack = (int) rand(5, 10);
}
$_baseAttack = rand(1, 6);
$_mainAttack = $_baseAttack + $_specialAttack;
echo "Base attack is $_baseAttack: and special attack is : $_specialAttack attack is : $_mainAttack<br/>";
}
function defend()
{
$_maxHealth = 20;
do{
$deflectChance = rand(1, 10);
$deflect = 0;
if ($deflectChance < 5) {
$deflect = 0;
echo 'attack cannot be deflected';
}
elseif ($deflectChance > 5) {
$deflect = (int) rand(0, 3);
echo "attack is deflected for {$deflect} damage";
}
$_currentHealth = $_maxHealth + $deflect - 5;
echo "<br/>health is {$_currentHealth} <br/>";
}while($_currentHealth > 0);
if($_currentHealth > 0) echo "Game over";
}
} //end of class
You are always calculating $_currentHealth based on $_maxHealth, not the previous $_currentHealth.
Add before the loop:
$_currentHealth = $_maxHealth;
And change $_currentHealth = $_maxHealth + $deflect - 5; to:
$_currentHealth = $_currentHealth + $deflect - 5;
You can try returning the main attack variable from the attack function and simply call it on the defend function.
you are calculation $_mainAttack but doesn't subtract it from your health, therefore your player can't die and you end within an endless loop.
So basically I am trying to get the sum of AveragePrice of every single page on this api. Right now it only gets first page the things i've tried have only gotten it to go on an endless loop crashing wamp. Heres my code for 1 page of working.
I am just really unsure how I can get it to loop through pages and get sum of every page.
<?php
function getRap($userId){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=1&itemsPerPage=14");
$results = file_get_contents($url);
$json = json_decode($results, true);
$data = $json['data']['InventoryItems'];
$rap = 0;
foreach($data as $var) {
$rap += $var['AveragePrice'];
}
echo $rap;
}
$userId = 1;
getRap($userId);
?>
You may get better answers by looking into the API you are working with regarding how many pages to look for. You want to loop until you hit the max pages. There should be an value in the result of your request that tells you that you've asked for a page that doesn't exist (ie. no more results). If you can get a total number of results to search for then you could do a for loop with that as your limit.
//Change the function to accept the page number as a variable
function getRap($userId, $i){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=14");
//work out how many pages it takes to include your total items
// ceil rounds a value up to next integer.
// ceil(20 / 14) = ceil(1.42..) == 2 ; It will return 2 and you will look for two pages
$limit = ceil($totalItems / $itemsPerPage);
// Then loop through calling the function passing the page number up to your limit.
for ($i = 0; $i < $limit; $i++) {
getRap($userId, $i);
}
If you cannot get the total number of items, you could loop while a fail state hasn't occured
// look for a fail state inside your getRap()
function getRap($userId, $i) {
if ($result = error) { //you will have to figure out what it returns on a fail
$tooMany = TRUE;
}
}
for ($i = 0; $tooMany !== TRUE ; $i++) {
getRap($userId, $i);
}
Edit: Reviewing my answer, looking for the fail state inside your function is poor form (and won't work because of the scope of the variable in this case). You could pass the variable back and forth, but I'll leave that part up to you.
To get the total, make sure that your function doesn't print the result (echo $rap) but returns it for further use.
Full example
<?php
function getRap($userId, $i){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=25");
$results = file_get_contents($url);
$json = json_decode($results, true);
if ($json['msg'] == "Inventory retreived!") {
$data = $json['data']['InventoryItems'];
$rap = 0;
foreach($data as $var) {
$rap += $var['AveragePrice'];
}
return $rap;
} else {
return FALSE;
}
}
$total = 0;
$userId = 1;
for ($i = 0; $i < 1000 /*arbitrary limit to prevent permanent loop*/ ; $i++) {
$result = getRap($userId, $i);
if ($result == FALSE) {
$pages = $i;
break;
} else {
$total += getRap($userId, $i);
}
}
echo "Total value of $total, across $pages pages";
?>
I am trying to create a dynamic page links created based on the number of rows in a mysql table. I would like to display 10 results per page and wish to have the php script create links to additional pages.
So I was thinking of using the num_rows and dividing it by 10 however if I have 53 rows the return would be 5.3 where as I would need 6 pages and not 5. I am thinking of using the round function and looping it through a for I statement until $pages > $rows_rounded. And every 10 rows add a link to pages($i) Is this the best method to acheive this or there an alternative simpler route to take?
pagenator class I made. getCurrentPages() returns all the pages you should be displaying in an array. so if you are on page one, and you want to display a total of 9 pages, you would get an array 1-9. if you were on page 10 however, your would get back an array 6-14. if there are 20 total pages and you are on page 20, you would get back an array 11-20.
<?php
class Lev_Pagenator {
private $recordsPerPage;
private $currentPage;
private $numberOfTotalRecords;
private $lastPage = null;
public function __construct($current_page, $number_of_total_records, $records_per_page = 25) {
$this->currentPage = $current_page;
$this->numberOfTotalRecords = $number_of_total_records;
$this->recordsPerPage = $records_per_page;
}
public function getCurrentStartIndex() {
return ($this->currentPage - 1) * $this->recordsPerPage;
}
public function getCurrentPages($number_of_pages_to_display = 9) {
$start_page = $this->currentPage - floor($number_of_pages_to_display / 2);
if ($start_page < 1) $start_page = 1;
$last_page = $this->getLastPage();
$pages = array($start_page);
for ($i = 1; $i < $number_of_pages_to_display; $i++) {
$temp_page = $start_page + $i;
if ($temp_page <= $last_page) {
$pages[] = $temp_page;
} else {
break;
}
}
return $pages;
}
public function getPreviousPage() {
if ($this->currentPage === 1) return false;
return $this->currentPage - 1;
}
public function getNextPage() {
if ($this->currentPage === $this->getLastPage) return false;
return $this->currentPage + 1;
}
public function getLastPage() {
if ($this->lastPage === null) $this->lastPage = ceil($this->numberOfTotalRecords / $this->recordsPerPage);
return $this->lastPage;
}
}
?>
EDIT (USAGE):
<?php
$pagenator = new Lev_Pagenator($current_page, $number_of_total_records, $records_per_page);
$pages_array = $pagenator->getCurrentPages($number_of_pages_to_display);
?>
The idea of a for loop sounds like a good one, you would use something like:
$rows_rounded = ceil(mysql_num_rows($result) / 10);
for($x = 1; $x <= $rows_rounded; $x++){
echo 'Page '.$x.'';
}
But you need to consider detecting the current page, so if, for example, the current page was 3, it might be a good idea to test for that in your for loop and if echoing the 3rd link maybe add some extra class to enable you to style it.
Im working with a php url shortener and my problem is that it only creates the MAX number of shortening codes up to 2 characters (eg domain.com/XX). I want it to go up to 5 characters (eg domain.com/XXXXX)
I believe i found the relevant code, but im not sure how to change it to allow for this modification
function decode_url_id($code)
{
$scheme = "abcdefghijklmnoprstuqwxvyz0123456789ABCDEFGHIJKLMNOPRSTQWXUVYZ";
$scheme_size = strlen($scheme);
$number = 0;
$code_size = strlen($code);
$code = strrev($code);
for($i = 0; $i < $code_size; $i++)
{
$digit_value = strpos($scheme, $code[$i]);
$number += ($digit_value * pow($scheme_size, $i));
}
return $number;
}
function encode_url_id($number, $code="")
{
$scheme = "abcdefghijklmnoprstuqwxvyz0123456789ABCDEFGHIJKLMNOPRSTQWXUVYZ";
$scheme_size = strlen($scheme);
if ($number >= $scheme_size)
{
$c = $number % $scheme_size;
$code .= $scheme[$c];
$number = floor($number / $scheme_size);
return encode_url_id($number, $code);
}
else
{
$code .= $scheme[$number];
$code = strrev($code);
}
return $code;
}
Am i barking up the wrong tree?
Why not just encode the ID of the URL in the database with http://www.pgregg.com/projects/php/base_conversion/base_conversion.inc.phps.
Example usage:
$new_url = base_base2base($link_id, 10, 62);