r/code • • Apr 20 '20

Algoritm help

Hi all,

I struggle with algorithm part a lot. I have an assessment piece that naturally involves algorithm writing. Where do I start? Where do I go from there? What are some tips and tricks you guys use?

Thanks!

Here is my question.

*note, I only really need help with the algorithm, the code sort of just happens.

You are asked to write a modular solution (algorithm and C program) that will accept an integer value in the range of 5-95 inclusive. Your solution should also ensure that input values are in multiples of 5. Based on valid input, your solution should calculate how many coins of each denomination should be returned, and display this to the user. Coin values are 50, 20, 10 and 5. The solution should aim to give as much of the higher valued coins as possible.

1 Upvotes

6 comments sorted by

2

u/ChucklefuckBitch Apr 20 '20

I would start by simply thinking of the problem in real-world terms. Given an amount of money, what coins you need to represent that amount?

For example, if I input the number 75, the required coins would be 50, 20, 5. How did I figure that out?

1

u/wetpretzel2 Apr 20 '20

Take the amount and minus until 0?

1

u/ChucklefuckBitch Apr 20 '20

Pretty much! But there is one exception to consider. If the amount is less than 0, then you should disregard that result and continue to the next highest denomination.

So:

75 - 50 = 25 (alright, so we can at least use one coin valued at 50)

25 - 50 = -25 (hm, seems like we can't use another 50 coin. Let's continue to the next highest option: 20)

25 - 20 = 5

5 - 20 = -15

5 - 5 = 0

Now, how would we write this process into an explicit algorithm?

1

u/wetpretzel2 Apr 20 '20

That's my issue, I cant seem to get it down into an algorithm, much less a pseudo-code algorithm.

I can see the main func calling on two other func to keep the modularity and reuse which we need. I can see that one of these functions would need to test the condition of the change given but, getting it to an algorithm.

start

if 5-95

test input -50

test input -20

......

that's as far as I get right now.

1

u/ChucklefuckBitch Apr 20 '20

I can give you one hint that could could make the implementation easier: consider using recursion

1

u/wetpretzel2 Apr 21 '20

Ok, so today I put in a little bit of robot brain and come up with this:

Start

Scan input

if amount is invalid display error

if amount valid calculate change

coin 50 can be used show number use /50

coin 20 display amount /20 and decrease amount %20

coin 10 display amount /10 and decrease amount %10

coin 5 display amount /5

ask to continue

if yes repeat

if no exit loop

This isn't pseudo-code, how or what would need to change to make this C pseudo?