How to get remaining value number in array using foreach - php

Basically i want to get the amount and the remaining value number but i didn't get the exact value.
this is my following code
$arr = [5000,2000];
$return = 0;
foreach($arr as $val) {
$sum = (3000 * 10) / 9;
if($val < $sum) {
$v += $val;
$return = ($v % $sum);
if($return == $v)
$return = 0;
} else {
$return = $val;
}
$amount = abs($val - $ret);
print_r("Return : ".$return . " Amount : " .$amount."<br>");
}
the result
Return : 5000 Amount : 5000
Return : 0 Amount : 2000
but that is wrong value, i want to get like this
Return : 1667 Amount : 3333
Return : 2000 Amount : 0
Summary :
I want to limit number base on $sum value and return the remaining value and get the amount,
so i write that code above but i can't figure it out.
sorry for my bad english
Thanks, sorry i'm new in php

If i understood you right. You need this.
$values = [5000, 2000];
foreach ($values as $value) {
$n = 3333;
$remain = $value - $n;
if ($remain < 0) {
print 'Return : ' . $value . ' Amount : 0';
} else {
print 'Return : ' . $remain . ' Amount : ' . $n;
}
}

Related

Basic perceptron for AND gate in PHP, am I doing it right? Weird results

I'd like to learn about neural nets starting with the very basic perceptron algorithm. So I've implemented one in PHP and I'm getting weird results after training it. All the 4 possible input combinations return either wrong or correct results (more often the wrong ones).
1) Is there something wrong with my implementation or the results I'm getting are normal?
2) Can this kind of implementation work with more than 2 inputs?
3) What would be the next (easiest) step in learning neural nets after this? Maybe adding more neurons, changing the activation function, or ...?
P.S. I'm pretty bad at math and don't necessarily understand the math behind perceptron 100%, at least not the training part.
Perceptron Class
<?php
namespace Perceptron;
class Perceptron
{
// Number of inputs
protected $n;
protected $weights = [];
protected $bias;
public function __construct(int $n)
{
$this->n = $n;
// Generate random weights for each input
for ($i = 0; $i < $n; $i++) {
$w = mt_rand(-100, 100) / 100;
array_push($this->weights, $w);
}
// Generate a random bias
$this->bias = mt_rand(-100, 100) / 100;
}
public function sum(array $inputs)
{
$sum = 0;
for ($i = 0; $i < $this->n; $i++) {
$sum += ($inputs[$i] * $this->weights[$i]);
}
return $sum + $this->bias;
}
public function activationFunction(float $sum)
{
return $sum < 0.0 ? 0 : 1;
}
public function predict(array $inputs)
{
$sum = $this->sum($inputs);
return $this->activationFunction($sum);
}
public function train(array $trainingSet, float $learningRate)
{
foreach ($trainingSet as $row) {
$inputs = array_slice($row, 0, $this->n);
$correctOutput = $row[$this->n];
$output = $this->predict($inputs);
$error = $correctOutput - $output;
// Adjusting the weights
$this->weights[0] = $this->weights[0] + ($learningRate * $error);
for ($i = 0; $i < $this->n - 1; $i++) {
$this->weights[$i + 1] =
$this->weights[$i] + ($learningRate * $inputs[$i] * $error);
}
}
// Adjusting the bias
$this->bias += ($learningRate * $error);
}
}
Main File
<?php
require_once 'vendor/autoload.php';
use Perceptron\Perceptron;
// Create a new perceptron with 2 inputs
$perceptron = new Perceptron(2);
// Test the perceptron
echo "Before training:\n";
$output = $perceptron->predict([0, 0]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([0, 1]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([1, 0]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([1, 1]);
echo "{$output} - " . ($output == 1 ? 'correct' : 'nope') . "\n";
// Train the perceptron
$trainingSet = [
// The 3rd column is the correct output
[0, 0, 0],
[0, 1, 0],
[1, 0, 0],
[1, 1, 1],
];
for ($i = 0; $i < 1000; $i++) {
$perceptron->train($trainingSet, 0.1);
}
// Test the perceptron again - now the results should be correct
echo "\nAfter training:\n";
$output = $perceptron->predict([0, 0]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([0, 1]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([1, 0]);
echo "{$output} - " . ($output == 0 ? 'correct' : 'nope') . "\n";
$output = $perceptron->predict([1, 1]);
echo "{$output} - " . ($output == 1 ? 'correct' : 'nope') . "\n";
I must thank you for posting this question, I have wanted a chance to dive a little deeper into neural networks. Anyway, down to business. After tinkering around and verbose logging what all is happening, it ended up only requiring 1 character change to work as intended:
public function sum(array $inputs)
{
...
//instead of multiplying the input by the weight, we should be adding the weight
$sum += ($inputs[$i] + $this->weights[$i]);
...
}
With that change, 1000 iterations of training ends up being overkill.
One bit of the code was confusing, different setting of weights:
public function train(array $trainingSet, float $learningRate)
{
foreach ($trainingSet as $row) {
...
$this->weights[0] = $this->weights[0] + ($learningRate * $error);
for ($i = 0; $i < $this->n - 1; $i++) {
$this->weights[$i + 1] =
$this->weights[$i] + ($learningRate * $inputs[$i] * $error);
}
}
I don't necessarily understand why you chose to do it this way. My unexperienced eye would think that the following would work as well.
for ($i = 0; $i < $this->n; $i++) {
$this->weight[$i] += $learningRate * $error;
}
Found my silly mistake, I wasn't adjusting the bias for each row of a training set as I accidentally put it outside the foreach loop. This is what the train() method should look like:
public function train(array $trainingSet, float $learningRate)
{
foreach ($trainingSet as $row) {
$inputs = array_slice($row, 0, $this->n);
$correctOutput = $row[$this->n];
$output = $this->predict($inputs);
$error = $correctOutput - $output;
// Adjusting the weights
for ($i = 0; $i < $this->n; $i++) {
$this->weights[$i] += ($learningRate * $inputs[$i] * $error);
}
// Adjusting the bias
$this->bias += ($learningRate * $error);
}
}
Now I get the correct results after training each time I run the script. Just 100 epochs of training is enough.

PHP sum each loop value

I wanted to make a simple calculations to summarized what I purchased.
Using $_GET every time the value is updated it should save in an array then when 'start' is executed, it gives the sum. Sorry the codes here are just googled and I'm not really a programmer. I don't know how to combine the two sets of code (array + sum).
$number = $_GET ['input'];
$arr = array ($number);
$data = array($arr);
foreach ($tareas as $tarea) {
$data[] = $tarea;
}
var_dump($data);
$sum = 0;
foreach($group as $key=>$arr) {
$sum+= $arr;
}
echo $sum;
So I got this code from withinweb.com and modified to make it simpler.
<?php session_start();
$products = array($_GET["prod"]);
$amounts = array($_GET ["cost"]);
if ( !isset($_SESSION["total"]) ) {
$_SESSION["total"] = 0;
for ($i=0; $i< count($products); $i++) {
// $_SESSION["qty"][$i] = 0;
$_SESSION["amounts"][$i] = 0;
}
}
//---------------------------
//Reset
if ( isset($_GET['reset']) )
{
if ($_GET["reset"] == 'true')
{
unset($_SESSION["qty"]); //The quantity for each product
unset($_SESSION["amounts"]); //The amount from each product
unset($_SESSION["total"]); //The total cost
unset($_SESSION["cart"]); //Which item has been chosen
}
}
//---------------------------
//Add
if ( isset($_GET["add"]) )
{
$i = $_GET["add"];
$qty = $_SESSION["qty"][$i] + 1;
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
$_SESSION["cart"][$i] = $i;
$_SESSION["qty"][$i] = $qty;
}
//---------------------------
//Delete
if ( isset($_GET["delete"]) )
{
$i = $_GET["delete"];
$qty = $_SESSION["qty"][$i];
$qty--;
$_SESSION["qty"][$i] = $qty;
//remove item if quantity is zero
if ($qty == 0) {
$_SESSION["amounts"][$i] = 0;
unset($_SESSION["cart"][$i]);
}
else
{
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
}
}
//cart
if ( isset($_SESSION["cart"]) ) {
$total = 0;
foreach ( $_SESSION["cart"] as $i ) {
echo '' . $products[$_SESSION["cart"][$i]] . ' - ' . $_SESSION["amounts"][$i] . '<br>';
$total = $total + $_SESSION["amounts"][$i];
}
$_SESSION["total"] = $total;
echo'
<br>
Total : ' . $total . '
';
}
?>
When I input ?add=0&prod=apple&cost=100, it gives me:
apple - 100
Total : 100
But when I add another session, ?add=1&prod=orange&cost=200 it doesn't give the right answer.
orange - 100
- 0
Total : 100
It should return me this value, I'm puzzled where could be the error.
apple - 100
orange - 200
Total : 300
Yes, I'm not a coder, but trying to solve a big problem.. :) Thanks for those who help.

floor value in php function

I have one android application in which I am using PHP API for get data from server. This is quote application and in which I have function of counting likes and shares of quotes. I am converting that count in k style number like 1K for 1000 etc with below function.
function Get_convert_to($value)
{
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . ' K';
} elseif ($value > 999999) {
$result = floor($value / 1000000) . ' M';
} else {
$result = $value;
}
return $result;
}
Now my issue is its returning 1K for even 1400....I want 1.4K for 1400. How can I do that?
Thanks
To get value like 1.4 (one decimal) use parameter to control decimal
<?php
function Get_convert_to($value){
if ($value > 1000) {
$result = round(($value / 1000),1) . ' K';
} elseif ($value > 999999) {
$result = round(($value / 1000000),1) . ' M';
} else {
$result = $value;
}
return $result;
}
echo Get_convert_to(1400);
?>
Output:
1.4K
You simply need to remove floor because it will give you nearest lower value after division. ec 1.4/1.2 will become 1
function Get_convert_to($value){
if ($value > 999 && $value <= 999999) {
$result = ($value / 1000) . ' K';
} elseif ($value > 999999) {
$result = ($value / 1000000) . ' M';
} else {
$result = $value;
}
return $result;
}
If you want control the number of decimal you can use number format on division
$result = number_format($value / 1000, 1, '.', '') . ' K'; ;

PHP - Generate a round number according to another number

How can generate a round number according to a number in PHP?
Ex: if my number is
235112, then I should get 300000 or
122432, then I should get 200000 or
328522, then I should get 400000 ?
You can use a helper function to have the round-up:
function roundup ($value, $places=0) {
if ($places < 0)
{
$places = 0;
}
$mult = pow(10, $places);
return ceil($mult*$value)/$mult;
}
and use it like roundup($value,-5); to roundup 5 digits
String approach :
$s as string input
$s = ($s[0] === '9' ? '1' . str_repeat('0', strlen($s)) : (((int)$s[0]) + 1) . str_repeat('0', strlen($s) - 1));
modified version of Gardax answer:
<?php
$str = "328522";
function ceiling($number)
{
$strlen = strlen($number);
$significance = "1";
for($i=0; $i<($strlen-1);$i++)
{
$significance .= "0";
}
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
echo ceiling($str);
?>

PHP based Blackjack script ( aces)

I've got a question. I've build this PHP script, it works just fine, except for the fact that aces don't work properly. If I draw 5 A 5 5, it thinks I have 26 etc.
Does anyone know how to solve this problem?
Function to evaluateHand:
function evaluateHand($hand) {
global $faces;
$value = 0;
foreach ($hand as $card) {
$values = explode("|",$card);
$value1= $values[0];
if($value1=="Q" OR $value1=="J" OR $value1=="K"){
$value = intval($value) + 10;
}
if ($value > 10 && $value1 == "A") {
$value = intval($value) + 1; // An ace can be 11 or 1
}
elseif($value < 12 && $value1 == "A"){
$value = intval($value) + 11; // An ace can be 11 or 1
}
else {
$value = intval($value) + intval($value1);
}
}
return $value;
}
Sort the list of cards so that aces are evaluated last.
As Quentin said, treat aces last. Also count how many aces there are in the hand (to avoid giving 11 to one ace and overflow if you have, let's say, three aces, instead of counting 1+1+1).
Treat all aces together, dividing the number of points left by the number of aces. If result is superior to 11, give 11 to one and 1 to the others. If not, give 1 to all aces.
Why global $faces;?
To make your code working just add asort($hand); in the top of the function.
This will order the array, to put the A as last.
EDIT: You are right. I have changed the function to always evaluate the aces as last.
function evaluateHand($hand) {
global $faces;
$value = 0;
$aces = 0;
foreach ($hand as $card) {
$values = explode("|",$card);
$value1= $values[0];
if($value1 == "A") {
$aces++;
}
else {
if($value1=="Q" OR $value1=="J" OR $value1=="K"){
$value = intval($value) + 10;
}
else {
$value = intval($value) + intval($value1);
}
}
}
while($aces > 0) {
if($value > 10) {
$value = intval($value) + 1;
}
elseif($value < 12){
$value = intval($value) + 11; // An ace can be 11 or 1
}
$aces--;
}
return $value;
}
As you said in one of the comments, the asort alone won't work, as the sorting goes like this:
0-9, then A to Z, so The Aces are still being checked before the other figures.
I modified a bit your function so it works better in that way:
function evaluateHand($hand) {
asort($hand);
print_r($hand);
$aces = 0;
global $faces;
$value = 0;
foreach ($hand as $card) {
$values = explode("|",$card);
$value1= $values[0];
if($value1=="Q" OR $value1=="J" OR $value1=="K"){
$value = intval($value) + 10;
} elseif($value1 == "A") {
$aces++;
} else {
$value = intval($value) + intval($value1);
}
}
if($aces > 0){
for($a = 0; $a < $aces; $a++){
if ($value > 10) {
$value = intval($value) + 1; // An ace can be 11 or 1
}elseif($value < 12){
$value = intval($value) + 11; // An ace can be 11 or 1
}
}
}
return $value;
}
What I have done is create an Aces counter ($aces = 0), and when there's an Ace we skip the sum, and increase the counter, after the foreach loop then we sum the desired value based on the total value of the hand, with another loop based on the aces we have in the array.

Categories