Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

2010 Homework #02 - Coins

Name: Anonymous 2010-01-10 4:35

How many ways can one make a single US dollar from exactly 10 coins? Write a program that calculates the answer to this. For bonus points, write one that can calculate the answer for any amount of money and any amount of coins.

50 cent pieces, quarters, dimes, nickels, and pennies are allowed.

The answer to the problem is 6. ENTERPRISE C SOLUTION in the next post.

Name: Anonymous 2010-01-10 4:36


#include <stdio.h>
int main(void) { printf("6\n"); return 0; }

Name: Anonymous 2010-01-10 4:36

/**********************************************************************
 *  Fuck y'all niggas, I'm not using the 80 character width standard  *
 *  And you'd better set your tab width to 4 spaces                   *
 **********************************************************************/
 
#include <stdio.h>

int debug = 0;
int money, coinmax;

int calc()
{
    int valids = 0;
    int halfds, quarters, dimes, nickels, pennies;
   
    for (halfds = 0; halfds <= coinmax; halfds++)
    {
        for (quarters = 0; quarters <= (coinmax - halfds); quarters++)
        {
            for (dimes = 0; dimes <= (coinmax - halfds - quarters); dimes++)
            {
                for (nickels = 0; nickels <= (coinmax - halfds - quarters - dimes); nickels++)
                {
                    for (pennies = 0; pennies <= (coinmax - halfds - quarters - dimes - nickels); pennies++)
                    {
                        if    (halfds + quarters + dimes + nickels + pennies == coinmax
                            && halfds * 50 + quarters * 25 + dimes * 10 + nickels * 5 + pennies == money)
                        {
                            valids++;
                            if (debug == 1)
                            {
                                printf    ("H:%d Q:%d D:%2d N:%d P:%d\n", halfds, quarters, dimes, nickels, pennies);
                            }
                        }
                    }
                }
            }
        }
    }
   
    return    valids;
}

int main()
{
    printf    ("Enter an amount of money in cents: ");
    scanf     ("%d", &money);
    printf    ("Enter a number of coins: ");
    scanf     ("%d", &coinmax);
   
    printf    ("%d combinations possible.\n", calc () );
    return    0;
}

Name: Anonymous 2010-01-10 4:39

>>2

The fastest smartass known to mankind.

Name: Anonymous 2010-01-10 5:00

>>3
O(n5) QUALITY!

Name: Anonymous 2010-01-10 12:15

>>3
/**********************************************************************
*  Fuck y'all niggas, I'm not using the 80 character width standard  *
*  And you'd better set your tab width to 4 spaces                   *
**********************************************************************/

I like the way you think, OP.

But you lack (void) in function definitions.

Name: Anonymous 2010-01-10 14:01

>>3
FORFORFORFORFORFORFOR

Name: Anonymous 2010-01-10 14:11

Wow.  You got some silly nested for looping stuff going on here.

Name: Anonymous 2010-01-10 14:36

I am unable to do this.

Name: Anonymous 2010-01-10 14:55

Interesting.  After some examination, you can break a half dollar into two variations of five coins: quarter dime dime nickel nickel nickel, and dime dime dime dime dime.
Never noticed that before.

Name: Anonymous 2010-01-10 14:55

Can this be done recursively?

Name: Anonymous 2010-01-10 14:56

>>10
And that's the sound of me failing.  That should just be:
>> quarter dime nickel nickel nickel

Name: Anonymous 2010-01-10 14:57

>>11
no
you do not have enough memory

Name: Anonymous 2010-01-10 15:00

quarters, dimes, nickels
lol faggot coins

Name: Anonymous 2010-01-10 15:03

>>11

Everything can be done recursively.

That doesn't mean you should, though.

Name: Expert Schemer 2010-01-10 15:06

>>15
U mad?

Name: Anonymous 2010-01-10 17:37

>>16

No, I'm not, actually.

Name: Anonymous 2010-01-10 18:30

>>3
Can this be done in a way that isn't pig disgusting?

Name: Anonymous 2010-01-10 18:48

>>13
I did it in C# recursively. I can't see why memory should be a problem - unless I'm mistaken the stack depth shouldn't be more than the amount of coins?

I made it a bit more dynamic. You can change the values for amount of money, amount of coins and the amount and types of coins.


using System;

namespace ValueSplit
{
  class Program
  {
    //change these values to fit another problem
    static int amountOfMoney = 100, amountOfCoins = 10;
    static int[] coins = new int[] { 50, 25, 10, 5, 1};

    static void Main(string[] args)
    {
      Console.WriteLine("Number of combinations: {0}", Combinations());
      Console.ReadLine();
    }

    static int Combinations()
    {
      return Combinations(new int[coins.Length], 0);
    }
   
    static int Combinations(int[] splitCount, int index)
    {
      int currentValue = 0;

      for (int i = 0; i < index; i++)
        currentValue += splitCount[i];
      int mayUse = amountOfCoins - currentValue;
      if (splitCount.Length - 1 == index)
      {
        splitCount[index] = mayUse;
        currentValue = 0;
        for (int i = 0; i < splitCount.Length; i++)
          currentValue += splitCount[i] * coins[i];
        return amountOfMoney == currentValue ? 1 : 0;
      }

      int combinations = 0;
      for (splitCount[index] = 0; splitCount[index] <= mayUse; splitCount[index]++)
        combinations += Combinations(splitCount, index + 1);
      return combinations;
    }
  }
}


I know I'm a whore for using C# and I already regret posting.

Name: Anonymous 2010-01-10 18:50

>>19
oops I mean the stack depth shouldn't be more than the amount of coin-types

Name: Anal Touring 2010-01-10 21:11

Forget it, it's Touring-complete

Name: Anonymous 2010-01-10 22:03

>>19
I really disapprove of the C# capitalization style. Function names should not be capitalized, and that's that.

Name: Anonymous 2010-01-10 22:04

>>22
Nothing should be capitalized, not even classes.

Name: Anonymous 2010-01-10 23:07

>>23
Especially not classes. Nor type names of any kind. Nor anything.

Name: Anonymous 2010-01-11 1:28

Obligatory Java.  The actual algorithm is the coinTrick() and writeCoupon() methods.  You can adjust the contents of the purse (what coins and how much they are worth) but I have not written the user-level method to do that; all methods assume they are working with initially unknown pocket change.

writeCoupon() ensures that only unique solutions are counted.  The program accrues extra work load transforming the unique solutions into user-friendly strings for console display in finalResults() and printChange().

import java.io.*;
import java.util.Arrays;
import java.lang.Integer;

public class TheTrick
{
    public static void main(String[] args)
    {
        CoinTrick trick = new CoinTrick(10, 1.00d);
        trick.play();
    }
}

class CoinTrick
{
    private String purse = "pndqh";
    private int[] purse_worth = { 1, 5, 10, 25, 50 };
    private int draw = purse.length() - 1;
    public int numOfCoins;
    public double amount;
    public int clen = 0;
    public String coupon = new String("");
   
    // Constructors
    public CoinTrick()
    {
        this(10, 1.00d);
    }
    public CoinTrick(int jingle, double price)
    {
        this.numOfCoins = jingle;
        this.amount = price;
    }
   
    // Start the program
    public void play()
    {
        String coins = new String("");
        this.coupon = new String("");
        this.clen = 0;
        for(; draw >= 0; draw--)
        {
            coins = "" + this.initAmount((int)(this.amount*100), draw);
            this.coinTrick(coins, coins.length());
        }
        this.finalResults();
    }
   
    // Produce a basic group of coins equal to 'amt'
    // Higher-value coins are prioritized
    // If you get more coins than you are allowed
    protected String initAmount(int amt, int n)
    {
        String str = new String("");
        int len = purse.length() - 1, draws = n;
        if(len < draws) { draws = len; }
       
        while(amt > 0)
        {
            if(amt >= this.purse_worth[draws])
            {
                str = str + this.purse.charAt(draws);
                amt = amt - this.purse_worth[draws];
            }
            else
            {
                draws--;
            }
        }
        if(str.length() > this.numOfCoins && draws - 1 >= 0)
        {
            draw = --n;
            str = this.initAmount(amt, draws);
        }
        return str;
    }
   
    // The recursion
    protected void coinTrick(String coins)
    {
        int n = str.length();
        if(n == this.numOfCoins)
        {
            this.writeCoupon(coins);
        }
        if(n <= this.numOfCoins)
        {
            int ndx = n;
            String str = "";
            while(ndx - 1 > 0)
            {
                ndx--;
                if((coins.charAt(ndx) == purse.charAt(0)) || (ndx + 1 < n && coins.charAt(ndx) == coins.charAt(ndx+1)))
                {
                    continue;
                }            this.coinTrick(coins.substring(0,ndx) + coins.substring(ndx+1) + this.makeChange(coins.charAt(ndx)));
            }
        }
    }
   
    // Used to exchange larger coins for smaller coins
    protected String makeChange(char c)
    {
        switch(c)
        {
            case 'h': return "qq";
            case 'q': return "ddn";
            case 'd': return "nn";
            case 'n': return "ppppp";
            default: return ("" + c);
        }
    }
   
    // Unique solutions
    protected void writeCoupon(String str)
    {
        int i = 0, j = str.length() - 1, n = this.purse.length();
        int[] unit = new int[n];
        Arrays.fill(unit, 0);
        while(j >= 0)
        {
            i = this.purse.indexOf(str.charAt(j));
            if(i != -1) { unit[(n - i - 1)]++; }
            j--;
        }
        String newStr = "";
        for(i = 0; i < n; i++)
        {
            if(i > 0) { newStr = newStr + ","; }
            newStr = newStr + "" + unit[i];
        }
        if(this.coupon.indexOf(newStr) == -1)
        {
            this.clen++;
            this.coupon += " " + newStr;
        }
    }
   
    // Outputs information ONLY regarding unique solutions
    protected void finalResults()
    {
        System.out.println("Using "+this.numOfCoins+" coins, I have found "+this.clen+" unique ways to produce $"+this.amount+".");
        String[] output = coupon.split("\\s");
        int i = 0, j = output.length;
        for(; i < j; i++)
        {
            this.printChange(output[i]);
        }
    }
    // Has a branched output depending on input
    // The "true" branch involves unique solutions
    // The "false" branch involves raw solutions
    protected void printChange(String str)
    {
        int i = 0, j = 0, n = 0, p = purse.length() - 1;
        if(str.indexOf(",") != -1)
        {
            String[] bStr = str.split(",");
            j = bStr.length;
            for(; i < j; i++)
            {
                n = Integer.parseInt(bStr[i]);
                while(n-- > 0)
                {
                    System.out.print(""+this.purse_worth[(p - i)]+" ");
                }
            }
        }
        else
        {
            j = str.length();
            for(; i < j; i++)
            {
                System.out.print("" + purse_worth[purse.indexOf(str.charAt(i))]+ " ");
            }
        }
        System.out.println("");
    }
}

Name: Anonymous 2010-01-11 10:30

Where are all the good languages?  I expected to see some interesting Perl at the least.  Instead two of the languages /prog/ deems as jokes have posted solutions.

Name: Anonymous 2010-01-11 10:37

>>26
``There are the languages everyone complains about, and there are the languages no one uses.'

Name: Anonymous 2010-01-11 10:49

>>26
Too busy writing real code, which doesn't leave enough time to solve toy problems on /prog/.

Name: Anonymous 2010-01-11 11:08

>>28
Why would such Real Good Programmers visit /prog/?

Name: Anonymous 2010-01-11 11:42

>>26
I didn't post a solution because this is a trivial problem. Everyone who has read their SICP today is familiar with it, and it has been discussed to death on /prog/ already.

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_Temp_52

(define (coin-combinations n d coins)
  (cond ((negative? d) 0)
        ((negative? n) 0)
        ((and (zero? n) (zero? d)) 1)
        (else
         (do ((c coins (cdr c))
              (a 0 (+ a (coin-combinations (- n 1) (- d (car c)) c))))
           ((null? c) a)))))

(coin-combinations 10 100 '(50 25 10 5 1))

Name: Anonymous 2010-01-12 12:57

>>26
good languages
Perl

IHBT.

Name: Anonymous 2010-01-12 14:57

>>27
Wait a second. Everyone complains about Haskell.

Does that mean people actually use it?

Name: Anonymous 2010-01-12 18:29

>>32
Only Uni students in CS. It's an academic curiosity of no practicality utility at all.

Name: Anonymous 2010-01-12 18:33

>>33
Mediocre troll is mediocre.

Name: Anonymous 2010-01-12 18:59

wo ist mein sussschilling

Name: Anonymous 2010-01-12 21:55

>>35
Bùhão.

Name: Anonymous 2010-01-15 21:40

I can't think of a new homework problem. Any suggestions?

Name: Anonymous 2010-01-15 21:53

>>37
It should involve outputting the word "Sussman" in some manner. Otherwise its hardly worth the time.

Name: Anonymous 2010-01-15 22:01

>>38
I'm on it.

Name: Anonymous 2010-01-15 23:00

This thread has been closed and replaced with the following thread:

Subject: Homework
Name: Anonymous
Email:

Write a LOGO program which outputs “Sussman” using the turtle.

Name: Anonymous 2010-01-15 23:29

>>40
rt 90 fd 10
repeat 4 [lt 45 fd 5]
repeat 4 [rt 45 fd 5]
fd 5

pu
fd 5
pd

rt 90 fd 22
lt 45 fd 5
lt 45 fd 10
lt 45 fd 5
lt 45 fd 22

pu
rt 90 fd 5
rt 90 fd 25
pd

lt 90 fd 10
repeat 4 [lt 45 fd 5]
repeat 4 [rt 45 fd 5]
fd 5

pu
fd 5
rt 90
fd 25
lt 90
pd

fd 10
repeat 4 [lt 45 fd 5]
repeat 4 [rt 45 fd 5]
fd 5

pu
fd 5 rt 90 fd 25
pd

lt 180 fd 25
rt 135 fd 10
lt 90 fd 10
rt 135 fd 25

pu
lt 90 fd 5 lt 75
pd

fd 26 rt 150 fd 26

pu
lt 75 fd 5 lt 90
pd

fd 25 rt 135 fd 20 lt 135
pu
fd 14
pd
lt 180 fd 25

Name: Anonymous 2010-01-16 5:15

Name: Anonymous 2010-01-16 8:04

>>41
This feels suspiciously like PostScript to me.

Name: Anonymous 2010-01-20 8:48

waysToChange maxCoins amount coins
   | amount == 0 && maxCoins == 0               = 1
   | amount <  0 || maxCoins == 0 || null coins = 0
   | otherwise =
      (+) (waysToChange (maxCoins - 1) (amount - head coins) coins)
          (waysToChange maxCoins amount (tail coins))

Name: Anonymous 2011-02-26 20:53

MAXIMUM INDENTATION

Don't change these.
Name: Email:
Entire Thread Thread List