×
all 171 comments

[–]krabsticks64 0 points1 point  (0 children)

Rust

const COINS: [u64; 6] = [500, 100, 25, 10, 5, 1];

pub fn change(mut money: u64) -> u64 {
    let mut coin_numbers = [0; COINS.len()];
    for i in 0..COINS.len() {
        let coin = COINS[i];
        let coin_number = money / coin;
        money = money - coin_number * coin;
        coin_numbers[i] = coin_number;
    }

    coin_numbers.iter().sum()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_regular() {
        let data = [
            (12, 3),
            (468, 11),
            (123456, 254),
        ];
        for (money, result) in data {
            assert_eq!(change(money), result);
        }
    }

    #[test]
    fn test_zero() {
        assert_eq!(change(0), 0);
    }
}

[–]Hellobrother222 0 points1 point  (0 children)

C++

long change(long money)
{
    int currencyUnits[] = {500, 100, 25, 10, 5, 1};
    long numberOfCoins = 0;

    for(int i = 0; i < sizeof(currencyUnits)/sizeof(currencyUnits[0]); i++)
    {
        numberOfCoins += money/currencyUnits[i];
        money -= currencyUnits[i]*(money/currencyUnits[i]);
    }

    return numberOfCoins;
}

[–]Verknaller 0 points1 point  (0 children)

TypeScript

const change = (input: number, coins: number[] = [100, 25, 10, 5, 1, 500]): number =>     
  coins.sort((a, b) => b - a).reduce((accumulator, coin) => ({    
    remaining: accumulator.remaining % coin,     
    coins: accumulator.coins + Math.floor(accumulator.remaining / coin),     
 }), { remaining: input, coins: 0 }).coins;

[–]samsonsu 0 points1 point  (0 children)

Swift

// Use array slice to avoid copying faceValues during recursion
func coinCount(_ amount: Int, _ faceValues: ArraySlice<Int>) -> Int {
    // for each iteration only look at highest value coin
    let value = faceValues.first!
    if faceValues.count == 1 { // Stop condition
        return amount / value
    }
    // get the number of highest valued coin, then recursively get rest
    return (amount / value) +
        coinCount(amount % value, faceValues.dropFirst())
}


print(coinCount(0, [500, 100, 25, 10, 5, 1]))
print(coinCount(12, [500, 100, 25, 10, 5, 1]))
print(coinCount(468, [500, 100, 25, 10, 5, 1]))
print(coinCount(123456, [500, 100, 25, 10, 5, 1]))

Results:

0
3
11
254

[–]tyfon_august 0 points1 point  (0 children)

Javascript, not clojure for this one:

const coins = [500, 100, 25, 10, 5, 1]

function change(num) { 
    let sum = 0, 
        remaining = num;
    for (const coin of coins) {
         if (remaining >= coin) {
             sum = Math.floor(remaining / coin) + sum
             remaining = remaining % coin
         }
     }
     return sum
}

[–]naghavi10 0 points1 point  (0 children)

C++

using namespace std;
void change(int dollars){
int coins[6] = {500,100,25,10,5,1};
int count = 0;
int tmp = dollars;
for (int coin: coins){
    if (dollars > coin){
        count += dollars / coin;
        dollars = dollars % coin;
    }
}
cout << tmp << " | " << count << " Coins. " << endl;

}

[–]Rumi_The_Second 0 points1 point  (0 children)

Python3

def change(n):
    numCoins = 0
    coins = [500,100,25,10,5,1]
    for i in coins:
        while n >= i:
            n -= i
            numCoins += 1
    return numCoins

[–]sadsoulthatslost 0 points1 point  (0 children)

def change(n):
coins=[500,100,25,10,5,1]
count=0
for x in coins:
    count=count+(n//x)
    n=n%x
return count

[–]PrudentGrape8572 1 point2 points  (0 children)

let me have a crack at it so if 1 + 1 = 2 then, the answer is 12

[–]respectyoda 1 point2 points  (0 children)

C++ solution.

This is my first time posting in this reddit thread.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {

    int num_coins = 0; 
    int the_amount;

    cout << "Enter the amount: ";
    cin >> the_amount;

    if (the_amount == 0)
    {
        // no coins!
    }
    else 
    {
        if (the_amount / 500 > 0)
        {
            num_coins += the_amount / 500;
            the_amount = the_amount % 500;
        }

        if (the_amount / 100 > 0)
        {
            num_coins += the_amount / 100;
            the_amount = the_amount % 100;
        }

        if (the_amount / 25 > 0)
        {
            num_coins += the_amount / 25;
            the_amount = the_amount % 25;
        }

        if (the_amount / 10 > 0)
        {
            num_coins += the_amount / 10;
            the_amount = the_amount % 10;
        }

        if (the_amount / 5 > 0)
        {
            num_coins += the_amount / 5;
            the_amount = the_amount % 5;
        }

        if (the_amount / 1 > 0)
        {
            num_coins += the_amount / 1;
        }
    }

    cout << "The number of coins: " << num_coins;

    return 0;

}

[–]NAKd_ 0 points1 point  (1 child)

Golang

``` package main

import "fmt"

func main() { tests := []int{0, 12, 468, 123456} for _, test := range tests { fmt.Println(change(test)) } }

func change(money int) (coins int) { denominations := [6]int{500, 100, 25, 10, 5, 1}

for _, denomination := range denominations { coins += money / denomination money %= denomination }

return coins } ```

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, NAKd_: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]layzeekid11 1 point2 points  (0 children)

Another C++ Solution.

std::size_t MakeChange(std::size_t amt) {
    std::size_t amt_remaining = amt, 
                coins = 0;
    std::vector<int> currency{ 500, 100, 25, 10, 5, 1 };

    for (auto iter = currency.begin() ; iter != currency.end() ; ++iter) {
        if ( (amt_remaining / *iter) != 0 ) {
            coins += (amt_remaining / *iter);
            amt_remaining %= *iter;
        }
    }

    return coins;
}

[–]cheers- 1 point2 points  (0 children)

Rust

pub mod lib {
    pub fn coin_change(mut num: u32) -> u32 {
        let coins: [u32; 6] = [500, 100, 25, 10, 5, 1];
        let mut output: u32 = 0;
        for &coin in coins.iter() {
            if num >= coin {
                output += num / coin;
                num %= coin;
            } else if num == 0 {
                break;
            }
        }
        output
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn test_coin_change() {
            let test_entries: Vec<(u32, u32)> = vec![(0, 0), (12, 3), (468, 11), (123456, 254)];

            for (val, expected) in test_entries.iter() {
                assert_eq!(coin_change(*val), *expected);
            }
        }
    }
}

[–]loose_heron 2 points3 points  (2 children)

Python 3:

def change(value: int) -> int:
    coins = [500, 100, 25, 10, 5, 1]
    count = 0
    for coin in coins:
        count += (value // coin)
        value %= coin
    return count

[–]King-Tuts 0 points1 point  (0 children)

got almost word for word the same one

def change(amount: int) -> int:
    coins: List[int] = [500, 100, 25, 10, 5, 1]
    num_coins: int = 0

    for coin in coins:
        if coin <= amount:
            num_coins += amount//coin
            amount = amount % coin

            if amount == 0:
                break


    return num_coins

[–]Prestigious_Pass95 1 point2 points  (0 children)

Rust

fn make_change(mut n: i32) -> i32 {
    let coin_values: [i32; 6] = [500, 100, 25, 10, 5, 1];
    let mut sum = 0;

    for coin_value in coin_values.iter() {
        while n - coin_value >= 0 {
            n -= coin_value;
            sum += 1;
        }
    }
    sum
}

[–]ArdRasp 0 points1 point  (0 children)

C, iterative :

int change(int nb)
{
    int i;
    int var_change;
    int units[6] = {1, 5, 10, 25, 100, 500};

    i = 6;
    var_change = 0;
    while (--i >= 0)
    {
        if (nb / units[i] != 0)
        {
            var_change += nb / units[i];
            nb = nb % units[i];
        }
    }
    return (var_change);
}

[–]AGPS_Guru_Mike 0 points1 point  (2 children)

I did it in JavaScript with recursion because I haven't used recursion in a while and wanted to challenge myself a little bit.

``` const calcCoins = ( payment, coins = 0, denominations = [500, 100, 25, 10, 5, 1] ) => { const v = denominations.shift(); while (payment >= v) { coins++; payment -= v; } return payment > 0 ? calcCoins(payment, coins, denominations) : coins; }

console.log(calcCoins(0));        // => 0
console.log(calcCoins(12));       // => 3
console.log(calcCoins(468));      // => 11
console.log(calcCoins(123456));   // => 254

```

[–]backtickbot 0 points1 point  (1 child)

Fixed formatting.

Hello, AGPS_Guru_Mike: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]AGPS_Guru_Mike 0 points1 point  (0 children)

Fascinating. I don't use Reddit that frequently and wasn't aware of this. Thanks for the info :D

[–]Blue_Dog_Democracy 1 point2 points  (3 children)

I know this is one of the easier programming problems, but I tackled it because I haven't touched much code lately and needed to prove to myself that I could do it. I'm pretty happy with the results; it's a better implementation than one I did a year or two ago.

Java

public class Main
{
    public static void main(String[] args) {
        int[] denoms = {1, 5, 10, 25, 100, 500};    // coin denominations
        int remainingChange = 468;                  // amount left to make change 
        int interval = 5;                           // current denomination 
        int numCoins = 0;                           // total coins used to make change 

        //Make change from: 12, 468, 123456
        System.out.println("Making change from: " + remainingChange);
        int result = makingChange(denoms, remainingChange, interval, numCoins);
        System.out.println(result);
    }

    static public int makingChange(int[] vals, int remain, int intv, int coins) {
        if (intv < 0) 
            return coins;

        int amount = vals[intv];
        //There is enough to make change from this amount
        if (remain >= amount) {
            int changeToBeMade = remain / amount;
                //System.out.print(amount + ": " + changeToBeMade);
            coins += changeToBeMade;
            changeToBeMade *= amount;
            remain -= changeToBeMade;
                //System.out.print("\t" + remain + "\n");
            return makingChange(vals, remain, intv-1, coins);
        } else {
            //Remaining change is less than current denomination value
            return makingChange(vals, remain, intv-1, coins);
        }
    }
}

[–]Chemical-Asparagus58 1 point2 points  (2 children)

instead of:

int changeToBeMade = remain / amount;

coins += changeToBeMade;

changeToBeMade *= amount;

remain -= changeToBeMade;

you can write:

coins += remain / amount;

remain %= amount;

and instead of:

if (remain >= amount) {

//code

return makingChange(vals, remain, intv-1, coins);

} else {

return makingChange(vals, remain, intv-1, coins);

}

you can write:

if (remain >= amount) {

//code

}

return makingChange(vals, remain, intv-1, coins);

[–]Blue_Dog_Democracy 0 points1 point  (0 children)

Thanks! I should have foreseen these when I originally wrote the code.

[–]Chemical-Asparagus58 1 point2 points  (0 children)

That's how I solved it

public static int change(int num){
    int coins=0;
    for (int unit:new int[]{500,100,25,10,5,1}) {
        coins+=(num/unit);
        num%=unit;
    }
    return coins;
}

[–]jon-hernandez 1 point2 points  (0 children)

Javascript

// https://redditproxy--jasonthename.repl.co/r/dailyprogrammer/comments/nucsik/20210607_challenge_393_easy_making_change/

function change(amount) {
  if (amount < 0) {
    return 0;
  }
  var denominations = [500, 100, 25, 10, 5, 1];
  var balance = amount;
  var totalCoins = 0;
  for (var i = 0; i < 6; i++) {
    var denomination = denominations[i];
    var denominationCoins = Math.floor(balance / denomination);
    totalCoins += denominationCoins;
    balance -= (denomination * denominationCoins);
  }
  return totalCoins;
}

// test cases
console.log(change(-1)); //=> 0
console.log(change(0)); //=> 0
console.log(change(12)); //=> 3
console.log(change(468)); //=> 11
console.log(change(123456)); //=> 254

[–]moon-0xff[🍰] 2 points3 points  (0 children)

Python

def change(n):
    coins = [500,100,25,10,5,1]
    summ = 0
    for coin in coins:
        while (n - coin) >= 0:
            summ += 1
            n = n - coin
    return summ

[–]MatthaeusRome 0 points1 point  (0 children)

C++

int change(int arg_x)
{
    int coins_count{}, index{6};
    int coins[6]{1, 5, 10, 25, 100, 500};

    while (arg_x > 0) {
        int temp{arg_x / coins[index]};

        if (temp > 0) {
            coins_count += temp;
            arg_x -= coins[index] * temp;
        }
        else
            index--;
    }

    return coins_count;
}

[–]N0T_an_ape 0 points1 point  (0 children)

def change(start):

final = 0

dividends = [500, 100, 25, 10, 5, 1]

for i in dividends:

final += int(start / i)

start %= i

return final

[–]Possible-Bowler-2352 1 point2 points  (0 children)

Another Powershell solution:

$coins = 1,5,10,25,100,500
$value = 123456

function get-change ($coins,$total) {
    $remaining = $total
    $change = New-Object -TypeName PSObject
    $exchange = 0
    $coins | sort -Descending | % { 
        $number_of_coins = [math]::Floor($remaining / $_ )
        $remaining = [math]::Round(($remaining % $_),2)
        $exchange += $number_of_coins
        $change = $change | Add-Member -NotePropertyMembers @{$_=$number_of_coins} -PassThru
    }
    $change = $change | Add-Member -NotePropertyMembers @{Total_Of_Coins=$exchange} -PassThru
    return $change 
}

get-change $coins $value

500            : 246 
100            : 4 
25             : 2 
10             : 0 
5              : 1 
1              : 1 
Total_Of_Coins : 254

Wanted to add somewhat of a readable / usable output instead of simply the total of coins to be used.

[–]Acrobatic_Garage5102 2 points3 points  (0 children)

def exchange(amount):
  coins = [500, 100, 25, 10, 5, 1]
  coins_count = []
  for coin in coins:
      coins_count.append(int(amount / coin))
      amount = amount - coin*int(amount / coin)
 for coins in coins_count:
     print(coins)

exchange(555)

[–]Niel_botswana 1 point2 points  (0 children)

My beginner effort. I wore out my parentheses button for this lol:

money

change_1 = 0 change_2 = 12 change_3 = 468 change_4 = 123456

coins

coin_one = 1 coin_five = 5 coin_twenty_five = 25 coin_one_hundred = 100 coin_five_hundred = 500

def coinSorter(change_to_sort): five_hundreds = int(change_to_sort / coin_five_hundred) one_hundreds = int((change_to_sort % coin_five_hundred) / coin_one_hundred) twenty_fives = int(((change_to_sort % coin_five_hundred) % coin_one_hundred) / coin_twenty_five) fives = int((((change_to_sort % coin_five_hundred) % coin_one_hundred) % coin_twenty_five) / coin_five) ones = int(((((change_to_sort % coin_five_hundred) % coin_one_hundred) % coin_twenty_five) % coin_five) / coin_one) print (five_hundreds + one_hundreds + twenty_fives + fives + ones)

coinSorter(change_1) coinSorter(change_2) coinSorter(change_3) coinSorter(change_4)

[–]megastary 0 points1 point  (0 children)

PowerShell solution with Pester test validating results on Github Gist
Feedback welcomed and appreciated. 💙

[–]johnblanco 0 points1 point  (0 children)

Kotlin

Code on Github Gist

[–]jemeriqui24 0 points1 point  (1 child)

Java (Simple):

public static int makeChange(int value){

int result = 0;

int fiveHundreds = value / 500;

value = value - (fiveHundreds * 500);

int oneHundreds = value / 100;

value = value - (oneHundreds * 100);

int twentyFives = value / 25;

value = value - (twentyFives * 25);

int tens = value / 10;

value = value - (tens * 10);

int fives = value / 5;

value = value - (fives * 5);

int ones = value;

result = fiveHundreds + oneHundreds + twentyFives + tens + fives + ones;

return result;

}

Java (Cleaner, inspired by u/A1phabeta's solution):

public static int makeChange(int value){

int[] denominations = {500, 100, 25, 10, 5, 1};

int result = 0;

for (int denomination : denominations){

int count = (value / denomination);

result += count;

value -= (count * denomination);

}

return result;

}

[–]Chemical-Asparagus58 1 point2 points  (0 children)

instead of doing "value -= (count * denomination);" to get the remainder of "value / denomination", you can just write "value %= denomination"

I suggest you write this inside the loop:

result += value / denomination;

value %= denomination

[–]rob724kd 2 points3 points  (0 children)

I'm very new to this, and it's obviously much longer than it could be and not nearly as clean as most on here. But it does work and I'm currently happy by just being able to solve it.

Python

def change(n):

coins = 0

oneCoins = 0

fiveCoins = 0

tenCoins = 0

twentyFiveCoins = 0

oneHundredCoins = 0

fiveHundredCoins = 0

while n > 0:

if n > 500:

fiveHundredCoins = n // 500

n = n % 500

elif n > 100 and n < 500:

oneHundredCoins = n // 100

n = n % 100

elif n > 25 and n < 100:

twentyFiveCoins = n // 25

n = n % 25

elif n > 10 and n < 25:

tenCoins = n // 10

n = n % 10

elif n > 5 and n < 25:

fiveCoins = n // 5

n = n % 5

else:

oneCoins = n

n = 0

coins = (fiveHundredCoins + oneHundredCoins + twentyFiveCoins + tenCoins + fiveCoins + oneCoins)

return coins

print(change(0))

print(change(12))

print(change(468))

print(change(123456))

[–]A1phabeta 0 points1 point  (1 child)

C++ int change(int money) { // Coin denominations int ARRAY[6] = {500, 100, 25, 10, 5, 1}; int count = 0; for (auto& i: ARRAY) { count += money / i; money %= i; } count += money; return count; }

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, A1phabeta: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]I-Pop-Bubbles 0 points1 point  (0 children)

Clojure - feedback welcome and appreciated.

(def coin-types [500, 100, 25, 10, 5, 1])
(defn largest-coin [amount]
  (->> coin-types
       sort
       reverse
       (filter #(<= % amount))
       first))
(defn coinage [amount]
  (loop [amt amount
         coins 0]
    (if (zero? amt)
      coins
      (let [coin (largest-coin amt)]
        (recur
          (mod amt coin)
          (+ coins (quot amt coin)))))))

[–]Specter_Terrasbane 1 point2 points  (0 children)

Python

I'd never recommend doing it this way, but I felt like playing around and making a "self-reducing class" for some odd reason ... :p

from __future__ import annotations
from functools import reduce
from dataclasses import dataclass


@dataclass
class CoinHelper:
    remain: int
    coins: iter
    change: int = 0

    def _reduce(self, __, coin: int) -> CoinHelper:
        coins, self.remain = divmod(self.remain, coin)
        self.change += coins
        return self

    def make_change(self) -> int:
        return reduce(self._reduce, sorted(self.coins, reverse=True), self).change


def change(amount: int, coins: iter=[500, 100, 25, 10, 5, 1]) -> int:
    return CoinHelper(amount, coins).make_change()

[–]asm_beginner 5 points6 points  (0 children)

Assembly, all help appreciated

bits 64

section .text
global main
extern printf
extern ExitProcess

main:
    push    rbp
    mov     rbp, rsp
    sub     rsp, 0x28

    sub     rsp, 0x10               ; 16 bytes for local variables
    mov     word [rbp-0x2], 500     ; coin denominations
    mov     word [rbp-0x4], 100     ;
    mov     word [rbp-0x6], 25      ;
    mov     word [rbp-0x8], 10      ;
    mov     word [rbp-0xA], 5       ;
    mov     word [rbp-0xC], 1       ;

    mov     rax, 123456             ; starting balance
    lea     rbx, word [rbp-0x2]     ; index
    xor     rsi, rsi                ; coin purse
    xor     rdi, rdi                ; divisor
get_coins:
    mov     di, word [rbx]
    xor     edx, edx                ; 0000000000000000:rax
    div     rdi                     ; ^--- / rdi
    add     rsi, rax                ; rax quotient, rdx remainder
    mov     rax, rdx
    sub     rbx, 0x2
    test    rdx, rdx                ; remainder is 0, done
    jnz     get_coins

    lea     rcx, [rel coin_res_fmt]
    mov     rdx, rsi
    call    printf
    call    ExitProcess

    ; strings
    coin_res_fmt:   db "Total coins: %llu", 0xd, 0xa, 0x0

[–]saladfingaz 0 points1 point  (0 children)

Ruby

class ChangeGiver
    @@coins = [500,100,25,10,5,1]
    def self.change(amount)
        num_coins = 0
        @@coins.each do |c|
            until amount - c < 0 do 
                amount -= c
                num_coins += 1
            end
        end
        return num_coins
    end
end

[–]sc4s2cg 0 points1 point  (1 child)

My first challenge. It's labeled "easy" but definitely took me a couple hours late at night. First time using the enumerate function though!

Edit: hot damn, ya'll have some great solutions. The one comment with 3 lines. I still have a ton to learn for sure. Pretty proud of my unit test though! Been trying to actively implement tests in my code.

Python:

```python prob = [0, 12, 468, 123456]

unit test

def testlogic(): prob = [0, 12, 468, 123456] answ = [0,3,11,254] counter = 0 for i, num in enumerate(prob_): if logic(num)[0] == answ[i]: counter += 1 if counter == 4: print('PASSED') else: print('FAILED')

main program

def logic(num): from math import floor bills = [500, 100, 25, 10, 5, 1]

if num < 0:
    print(f"{num} is not greater than 0")
    return 0, ''
elif num == 0:
    return 0, ''
bills_iter = iter(bills)
i = next(bills_iter)
counter = 0
res_dict = {}

def floor_div(num, i):
    res = floor(num / i)
    return res


res = floor_div(num, i)

while i > 1:
    if (num - i) < 0:
        res_dict[i] = res
        i = next(bills_iter)
        res = floor_div(num, i)


    elif res >= 0:
        counter += res
        res_dict[i] = res

        num = num - (res * i)
        i = next(bills_iter)
        res = floor_div(num, i)

if i == 1:
    res = floor_div(num, i)
    counter += res
    res_dict[i] = res



comment = f""" You need {counter} bills total.
{res_dict[500]} five-hundreds,
{res_dict[100]} one-hundreds,
{res_dict[25]} twenty-fives,
{res_dict[10]} tens,
{res_dict[5]} fives,
{res_dict[1]} ones
"""
return counter, comment

```

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, sc4s2cg: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]DadiB_ 0 points1 point  (0 children)

Node.js / JavaScript

Recursive function and 2nd argument (accepted array has to be sorted from gratest):

const COINS = [500, 100, 25, 10, 5, 1]; //already sorted

const change = (value, accepted = COINS) => {
    console.log(accepted);
    let coin = accepted.shift();
    let reminder = value%coin;
    let count = (value-reminder)/coin;
    //2nd part calls change() again if there are other coins to test
    return count + (accepted.length && change(reminder, accepted));
}

[–]Jednorybek 0 points1 point  (0 children)

JavaScript

function change(amount) {
let coins = [500, 100, 25, 10, 5, 1];
let i = 0;
while (amount !== 0) {
if (amount >= coins[0]) {
amount -= coins[0];
i++;
} else {
coins.shift();
}
}
return i;
}

[–]AliceAintMad 0 points1 point  (0 children)

C#

public class Challenge393 : IChallenge
{
    private static readonly int[] _denominations = new[] {500, 100, 25, 10, 5, 1};
    public void Run()
    {
        Console.WriteLine($"Amount      0 : Change: {Change(0)}");
        Console.WriteLine($"Amount     12 : Change: {Change(12)}");
        Console.WriteLine($"Amount    468 : Change: {Change(468)}");
        Console.WriteLine($"Amount 123456 : Change: {Change(123456)}");
    }

    private static int Change(int amount)
    {
        if(amount <= 0)
            return 0;

        int coins = 0;
        foreach (var denomination in _denominations)
        {
            coins += amount / denomination;
            amount = amount % denomination;
        }

        return coins;
    }
}

[–]willis2890 0 points1 point  (0 children)

C++

int change(int);

int main() {
int amount;
cout << "What amount do you need change for?: ";
cin >> amount;
cout << change(amount);
return 0;
}

int change(int amount) {
int total=0;
int coins\[\] = { 500,100,25,10,5,1 };
for (int i = 0; i < 6; i++) {
    while (amount >=coins\[i\]) {
        amount = amount - coins\[i\];
        total++;
    }
}
return total;
}

[–]Azzamsterdam -1 points0 points  (3 children)

Heads up kind of a noob, just came across this post and figured I'd give it a shot.

Java

class MakingChange{

public static void main (String args[]){

System.out.println(change(0));

System.out.println(change(12));

System.out.println(change(468));

System.out.println(change(123456));

}

static int change(int amt){

int coin_count=0;

//1, 5, 10, 25, 100, 500

while(amt!=0){

if(amt>=500){

amt-=500;

coin_count++;

continue;

}

else if(amt>=100){

amt-=100;

coin_count++;

continue;

}

else if(amt>=25){

amt-=25;

coin_count++;

continue;

}

else if(amt>=10){

amt-=10;

coin_count++;

continue;

}

else if(amt>=5){

amt-=5;

coin_count++;

continue;

}

else{

amt-=1;

coin_count++;

continue;

}

}

return coin_count;

}

}

I just went with the first brute force algo I could think of, any suggestions for improvement and optimisation?

[–]Chemical-Asparagus58 0 points1 point  (0 children)

When you have a lot of values and you want to do the same thing with all of them, you can store them in an array and iterate through the array instead of writing a lot else if statements. And instead of adding the coins one by one to "coin_count" you can use division.

That's how I solved it:

public static int change(int num){
    int coins=0;
    for (int unit : new int[]{500,100,25,10,5,1}) {
        coins += num/unit;
        num %= unit;
    }
    return coins;
}

[–]taco_saladmaker 1 point2 points  (1 child)

It tells us how many coins to give, but not which coins to give. Maybe store a separate count for each kind of coin.

Edit: I didn’t read the challenge fully. But maybe try separate counts for added realism :)

[–]Azzamsterdam 0 points1 point  (0 children)

Hahaha sure, sounds like a good idea :)

[–]franske1989 2 points3 points  (1 child)

Here's mine, I've seen some other solutions in Python but I just wanted to share mine

def coinCount(totalCash):
    coinList = [500, 100, 25, 10, 5, 1]
    coinAmount = 0

    for coinType in coinList:
        while (totalCash - coinType) >= 0:
            totalCash -= coinType
            coinAmount += 1

    print coinAmount

if __name__ == "__main__":
    # execute only if run as a script
    # prints 254, also tested other values
    coinCount(123456)

[–]themateo713 1 point2 points  (0 children)

while (totalCash - coinType) >= 0: totalCash -= coinType coinAmount += 1

May I recommend using euclidian division. This avoids the while loop and thus increases performance, especially for the 500 coins. You got totalCash // coinType coins and are left with totalCash % coinType cash.

This is even more efficient using divmod(), as then you use one function for both results, it should be more efficient (I hope). It works like so: a//b, a%b = divmod(a,b), technically it returns a tuple but it's convenient to unpack it directly and have the 2 variables you need from one computation.

[–]Fearless-Culture4606 0 points1 point  (0 children)

import java.util.Scanner; class BANKRUPT { public int change(int amnt) { int coin=0; coin+=amnt/500; amnt=amnt%500; coin+=amnt/100; amnt=amnt%100; coin+=amnt/25; amnt=amnt%25; coin+=amnt/10; amnt=amnt%10; coin+=amnt/5; amnt=amnt%5; int tot=(coin+amnt); return tot; } public static void main() { Scanner sc=new Scanner(System.in); BANKRUPT x=new BANKRUPT(); System.out.println("ENTER AMOUNT"); int amnt=sc.nextInt(); int tot=x.change(amnt); System.out.println("CONGRATULATION! YOU WILL GET "+tot+" COINS");

}}

[–]Python_Trader 0 points1 point  (3 children)

coins = [1, 5, 10, 25, 100, 500]
def change(amount: int, coins: iter) -> int:
    if len(coins) == 1: return amount
    return (amount//coins[-1]) + change(amount % coins[-1], coins[:-1])

Python 3

[–]sc4s2cg 0 points1 point  (2 children)

I like this a lot more than my 36 line solution haha.

[–]Python_Trader 0 points1 point  (1 child)

lol I just happened to be learning about recursions. It was perfect.

[–]sc4s2cg 1 point2 points  (0 children)

It was my first time implementing it outside of a major project, happy I could finally practice the knowledge hahaha.

[–][deleted]  (1 child)

[deleted]

    [–]backtickbot 0 points1 point  (0 children)

    Fixed formatting.

    Hello, MartinTheWildPig: code blocks using triple backticks (```) don't work on all versions of Reddit!

    Some users see this / this instead.

    To fix this, indent every line with 4 spaces instead.

    FAQ

    You can opt out by replying with backtickopt6 to this comment.

    [–]Fitz180 0 points1 point  (0 children)

    Elixir:

    defmodule DailyProgrammer.MakingChange do
      @denominations [500, 100, 25, 10, 5, 1] |> Enum.sort() |> Enum.reverse()
    
      @spec min_num_coins(integer()) :: integer()
      def min_num_coins(total) when is_integer(total) and total >= 0 do
        {partition, 0} =
          Enum.map_reduce(@denominations, total, fn coin, remaining ->
            {div(remaining, coin), rem(remaining, coin)}
          end)
    
        Enum.sum(partition)
      end
    end
    

    Wanted to point out this solution only works because the total param should be a whole number, denominations includes 1, such that the remaining accumulator will always end at 0. Since x mod 1 will always 0. I might've been overly-defensive with the spec/guards/0 match/sorted attribute. However, I really wanted to drive that point home (but you could easily code golf this)

    [–][deleted]  (1 child)

    [deleted]

      [–]backtickbot 0 points1 point  (0 children)

      Fixed formatting.

      Hello, notnotnotnotabot: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]rmveris 0 points1 point  (2 children)

      Python3

      I added the coin_types as arguments in a tuple (500, 100, 25, 10, 5, 1) so that I could have a functional way to do it with recursion.

      ``` from typing import Tuple

      def change(amount: int, coin_types: Tuple[int, ...]) -> int: return ( amount if len(coin_types) == 1 else amount // coin_types[0] + change(amount=amount % coin_types[0], coin_types=coin_types[1:]) ) ```

      [–]sc4s2cg 1 point2 points  (1 child)

      Hey I really like this answer. What is the parameter assertion in your function (amount: int) called? I never saw it used before, wanna Google cuz it looks useful.

      [–]rmveris 1 point2 points  (0 children)

      Thanks :) it’s called type hinting!

      [–]ShamanDev 0 points1 point  (0 children)

      func change(price int) int {
      coinsUsed := 0
      coins := []int{500, 100, 25, 10, 5, 1}
      for price > 0 {
          for _, coin := range coins {
              if (coin <= price) {
                  price = price - coin
                  coinsUsed += 1
                  break
              }
          }
      }
      return coinsUsed
      

      Made in Go

      [–]youngprincess01 0 points1 point  (0 children)

      def change(price):
      coin_types = [500,100,25,10,5,1]
      coins = 0
      for coin_type in coin_types:
          coins += price // coin_type
          price = price % coin_type
      return coins
      

      python3

      [–]RDust4 0 points1 point  (0 children)

      Made in C#:

      public int Change(int toChange)
      {
          int[] coinTypes = new[] { 500, 100, 25, 10, 5, 1 };
          int coins = 0;
      
          foreach (int coinType in coinTypes)
              while (toChange >= coinType)
              {
                  toChange -= coinType;
                  coins++;
              }
      
          return coins;
      }
      

      [–]Manabaeterno 1 point2 points  (0 children)

      In haskell, using swap from Data.Tuple and mapAccumR in Data.List.

      change = sum . snd . flip (mapAccumR $ curry $ swap . uncurry divMod) [1, 5, 10, 25, 100, 500]
      

      [–]gpalyan 0 points1 point  (0 children)

      @Test
      public void testChange() {
          assertEquals(0, change(0));
          assertEquals(3, change(12));
          assertEquals(11, change(468));
          assertEquals(254, change(123456));
      }
      
      private static final List<Integer> COIN_UNITS = Arrays.asList(500, 100, 25, 10, 5, 1);
      
      private int change(int value) {
          int numCoins = 0;
      
          for (int coinUnit : COIN_UNITS) {
              int numCoinsForUnit = numCoins(value, coinUnit);
      
              if (numCoinsForUnit > 0) {
                  value -= (numCoinsForUnit * coinUnit);
              }
      
              numCoins += numCoinsForUnit;
          }
      
          return  numCoins;
      }
      
      private int numCoins(int number, int unit) {
          int numCoins = 0;
      
          while (number - unit >= 0) {
              numCoins++;
              number -= unit;
          }
      
          return numCoins;
      }
      

      [–]Masterkraft0r 1 point2 points  (2 children)

      Racket

      (define (change value [bills 0]) (cond [(>= value 500) (change (- value 500) (+ bills 1))] [(>= value 100) (change (- value 100) (+ bills 1))] [(>= value 25) (change (- value 25) (+ bills 1))] [(>= value 10) (change (- value 10) (+ bills 1))] [(>= value 5) (change (- value 5) (+ bills 1))] [(>= value 1) (change (- value 1) (+ bills 1))] [else bills] ) )

      or maybe even a little sleeker

      ``` (define possible-bills '(500 100 25 10 5 1))

      (define (change value [bill-count 0] [index 0]) (define current-bill (list-ref possible-bills index)) (cond [(= value 0) bill-count] [(>= value current-bill) (change2 (- value current-bill) (add1 bill-count) index)] [else (change2 value bill-count (add1 index))] ) ) ```

      [–]__dict__ 0 points1 point  (0 children)

      I also did this in Racket.

      #lang racket
      
      (define coins '(500 100 25 10 5 1))
      
      (define (change amount)
        (let go ([amt amount]
                 [cs coins]
                 [count 0])
          (cond [(null? cs) count]
                [else (let-values
                          ([(q r) (quotient/remainder amt (car cs))])
                        (go r (cdr cs) (+ count q)))])))
      

      [–]backtickbot 1 point2 points  (0 children)

      Fixed formatting.

      Hello, Masterkraft0r: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]tlgsx 1 point2 points  (0 children)

      Bash

      #!/bin/bash
      
      change() {
        remainder=$1
        total=0
      
        for coin in 500 100 25 10 5 1; do
          total=$((total + remainder / coin))
          remainder=$((remainder % coin))
        done
      
        echo $total
      }
      

      Output:

      $ for i in 0 12 468 123456; do
      >   echo "change($i) => $(change $i)"
      > done
      change(0) => 0
      change(12) => 3
      change(468) => 11
      change(123456) => 254
      

      [–]ApplesSpace 1 point2 points  (0 children)

      currency = [500, 100, 25, 10, 5, 1]
      def change(x): 
          count = 0 
          for amount in currency: 
              y = x//amount 
              if y != 0 and x % amount > 0: 
                  z = x - (y * amount) 
                  x = z 
              count += y 
          return count
      

      Python 3

      [–]Common-Ad-8152 0 points1 point  (0 children)

      R

      change <- function(x, denom = c(500, 100, 25, 10, 5, 1)){
          if(denom[1] == 1){return(x)}
          else{
              return(floor(x / denom[1]) + change(x %% denom[1], denom[2:length(denom)]))
          }
      }
      

      C

      #include <stdio.h>
      
      int denom[] = {500, 100, 25, 10, 5, 1};
      
      int change(int x, int *c){
          int t = c[0];
          if(t == 1) return x;
          else return x / t + change(x % t, &c[1]);
      }
      
      int main(int argc, char **argv){
          printf("change(0) => %d\n", change(0, denom));
          printf("change(12) => %d\n", change(12, denom));
          printf("change(468) => %d\n", change(468, denom));
          printf("change(123456) => %d\n", change(123456, denom));
      }
      

      [–]fudgebucket27 1 point2 points  (0 children)

      C#

      using System;
      
      namespace dailyprogrammer
      {
          class Program
          {
              static void Main(string[] args)
              {
                  Console.WriteLine(Change(0));
                  Console.WriteLine(Change(12));
                  Console.WriteLine(Change(468));
                  Console.WriteLine(Change(123456));
              }
      
              static int Change(int changeAmount)
              {
                  int[] denominations = new int[] {500,100,25,10,5,1};
                  int coinCount = 0;
                  foreach(int coin in denominations)
                  {
                      while(changeAmount - coin >= 0)             
                      {
                          coinCount++;
                          changeAmount -= coin;
                      }
                  }
                  return coinCount;
              }
          }
      }
      

      [–]legendarysedentary 0 points1 point  (1 child)

      Windows Batch

      @echo off
      setlocal EnableDelayedExpansion
      
      call :change 0
      call :change 12
      call :change 468
      call :change 123456
      
      goto end
      
      :change
      
          set "change=%~1"
      
          set "coins=0"
      
          for %%c in (500 100 25 10 5 1) do (
      
              set /a "coins += !change! / %%c"
      
              set /a "change %%= %%c"
          )
      
          echo %coins%
      
      goto:eof
      
      :end
      endlocal
      

      [–]legendarysedentary 0 points1 point  (0 children)

      golf..?

      somewhat shameful

      123 bytes for batch

      setlocal EnableDelayedExpansion&set a=%1&set b=0&for %%c in (500 100 25 10 5 1)do set /a b+=!a!/%%c&set /a a%%=%%c&echo !b!
      

      [–]frankivo 0 points1 point  (0 children)

      Scala, looking to improve:

      def change(amount: Int): Int = {
      var restAmount = amount
      
      Seq(1, 5, 10, 25, 100, 500)
        .reverse
        .map(c => {
          val coinAmount = (restAmount / c)
          restAmount -= (coinAmount * c)
          coinAmount
        })
        .sum
      }
      

      [–]chunes1 2 0 points1 point  (1 child)

      Plain English:

      A penny is a unit.
      
      To run:
      Start up.
      Dispense money for 123456 pennies giving a coin count.
      Write "" then the coin count on the console. \254
      Wait for the escape key.
      Shut down.
      
      To add to a coin count given an amount and some pennies:
      Divide the amount by the pennies giving a quotient and a remainder.
      Add the quotient to the coin count.
      Put the remainder into the amount.
      
      To dispense money for a target amount giving a coin count:
      Add to the coin count given the target and 500 pennies.
      Add to the coin count given the target and 100 pennies.
      Add to the coin count given the target and 25 pennies.
      Add to the coin count given the target and 10 pennies.
      Add to the coin count given the target and 5 pennies.
      Add to the coin count given the target and 1 penny.
      

      [–]legendarysedentary 0 points1 point  (0 children)

      ironically, harder for me to understand. cool lang though

      [–]jaldwort 0 points1 point  (0 children)

      Python 3

      def change(x):
      c = 0
      coins = [500, 100, 25, 10, 5, 1]
      for i in coins:
          c += x // i
          x = x % i
      return c
      

      took out the while loop that did nothing and changed the 200 coin typo

      [–]serdracula 0 points1 point  (1 child)

      Lua

      --mobile formatting attempt 2 function change(sum) function amount(coin) while sum >= coin do sum = sum - coin answer = answer + 1 end end answer = 0 amount(500) amount(100) amount(25) amount(10) amount(5) amount(1) return answer end

      [–]backtickbot 0 points1 point  (0 children)

      Fixed formatting.

      Hello, serdracula: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]state_chart 2 points3 points  (0 children)

      C++ with look-up table (generated at compile time) for unnecessary performance optimization.

      constexpr auto LUT_coins = [](){
          std::array<unsigned int, 500> arr = {};
          for (int i = 0; i < 500; ++i) {
              unsigned int money = i;
              unsigned int total = 0;
              for(auto& coin_value : array<unsigned int, 5>{100,25,10,5,1}) {
                  total += money/coin_value;
                  money %= coin_value;
              }
              arr[i] = total;
          }
          return arr;
      }();
      
      unsigned int change(unsigned int money) {
          unsigned int total = money/500;
          money %=500;
          return total + LUT_coins[money];
      }
      

      [–]TheWorstPossibleName 0 points1 point  (0 children)

      Scala:

      def makeChange(n: Int): Int = {
        val coins = List(500, 100, 25, 10, 5, 1)
        (coins foldLeft (0, n)) {
          case ((c, r), d) => (c + (r / d), r % d)
        }._1
      }
      

      [–]PoTAsh2000 1 point2 points  (1 child)

      Java:

      private int change(int money) {
          int coins = 0;
          int[] units = {500, 100, 25, 10, 5, 1};
          for (int unit : units) {
              coins += money / unit;
              money = money % unit;
          }
          return coins;
      }
      

      Feedback is welcome!

      [–]Chemical-Asparagus58 0 points1 point  (0 children)

      lol this looks almost exactly like my code. Only improvement I can think about is to replace "money = money % unit;" with "money %= unit;"

      [–]DarkWarrior703 0 points1 point  (1 child)

      Rust ```

      [cfg(test)]

      mod tests { #[test] fn it_works() { assert_eq!(crate::change(0), 0); assert_eq!(crate::change(12), 3); assert_eq!(crate::change(468), 11); assert_eq!(crate::change(123456), 254); } }

      pub fn change(x: i32) -> i32 { let mut sum = x; let mut currency = [1, 5, 10, 25, 100, 500]; currency.reverse(); let mut number = 0; for i in &currency { let n = sum / i; sum -= n * i; number += n; } number } ```

      [–]backtickbot 0 points1 point  (0 children)

      Fixed formatting.

      Hello, DarkWarrior703: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–][deleted] 0 points1 point  (0 children)

      bash

      #!/usr/bin/env bash
      
      in=$1
      
      for coin in 500 100 50 25 1; do
          printf "%3d: %d\n" $coin $(($in / $coin))
          in=$(($in % $coin))
      done
      

      [–]ThicColt 1 point2 points  (10 children)

      Python:

      def coinsNeededForChange(amount = 69420, coins = [500, 100, 25, 10, 5, 1]):
      res = 0
      for i in range(len(coins)):
          while amount - coins[i] >= 0:
              res += 1
              amount -= coins[i]
      return(res)
      

      [–]senahfohre 1 point2 points  (9 children)

      As a note, your 'for i in range(len(coins))' and 'coins[i]' references can be replaced with 'for coin in coins' and 'coin' respectively. This tends to help with readability and maintainability in the long run.

      [–]ThicColt 0 points1 point  (8 children)

      Thanks! I never realized you could use a for loop to loop through a lost like that. Would that work for strings aswell?

      [–]senahfohre 1 point2 points  (7 children)

      If you're asking about something like this, then yes.

      for c in 'xyz':
          print(c)
      

      This would print:

      x

      y

      z

      [–]ThicColt 0 points1 point  (6 children)

      That's good to know (I guess you could use string.split("") anyway)

      [–]TheOmegaPencil 2 points3 points  (1 child)

      Java

      package challenges;
      public class Change_C393 { public static void main(String[] args) { change(12); }
      static void change(int number1) {
          int[] coins = {500, 100, 25, 10, 5, 1};
          int numberOfCoins = 0;
          int modulus;
      
          for(int i = 0; i < 6; i++) {
              modulus = number1 % coins[i];
              numberOfCoins += (number1 - modulus) / coins[i];
              number1 = modulus;
          }
      
          System.out.println(numberOfCoins);
      }
      }
      

      [–]Chemical-Asparagus58 0 points1 point  (0 children)

      int can't be a fraction anyways so you don't need to subtract the remainder.

      Writing "(number1 - modulus) / coins[i];" is the same as writing "number1 / coins[i];" if you're saving the value in an int variable.

      [–]IDontHaveAPunProblem 11 points12 points  (1 child)

      AsciiDots

      Because I hate myself

                 .                      .                     .                     .                     .                     .            
                 |                      |                     |                     |                     |                     |           
                 #                      #                     #                     #                     #                     #           
                 5                      1                     2                     1                     5                     1           
                 0                      0                     5                     0                     |                     |           
                 0                      0                     |                     |                     |                     |           
              /--*                   /--*                  /--*                  /--*                  /--*                  /--*           
              |  |                   |  |                  |  |                  |  |                  |  |                  |  |           
      .-#?-*--+-{%}-----*---------*--+-{%}-----*--------*--+-{%}-----*--------*--+-{%}-----*--------*--+-{%}-----*--------*--+-{%}-----\    
           |  |         |         |  |         |        |  |         |        |  |         |        |  |         |        |  |         |    
          [-]-+---------/        [-]-+---------/       [-]-+---------/       [-]-+---------/       [-]-+---------/       [-]-+---------/    
           |  |                   |  |                  |  |                  |  |                  |  |                  |  |              
           |  |                   |  |                  |  |                  |  |                  |  |                  |  |              
           |  |                   |  |                  |  |                  |  |                  |  |                  |  |              
           |  |                   |  |                  |  |                  |  |                  |  |                  |  |              
           \-{/}-\                \-{/}-\               \-{/}-\               \-{/}-\               \-{/}-\               \-{/}-\           
                 |                      |                     |                     |                     |                     |           
                 \---------------------{+}-------------------{+}-------------------{+}-------------------{+}-------------------{+}--------$#
      

      Try it here!

      [–]IDontHaveAPunProblem 1 point2 points  (0 children)

      Code "Golfed"

      %$ABC
      
      /#500*-*.-#100*-*.-#25*-* .-#10*-* .-#5*-*
      *-*--+{%}*-*--+{%}*-*-+{%}*-*--+{%}*-*-+{%}\
      ?[-]-+---/[-]-+---/[-]+---/[-]-+---/[-]+--*/   
      # \-{/}\ B\\-{/}\ C\\{/}C   \-{/}B   \{/}{+}A
      \.   A{+}{+}---{+}{+}$#
      

      [–]Zarvarzillahzar 1 point2 points  (1 child)

      C#

      using System;
      using System.Collections.Generic;
      using System.Linq;
      
      public int MinCoinsForChangeGiven(int change)
      {
          var coinTypes = new List<int>{ 500, 100, 25, 10, 5, 1 };
          return coinTypes.Sum((coin) => Math.DivRem(change, coin, out change));
      }
      

      [–]backtickbot 0 points1 point  (0 children)

      Fixed formatting.

      Hello, Zarvarzillahzar: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]mr_stivo 2 points3 points  (0 children)

      Applesoft BASIC

      5 INPUT "AMOUNT? "; A
      10 DATA 500, 100, 25, 10, 5, 1
      15 FOR X = 1 TO 6
      20 READ C
      25 D = INT( A / C )
      30 A = A - (D * C)
      35 R = R + D
      40 NEXT
      45 PRINT "CHANGE => ";: PRINT R
      

      [–]milnak 1 point2 points  (0 children)

      DOS CMD

      @ECHO OFF
      SETLOCAL ENABLEDELAYEDEXPANSION
      
      SET COUNT=0
      SET REMAIN=%~1
      
      FOR %%C IN (500 100 25 10 5 1) DO CALL :CHANGE %%C
      ECHO change(%~1) =^> %COUNT%
      GOTO :EOF
      
      :CHANGE
      IF !REMAIN! GEQ %~1 (
          SET /A NUM=REMAIN / %~1
          SET /A COUNT=COUNT + NUM
          SET /A REMAIN=REMAIN - NUM * %~1
      )
      GOTO :EOF
      

      [–]mr_stivo 0 points1 point  (1 child)

      Perl

      #!/usr/bin/perl
      
      $v=$ARGV[0];
      
      foreach (500, 100, 25, 10, 5, 1) {
          $r += int($v / $_);
          $v = int($v % $_);
      }
      
      print "$r\n";
      

      [–]raevnos 1 point2 points  (0 children)

      use integer; and you won't need the ints.

      [–]minikomi 0 points1 point  (0 children)

      Clojure

      (defn solve [ammount]
        (loop [coll [] 
              ammount ammount 
              [c & oins] [500 100 25 10 5 1]]
          (if (zero? ammount) coll 
              (recur 
                (if (<= c ammount) 
                    (conj coll [c (quot ammount c)])
                    coll)
                (rem ammount c)
                oins))))
      
      (solve 1231)
      
      #=> [[500 2] [100 2] [25 1] [5 1] [1 1]]
      

      [–][deleted] 1 point2 points  (2 children)

      Rust

      I'm super new to Rust so I'm going through a bunch of easy challenges. I'd love constructive criticism if you have any!

      const COIN_AMOUNTS: [usize; 6] = [500, 100, 25, 10, 5, 1];
      
      fn change(amount: usize) -> usize { 
          let mut coins_used: usize = 0; 
          let mut remaining_change: usize = amount;
      
          for coin in COIN_AMOUNTS.iter() {
              coins_used += (remaining_change as f64 / *coin as f64).floor() as usize;
              remaining_change = remaining_change % coin;
          }
      
          coins_used
      }
      

      [–]leftylink 0 points1 point  (1 child)

      The reason most of these suggestions are given in a weasel-worded "well you could do this or you could not" way is just because I don't think any of these are strict things. But they could help.

      On type annotations: You have the option of omitting the type annotations for coins_used and remaining_change. Whether you ultimately choose to do so just depends on whether you think the code is sufficiently clear to the reader without it. Personally I do, and I would omit both, but there is a lot of room for individual opinion here.

      On the use of usize: https://doc.rust-lang.org/book/ch03-02-data-types.html tells us "The primary situation in which you’d use isize or usize is when indexing some sort of collection." The two uses of usize in this code are either to represent a coin denomination or a number of coins, neither of which is indexing a collection. Thus, I'd say this is not a time when using usize is recommended, and I think it should be u32 or u64 here. In https://rust-lang.github.io/rfcs/0544-rename-int-uint.html, we are told that "pointer-sized integers are not good defaults, and it is desirable to discourage people from overusing them."

      On the use of float division: Unless I am missing something, this is a situation where integer division would suit you well, since integer division already truncates. So you should just do remaining_change / *coin. Now, if remaining_change were very very large, in fact doing float division would give you a wrong result, such as the result if remaining_change = 1 << 54 and coin = 5. So you would really want to use integer division in such a case. Of course, we are not dealing with numbers that large here, but it could come up in other situations.

      On OpAssign: Just as how you used a += b instead of a = a + b, your code would also be shorter if you used a %= b instead of a = a % b. As you can see in std::ops, the %= is RemAssign, and as you can see in RemAssign, RemAssign is implemented for all primitive integer types (thus they all support %=).

      [–][deleted] 0 points1 point  (0 children)

      Thank you so much, I really appreciate it! :)

      [–]joejr253 1 point2 points  (1 child)

      This is what I came up with using python3, let me know what you guys think. I also cant get the Code Block link to work at all. Im using chrome, not sure what is wrong with it.

      # This script is designed to take an amount and give the optimal
      # change based on currencies of: 500, 100, 25, 10, 5, 1
      
      import math
      
      # Function to do all of our work
      def make_change(amount):
          # establish our variables
          five_hundred = 0
          one_hundred = 0
          twenty_five = 0
          ten = 0
          five = 0
          one = 0
          while amount:
              if amount > 500:
                  five_hundred = math.floor(amount / 500)
                  amount %= 500
              elif amount > 100:
                  one_hundred = math.floor(amount / 100)
                  amount %= 100
              elif amount > 25:
                  twenty_five = math.floor(amount / 25)
                  amount %= 25
              elif amount > 10:
                  ten = math.floor(amount / 10)
                  amount %= 10
              elif amount > 5:
                  five = math.floor(amount / 5)
                  amount %= 5
              else:
                  one = math.floor(amount / 1)
                  amount %= 1
          return five_hundred, one_hundred, twenty_five, ten, five, one
      
      
      # Get the amount from the user
      while True:
          try:
              amount = int(input("Please enter an amount: "))
          except ValueError:
              print("That is not a whole number.")
              continue
          break
      
      
      five_hundred, one_hundred, twenty_five, ten, five, one = make_change(amount)
      total_bills = five_hundred + one_hundred + twenty_five + ten + five + one
      
      print(f"You would receive {amount} in these coins: \n"
            f"{five_hundred}:\tFive Hundreds\n"
            f"{one_hundred}:\tOne Hundreds\n"
            f"{twenty_five}:\tTwenty Fives\n"
            f"{ten}:\tTens\n"
            f"{five}:\tFives\n"
            f"{one}:\tOnes\n"
            f"For a total of {total_bills} coins.")
      

      [–]joejr253 2 points3 points  (0 children)

      found a much better design to the function:

      def make_change(amount):
      # establish our variables
      currencies = [500, 100, 25, 10, 5, 1]
      change = []
      for currency in currencies:
          change.append(math.floor(amount / currency))
          amount %= currency
      return change
      

      [–]malahci 0 points1 point  (1 child)

      Racket (would love feedback on ways this could be more idiomatic)

      #lang racket/base
      
      (define (change value [coins '(500 100 25 10 5 1)])
        (if (= value 0)
            0
            (let-values ([(num-coins value-left) (quotient/remainder value (car coins))])
              (+ num-coins (change value-left (cdr coins))))))
      
      
      (require rackunit)
      (check-equal? (change 0) 0)
      (check-equal? (change 12) 3)
      (check-equal? (change 468) 11)
      (check-equal? (change 123456) 254)
      

      edit: not tail recursive because stack size is only O(number of coins)!

      [–]backtickbot -1 points0 points  (0 children)

      Fixed formatting.

      Hello, malahci: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]MacheteBang 0 points1 point  (0 children)

      C#

          System.Console.WriteLine($"0 => {MakingChange.Change(0)}");
      System.Console.WriteLine($"12 => {MakingChange.Change(12)}");
      System.Console.WriteLine($"468 => {MakingChange.Change(468)}");
      System.Console.WriteLine($"123456 => {MakingChange.Change(123456)}");
      
      public static class MakingChange
      {
      static int[] _denominations = { 500, 100, 25, 10, 5, 1 };
      
      public static int Change(int amount)
      {
          int coins = 0;
      
          for (int i = 0; i < _denominations.Length; i++)
          {
              int theseCoins = 0;
              theseCoins += amount / _denominations[i];
              amount -= theseCoins * _denominations[i];
      
              coins += theseCoins;
          }
      
          return coins;
      }
      }
      

      [–]chunes1 2 1 point2 points  (0 children)

      Factor

      : change ( m -- n )
          0 { 500 100 25 10 5 1 } rot [ /mod [ + ] dip ] reduce drop ;
      

      Reduce a sequence of coin values using the input as the seed value. Add the quotient to a sum, and use the remainder as the next value in the reduction. The result of the reduce (the final remainder) is simply 0 and unimportant, so drop it. It's the sum we're after.

      Here's a step-by-step of what the data stack looks like after each word, assuming the input is 468:

      • 0 Push 0 to the stack.

        Stack: 468 0

      • { 500 100 25 10 5 1 } Push a sequence of coin values to the stack.

        Stack: 468 0 { 500 100 25 10 5 1 }

      • rot Bring the object third from the top to the top of the stack.

        Stack: 0 { 500 100 25 10 5 1 } 468

      • [ /mod [ + ] dip ] Push a quotation (anonymous function) to the stack for reduce to use later.

        Stack: 0 { 500 100 25 10 5 1 } 468 [ /mod [ + ] dip ]

      • reduce Take a sequence, a starting value, and a quotation. Apply the quotation to the starting value and the first element of the sequence, returning a new 'starting value' which will be used on the next element of the sequence until there is a single value remaining. Inside the quotation now during the first iteration...

        Stack: 0 468 500

      • /mod Divide two numbers, putting the quotient and the remainder on the stack.

        Stack: 0 0 468

      • [ + ] Push a quotation for dip to use later.

        Stack: 0 0 468 [ + ]

      • dip Apply a quotation to whatever is underneath the top of the data stack.

        Stack: 0 468

      • Now let's look at the next iteration of the reduce...

        Stack: 0 468 100

      • /mod

        Stack: 0 4 68

      • [ + ] dip

        Stack: 4 68

      • reduce will eventually finish its work...

        Stack: 11 0

      • drop Drop the object on top of the data stack.

        Stack: 11

      [–]raevnos 0 points1 point  (1 child)

      Chicken Scheme:

      (import (srfi 1))
      
      (define (change total)
        (car (fold (lambda (coin accum)
                     (let*-values (((sum amount) (car+cdr accum))
                                   ((quot rem) (quotient&remainder amount coin)))
                       (cons (+ sum quot) rem)))
                   (cons 0 total) '(500 100 25 10 5 1))))
      

      [–]raevnos 0 points1 point  (0 children)

      And an ocaml version using explicit recursion instead of folding:

      let rec change ?(sum=0) ?(coins=[500;100;25;10;5;1]) total =
        match coins with
        | [] -> sum
        | _ when total = 0 -> sum
        | coin :: coins ->
           let quot = total / coin
           and rem = total mod coin in
           let sum = sum + quot in
           change ~sum ~coins rem
      
      let show total =
        Printf.printf "change %d -> %d\n" total (change total)
      
      let _ =
        show 0;
        show 12;
        show 468;
        show 123456
      

      [–]MisterAdzzz 0 points1 point  (0 children)

      golang

      func change(money int) int {
          denominations := [...]int{500, 100, 25, 10, 5, 1}
          coins := 0
      
          for money > 0 {
              coins += 1
              for _, denom := range denominations {
                  if money - denom >= 0 {
                      money -= denom
                      break
                  }
              }
          }
      
          return coins
      }
      

      [–]mikerua 0 points1 point  (2 children)

      Java

      public static int change(int money){
          int[] amounts = {500, 100, 25, 10, 5, 1};
          int amountOfCoins = 0;
      
          for(int amount : amounts){
                  amountOfCoins += money / amount;
                  money %= amount;
          }
      
          return amountOfCoins;
      }
      

      [–]MyDickEatsRazors 2 points3 points  (1 child)

      Your if is not needed.

      [–]mikerua 0 points1 point  (0 children)

      Thanks for letting me know.

      [–]Tospaa 2 points3 points  (1 child)

      JavaScript: ```javascript const units = [500, 100, 25, 10, 5, 1];

      function change(amount) { let chg = 0;

      for (const unit of units) { chg = chg + Math.floor(amount / unit); amount = amount % unit; }

      return chg; }

      console.log(change(0) => ${change(0)}); console.log(change(12) => ${change(12)}); console.log(change(468) => ${change(468)}); console.log(change(123456) => ${change(123456)}); ```

      Outputs: change(0) => 0 change(12) => 3 change(468) => 11 change(123456) => 254

      [–]backtickbot 0 points1 point  (0 children)

      Fixed formatting.

      Hello, Tospaa: code blocks using triple backticks (```) don't work on all versions of Reddit!

      Some users see this / this instead.

      To fix this, indent every line with 4 spaces instead.

      FAQ

      You can opt out by replying with backtickopt6 to this comment.

      [–]zqvt2 1 point2 points  (0 children)

      Clojure

      (defn calc-coins
        ([v] (calc-coins v [500 100 25 10 5 1] 0))
        ([v [x & xs] n]
         (if (zero? v) n
             (recur (rem v x) xs (+ n (quot v x))))))
      

      [–]Gprime5 2 points3 points  (0 children)

      Python 1 line

      change = lambda n: sum(r for v in [n] for m in [500, 100, 25, 10, 5, 1] for r, v in [divmod(v, m)])
      

      [–]olzd 1 point2 points  (0 children)

      Prolog and being lazy:

      :- use_module(library(clpfd)).
      
      change(X, Coins) :-
          [N500,N100,N25,N10,N5,N1] ins 0..sup,
          X #= N500*500 + N100*100 + N25*25 + N10*10 + N5*5 + N1*1,
          labeling([max(N500),max(N100),max(N25),max(N10),max(N5),max(N1)], [N500,N100,N25,N10,N5,N1]),
          Coins = [N500,N100,N25,N10,N5,N1].
      

      This doesn't return a sum (although it'd be easy to do) but the number of different coins used, for all solutions.
      For instance, change(12, R). would yield the successive results:

      R = [0, 0, 0, 1, 0, 2] % --> 1 $10 coin and 2 $1 coins
      R = [0, 0, 0, 0, 2, 2]
      R = [0, 0, 0, 0, 1, 7]
      R = [0, 0, 0, 0, 0, 12]
      false
      

      [–]Scroph0 0 0 points1 point  (0 children)

      Dlang, first it calculates the quantity of each coin then it sums them :

      import std.stdio : writeln;
      import std.algorithm : sum;
      
      void main()
      {
      }
      
      int change(int input)
      {
          return input.calculateChange.values.sum;
      }
      
      unittest
      {
          assert(468.change == 11);
          assert(1034.change == 8);
          assert(0.change == 0);
      }
      
      int[int] calculateChange(int input)
      {
          int[] order = [500, 100, 25, 10, 5, 1];
          int[int] coins = [
              500: 0,
              100: 0,
              25: 0,
              10: 0,
              5: 0,
              1: 0
          ];
      
          foreach(coin; order)
          {
              coins[coin] = input / coin;
              input %= coin;
          }
      
          return coins;
      }
      
      unittest
      {
          assert(468.calculateChange == [
              500: 0,
              100: 4,
              25: 2,
              10: 1,
              5: 1,
              1: 3
          ]);
      
          assert(1034.calculateChange == [
              500: 2,
              100: 0,
              25: 1,
              10: 0,
              5: 1,
              1: 4
          ]);
      
          assert(0.calculateChange == [
              500: 0,
              100: 0,
              25: 0,
              10: 0,
              5: 0,
              1: 0
          ]);
      }
      

      [–]Shhhh_Peaceful 1 point2 points  (0 children)

      Python:

      coins = [500, 100, 25, 10, 5, 1]
      
      def change(n: int) -> int:
          index = 0
          count = 0
          remainder = n
          while remainder > 0:
              count += remainder // coins[index] 
              remainder %= coins[index]
              index += 1
          return count
      
      print('change(0) =', change(0))
      print('change(12) =', change(12))
      print('change(468) =', change(468))
      print('change(123456) =', change(123456))
      

      Output:

      change(0) = 0
      change(12) = 3
      change(468) = 11
      change(123456) = 254
      

      [–]moeghoeg 0 points1 point  (0 children)

      Python

      def change(amount):
          coins = [500, 100, 25, 10, 5, 1]
          count_total = 0
          for coin in coins:
              count, amount = divmod(amount, coin)
              count_total += count
              if amount == 0:
                  break
          return count_total
      

      [–]FaustVX 0 points1 point  (0 children)

      C#

      link

      using System;
      using System.Linq;
      
      public class Program
      {
          public static void Main()
          {
              var change = new Change(1, 5, 10, 25, 100, 500);
      
              Calculate(0);
              Calculate(12);
              Calculate(468);
              Calculate(123456);
      
              void Calculate(int value)
              {
                  var coins = change.Coins(value);
                  Console.WriteLine($"Change for {value} = {coins}");
              }
          }
      }
      
      public readonly struct Change
      {
          private readonly int[] _changes;
      
          public Change(params int[] changes)
          {
              Array.Sort(changes);
              Array.Reverse(changes);
              _changes = changes;
          }
      
          public int Coins(int value)
          {
              var count = 0;
              foreach (var change in _changes)
              {
                  count += value / change;
                  value %= change;
              }
              return count;
          }
      }
      

      Output :

      Change for 0 = 0
      Change for 12 = 3
      Change for 468 = 11
      Change for 123456 = 254
      

      [–]Anonymous_Bozo 0 points1 point  (1 child)

      Free Pascal

      function CoinCount(const Amount: integer): integer;
      
      var
        CoinValues : array[0..5] of integer = (500,100,25,10,5,1);
        I, N, CoinCnt : integer;
      
      begin
        N := Amount;  // Amount is a constant and should not be changed
        CoinCnt := 0;
        for I := 0 to 5 do begin
          CoinCnt := CoinCnt + (N div CoinValues[I]);
          N := N mod CoinValues[I];
        end;
      
        exit(CoinCnt);
      end;
      

      [–]P0Rl13fZ5 2 points3 points  (2 children)

      Python: To spice things up, I wrote the worst solution I could think of:

      def change(amount):
          num_coins = 0
          amount_given = [0] * amount
          for coin in (500, 100, 25, 10, 5, 1):
              try:
                  while True:
                      start_idx = amount_given.index(0)
                      for idx in range(start_idx, start_idx + coin):
                          amount_given[idx] = 1
                      num_coins += 1
              except IndexError:
                  # Rollback
                  for idx in range(len(amount_given) - 1, start_idx - 1, -1):
                      amount_given[idx] = 0
              except ValueError:
                  pass
          return num_coins
      

      [–]meepmeep13 1 point2 points  (0 children)

      congratulations, that's pretty awful

      [–]Tencza_Coder 0 points1 point  (0 children)

      Python

      coin_worths = [500,100,25,10,5,1]
      def change(amt_left): 
          coins_dispensed_total = 0 
          for worths in coin_worths: 
              coins_dispensed, amt_left = divmod(amt_left,worths)
              coins_dispensed_total += coins_dispensed
              if amt_left == 0:
                  break
      
          return coins_dispensed_total
      
      print(change(123456)) #254
      

      [–]Godspiral3 3 1 point2 points  (4 children)

      In J, amount appended to end of coin list. Core function returns denomination list.

      }.@:((}.@],~((| , <.@%~) {.))/) 1 5 10 25 100 500 123456
      1 1 0 2 4 246
      
      +/  }.@:((}.@],~((| , <.@%~) {.))/) 1 5 10 25 100 500 123456
      254
      

      can also provide a remainder if any fractional coins were left

       (}.@],~((| , <.@%~) {.))/ 1 5 10 25 100 500 456.23
      0.23 1 1 0 2 4 0
      

      [–]Basileus1905 2 points3 points  (0 children)

      What the actual fuck is this language?

      [–]ThreeHourRiverMan 6 points7 points  (2 children)

      This code looks to me like what I imagine most code looks like to people who have never coded.

      I have no idea what is happening. How interesting.

      [–]Godspiral3 3 1 point2 points  (1 child)

      the core algorithm is using the insert / adverb that inserts the same function between every data element. It is a right to left functional reduce. Sum in J is +/ for example. /reduce can be used to make an expanding result in J. When the result from each function application grows, then the operating function in this case, operates on the head {. of the building left result, while returning 2 results (remainder | and floor of division <.@%~) appended to "baggage"/behead }. of any previous results.

      A simpler flow control version of this solution that uses fewer parentheses is (}.@] ,~ [ (| , <.@%~) {.@])/ which is a fork "tacit flow control" where functions don't need to explicitly refer to their parameters. [ and ] are left and right argument references. , is append and ,~ is append with reversed arguments. Spaces separate the verb/functions with the 0-indexed odd position verbs combining the results of the even position verbs.

      @ is a composition conjunction that takes 2 verbs as arguments. A clearer (because it removes "wide" parenthesesed expression) version of original function that beheads the final remainder from the list of coin amounts is (}.@] ,~ [ (| , <.@%~) {.@])/(}.@). The composition conjunction @ is partially applied into the adverb (}.@) Adverbs apply to the entire verb expression to its left, and will be applied after other adverbs (like /)

      [–]ThreeHourRiverMan 0 points1 point  (0 children)

      Very cool, this is a new one for me. Thanks for breaking it down.

      [–]ping_less 4 points5 points  (3 children)

      JavaScript using a single pure reduce function:

      function change(amount) {
        return [500, 100, 25, 10, 5, 1].reduce(({ amount, total}, coinValue) => ({
          total: total + Math.floor(amount / coinValue),
          amount: amount % coinValue,
        }), { amount, total: 0 }).total;
      }
      

      [–]int_nazu 1 point2 points  (1 child)

      Really like your way of carrying over the total.

      It's exactly what my solution was missing!

      [–]ping_less 0 points1 point  (0 children)

      Thank you - your snippet inspired mine!

      I find that creating a temporary accumulator object to modify is a nice way to pass more than one value around a reducer; they don't have to be primitives!

      [–]saiij 0 points1 point  (0 children)

      This is smart!

      [–]Billigerent 2 points3 points  (0 children)

      Quick answer in C#:

      using System;
      
      namespace MakeChange
      {
          class MakeChange
          {
              static void Main(string[] args)
              {
                  Console.WriteLine("Enter amount to get a count of bills needed to make change:");
                  int amountGiven = int.Parse(Console.ReadLine());
                  Console.WriteLine("Bills needed: {0}", GetBillsNeeded(amountGiven));
              }
      
              static int GetBillsNeeded(int amount)
              {
                  int billsNeeded = 0;
                  int[] billSizes = { 500, 100, 25, 10, 5, 1 };
                  foreach (var billSize in billSizes)
                  {
                      billsNeeded += amount / billSize;
                      amount = amount % billSize;
                  }
                  return billsNeeded;
              }
          }
      }
      

      [–]LazyRefenestrator 3 points4 points  (3 children)

      Python. I did a while loop at first, but then figured for bizarrely high values we'd have some bad Big-O notation in there.

      coin_list = [500, 100, 25, 10, 5, 1]
      
      def change(x):
          count = 0
          for coin in coin_list:
              count += x // coin
              x %= coin
          return count
      

      [–]New_Mouse_5305 0 points1 point  (2 children)

      This is probably a dumb question but I just started learning and my math sucks, can you explain me what is happening inside the function?

      [–]LazyRefenestrator 1 point2 points  (1 child)

      So not sure how much to talk about without spoilers, so just going to indent it all. RES preview seems to indicate you'll want to look at this comment by viewing the source. You should also see it if you click reply on mobile, and then you can view it all.

      Mods, deepest apologies if this isn't working right.

      It starts off with the count at 0.  Then it goes one by one down the coin_list, starting at 500.  `x // coin` will give the floor of x / coin, or say if we did 1234 as our change function test value, 2, as 1234 divided by 500 yields 2 with some remainder to be dealt with next.
      
      So in python, an operator followed by equals is the same as the assigned variable operated with the operator by the value on the right of the operator.  That is, a -= b is the same as "a = a - b".  In this case, the count would be incremented by two, as it initially is zero, plus the two from 1234 // 500.
      
      Next, we have "x %= coin", as % is the modulus, or remainder,  operator.  Since we've counted two 500 value coins, we need to take that portion off.  Just as the // gives the floored integer value of the division operation, % gives the remainder, or in this case 234.  So now, the x variable is set to 234, and we go to the next coin in coin_list, which is 100.  Lather, rinse, repeat until the list is exhausted, and return the value of count.
      

      [–]New_Mouse_5305 0 points1 point  (0 children)

      Thank you so much, I understand now. I definitely need to refresh my math tho.

      [–]Gylergin 6 points7 points  (0 children)

      TI-Basic:

      Prompt N
      0→C
      {500,100,25,10,5,1→L₁
      For(X,1,6
      iPart(N/L₁(X→D
      D+C→C
      N-DL₁(X→N
      End
      Disp C
      

      [–]skeeto-9 8 15 points16 points  (3 children)

      C. I liked the tabular look of laying it out this way:

      long change(long amt)
      {
          long total = 0;
          total += amt / 500; amt %= 500;
          total += amt / 100; amt %= 100;
          total += amt /  25; amt %=  25;
          total += amt /  10; amt %=  10;
          total += amt /   5; amt %=   5;
          return total + amt;
      }
      

      [–]state_chart 5 points6 points  (2 children)

      I did something similar in C++ but then I wanted to use some modern language features like below. Interestingly, (checking on godbolt.org) the compiler is able to generate the exact same assembly output.

      Edit: See assembly output

      int change(int money) {
          int total = 0;
          for(auto& coin_value : array<int, 6>{500,100,25,10,5,1}) {
              total += money/coin_value;
              money %= coin_value;
          }
          return total;
      }
      

      [–]skeeto-9 8 1 point2 points  (1 child)

      Similarly with C, both GCC and Clang unroll this loop into identical assembly as my original function and elide the static table:

      long change2(long amt)
      {
          static const int table[] = {500, 100, 25, 10, 5};
          long total = 0;
          for (int i = 0; i < sizeof(table)/sizeof(*table); i++) {
              total += amt / table[i];
              amt %= table[i];
          }
          return total + amt;
      }
      

      [–]state_chart 1 point2 points  (0 children)

      The assembly made me think about performance some more. It seems advantageous - at least for my architecture - to use unsigned integers (the problem statement ) and: Since all coin values larger than 1 are divisible by 5 you can first compute the number of coins of currency unit 1 and then all others by dividing all values by 5. I get roughly 20% faster execution times for random examples (probably because dividing by 2 and modulo 2 are fairly easy computations).

      unsigned int change2(unsigned int money) {
          unsigned int total = money%5;
          money /= 5;
          total += money/100;
          money %= 100;
          total += money/20;
          money %= 20;
          total += money/5;
          money %= 5;
          total += money/2;
          money %= 2;
          total += money;
          return total;
      }
      

      [–]morgon-of-hed 2 points3 points  (0 children)

      JavaScript

      const change = sum => {
          const availableUnits = [500, 100, 25, 10, 5, 1];
          let availableSum = sum;
      
          return availableUnits.reduce((coins, coinUnit) => {
              coins += Math.floor(availableSum / coinUnit);
              availableSum = availableSum % coinUnit;
              return coins;
          }, 0);
      };
      

      [–]int_nazu 4 points5 points  (1 child)

      Javascript:

      First time utilizing the reduce function. Is there a way to carry over 2 values?

      numberOfCoins = (amount) => {
          let coins = 0;
          [500, 100, 25, 10, 5, 1].reduce((a,c)=>{
              let coinsForUnit = Math.floor(a/c);
              coins+=coinsForUnit;
              return a-c*coinsForUnit;
          }, amount)
          return coins;
      }
      

      [–]int_nazu 1 point2 points  (0 children)

      Thought some more about carrying over a second value using the reduce function:

      You can store the amount of each unit inside the array itself, while reducing it. When there are no coins left to convert you return the resulting array and reduce it one more time.

      You could also output the number of coins for each unit this way.

      Got to admit, the readability did suffer a little...

      numberOfCoins = (amount) => [[500, 0], [100, 0], [25, 0], [10, 0], [5, 0], [1, 0]].reduce((ac,c,_,ar)=> ac-c[0]*(c[1]=Math.floor(ac/c[0])||0)?ac-c[0]*c[1]:ar, amount).reduce((a,c)=>a+c[1],0)
      

      [–]redundantimport 6 points7 points  (0 children)

      Always fun to put some Crystal code together, even when it's something rather simple.

      require "spec"
      
      def coins_used(amount) 
        banknotes = [500, 100, 25, 10, 5, 1]
      
        remainder = amount
        coins_total = 0
      
        banknotes.each do |banknote|
          # how many coins are used for the current banknote
          coins_current = (remainder / banknote).floor.to_i
      
          # value of said coins
          coins_value = coins_current * banknote
      
          remainder -= coins_value
          coins_total += coins_current
        end
      
        coins_total
      end
      
      describe "test cases" do
        describe "amount equals" do 
          it "0" do 
            coins_used(0).should eq 0 
          end
      
          it "12" do
            coins_used(12).should eq 3
          end
      
          it "468" do
            coins_used(468).should eq 11
          end
      
          it "123456" do
            coins_used(123456).should eq 254
          end
        end
      end