Home > database >  using if statement count number of notes given in amount
using if statement count number of notes given in amount

Time:02-06

i have a assingment and i am so confuse i dont know how to solve my problem,

Assingment :

Make a system which should have the capability to analyze the total number of possible notes in a given amount using only if statement,

Example
Input:

Input amount: 575

Output

Total number of notes:

500: 1
100: 0
50: 1
20: 1
10: 0
5: 1
2: 0
1: 0

plese tell me how i write code of this,

i need your help i don't know how i make this,

CodePudding user response:

Here's using the numbers 500, 100, 50, 20, 10, 5, 2, 1:

function get_breakdown($number) {
    $notes = [500, 100, 50, 20, 10, 5, 2, 1];
    $breakdown = [];

    foreach ($notes as $note) {
        if ($number >= $note) {
            $count = intval($number / $note);
            $number = $number - ($count * $note);
            $breakdown[$note] = $count;
        }
    }

    return $breakdown;
}

$number = 575;
$breakdown = get_breakdown($number);

foreach ($breakdown as $note => $count) {
    if ($count > 0) {
        echo $count . " x " . $note . "<br>";
    }
}

This will output: 1 x 500 1 x 50 1 x 20 1 x 5

CodePudding user response:

Assuming the keys won't change:

<?php

function getPossibleNotes($input, $keysArray = [500, 100, 50, 20, 10, 5, 2, 1])
{
    $responseArray = array_combine($keysArray, array_fill(0, count($keysArray), 0));

    foreach($keysArray as $comparison){
        if($input >= $comparison){
            $input -= $comparison;
            $responseArray[$comparison] = 1;
        }
        if($input <= 0){
            break;
        }
    }
    return $responseArray;
}

//When Input = 575

print_r(getPossibleNotes(575));

/*
Array
(
    [500] => 1
    [100] => 0
    [50] => 1
    [20] => 1
    [10] => 0
    [5] => 1
    [2] => 0
    [1] => 0
)*/





  • Related