Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Your task is to sort an array containing the strings "quarter", "dime", "nickel", and "penny" any number of times in no specific order and sort them so that they are in this order: quarter dime nickel penny (in other words, greatest to least monetary value).


Rules

  1. Your program must take an array as input containing the names of U.S coins and sort them from greatest to least by monetary value.
    • For those who are not from the U.S or don't use change, the values of U.S coins, from greatest to least, are:
      • Quarter: 25 cents
      • Dime: 10 cents
      • Nickel: 5 cents
      • Penny: 1 cent
  2. You may sort this array in any way you wish, as long as the output is ordered by the monetary values shown above.
  3. Input can be taken in any way, be it command-line arguments or STDIN.
  4. An input array would be all lowercase strings, something like this:
    • quarter dime nickel nickel quarter dime penny penny
  5. The actual format of input and output is up to you.

Test Cases

"penny nickel dime quarter" 
-> "quarter dime nickel penny"

"nickel penny penny quarter quarter quarter dime dime dime dime"
-> "quarter quarter quarter dime dime dime dime nickel penny penny"

"quarter dime nickel nickel quarter dime penny penny"
-> "quarter quarter dime dime nickel nickel penny penny"

This is , so standard rules & loopholes apply.

share|improve this question
    
Let us continue this discussion in chat. – ckjbgames 14 hours ago
    
All test cases should include output. In the mobile the second and third cases are shown in two lines, so it looks as if the second line is the output – Luis Mendo 14 hours ago
    
i'm canadian, can i assume the input has no pennies? ;) – undergroundmonorail 12 hours ago

18 Answers 18

Japt, 5 3 bytes

ñg9

Test it online!

Explanation

I, too, have added a sorting function to my language in the last few weeks :-) ñ takes in an array and a function and sorts the array as if each item had been mapped through that function.

The g function on a string takes in a number n and returns the nth char in the string, wrapping if n is negative or past the end of the string. The strings can thus be aligned as follows:

quarterquarter...
dimedimedimedi...
nickelnickelni...
pennypennypenn...

The 9th char (0-indexed) of each string has been highlighted in bold. These are in the correct order, so all we have to do is ñg9. (Though now that I look back on it, ñg5 would work as well...)

share|improve this answer
    
It should also work with 5, i think. – FlipTack 15 hours ago
    
@FlipTack Yeah, I just noticed that myself. Not that it makes a difference ;-) – ETHproductions 15 hours ago

V, 7 bytes

ú/¨qu©¿

Try it online!

This uses the spiffy new sort command I added to V around a week ago (ú). Sweet timing!

The way this works is by sorting every line by default sorting (ASCII values) but ignoring the first match of a certain regex. In this case, the regex is (qu)?, although it has some gross non-ASCII stuff to avoid using backslashes. If you ignore the first two letters of "quarter", it starts with 'a', and then all of the coins are already in alphabetical order.

Non-competing version, 4 bytes

ú!/.

This feature was already implemented, but I hadn't tested it extensively yet so it had a bug that I only realized because of this challenge. There is no TIO link because TIO is slightly behind.

This works by reverse sorting every line but ignoring the first character on each line.

share|improve this answer

Python, 36 bytes

lambda a:a.sort(key=lambda x:x[-5:])

Unnamed function that sorts the list in-place by the key function given.

The slices of each coin name are then, arter, dime, ickel, and penny - which are in alphabetical (or more importantly, ordinal) order.

share|improve this answer
    
Oh oops - if I don't get the el the wrong way around I miss the c :p – Jonathan Allan 14 hours ago

Python 3, 42 41 38 bytes

An unnamed lambda function which takes input as a list of strings, sorts in place.

(Outgolfed by Jonathan Allan)

lambda x:x.sort(key=lambda s:(s*2)[5])

Try it online!

Other solutions I messed around with:

lambda x:x.sort(key=lambda s:s*(s<'q'))
lambda x:x.sort(key=lambda s:(s+'pi')[5])
lambda x:x.sort(key=lambda s:ord(s[3])%16)
share|improve this answer

Jelly, 4 bytes

6ịµÞ

Try it online! (the footer, ÇY, joins the resulting list with line feeds for a prettier print out.)

How?

6ịµÞ - Main link: list of strings
  µ  - monadic chain separation
   Þ - sort the list of strings by the monadic function:
6ị   - the sixth index - Jelly indexing is modular and 1-based

The Nth index of a list in Jelly is the Nth item starting at the left, counting from 1, and looping back to the start when need be. (The 0th is at the right, the -1th one left of that and so on too).

So the sixth character of ['d','i','m','e'] is 'i' since six is congruent to two modulo four.

The sixth character of the four coins in order are quarter, dime, nickel, penny . These are in alphabetical (or more importantly, ordinal) order.


Another way to achieve the same thing would be to sort by the rotated strings with ṙ5µÞ, where rotates to the right, making the strings erquart, imed, lnicke, and penny.

share|improve this answer

Pyke, 9 7 5 bytes

.#5R@

Try it here!

.#5R@ - sort_by:
  5R@ -  i[5]
share|improve this answer

CJam, 8 bytes

q~{5=}$p

Try it online!

Explanation

q~        Get and eval all input (array of coin names)
  {5=}$   Sort the array by the 5th index of each element (array indices loop in CJam)
       p  Print the result
share|improve this answer

Bash (+coreutils) 11 bytes

Golfed

sort -rk1.2

Test

>echo penny nickel dime quarter|tr ' ' '\n'|sort -rk1.2

quarter
dime
nickel
penny

Try It Online !

share|improve this answer

Retina, 10

  • 6 10 bytes saved thanks to @ETHproductions
q
b
O`
b
q
  • Substitute q to b
  • Sort
  • Substitute b back to q

Try it online.

share|improve this answer
    
@ETHproductions Great - thanks! – Digital Trauma 14 hours ago

Python, 32 bytes

lambda s:s.sort(key="npr".strip)

Try it online! Sorts the list in place.

The idea is to use a sorting key function without a lambda. A good candidate was x.strip, which takes the string x and removes its the left and right edges all characters in the input. For example, "abcdef".strip("faces") == "bcd".

The method "npr".strip takes:

quarter ->  np
dime    ->  npr
nickel  ->  pr
penny   ->  r

which are lexicographically sorted. I found the string npr by brute force. npu and npt also work, and there are none shorter.

share|improve this answer

V, 8 7 bytes

1 byte saved thanks to @DJMcMayhem

Úçq/:m0

[Try it online!]

See @DJMcMayhem's answer in V (1 0 bytes shorter than mine)

Try it online!

Ú                    " sort all lines "
 ç                   " globally "
  q/                 "  where there a q is matched, "
    :m0              "  move it to the top of the buffer "

Here is an older solution at 1 byte larger, but I really like it.

V, 8 bytes

Ú/q
dGHP

[Try it online!]

Try it online!

Explanation

Ú        " sorts the lines

Now the buffer will be in this format:

dimes
nickels
pennies
quarters

The only thing left to do now is to move the quarters to the top.

/q      " search for a q "
dG      " delete everything from the first quarter to the end of buffer "
HP      " and paste it at the top of the buffer
share|improve this answer
    
You can do :m0 on your alternate solution to save a byte (and tie me) Úçq/:m0 – DJMcMayhem 12 hours ago
    
@DJMcMayhem Thanks, TIL about :move – Kritixi Lithos 1 hour ago

PowerShell, 21 bytes

$args|sort{($_*3)[9]}

Try it online!

Explanation

Shamelessly stole the algorithm in ETHproductions's answer (basically). I multiply each string by 3, then sort based on the 9th character of the resulting string.

share|improve this answer
    
What is $_ in PowerShell? – ckjbgames 15 hours ago
    
@ckjbgames In a pipeline, within a scriptblock, it refers to the current item. So something like 1,2,3,4 | ForEach-Object { $_*2 } will output each number times 2; the script block is run once per input item. – briantist 15 hours ago
    
That makes sense. – ckjbgames 14 hours ago

Bash + coreutils, 18

tr q b|sort|tr b q
  • Transliterate q to b
  • Sort
  • Transliterate b back to q

Try it online.

share|improve this answer

JavaScript (ES6), 35 33 bytes

a=>a.sort(([,...a],[,...b])=>b>a)

Test cases

let f =

a=>a.sort(([,...a],[,...b])=>b>a)

console.log(f(['penny','nickel','dime','quarter']).join` `);
console.log(f(['nickel','penny','penny','quarter','quarter','quarter','dime','dime','dime','dime']).join` `);
console.log(f(['quarter','dime','nickel','nickel','quarter','dime','penny','penny']).join` `);

share|improve this answer

Batch, 82 bytes

@for %%c in (quarter dime nickel penny)do @for %%a in (%*)do @if %%a==%%c echo %%c

Takes input as command-line arguments and outputs to STDOUT. Works by concatenating the lists resulting from filtering the original list on each coin.

share|improve this answer

T-SQL, 41 36 34 bytes

select*from @ order by right(a,5)

Explanation

Assume the input is pre-loaded in a table variable named @, with a single column named a, where each value is one coin to be sorted.

The select * from @ part is boiler-plate 'get all values to return'. The real magic happens in the order by clause.

Using the same strategy as Johnathan Allan, I sort by the last five characters (SQL will return the entire string if it's too short): arter, dime, ickel, penny.

share|improve this answer
    
q is the next letter after p, so for a simple mod to result in q less than p the value needs to be a factor of q, which is prime. You could subtract 1 first and then a modulus of 7 would work, but that would presumably take at least as many bytes as 113. – Neil 14 hours ago
    
@Neil Yeah, I realized 113 being prime was wrecking my attempts to reduce the count. Doing -1 and then mod 7 is more bytes (including required parentheses. – Brian J 14 hours ago

Ruby, 34 bytes

->m{m.sort_by{|c|c[1..2]}.reverse}

input and output as an array of strings

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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