Programming Challenge

Uh oh, Sup Forums! Hime needs your help!

She's spending a summer in America, and she's taken on a job as a waitress. But she doesn't know how to make change in American money!

Write a program that accepts a string and outputs the smallest number of coins needed to make change, using only quarters, dimes, nickels, and pennies.

Example:
input: "$1.05"
output: "4 Quarters, 1 Nickel"

Good luck!

Other urls found in this thread:

ghostbin.com/paste/a2up5
pastebin.com/Wv0pCe0d
ghostbin.com/paste/dkuhb
twitter.com/SFWRedditImages

>quarters, dimes, nickels, and pennies
lol poorfag

I'm not doing your homework for you user. this is elementary stuff you learn right after hello world.

You know, this would actually be an interesting challenge if you were forced to parse a floating point value from a string without using standard library function like sscanf or parseFloat.

Hime should quit and become my sugar girl instead, I'd take care of her well hehe

import std.stdio;

void main()
{
//get input
double dollar;
readf(" %s", &dollar);

//set currency and rate
immutable string[4] coins = ["Quarter(s)", "Dime(s)", "Nickel(s)", "Penny(/ies)"];
immutable double[4] coins_in_dollars = [0.25, 0.1, 0.05, 0.01];

//conversion loop
import std.conv;
auto rest = dollar;
int[string] dollar_in_coins;
foreach (index, coin; coins)
{
dollar_in_coins[coin] = (rest/coins_in_dollars[index]).to!int;
rest -= (coins_in_dollars[index])*dollar_in_coins[coin]; //rest = rest - rate x coins
}

//print output
writeln(dollar_in_coins);
}

$ echo 1.06 | dub run
Performing "debug" build using dmd for x86_64.
dtest ~master: building configuration "application"...
Linking...
Running ./dtest
["Dime(s)":0, "Nickel(s)":1, "Penny(/ies)":1, "Quarter(s)":4]

myFunction(1.05);

function myFunction(cash) {

var coins = [];
var increments = [0.25, 0.10, 0.05, 0.01];
var floatValue = parseFloat(cash);

for (var i = 0; i < 4; i++) {
var value = (floatValue - (floatValue % increments[i])) / increments[i];
floatValue -= value * increments[i];
coins.push(value);
}

document.getElementById("textHere").innerHTML = "Hime should give " + coins[0] + " quarters, " + coins[1] + " dimes, " + coins[2] + " nickles, " + coins[3] + " and pennies.";

}

>She

Prolog
changes(_, [], []).
changes(0, _, []).
changes(N, [[Dn,Dv]|Ds], [[C,Dn]|R]):-
divmod(N, Dv, C, M),
changes(M, Ds, R).

print_tokens([]).
print_tokens([[0,Dn]|R]):- print_tokens(R).
print_tokens([[C,Dn]|R]):-
format("~w ~w", [C,Dn]),
(R \= [], write(", "); true),
print_tokens(R).

print_changes(N):-
Ds = [["Quarter(s)",25], ["Dime(s)",10], ["Nickel(s)",5], ["Penn(y/ies)", 1]],
M is round(N*100),
changes(M, Ds, X),
print_tokens(X).

I'll take that challenge.
Sup Forums won't let me post my code for some reason, it thinks it's spam.
ghostbin.com/paste/a2up5

>It'd be actually interesting if I was going to re-invent the wheel xD

Yes?
It's a good learning exercise.

function getChange(amount) {

var change = [25, 10, 5, 1];
var result = [0, 0, 0, 0];
amount *= 100;

for(var i = 0; i < 4; i++){
result[i] = amount/change[i] >= (amount/change[i]).toFixed(0) ? (amount/change[i]).toFixed(0) : 0;
amount = amount % change[i];
}

return result;
}

var change = getChange(1.37);

document.getElementById("answer").innerHTML = change[0] + ' quarters, ' + change[1] + ' dimes, ' + change[2] + ' nickels, ' + change[3] + ' pennies';

Rust's parse() method doesn't like the dollar sign, so I used scanf instead :3

extern crate libc;

use libc::scanf;

struct Change {
pennies: u32,
nickels: u32,
dimes: u32,
quarters: u32,
}

impl Change {
fn print(self) {
let pstr = match self.pennies {
0 => String::new(),
1 => String::from("1 Penny "),
p => format!("{} Pennies ", p),
};

let nstr = match self.nickels {
0 => String::new(),
1 => String::from("1 Nickel "),
n => format!("{} Nickels ", n),
};

let dstr = match self.dimes {
0 => String::new(),
1 => String::from("1 Dime "),
d => format!("{} Dimes ", d),
};

let qstr = match self.quarters {
0 => String::new(),
1 => String::from("1 Quarter "),
q => format!("{} Quarters ", q),
};

println!("{}{}{}{}", qstr, dstr, nstr, pstr);
}
}

fn to_change(cents: u32) -> Change {
Change {
pennies: cents % 5,
nickels: if ((cents % 25) % 10) > 5 { 1 } else { 0 },
dimes: (cents % 25) / 10,
quarters: cents / 25,
}
}

fn main() {
let mut dollars: f32 = 0.0;
let fmtstr = b"$%f\0";
unsafe { scanf(fmtstr.as_ptr() as *const i8, &mut dollars); }

if dollars < 0.0 { panic!("Cannot parse negative money"); }

let cents = (dollars * 100.0) as u32;
to_change(cents).print();
}

i already did this for school but it was more complicated so im the smartest here

var2 = float(input("Please enter something: "))
print(int(var2/.25), " Quaters ", int(var2%.25/.10), " Dimes ", int(var2/.25%.10/.05), " Nickels ", int(var2/.25%.10%.05/.01))


This is what peack efficency looks like

#include
int p(ch𝕒r* h, ch𝕒r* i, int m, int e){printf("%d %s%s ",e/m,h,e/m==𝟙?"":i);
return e%m;}int m𝕒in(){int t=𝟘;ch𝕒r c;while((c=getch𝕒r())!=EOF){
if(c>'/'&&c

python
import string

def make_change(amount):
cash_amount = float(''.join(letter for letter in amount if letter == "." or letter in string.digits))
coins = {
0.25: ['Quarters',0],
0.10: ['Dimes',0],
0.05: ['Nickels',0],
0.01: ['Pennies',0]}
for coin in coins:
coin_amount = cash_amount // coin
if coin_amount > 0:
coins[coin][1] += coin_amount
cash_amount -= coin * coin_amount

if coins[coin][1] > 0:
print(str(coins[coin][0]) + ": " + str(coins[coin][1]))


input_amount = input("Input: ")
make_change(input_amount)


result:
$ python change.py
Input: $1.05
Quarters: 4.0
Nickels: 1.0


im an autist btw

I don't know why Sup Forums made me post it in that weird font, it wouldn't post otherwise. Anyway, here's proof that my code actually works.

You're fucking shit.

>javascript
but I like using mod

literally read string,split,take 1, drop1, convert to double

I don't even use rust

this is terrible. I would show you the right way to do it but I am on my phone

The best way is probably recursion.

>she
It's true that I haven't finished the series and I probably never will, but I'm pretty 100% sure that's just a crossdressing guy

Unrelated question...
I have somehow screwed up my locale on my desktop, so I can't paste code here.
The text is encoded as utf8, which should be fine.
Does anyone know how to debug stuff like this?

I started off with floats and the massive rounding errors were skipping over nickels.

const char *make_change(double amt)
{
static char buf[255] = { 0 };
struct { const char *n; double v; int c; } arr[] = {
{ "Quarter", 0.25, 0 },
{ "Dime", 0.10, 0 },
{ "Nickel", 0.05, 0 },
{ "Cent", 0.01, 0 }
};
unsigned i, idx = 0;
for (i = 0; i < sizeof arr / sizeof *arr; i++)
{
while (amt >= arr[i].v)
{
amt -= arr[i].v;
arr[i].c++;
}
const char *pl; /* plural */
if (arr[i].c && (pl = (arr[i].c > 1) ? "s" : ""))
idx += sprintf(&buf[idx], "%d %s%s ", arr[i].c, arr[i].n, pl);
}
return buf;
}

Thats why when working with money you use an int of cents.

No that is just shit that u managed to cram into two lines.

This shit is CS50 week 1.

Also, what language is this?

good to know i can post my assignments on Sup Forums and neckbeards will do it for me

>int of cents
Enjoy your overflow / underflow errors, pleb. Professionals use bigints.

Pleb, real men use biggerints.

Part 1:

#include
#include
#include
#include

double process_coin(double* cash, double cv){
//divide by change value and round down
double ret = floor(*cash / cv);
//subtract how much in the coin we've processed from the cash amount
*cash -= (ret * cv);
return ret;
}

Part 2:

int main(int args, char** argv){

double cash;

//make sure we have (a) argument(s)
if(args == 1){
printf("Error: No Arguments\n");
return -1;
}

char* pruned_string;

//get that dollar sign out of our input if it's there
if(argv[1][0] == '$'){
pruned_string = strtok(argv[1], "$");
}else{
pruned_string = argv[1];
}

//we now have the raw cash value
cash = strtof(pruned_string, 0);

//process money
double num_quarters = process_coin(&cash, 0.25);
double num_dimes = process_coin(&cash, 0.10);
double num_nickels = process_coin(&cash, 0.05);
double num_pennies = process_coin(&cash, 0.01);

//choose tags
char* quarter_tag = "Quarter";
if(num_quarters != 1){ quarter_tag = "Quarters";}
char* dime_tag = "Dime";
if(num_dimes != 1){ dime_tag = "Dimes";}
char* nickel_tag = "Nickel";
if(num_nickels != 1){ nickel_tag = "Nickels";}
char* penny_tag = "Penny";
if(num_pennies != 1){ penny_tag = "Pennies";}

printf("Change: %f %s, %f %s, %f %s, %f %s\n", num_quarters, quarter_tag, num_dimes, dime_tag, num_nickels, nickel_tag, num_pennies, penny_tag);

return 0;
}

Output:

Change: 4.000000 Quarters, 0.000000 Dimes, 0.000000 Nickels, 0.000000 Pennies

>recursive reduction
>no recursion
classic /g
using System;
using static System.Console;
class Program
{
static void Main(string[] args)
{
Write(change(1.05));
}
static string change(double dollas, int index = 0)
{
if(index==3) return "";
var names = new (string,double)[] {("Quaters", .25),("Dimes", .1),("Nickels", .01)};
return
$@"{
names[index].Item1
}: {
Math.Floor(dollas/names[index].Item2)
} {
change(dollas%names[index].Item2,++index)
}";
}
}

```
def split(float amount){
int rest = (amount * 100).round() as int //
println "${rest/coin_size as int} ${pretty_names[index]}"
rest = rest % coin_size
}
}
println "Splitting \$1.17:"
split(1.17)
```

>2017
>using cash

>Microcuck
>Tries to talk down on others

u mad bro?

This one's recursive.

yeah i looked pretty hard at that one and couldnt figure out what the fuck was going on

coins = {
'1 Grosz': 0.01,
'2 Grosze': 0.02,
'5 Grosze': 0.05,
'10 Groszów': 0.10,
'20 Groszy': 0.20,
'50 Groszy': 0.50
}
i = iter(list(coins)[::-1])

def Calculate_Change(price):

j = next(i)
number = price // coins[j]
print ('{} coins of type {}'.format(number, j))

try:
Calculate_Change(round(price - number * coins[j], 2))
except StopIteration:
pass


output
Calculate_Change(0.88)
1.0 coins of type 50 Groszy
1.0 coins of type 20 Groszy
1.0 coins of type 10 Groszów
1.0 coins of type 5 Grosze
1.0 coins of type 2 Grosze
1.0 coins of type 1 Grosz

D

>anime
please find the nearest tree and hang yourself

FizzBuzz is even easier and there's a fucking FizzBuzz thread every other day. Why don't you shut the fuck up and post a solution or don't post anything at all.

what a faguette

stfu

When do waitresses make change?
That's the cashier's problem, and modern registers will literally tell you how many of each coin to give back to the customer.

Fuck your parsing nigga.
(defvar *coins*
'(1 5 10 25))

(defun foo (n)
(apply #'max
(cons 0 (remove-if #'(lambda (x)
(> x n))
*coins*))))

(defun number->name (n)
(case n
(25 'quarter)
(10 'dime)
(5 'nickel)
(1 'penny)))

(defun coin (n)
(cdr (loop as i = n then (- i k)
as k = 0 then (foo i)
until (>= 0 i)
collect k)))

(defun himegoto (n)
(mapcar #'number->name
(coin n)))

dumb hime poster

>But she doesn't know how to make change in American money!
But I'm not American and I don't know how either

correct

import Text.Read
import Data.Ratio
import Data.Fixed

data Change =
Change
{ quarters :: Int
, dimes :: Int
, nickels :: Int
, pennies :: Int
} deriving (Show)

getChange :: String -> Maybe Change
getChange input = fmap calcChange (parseInput input)
where
parseInput :: String -> Maybe Float
parseInput = readMaybe . (filter (/= '$'))

calcChange :: Float -> Change
calcChange amount = Change { quarters = quarters, dimes = dimes, nickels = nickels, pennies = pennies }
where
getResults amount [] = []
getResults amount (frac : fracs) = div : (getResults mod fracs)
where (div, mod) = (divMod' amount frac) :: (Int, Rational)

rationalAmt = approxRational (abs amount) 0.001
[quarters, dimes, nickels, pennies] = getResults rationalAmt [0.25, 0.10, 0.05, 0.01]

Forgot the

main = fmap getChange getLine >>= (putStrLn . show)

What's the point of writing haskell if you're not going to make the variable names as terse as possible?

4chizzile thinks my post is spam so here it is in go:

pastebin.com/Wv0pCe0d

whats the best way to only post coins that have a value greater then 0 without tons of if statements?

>go
Spam protection is working then

That was a pretty good one.

Been looking at C# lately, so ...

using System;

class ChangeProgram {
static void MakeChange(double amount) {
int quarters = (int)(amount / 0.25);
amount %= 0.25;
int dimes = (int)(amount / 0.1);
amount %= 0.1;
int nickels = (int)(amount / 0.05);
amount %= 0.05;
int pennies = (int)(Math.Floor(amount * 100));
Console.WriteLine("Quarters: {0}", quarters);
Console.WriteLine("Dimes: {0}", dimes);
Console.WriteLine("Nickels: {0}", nickels);
Console.WriteLine("Pennies: {0}", pennies);
}

static void Main() {
double amount;
Console.Write("Enter an amount: $");
if (double.TryParse(Console.ReadLine(), out amount)) {
MakeChange(amount);
} else {
Console.WriteLine("Error: Could not convert value to double");
}
}
}

why didn't you just go

pennies = amount (mod 100)
quarters = amount (mod 25)
dimes = amount (mod 10)
nickels = amount (mod 5)

You can't get a job in America as a foreigner that easily, holy shit. Fucking Nipniggers

this won't work, but how can it be done recursively?

what OS?

on linux you need to change your locale.conf
windows, you need go to control panel, region/language and try to fix it, else reinstall

mac, just change the region in sysprefs, you'll find the encoding options nearby

C programmers are incredibly dumb and try too hard to fit in. And their finished product is guaranteed to be flawed.

America has dollar and half dollar coins, Hime.

Er, what? If amount were 1.05, then

pennies = 1.05 % 100 = 1.05
quarters = 1.05 % 25 = 1.05
dimes = 1.05 % 10 = 1.05
nickels = 1.05 % 5 = 1.05

The point is to first see how many quarters you many quarters will get you close to the amount. Then, you deal with whatever the remainder is. It's a classic greedy algorithm.

last time I saw a kennedy half-dollar was 15 years ago
dollar coins have not caught on and never well, they just end up in people's coin jars because most machines don't accept them

#include

int main(int argc, char **argv) {
puts(">she");
return 0;
}

>Anime
Hi.
Go to hell.

Wow, simply epic user. I agree, all anime-tards can go to h*ck, you wanna hang out later and make rage comics?

who in the fuck is Hime

>I don't want to know how anything I use works xD (posted from my iphone btw)

public static void main(String[] args) {
String text = "$1.05";
int dollars, cents;

dollars = Integer.parseInt( text.substring(text.indexOf('$')+1, text.indexOf('.')) );
cents = Integer.parseInt( text.substring(text.indexOf('.')+1) );

int quarters=0, dimes=0, nickels=0, pennys=0;

int sum = dollars * 100 + cents;

while (sum > 0){
if (sum >= 25){
sum -= 25;
quarters++;
}
else if (sum >= 10){
sum -= 10;
dimes++;
}
else if (sum >= 5){
sum -= 5;
nickels++;
}
else if (sum >= 1){
sum -= 1;
pennys++;
}
}

if (quarters > 1)
System.out.println(quarters + " Quarters");
else if (quarters > 0)
System.out.println(nickels + " quarter");
if (dimes > 1)
System.out.println(dimes + " dimes");
else if (dimes > 0)
System.out.println(nickels + " dime");
if (nickels > 1)
System.out.println(nickels + " nickels");
else if (nickels > 0)
System.out.println(nickels + " nickel");
if (pennys > 1)
System.out.println(pennys + " pennys");
else if (pennys > 0)
System.out.println(nickels + " penny");
}

end your life right now

const coins = {
Quarters: "0.25",
Dimes: "0.10",
Nickels: "0.05",
Pennies: "0.01"
}

let input = prompt("Enter your value: ", "$1.05").slice(1);

let result = 0;
let resultString = "";

let i = 0;
for (let prop in coins) {
while (true) {
if (result + +coins[prop] > +input) {
if (i) {
resultString += ` ${i} ${prop}`;
}
i = 0;
break;
}
result += +coins[prop];
i++;
}
}

alert(resultString);

Thread is dead! Sad!

I write direct machine code, bro. I know better :d:d

how would u use a fucking parseFloat if there's a $ at the start

>I know better
to not know?

That's a dude, right

...

This is horrible. Also input of "$0.26" prints out
0 quarter
0 penny

Such boring denominations.

I propose the same challenge, except the denominations are 1c, 15c and 25c.

>Anime
Go to hell.

You seem to be new here. All the *chan websites are born out of anime culture.
We apologize that seems to intrinsically trigger your plebbit sensibilities.

The last time you posted this epic comment you deleted it, why? It was so clever the first time, I'm glad you brought it back!

Let me dust off my fingers and show you how a true alpha does it.

ghostbin.com/paste/dkuhb

thanks, you are such a nice guy, user!

splice?

How exactly hard is it to just use println!() ???

input: "debit card"
output: "coins are for morons"

import sys

DENOMS = (
('Quarter', 'Quarters', 25),
('Dime', 'Dimes', 10),
('Nickel', 'Nickels', 5),
('Penny', 'Pennies', 1)
)

if len(sys.argv) != 2:
print('faggot')
sys.exit(1)
cash = int(float(sys.argv[1]) * 100)
for denom, plural_denom, value in DENOMS:
coins = cash // value
cash -= (coins * value)
print('{} {}'.format(coins, plural_denom if coins != 1 else denom))

Umm that's not a program, sweetie ;) you'd better learn how to make change too, cause once you get out of high school you're going to have to know how to do it for your job at McDonald's ;) ;) ;)

...

>Anime
Go to hell.

stop posting this on every thread

Newfag here, how do I get the white text box to put code in?