Today's challenge is to implement a change
function that will accept an integer parameter that represents cents. The function should return the optimal change using the least number of coins.
The function should also return a key for each coin of US currency (specifically 25¢, 10¢, 5¢, and 1¢ coins). The value of each coin should represent the count of each coin in the change. The value for each coin that is not included should return 0.
Ex.
change(31)
{ 25 => 1, 10 => 0, 5 => 1, 1 => 1 }
Good luck!
This challenge comes from user Lordnibbler on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (17)
x86_64 assembly (System V ABI, GNU assembler), for those concerned about speed.
change.S:
change.h:
I am concerned about speed
we need to get that stuff off the streets smh
causin' good folk to think they need to write stuff in assembly, fcol >.>
Hey there, thank you for your comment!
We might think that the
COINS
variable declared with aconst
operator is indeed a constant but it is not. It is not possible to assign another array, but you can still update its values by targeting its indexes. This means that the function is inpure because its result is not predictable as it relies on an out-scope variable that can be updated outside of the function call, but used inside the function. The oustide world can update the array like so:The solution would be to declare the array as a freezed array in JavaScript:
That way, no side-effects possible. This would also allow the function to be pure again. Another solution would be to declare the
COINS
variable inside the function, or even better, declare another parameter if the coins variable is something to be changed later.ruby <3
JavaScript
Pure variant of what has already been made in JavaScript.
Performance
I am curious about the performance in those kind of challenge. I am totally aware that JavaScript is not the fastest to do this kind of thing and the idea is not to bash any language of implementation. I'm just a guy curious about that. If some of you are willing to take the habit to post the performance for one milion iterations that would be cool to compare with others!
Source-Code
Available online.
Rust, iterative style:
My solution in js
This is a nice solution in Java. But don't forget to remove the
number = 74;
, otherwise the function will always write the same results.Just my two cents, in Gwion
prints
It probably could be written better, but looks like it gets the job done.
JavaScript with reduce:
Go - with tests:
change.go:
change_test.go
change_test_cases.go