PHP code that generates words to C,C++ code - php

I had to develop a mini program that generates words from the given letters and some rules. I did this in PHP and it works great, BUT: now I need this code translated to C or C++. I've tried to implement it, but I have some troubles with string arrays. Moreover, I'm not good in C, even C++.
Someone, please help me to implement this code. Will do smth for you if I can. Thank you.
Here is the code attached:
<?php
$val_n = array("S","D","R");
$val_t = array("a","b","c","d","f");
$reguli = array(
array("S" => "aS"),
array("S" => "bD"),
array("S" => "fR"),
array("D" => "cD"),
array("D" => "dR"),
array("R" => 'bR')
);
$rez = array();
$pas = array();
$parcurgere = array();
$parc_sf = array();
function generare($val_n, $reguli, $cuvint, $parcurgere)
{
global $rez;
global $pas;
global $parcurgere;
global $parc_sf;
if( strlen($cuvint) >= 6)
{
if( $cuvint[strlen($cuvint) -1] == 'R' )
{
$cuvint[strlen($cuvint) -1] = "f";
if( ! in_array($cuvint, $rez) )
{
$rez[] = $cuvint;
array_push($parc_sf,$cuvint[strlen($cuvint) -1] = "f");
array_push($pas,$parcurgere);
}
} else if( $cuvint[strlen($cuvint) -1] == 'D' )
{
$cuvint[strlen($cuvint) -1] = "d";
if( ! in_array($cuvint, $rez) )
{
$rez[] = $cuvint;
array_push($parc_sf,$cuvint[strlen($cuvint) -1] = "d");
array_push($pas,$parcurgere);
}
}
} else if( $cuvint[strlen($cuvint) -1] != 'f' || $cuvint[strlen($cuvint) -1] != 'd')
{
foreach($reguli as $reg)
{
if(isset($reg[substr($cuvint, -1)]))
{
$pasi = $reg[substr($cuvint, -1)];
array_push($parcurgere,$pasi);
$cuvint .= $reg[substr($cuvint, -1)];
//$cuvint[strlen($cuvint)-3] = '';
generare($val_n, $reguli, $cuvint, $parcurgere);
}
}
}
}
$cuvint = "S";
$pasi = '';
generare($vn, $reguli, $cuvint, $parcurgere);
?>

I would suggest to look at std::vector which represents arrays that can change in size.
For the associate arrays (array("S" => "aS")), you can look at std::map or std::unordered_map

Related

Wordpress custom taxonomy hierarchy insert

I am having some trouble getting this loop to work properly.
I want to insert Country, State, City, Community from google maps as heiarchy in a custom taxonomy of wordpress. All the variables get set but when it runs through the for loop it only populates and inserts the country or 1st array $loop[0].
I am using $pastID[$d] to save the last term_id to use it as the parent in the next term. If this is just bad let me know.
I have to use Globals as I am connecting with an existing plugin also.
$custom_tax_name = "location";
$loop = array();
$loop[0] = $country = $GLOBALS['custom_array']['country'];
$loop[1] = $state = $GLOBALS['custom_array']['state'];
$loop[2] = $city = $GLOBALS['custom_array']['city'];
$loop[3] = $community = $GLOBALS['custom_array']['community'];
$pastID = array();
$terms = array();
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}
Ok So I was able to figure this out after taking a look and feel a little slow here.
the $pastID needed to have $i variable when setting it and $d when referencing it on the next loop. The code below will create a hierarchy taxonomy up to 4+ deep using my variables for country, state, city, and community. It will check if the variable exist and if it does not it will make sure it has a parent to associate it with or not insert it. Anyways thanks.
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$i] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}

"Cannot get return value of a generator that hasn't returned " php backtracking

I am trying to do backtracking to solved a problem but I get this error:
Error: genator hasn´t returned
Fisrt I will introduce the main problem that the software must resolve:
I have been trying to create the software for a hospital, this
software must create a schedule with the doctors for each day. Each
day must have 5 assigned doctors, one for a specialty called "trauma",
another for "ucr" and another for "box13".
Before assigning doctors, the user must enter the number of holes of
each type that doctor can do that month. So I know how many "trauma",
"ucr" or "box13" have any doctor that month.
Aaah! one more thing, you can not assign a doctor two days in a row.
So I decided to create a backtracking algorithm, the problem is that I am getting a Generator object at the end of the execution but I don´t get a valid return.
function bt($ps){
if($ps->is_solution()){
return $ps->get_solution();
}
else{
yield from $ps->successors();
}
}
class Briker_vc_PS{
public function __construct( $decisiones, $diasTotalFinal, $fechaInicio, $box13, $ucr, $trauma, $numGuardiasAsig){
$this->decisiones= $decisiones;
$this->diasTotalFinal = $diasTotalFinal;
$this->fechaInicio = $fechaInicio;
$this->box13 = $box13;
$this->ucr = $ucr;
$this->trauma = $trauma;
$this->numGuardiasAsig = $numGuardiasAsig;
}
public function is_solution(){
return $this->numGuardiasAsig == $this->diasTotalFinal*5;
}
public function get_solution(){
return $this->decisiones;
}
public function state(){
return $this->decisiones[$this->fechaInicio];
}
public function successors(){
if( array_key_exists( $this->fechaInicio, $this->decisiones) == false ){
$this->decisiones[$this->fechaInicio] = [];
}
if( array_key_exists( 'ids', $this->decisiones[$this->fechaInicio]) == false ){
$this->decisiones[$this->fechaInicio]['ids'] = [];
}
if( array_key_exists( $this->fechaInicio ,$this->decisiones) and array_key_exists( 'box13' ,$this->decisiones) and array_key_exists( 'trauma' ,$this->decisiones) and array_key_exists( 'ucr' ,$this->decisiones)){
if( (count($this->decisiones['trauma'])==1) and (count($this->decisiones['ucr'])==2) and (count($this->decisiones['box13'])==2) ){
$this->fechaInicio = date("Y-m-d",strtotime($this->fechaInicio." +1 day"));
$this->decisiones[$this->fechaInicio]['date'] = $this->fechaInicio;
}
}
$anterior = date("Y-m-d",strtotime($this->fechaInicio." -1 day"));
$Lista=[];
if( array_key_exists( 'trauma' ,$this->decisiones) == false ){
foreach($this->trauma as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
$decisions[$this->fechaInicio]['trauma'] = [$key];
$auxtra= $this->trauma;
if($auxtra[$key] -1 == 0){
unset($auxtra[$key]);
}else{
$auxtra[$key] = $auxtra[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $this->ucr, $auxtra, $num));
}
}
}
if( (array_key_exists( 'box13' ,$this->decisiones) == false) or (count($this->decisiones['box13'])<2) ){
foreach($this->box13 as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'box13' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['box13'] = array();
}
$decisions[$this->fechaInicio]['box13'][] = $key;
$auxbox13= $this->box13;
if($auxbox13[$key] -1 == 0){
unset($auxbox13[$key]);
}else{
$auxbox13[$key] = $auxbox13[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt( new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $auxbox13, $this->ucr, $this->trauma, $num));
}
}
}
if( (array_key_exists( 'ucr' ,$this->decisiones) == false) or (count($this->decisiones['ucr'])<2) ){
foreach($this->ucr as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'ucr' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['ucr'] = array();
}
$decisions[$this->fechaInicio]['ucr'][] = $key;
$auxucr= $this->ucr;
if($auxucr[$key] -1 == 0){
unset($auxucr[$key]);
}else{
$auxucr[$key] = $auxucr[$key] -1;
}
$decisions[$this->fechaInicio]['ids'][] = $key;
$num = $this->numGuardiasAsig +1 ;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $auxucr, $this->trauma, $num));
}
}
}
}
protected $GuardiasMedico;
protected $decisiones;
}
And this is the main program
$month = $_REQUEST['mes'];
$year = $_REQUEST['any'];
$fecha_inicio = "01-".$month."-".$year;
// fisrt i get the number of "trauma", "ucr" and "box13" for each doctor
// And i create a array with it with key the doctor_id
$db = new SQLite3($dbname);
$result = $db->query('SELECT m.id, m.nombre, m.apellido, mgm.ucr, mgm.trauma, mgm.box13 FROM medico AS m INNER JOIN MedicoGuardiaMes AS mgm ON m.id = mgm.doctor_id WHERE m.borrado = 0 AND mgm.mes = '.$month.' AND mgm.any = '.$year);
$box13 = [];
$ucr = [];
$trauma = [];
while($res = $result->fetchArray()){
$box13[$res['id']] = $res['box13'];
$ucr[$res['id']] = $res['ucr'];
$trauma[$res['id']] = $res['trauma'];
}
// I create the solution array and add the last day from the previous month
$dataBaseDecisiones = [];
$anterior = date("Y-m-d",strtotime($fecha_inicio." -1 day"));
$dataBaseDecisiones[$anterior] = [];
$dataBaseDecisiones[$anterior]['ids'] = [];
$diasTotalFinal=cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Finally I create the initial object and starts the backtracking
$initial_ps = new Briker_vc_PS($dataBaseDecisiones, $diasTotalFinal, $fecha_inicio, $box13, $ucr, $trauma, $numGuardiasAsig);
var_dump( bt($initial_ps)->getReturn() );
I don´t know why this code is not working or if I am using yield the right way.
The problem that is reported happens because of the last line in your code:
bt($initial_ps)->getReturn();
When bt executes the else part it performs a recursive search until there is a return, and then it yields that value. But that does not finish the iterator's results and this yielded value is not considered the iterator's return value. So getReturn() triggers the exception you got.
You don't explain what you intend to get as output in that var_dump. If you want to output all the yielded results, then collect all those results first, for instance with iterator_to_array:
$iter = bt($initial_ps);
print_r(iterator_to_array($iter));
And only then you can execute:
print_r($iter->getReturn());

Big Associative Array into Smaller Associative Arrays using Array_filter

I'm working on calculating the pass ratings of various football players. I have a .txt file that I'm pulling the info from.
while($line = fgetcsv($fp, 255, ',')){
$rate = round(calcPR($line),2);
$rating[$line[0]] = $rate;
} return $rating;
That was the portion of my function where I'm using a $fp to read from my .txt file and here is where I'm trying to display the data, but before I attempt to display my data I try to split the data into pass ratings that are great,good,mediocre, and poor.
For a great rating, they need to be above 95 so I have:
$grtRating = array_filter($rating,function(){
return $rating > 95;
});
The rest of my code for good, mediocre, and poor looks just about the same, but with different criteria. How can I get this $grtRating array to store only the scores that are above 95?
Currently when I run my program it basically ignores the operators and displays all of the ratings no matter how low.
UPDATE:
Output of $poorRating array: (This is everything < 86)
Array ( [Cody Kessler] => 85.91 [Kirk Cousins] => 82.34 [Jacoby Brissett] => 81.68 [Ryan Tannehill] => 81.2 [Tyrod Taylor] => 79.29 [Ben Roethlisberger] => 77.49 [Shaun Hill] => 77.32 [Carson Palmer] => 74.79 [Jameis Winston] => 73.93 [Marcus Mariota] => 73.06 [Joe Flacco] => 71.77 [Cam Newton] => 70.32 [Josh McCown] => 70.25 [Trevone Boykin] => 69.2 [Jay Cutler] => 68.46 [Blake Bortles] => 67.13 [Brock Osweiler] => 66.1 [Blaine Gabbert] => 63.35 [Case Keenum] => 60.63 [Ryan Fitzpatrick] => 48.93 [Robert Griffin III] => 48.54 [Drew Stanton] => 34.36 [Kellen Clemens] => 2.07 )
I think the problem might be in how I output my code then. I have my links in an unordered list.
Here is an example:
<a href='pr.php?action=all'>All Ratings</a>
I have a pr.php?action=great',pr.php?action=good', pr.php?action=mediocre', andpr.php?action='poor'.
Here is how I output everything, is the problem how I do that?
$mode = 'all';
if ($_GET['action'] == 'great') $mode = 'great';
if ($_GET['action'] == 'good') $mode = 'good';
if ($_GET['action'] == 'mediocre') $mode = 'mediocre';
if ($_GET['action'] == 'poor') $mode = 'poor';
if($mode == 'great'){
foreach($greatRating as $name=>$pr){
echo "<tr><td>{$name}</td><td>{$pr}</td></tr>\n";
}
}
if($mode == 'good'){
foreach($goodRating as $name=>$pr){
echo "<tr><td>{$name}</td><td>{$pr}</td></tr>\n";
}
}
if($mode == 'mediocre'){
foreach($mediocreRating as $name=>$pr){
echo "<tr><td>{$name}</td><td>{$pr}</td></tr>\n";
}
}
if($mode == 'poor'){
foreach($poorRating as $name=>$pr){
echo "<tr><td>{$name}</td><td>{$pr}</td></tr>\n";
}
}
if($mode = 'all'){
foreach($rating as $name=>$pr){
echo "<tr><td>{$name}</td><td>{$pr}</td></tr>\n";
}
}
echo "</table></div>\n";
}
Would you please help me figure out where my error is?
Replace
$grtRating = array_filter($rating,function(){
return $rating > 95;
});
with
$grtRating = array_filter($rating, function($val) {
return $val > 95;
});
In the first one, you did not include the callback argument that contains the value passed from each iteration of the array, which will be the one used in your evaluation.

PHP Getting average grade

I need to get the average number of a grade in a function. Doesn't seem to work completly.. Thanks for your help.
This is what I have so far:
<?php
function povprecje($d,$t){
$v=0;
foreach($t as $x=>$y){
foreach($y as $d=>$grade){
$v = $v+$grade;
$v = $v/count($grade);
return $v;
}
}
}
$t = array(
"Student" => array(
"math" => 3,
"algebra" => 4,
"science" => 4
)
);
echo povprecje("math",$t);
?>
Maybe You wanted to achieve this?
function povprecje($sSubject, $aGrades) {
$iGradesSum = 0;
$iAmount = 0;
foreach($aGrades as $aStudentGrades) {
if(isset($aStudentGrades[$sSubject])) {
$iGradesSum+= $aStudentGrades[$sSubject];
$iAmount++;
}
}
return $iGradesSum / $iAmount;
}
Function call:
echo povprecje("math", $t);

Google Analytics PHP API (GAPI) non-mobile browsers

I am trying to display the top 5 of non-mobile browsers with GAPI.
I can't seem to find a way of doing this, is this even possible?
This is how I get the percentage of mobile visits:
$ga->requestReportData(GA_PROFILE_ID, array("isMobile"), array("visits"), '-visits', null, $startdate, $enddate);
foreach ($ga->getResults() AS $result) {
if ((string)$result == "Yes") $mobile["yes"] = $result->getVisits();
else $mobile["no"] = $result->getVisits();
}
This is how I ended up doing it:
public function getDevices($max = 5) {
$this->ga->requestReportData($this->profileid, array('mobileDeviceInfo'), array('visits'), '-visits', 'mobileDeviceInfo != (not set) && mobileDeviceInfo != (not provided)', $this->startdate, $this->enddate, 1, $max);
foreach ($this->ga->getResults() as $result) {
$device[] = (string)$result;
$visits[] = $result->getVisits();
}
if (!isset($device) OR !isset($visits)) {
$device[] = "Niet genoeg data beschikbaar";
$visits[] = "0";
}
$return = array("device" => $device, "visits" => $visits);
return $return;
}

Categories