37
\$\begingroup\$

I know, the title cracks you up


Given an amount of money, output the fewest number of coins that make up that amount.

Examples

0.1
1 dime

0.01
1 penny

0.28
1 quarter 3 penny

0.56
2 quarter 1 nickel 1 penny

1.43
5 quarter 1 dime 1 nickel 3 penny

Spec

  • 100 cents in a dollar.
  • The values of each type of coin is:
    • penny 1 cent
    • nickel 5 cents
    • dime 10 cents
    • quarter 25 cents

Built-ins which trivialize this task are not allowed.

I/O

Input is a decimal representing the dollar value of the total

  • No need to pluralize
  • Order: quarter -> penny
  • Output should be <#_of_coins> <coin type>
  • Separators: , or , (comma and a space) or

The only trailing whitespace allowed is a single trailing newline/space.


If there is zero of a coin type, that coin type should not be shown. E.g. 0.25 -> 1 quarter not 1 quarter 0 dime 0 nickel 0 penny

\$\endgroup\$
  • \$\begingroup\$ @VoteToClose no, but I'll allow commas as a seperaor \$\endgroup\$ – Downgoat Feb 3 '16 at 1:12
  • \$\begingroup\$ Last example is 1.43, which is greater than 1 \$\endgroup\$ – Luis Mendo Feb 3 '16 at 1:16
  • \$\begingroup\$ @LuisMendo oh whoops, the (less than 1) part shouldn't of been there. Forgot to remove that in the sandbox I guess \$\endgroup\$ – Downgoat Feb 3 '16 at 1:17
  • \$\begingroup\$ Is it okay if the output is 2 quarter(2 spaces)1 nickel 1 penny? \$\endgroup\$ – Conor O'Brien Feb 3 '16 at 1:24
  • 1
    \$\begingroup\$ @DigitalTrauma 13.00 can be a possible input but the input will never be 13. I'll always have a decimal \$\endgroup\$ – Downgoat Feb 3 '16 at 6:29

27 Answers 27

6
\$\begingroup\$

CJam, 60

q~e2i[25A5]{md}/]" quarterx dimex nickelx penny"'x/.+{0#},S*

This script seems to have alot of room for improvement but this is shorter than any so far. This makes use of the built in "md" command which returns both the integer result of a division and the remainder. It does the following:

  • reads input (if it were a function I guess you can remove q~ for two less characters)
  • multiples the input by 100 and converts it to an integer
  • performs "md" using [25 10 5] which results in the remainders on the stack
  • combines the numbers and coin names
  • removes the number and coin name if the former is 0
  • adds pre-number zeros

Try it here

prior versions:

q~e2i[25A5]{md}/]_:!:!" quarter x dime x nickel x penny"'x/.*.+e_0-
q~e2i[25A5]{md}/]_:!:!\" quarter x dime x nickel x penny"'x/.+.*
| improve this answer | |
\$\endgroup\$
13
\$\begingroup\$

JavaScript ES6, 107 bytes

n=>((n*=100)/25|0)+` quarter ${(n%=25)/10|0} dime ${n%10/5|0} nickel ${n%5|0} penny`.replace(/ ?0 \S+/g,"")

Simple maths.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nice job! I thought there was a closed-formula ish solution \$\endgroup\$ – Conor O'Brien Feb 3 '16 at 1:45
  • \$\begingroup\$ ? Doesn't this output the coin type if there are zero of that coin type ? \$\endgroup\$ – Frentos Feb 4 '16 at 12:24
  • \$\begingroup\$ @Frentos no, there is a Regex at the end which removes coin types that have zero coins \$\endgroup\$ – Downgoat Feb 5 '16 at 1:14
  • \$\begingroup\$ @Doᴡɴɢᴏᴀᴛ: sorry, didn't realise the text area scrolled right in the absence of visual clues :-) \$\endgroup\$ – Frentos Feb 5 '16 at 1:23
  • \$\begingroup\$ Do you need the |0 after the n%5? \$\endgroup\$ – Neil Feb 7 '16 at 19:51
12
\$\begingroup\$

Python 2, 120 bytes

n=int(round(input()*100))
a=25
for b in"quarter","dime","nickel","penny":
 if n>=a:print"%d "%(n/a)+b,
 n%=a;a=40/a+5^12

Just to be safe, changed to something that definitely works to fix @Ogaday's comment, for now at least. I'm uncertain whether or not I need the int() as well, but I'm having trouble convincing myself that I don't.

print`n/a`+" "+b,

is an extra byte off, but prints an extra L for large inputs (although this code doesn't work for extremely large inputs anyway, due to float precision).

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You just made all the time I spent improving my solution to outgolf Mego's go to waste. Good job though! \$\endgroup\$ – Alexander Revo Feb 3 '16 at 8:41
  • 2
    \$\begingroup\$ +1 - I wish I knew what magic you used to come up with a=40/a+5^12 \$\endgroup\$ – Digital Trauma Feb 3 '16 at 23:11
  • \$\begingroup\$ @DigitalTrauma Tried a bunch of arithmetic operators, eg [x^k for x in [10, 5, 1]] and [k/y for y in [25, 10, 5]] for different k, then saw that two lists were offset by 5. Probably suboptimal, but I haven't had time to brute force. \$\endgroup\$ – Sp3000 Feb 3 '16 at 23:20
  • \$\begingroup\$ This actually fails (for me at least) on inputs of 10.03 and 10.04. It's to do with Python's representation of floats and how it rounds them to ints. Try "print %d"%(10.03*100). \$\endgroup\$ – Ogaday Feb 5 '16 at 18:09
  • \$\begingroup\$ n=int(''.join(raw_input().split("."))) may work, but it's pretty verbose. \$\endgroup\$ – Sherlock9 Feb 5 '16 at 23:33
7
\$\begingroup\$

dc, 104

Newlines added for "readability":

[dn[ quarter ]n]sq
[dn[ dime ]n]sd
[dn[ nickel ]n]sn
[d1/n[ penny ]n]sp
?A0*
25~rd0<qst
A~rd0<dst
5~rd0<nst
d0<p
| improve this answer | |
\$\endgroup\$
  • 15
    \$\begingroup\$ dc: Now with Readability™ \$\endgroup\$ – Alex A. Feb 3 '16 at 1:27
6
\$\begingroup\$

Retina, 97

Thanks (as always) to @randomra - saved 1 byte.

Assumes input is either in the form xxx.yy or xxx.y.

\..$
$&0
\.

.+
$0$*:
(:{25})+
$#1 quarter 
(:{10})+
$#1 dime 
(:{5})+
$#1 nickel 
(:)+
$#1 penny

Try it online.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ $& is the same as $0 so you can save a byte in $0.0 by $&0. \$\endgroup\$ – randomra Feb 3 '16 at 14:58
  • \$\begingroup\$ By inputing something like 0.9999999, the output is a little crazy \$\endgroup\$ – Anthony Pham Feb 3 '16 at 22:46
  • \$\begingroup\$ @PythonMaster I'll add support for that when the Fed starts minting 10 micropenny pieces ;-) \$\endgroup\$ – Digital Trauma Feb 3 '16 at 22:59
4
\$\begingroup\$

Vitsy, 110 100 97 bytes

Yeah, hold on, I'm still methodizing this.

aa**Dv52^1m([N' retrauq 'Z]v52^MDva1m([N' emid 'Z]vDvaM51m([N' lekcin 'Z]v5MD([N'ynnep 'Z]
/D1M-D

Explanation in soon-to-come verbose mode:

push a;
push a;
multiply top two;
multiply top two;
duplicate top item;
save top as temporary variable;
push 5;
push 2;
push second to top to the power of top;
push 1;
goto top method;
if (int) top is 0;
begin recursive area;
output top as number;
push " quarter ";
output stack as chars;
end recursive area;
save top as temporary variable;
push 5;
push 2;
push second to top to the power of top;
modulo top two;
duplicate top item;
save top as temporary variable;
push a;
push 1;
goto top method;
if (int) top is 0;
begin recursive area;
output top as number;
push " dime ";
output stack as chars;
end recursive area;
save top as temporary variable;
duplicate top item;
save top as temporary variable;
push a;
modulo top two;
push 5;
push 1;
goto top method;
if (int) top is 0;
begin recursive area;
output top as number;
push " nickel ";
output stack as chars;
end recursive area;
save top as temporary variable;
push 5;
modulo top two;
duplicate top item;
if (int) top is 0;
begin recursive area;
output top as number;
push " penny";
output stack as chars;
end recursive area;
:
divide top two;
duplicate top item;
push 1;
modulo top two;
subtract top two;
duplicate top item;

Try it online!

| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ retrauq almost seems like a word... \$\endgroup\$ – Conor O'Brien Feb 3 '16 at 1:47
  • \$\begingroup\$ The permalink isn't working \$\endgroup\$ – Downgoat Feb 7 '16 at 17:41
  • \$\begingroup\$ Fixed, sorry. Old code link. :P \$\endgroup\$ – Addison Crump Feb 7 '16 at 18:43
4
\$\begingroup\$

LabVIEW, 62 LabVIEW Primitives

I created 2 arrays for the names and values and iterate through them from the top (index array with i) using a modulo operator (the R IQ thing). The remaining coins are passed into the shift register.

If the value is bigger than 0 I convert the number to string and concatenate the passed down string, the number and the name of the coin and put it back into the shift register.

I just realized my gif doesn´t show the false case but there is nothing to see anyway, it just passes through the string that came in.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ How do "primitives" compare to bytes? Does "x primitives" beat "y bytes" when x<y? Just asking \$\endgroup\$ – Luis Mendo Feb 3 '16 at 15:12
  • \$\begingroup\$ You can check the link to see how primitives are counted. Giving size of labview code in byte would be kinda useless, since an empty vi is already ~10kb big. By experience there are a few more primitives than bytes in a golfing language so this would be around 50-60 bytes in CJam or the like. \$\endgroup\$ – Eumel Feb 3 '16 at 16:00
  • 1
    \$\begingroup\$ @LuisMendo We can't bound the information content of a LabView file above by one byte per primitive, so it would be unfair to count LabView at one byte per primitive. \$\endgroup\$ – lirtosiast Feb 6 '16 at 4:00
  • \$\begingroup\$ @ThomasKwa tbh with a well made golfing language you probably could, each operation 1 byte 1 byte per wire for each input loops are 2-4 bytes for for and whiles are 3 primitives and so on \$\endgroup\$ – Eumel Feb 9 '16 at 9:23
3
\$\begingroup\$

Java 8 lambda, 165 bytes

Expects input y as either double or float.

y->{int c,d=(int)(y*100);return(((c=d/25)>0)?c+" quarter ":"")+(((c=(d=d%25)/10)>0)?c+" dime ":"")+(((c=(d=d%10)/5)>0)?c+" nickel ":"")+(((d=d%5)>0)?d+" penny":"");}

So much ternary. ;-;

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ ;-; What is that? Is that a wampa? \$\endgroup\$ – beaker Feb 3 '16 at 19:45
  • 1
    \$\begingroup\$ @beaker Crying. \$\endgroup\$ – Addison Crump Feb 3 '16 at 19:52
  • \$\begingroup\$ I know it's been four years (lol), but here is 149 bytes. Summary of changes: d=(int)(y*100); to d=100;d*=y;; ((c=d/25)>0)?c+ to d/25>0?d/25+; d=d%25 to d%=25; (c=(d=d%10)/5) to (c=d%10/5); and ((d=d%5)>0)?d+ to d%5>0?d%5+. \$\endgroup\$ – Kevin Cruijssen Mar 3 at 13:46
2
\$\begingroup\$

JavaScript ES6, 202 200 bytes

I hope this can be golfed...

r=>eval('i=[.25,.1,.05,.01];v=[0,0,0,0];for(k=0;k<4;k++)for(;r>=i[k];v[k]++,r-=i[k],r=((r*100+.01)|0)/100);v.map((x,i)=>x?x+" "+"quarter0dime0nickel0penny".split(0)[i]:"").join` `.replace(/ +/g," ")')

Ungolfed code:

function m(r){
    i=[.25,.1,.05,.01]
    v=[0,0,0,0]
    for(k=0;k<4;k++)for(;r>=i[k];v[k]++,r-=i[k],r=((r*100+.01)|0)/100);
    return v.map((x,i)=>x?x+" "+"quarter0dime0nickel0penny".split(0)[i]:"").join(" ").replace(/ +/g," ");
}
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Japt, 77 bytes

` {U*=L /25|0} quÂòr {U%=25 /A|0} ÜX {U%A/5|0} Íõel {U%5|0} p¿ny` r" 0 %S+" x

Thankfully, all four coin names are compressable. The ¿ should be the literal byte 0x81. Test it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Just tried it with some random inputs, it's one cent off on 18.33: 73 quarter 1 nickel 2 penny. 73*.25 + 1*.05 + 2*.01 = 18.32 instead of 18.33. \$\endgroup\$ – D. Strout Feb 4 '16 at 3:36
2
\$\begingroup\$

C, 147 144 142 140 bytes

a[]={25,10,5,1},m,i=0;f(float n){for(m=n*100;i<4;m%=a[i++])m/a[i]&&printf("%d %s ",m/a[i],(char*[]){"quarter","dime","nickel","penny"}[i]);}

Ungolfed with tests:

#include <stdio.h>

a[]={25,10,5,1},m,i=0;

f(float n)
{
    for(m=n*100;i<4;m%=a[i++])
        if(m/a[i])
            printf("%d %s ",m/a[i],(char*[]){"quarter","dime","nickel","penny"}[i]);
}

int main()
{
    float test[] = {.1, .01, .28, .56, 1.43};
    for(int j = 0; j < 5; i = 0)
    {
        f(test[j++]);
        printf("\n");
    }
}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Maybe try replacing char*[] with char**, int a[] with int*a, and put the m%=a[i++] in the last part of the for loop. Should save 4 bytes. Haven't tested it yet, so just try each of them. \$\endgroup\$ – takra Feb 4 '16 at 2:46
  • \$\begingroup\$ @minerguy31 I wouldn't be able to use list initializers if I use pointers instead of arrays. Moved the m%=a[i++] bit though, thanks. \$\endgroup\$ – Alexander Revo Feb 4 '16 at 6:14
  • 1
    \$\begingroup\$ Also, you may be able to replace if(m/a[i]) with m/a[i]&& to save 2 more bytes. \$\endgroup\$ – takra Feb 5 '16 at 0:21
  • \$\begingroup\$ Also try using "quarter\0dime\0nickel\0penny" in the printf. Each \0 terminates the string,saving 1 char each \$\endgroup\$ – takra Feb 5 '16 at 0:27
  • \$\begingroup\$ @minerguy31 using string with \0 causes the program to crash. I'm not sure how iteration is supposed to work over such string anyway. \$\endgroup\$ – Alexander Revo Feb 5 '16 at 7:17
2
\$\begingroup\$

MATL, 82 106 107

'%i quarter %i dime %i nickel %i penny'i[.25 .1 .05]"@2#\w]100*Yo5$YD'0 \S+ ?'[]YX

Try it at MATL Online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I really need to include string compression in MATL \$\endgroup\$ – Luis Mendo Feb 3 '16 at 1:42
2
+100
\$\begingroup\$

APL (Dyalog Unicode), 185 176 bytes

{' '∘(1↓,(/⍨)1(⊢∨⌽)0,≠)⍕,⍉(z[1;]≠0)/z←'quarter' 'dime' 'nickel' 'penny',[0.5]⍨{(⌊(⍵÷25)),(⌊(25|⍵)÷10),(⌊(10|25|⍵)÷5),⌊5|⍵}⍵×100}

Try it online!

The decomposition is in two parts: Computation, and Formatting

Computation:

{(⌊(⍵÷25)),(⌊(25|⍵)÷10),(⌊(10|25|⍵)÷5),⌊5|⍵}⍵×100
{                                           }         A dfn that takes...
                                             ⍵×100    ...the input argument of the entire function, and multiplies by 100 to convert
                                                        from dollars-and-cents to cents, then generates a vector, consisting of ...
 (⌊(⍵÷25)),                                          ...the number of quarters, computed as the the round-down-to-integer of
                                                        the number of cents divided by 25, followed by...
           (⌊(25|⍵)÷10),                             ...the number of dimes, computed as the round-down-to-integer of the remainder of
                                                        the number of cents divided by 25, divided by 10, followed by...
                        (⌊(10|25|⍵)÷5),              ...the number of nickels, computed as the round-down-to-integer of the remainder
                                                        from dividing (the remainder of the number of cents divided by 25) by ten,
                                                        divided by five, followed by...
                                       ⌊5|⍵          ...the number of pennies, computed as the round-down-to-integer of the
                                                        remainder from dividing the number of cents by five.

Computation is complete, and gives a vector of coin counts; the remainder is formatting:

' '∘(1↓,(/⍨)1(⊢∨⌽)0,≠)⍕,⍉(z[1;]≠0)/z←'quarter' 'dime' 'nickel' 'penny',[0.5]⍨    Append the result of the computation to this expression
                                       'quarter' 'dime' 'nickel' 'penny'           Take a vector of coin names, and...
                                                                              ⍨    ...swap it with the computation result, then...
                                                                        ,[0.5]     ...append the two along a 'side-by-side' axis. This gives
                                                                                    a matrix which, if printed out, would have the coin counts
                                                                                    above the coin name.  Then...
                                    z←                                            ...assign it to a temporary variable, and...
                          (z[1;]≠0)                                               ...generate a vector of 1s and 0s such that the 0s in this
                                                                                    vector are in the same position as any 0s in the computation, then...
                                   /                                              ...use that vector to compress out the columns in the matrix where the
                                                                                    coin count is zero, then...
                         ⍉                                                        ...transpose the matrix along its main diagonal. This converts it to two
                                                                                    columns; left is coin counts, right is coin names. Then...
                        ,                                                         ..."unravel" the matrix into a linear vector; the result now has the coin
                                                                                     count followed by the coin name - but there will be too many spaces, so...
                      ⍕                                                          ...convert to a character representation instead of a vector of
                                                                                    mixed objects, then...
' '               0,≠                                                            ...this is a fork, with left argument being the space all the way at the
                                                                                    beginning (S), and right argument being the formatted string (F). It is
                                                                                    interpreted as S 0 F , S ≠ F. S ≠ F generates a vector C of 0s and 1s, 
                                                                                    where the 0s are at the same positions as the spaces. S 0 F is a
                                                                                    constant 0. 0 , C prepends a 0 to the vector C (C2). Then...
            1(⊢∨⌽)                                                               ...we "go up a level" and see a new fork, 1 (⊢∨⌽) C2. This is interpreted
                                                                                    as S 1 F (which is constant 1) (⊢∨⌽) S C2 F (which is constant C2). The
                                                                                    central (⊢∨⌽) is itself a fork with arguments 1 and C2, so is interpreted
                                                                                    as (1⊢C2)∨(1⌽C2). Dyadic ⊢ is right-identity, or C2, and 1⌽C2 takes the 
                                                                                    zero at the beginning of C2 and moves it to the end (C3). ∨ is logical OR, 
                                                                                    so C2 OR C3 gives a vector C4 of 1s and 0s where the 0s are positioned to
                                                                                    correspond with the first space of a pair of consecutive spaces. This...
       ,(/⍨)                                                                     ...becomes the right argument to /⍨ with the left argument being S , F.
                                                                                    S , F is the formatted string with a space prepended (SF), so we now have
                                                                                    SF /⍨ C4. ⍨ is an operator saying "swap the arguments of (in this case) /"
                                                                                    so that we're really computing C4 / SF. Dyadic / with a left argument of
                                                                                    1s and 0s is "compression"; it returns those elements of its right
                                                                                    argument that corresponds to 1s in the left argument. So, where C4 has a 0,
                                                                                    the corresponding character in SF is omitted. Since C4 only had 0s where
                                                                                    there was a space immediately before another space, the result is the
                                                                                    compression of all multi-space substrings to single spaces. Then...
     1↓                                                                          ...we drop the first character (a space) of the result. This gives us a string
                                                                                    which contains no leading or trailing spaces, and no sequence of more than
                                                                                    one space within the string.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 156 145 144 bytes

No match to ETHproduction's formula answer, but anyway...

function c(t){n=['quarter','dime','nickel','penny'];v=[.25,.1,.05,.01];s='';for(i in v){c=t/v[i]|0;if(c>0)s+=c+' '+n[i]+' ';t-=c*v[i];}return s}

This is one of my first rounds of golfs, so any improvements are highly appreciated! I already stole ETH's "xor trunc" -- sorry man, it was just too smart :-)

More readable:

function c(t)
{
  n = ['quarter', 'dime', 'nickel', 'penny'];
  v = [.25, .1, .05, .01];
  s = '';
  for(i in v)
  {
    c = t/v[i]|0;
    if(c>0) s += c+' '+n[i]+' ';
    t -= c*v[i];
  }
  return s
}

Note: While testing I realised that JavaScript (at least on my machine?) divides 1.13 / 0.01 to 1.12999..., making my (and probably all other JS submissions) not work 100% properly...

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I don't think you need the very last semicolon. \$\endgroup\$ – Downgoat Feb 3 '16 at 23:31
1
\$\begingroup\$

Kotlin, 147 bytes

{listOf("quarter" to 25,"dime" to 10,"nickel" to 5,"penny" to 1).fold((it*100).toInt()){d,(n,a)->val z=d/a
if(z>0){print("$z $n ")
d-(z*a)}else d}}

Beautified

{
    listOf(
            "quarter" to 25,
            "dime" to 10,
            "nickel" to 5,
            "penny" to 1).fold((it * 100).toInt()) { d, (n, a) ->
        val z = d / a
        if (z > 0) {
            print("$z $n ")
            d - (z * a)
        } else d
    }
}

Test

import java.io.ByteArrayOutputStream
import java.io.PrintStream

var f:(Double)->Unit =
{listOf("quarter" to 25,"dime" to 10,"nickel" to 5,"penny" to 1).fold((it*100).toInt()){d,(n,a)->val z=d/a
if(z>0){print("$z $n ")
d-(z*a)}else d}}

val TEST = listOf(
        0.1 to "1 dime",
        0.01 to "1 penny",
        0.28 to "1 quarter 3 penny",
        0.56 to "2 quarter 1 nickel 1 penny",
        1.43 to "5 quarter 1 dime 1 nickel 3 penny"
)

fun main(args: Array<String>) {
    val temp = ByteArrayOutputStream()
    System.setOut(PrintStream(temp))
    for ((input, output) in TEST) {
        temp.reset()
        f(input)
        println()
        val text = temp.toString().trim()
        if (text != output) {
            throw AssertionError("$input '$output' != '$text'")
        }
    }
}

TIO

TryItOnline

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 34 bytes

т*ò25‰`T‰`5‰`)“œ¤æáeàë×ä“#øʒнĀ}˜ðý

Outputs with spaces like the examples.

Try it online or verify all test cases.

Explanation:

т*              # Multiply the (implicit) input-decimal by 100
  ò             # Bankers-round this to the nearest integer (to both prevent floating point
                # inaccuracies, as well as removing the ".0" from the ouput-numbers)
   25‰          # Take the divmod-25
      `         # Push both values separated to the stack
       T‰       # Take the divmod 10 on the top value
         `      # Push both values separated to the stack
          5‰    # Take the divmod 5 on the top value
            `   # Push both values separated to the stack
             )  # Wrap all values on the stack into a list
“œ¤æáeàë×ä“     # Push dictionary string "quarter dime nickel penny"
           #    # Split it on spaces
            ø   # Zip/transpose, creating pairs with the earlier integer list
ʒ               # Filter this list by:
 н              #  Where the first item (the integer)
  Ā             #  Is not 0
}˜              # After the filter: flatten the list of pairs
  ðý            # And join this list with a space delimiter
                # (after which this is output implicitly as result)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why “œ¤æáeàë×ä“ is "quarter dime nickel penny".

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Very good! Certainly beats the brute-force approach. As a 34 byte alternative, you can use a loop 521vy5*‰`}) instead of repeating divmod 25‰`T‰`5‰`). \$\endgroup\$ – Grimmy Mar 9 at 16:38
1
\$\begingroup\$

PowerShell, 120 118 115 bytes

Inspired by Veskah

$n=100*"$args"
''+(25,10,5,1|%{for($i=0;($n-=$_)-ge0){++$i}$n+=$_
$i;(echo quarter dime nickel penny)[$p++]}|?{$i})

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 133 131 130 123 110 bytes

-8 bytes by snagging several tricks from mazzy's answer
-13 bytes thanks directly to mazzy

$n=100*"$args"
''+(25,10,5,1|%{($y=$n/$_-replace'\..*');(echo quarter dime nickel penny)[$i++];$n%=$_}|?{+$y})

Try it online!

Each iteration (i.e. 25,10,5,1) generates two lines of output through the pipeline: the number and the coin size. |?{+$y} is a where clause that filters out both generations if $y is 0, which is the truncated result of $n/$coin_size.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ -replace gives a shorter code Try it online! \$\endgroup\$ – mazzy Mar 9 at 16:16
1
\$\begingroup\$

T-SQL, 181 bytes

I added some linebreaks to make it readable

DECLARE @2 decimal(10,2)=1.43

DECLARE @ INT=@2*100
SELECT string_agg(left(nullif(c,0),99)
+' '+trim(substring('quarterdime    nickle  penny',b*8,8)),' ')
FROM(values(0,@/25),(1,@%25/10),(2,@%25%10/5),(3,@%5))p(b,c)

Try it online

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 5 - 128 124 bytes

I guess this can be re-written to be much shorter but I really can't see it.

$s=<>*100;@v=($s/25,$s%2.5,$s%25%10/5,$s%250%5);map{$l=int($_);print$l.$".qw(quarter dime nickel penny)[$i].$"if$l>0;$i++}@v

EDIT: Just a math trick to save 4 chars.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 6, 96 bytes

$/=get;put map {$_=Int($//$^a);$/%=$a;"$_ $^b" if $_},<.25 quarter .1 dime .05 nickel .01 penny>
$/ = get; # set $/ to the input

# print the following list with spaces between
# and a newline at the end
put map {
  # the parameters to this block are $a, and $b
  # which are declared as placeholder parameters $^a, and $^b

  $_ = Int( $/ / $^a ); # set $_ to the count of the current coin

  $/ %= $a;             # set $/ to the modulus of itself and the current coin

  "$_ $^b" if $_        # return a string if $_, otherwise return Empty
},
<
  .25 quarter
  .1  dime
  .05 nickel
  .01 penny
>

Usage:

for amount in  0.1  0.01  0.28  0.56  1.43; do
  echo $amount | perl6 -e'…';
done
1 dime
1 penny
1 quarter 3 penny
2 quarter 1 nickel 1 penny
5 quarter 1 dime 1 nickel 3 penny
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 2, 167 161 bytes

Update 1: Stole Sp3000's idea to use input() and make my code a script instead of a function.

a=input()*100;k={25:0,10:0,5:0,1:0}
for i in k:k[i]=a//i;a%=i
print' '.join(['%d %s'%(k[x],{25:'quarter',10:'dime',5:'nickel',1:'penny'}[x]) for x in k if k[x]])
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C, 162 bytes

Unfortunately, doesn't work without the #include.

#include <stdlib.h>
i,a[]={25,10,5,1};main(c,v)char**v;{for(c=atof(v[1])/.01;c;c%=a[i++])c/a[i]?printf("%d %s ",c/a[i],"quarter\0dime\0   nickel\0 penny"+8*i):0;}

Ungolfed

#include <stdlib.h>

i,a[]={25,10,5,1}; /* loop index, coin values */

main(c,v) char**v;
{
    /* Get dollar amount from command line, convert to pennies */
    for (c=atof(v[1])/.01;c;c%=a[i++]) /* loop while still change... */
    {
        c/a[i] /* if there are coins at this index... */
            ? printf("%d %s ", c/a[i], "quarter\0dime\0   nickel\0 penny"+8*i) /* print out how many */
            : 0;
    }
}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Lua 5.3, 141 139 132 131 bytes

Sort of based on Sp3000's Python answer, but with my own magic formula.

n=.5+100*io.read'n'a=25
for s in("quarter dime nickle penny "):gmatch".- "do
_=n<a or io.write(s,~~(n//a)," ")n=n%a
a=35%a|#s%2
end

Edit -- improved the a formula. Previously it was a=a*3%13~#s%4.

Edit 2 -- previously I was using math.ceil to round and convert to integer. Now I am reusing // to round and adding ~~ to convert to integer.

Edit 3 -- shaved a character by changing the pattern from "%w+ " to ".- ".

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

K (oK), 95 78 bytes

Solution:

{" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100*

Try it online!

Example:

{" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100*0.92
"3 quarter 1 dime 1 nickel 2 penny"
{" "/,/`quarter`dime`nickel`penny{("";$y,x)y>0}'(-c,1)!'{y!x}\x,c:25 10 5}100*0.95
"3 quarter 2 dime"

Explanation:

Modulo the input by each coin, then divide coins by the result.

Feed each result along with the name of the coin into a function, returning the string value of both if number of coins is non-zero.

Flatten everything down and join together with whitespace.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Swift, 164 bytes

Assuming input is i

let m=[("quarter",25),("dime",10),("nickel",5),("penny",1)]
var b=Int(i*100)
print(m.reduce(""){o,t in
let(n,v)=t,
x=Int(b/v)
b-=x*v
return x==0 ?o:o+"\(x) \(n) "})

Try it

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Mathematica 30 bytes

This submission may not qualify, as it makes use of a readily available built-in! But some may find it useful for understanding the connection to Frobenius equations.

The task can be understood as a search for all solutions to the Frobenius equation, 25q+10d+5n+p=t, where q, d, n, p, and t, represent quarters, dimes, nickels, pennies, and total, respectively.

FrobeniusSolve[{25,10,5,1},#]&

The Frobenius equation 25q+10d+5n+p=100 represents all cases that sum to 100 cents.

The first solution, below, represents 100 pennies; the second solution represents 1 nickel and 95 pennies. And so on...

FrobeniusSolve[{25,10,5,1},100]


{{0, 0, 0, 100}, {0, 0, 1, 95}, {0, 0, 2, 90}, {0, 0, 3, 85}, {0, 0, 4, 80}, {0, 0, 5, 75}, {0, 0, 6, 70}, {0, 0, 7, 65}, {0, 0, 8, 60}, {0, 0, 9, 55}, {0, 0, 10, 50}, {0, 0, 11, 45}, {0, 0, 12, 40}, {0, 0, 13, 35}, {0, 0, 14, 30}, {0, 0, 15, 25}, {0, 0, 16, 20}, {0, 0, 17, 15}, {0, 0, 18, 10}, {0, 0, 19, 5}, {0, 0, 20, 0}, {0, 1, 0, 90}, {0, 1, 1, 85}, {0, 1, 2, 80}, {0, 1, 3, 75}, {0, 1, 4, 70}, {0, 1, 5, 65}, {0, 1, 6, 60}, {0, 1, 7, 55}, {0, 1, 8, 50}, {0, 1, 9, 45}, {0, 1, 10, 40}, {0, 1, 11, 35}, {0, 1, 12, 30}, {0, 1, 13, 25}, {0, 1, 14, 20}, {0, 1, 15, 15}, {0, 1, 16, 10}, {0, 1, 17, 5}, {0, 1, 18, 0}, {0, 2, 0, 80}, {0, 2, 1, 75}, {0,2, 2, 70}, {0, 2, 3, 65}, {0, 2, 4, 60}, {0, 2, 5, 55}, {0, 2, 6, 50}, {0, 2, 7, 45}, {0, 2, 8, 40}, {0, 2, 9, 35}, {0, 2, 10, 30}, {0, 2, 11, 25}, {0, 2, 12, 20}, {0, 2, 13, 15}, {0, 2, 14, 10}, {0, 2, 15, 5}, {0, 2, 16, 0}, {0, 3, 0, 70}, {0, 3, 1, 65}, {0, 3, 2, 60}, {0, 3, 3, 55}, {0, 3, 4, 50}, {0, 3, 5, 45}, {0, 3, 6, 40}, {0, 3, 7, 35}, {0, 3, 8, 30}, {0, 3, 9, 25}, {0, 3, 10, 20}, {0, 3, 11, 15}, {0, 3, 12, 10}, {0, 3, 13, 5}, {0, 3, 14, 0}, {0, 4, 0, 60}, {0, 4, 1, 55}, {0, 4, 2, 50}, {0, 4, 3, 45}, {0, 4, 4, 40}, {0, 4, 5, 35}, {0, 4, 6, 30}, {0, 4, 7, 25}, {0, 4, 8, 20}, {0, 4, 9, 15}, {0, 4, 10, 10}, {0, 4, 11, 5}, {0, 4, 12, 0}, {0, 5, 0, 50}, {0, 5, 1, 45}, {0, 5, 2, 40}, {0, 5, 3, 35}, {0, 5, 4, 30}, {0, 5, 5, 25}, {0, 5, 6, 20}, {0, 5, 7, 15}, {0, 5, 8, 10}, {0, 5, 9, 5}, {0, 5, 10, 0}, {0, 6, 0, 40}, {0, 6, 1, 35}, {0, 6, 2, 30}, {0, 6, 3, 25}, {0, 6, 4, 20}, {0, 6, 5, 15}, {0, 6, 6, 10}, {0, 6, 7, 5}, {0, 6, 8, 0}, {0, 7, 0, 30}, {0, 7, 1, 25}, {0, 7, 2, 20}, {0, 7, 3, 15}, {0, 7, 4, 10}, {0, 7, 5, 5}, {0, 7, 6, 0}, {0, 8, 0, 20}, {0, 8, 1, 15}, {0, 8, 2, 10}, {0, 8, 3, 5}, {0, 8, 4, 0}, {0, 9, 0, 10}, {0, 9, 1, 5}, {0, 9, 2, 0}, {0, 10, 0, 0}, {1, 0, 0, 75}, {1, 0, 1, 70}, {1, 0, 2, 65}, {1, 0, 3, 60}, {1, 0, 4, 55}, {1, 0, 5, 50}, {1, 0, 6, 45}, {1, 0, 7, 40}, {1, 0, 8, 35}, {1, 0, 9, 30}, {1, 0, 10, 25}, {1, 0, 11, 20}, {1, 0, 12, 15}, {1, 0, 13, 10}, {1, 0, 14, 5}, {1, 0, 15, 0}, {1, 1, 0, 65}, {1, 1, 1, 60}, {1, 1, 2, 55}, {1, 1, 3, 50}, {1, 1, 4, 45}, {1, 1, 5, 40}, {1, 1, 6, 35}, {1, 1, 7, 30}, {1, 1, 8, 25}, {1, 1, 9, 20}, {1, 1, 10, 15}, {1, 1, 11, 10}, {1, 1, 12, 5}, {1, 1, 13, 0}, {1, 2, 0, 55}, {1, 2, 1, 50}, {1, 2, 2, 45}, {1, 2, 3, 40}, {1, 2, 4, 35}, {1, 2, 5, 30}, {1, 2, 6, 25}, {1, 2, 7, 20}, {1, 2, 8, 15}, {1, 2, 9, 10}, {1, 2, 10, 5}, {1, 2, 11, 0}, {1, 3, 0, 45}, {1, 3, 1, 40}, {1, 3, 2, 35}, {1, 3, 3, 30}, {1, 3, 4, 25}, {1, 3, 5, 20}, {1, 3, 6, 15}, {1, 3, 7, 10}, {1, 3, 8, 5}, {1, 3, 9, 0}, {1, 4, 0, 35}, {1, 4, 1, 30}, {1, 4, 2, 25}, {1, 4, 3, 20}, {1, 4, 4, 15}, {1, 4, 5, 10}, {1, 4, 6, 5}, {1, 4, 7, 0}, {1, 5, 0, 25}, {1, 5, 1, 20}, {1, 5, 2, 15}, {1, 5, 3, 10}, {1, 5, 4, 5}, {1, 5, 5, 0}, {1, 6, 0, 15}, {1, 6, 1, 10}, {1, 6, 2, 5}, {1, 6, 3, 0}, {1, 7, 0, 5}, {1, 7, 1, 0}, {2, 0, 0, 50}, {2, 0, 1, 45}, {2, 0, 2, 40}, {2, 0, 3, 35}, {2, 0, 4, 30}, {2, 0, 5, 25}, {2, 0, 6, 20}, {2, 0, 7, 15}, {2, 0, 8, 10}, {2, 0, 9, 5}, {2, 0, 10, 0}, {2, 1, 0, 40}, {2, 1, 1, 35}, {2, 1, 2, 30}, {2, 1, 3, 25}, {2, 1, 4, 20}, {2, 1, 5, 15}, {2, 1, 6, 10}, {2, 1, 7, 5}, {2, 1, 8, 0}, {2, 2, 0,  30}, {2, 2, 1, 25}, {2, 2, 2, 20}, {2, 2, 3, 15}, {2, 2, 4, 10}, {2, 2, 5, 5}, {2, 2, 6, 0}, {2, 3, 0, 20}, {2, 3, 1, 15}, {2, 3, 2, 10}, {2, 3, 3, 5}, {2, 3, 4, 0}, {2, 4, 0, 10}, {2, 4, 1, 5}, {2, 4, 2, 0}, {2, 5, 0, 0}, {3, 0, 0, 25}, {3, 0, 1, 20}, {3, 0, 2,  15}, {3, 0, 3, 10}, {3, 0, 4, 5}, {3, 0, 5, 0}, {3, 1, 0, 15}, {3,  1, 1, 10}, {3, 1, 2, 5}, {3, 1, 3, 0}, {3, 2, 0, 5}, {3, 2, 1, 0}, {4, 0, 0, 0}}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.