21
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ – ckjbgames Feb 3 '17 at 19:24
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – Luis Mendo Feb 3 '17 at 19:33
  • 4
    \$\begingroup\$ i'm canadian, can i assume the input has no pennies? ;) \$\endgroup\$ – undergroundmonorail Feb 3 '17 at 21:48
  • 1
    \$\begingroup\$ @undergroundmonorail Sadly, no. \$\endgroup\$ – ckjbgames Feb 5 '17 at 13:46
  • 1
    \$\begingroup\$ What happened to loonies and half-dollars? \$\endgroup\$ – Adám Feb 6 '17 at 6:29

32 Answers 32

26
\$\begingroup\$

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...)

\$\endgroup\$
  • \$\begingroup\$ It should also work with 5, i think. \$\endgroup\$ – FlipTack Feb 3 '17 at 19:08
  • \$\begingroup\$ @FlipTack Yeah, I just noticed that myself. Not that it makes a difference ;-) \$\endgroup\$ – ETHproductions Feb 3 '17 at 19:09
  • \$\begingroup\$ This. Cannot. Be. Defeated. \$\endgroup\$ – ckjbgames Mar 19 '17 at 21:28
  • 1
    \$\begingroup\$ @ckjbgames Dennis didn't post any answers ;-) \$\endgroup\$ – ETHproductions Apr 26 '17 at 16:55
  • 1
    \$\begingroup\$ @ETHproductions He probably will. Just show him this question. \$\endgroup\$ – ckjbgames Apr 26 '17 at 17:03
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Oh oops - if I don't get the el the wrong way around I miss the c :p \$\endgroup\$ – Jonathan Allan Feb 3 '17 at 19:52
7
\$\begingroup\$

Bash + coreutils, 18

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

Try it online.

\$\endgroup\$
6
\$\begingroup\$

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)
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ What is $_ in PowerShell? \$\endgroup\$ – ckjbgames Feb 3 '17 at 19:15
  • \$\begingroup\$ @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. \$\endgroup\$ – briantist Feb 3 '17 at 19:18
  • \$\begingroup\$ That makes sense. \$\endgroup\$ – ckjbgames Feb 3 '17 at 19:31
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

Bash (+coreutils) 11 bytes

Golfed

sort -rk1.2

How It Works

Reverse sort, with the "sort key" from the second character of the first field (word) till the end of line, i.e.:

uarter
ime
ickel
enny

Test

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

quarter
dime
nickel
penny

Try It Online !

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Pyke, 9 7 5 bytes

.#5R@

Try it here!

.#5R@ - sort_by:
  5R@ -  i[5]
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ @ETHproductions Great - thanks! \$\endgroup\$ – Digital Trauma Feb 3 '17 at 19:57
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ You can do :m0 on your alternate solution to save a byte (and tie me) Úçq/:m0 \$\endgroup\$ – DJMcMayhem Feb 3 '17 at 21:38
  • \$\begingroup\$ @DJMcMayhem Thanks, TIL about :move \$\endgroup\$ – Cows quack Feb 4 '17 at 8:30
3
\$\begingroup\$

Japt, 3 bytes

ñé5

Try it online!


A couple other 3-byte solutions:

üÅw

Try it online!


ü é

Try it onlin!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Neil Feb 3 '17 at 19:46
  • \$\begingroup\$ @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. \$\endgroup\$ – Brian J Feb 3 '17 at 19:50
1
\$\begingroup\$

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` `);

\$\endgroup\$
1
\$\begingroup\$

Befunge, 158 bytes

~:0`v0v4<~_
9:%8_^>8*`^1p9\+1g
$:!#@_1-0" ynnep">:#,_>
1-0" lekcin">:#,_>$:!#^_
" emid">:#,_>$:!#^_1-0
>:#,_$1>-:!#^_0" retrauq"
*84g9< ^*84g91-*84g94-*84g96-

Try it online!

String processing and sorting are not the sorts of things you'd typically want to attempt in Befunge, but this solution is taking advantage of John Kasunich's observation that we don't actually need to sort anything. We just count the number of occurrences of each coin (which can easily be determined from the first character), and then output that many of each coin name in the appropriate order.

It's still not at all competitive with other languages in terms of size, but this approach is at least better than it would have been if we'd tried to handle the challenge as a string sorting exercise.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 3 bytes

@D5

Demonstration

Based on ETHproductions's answer in Japt.

Explanation:

@D5
@D5Q    Variable introduction
 D Q    Sort the input by
@ 5     Its fifth character
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog APL), 11 bytes

Takes and returns list of strings.

{⍵[⍋↑5⌽¨⍵]}

Try it online!

{ anonymous function:

⍵[] the argument indexed by

 the ascending-making indices of

 the matrix whose rows are the padded

5⌽ five-steps-rotated

¨⍵ items of the argument

}

\$\endgroup\$
1
\$\begingroup\$

Brachylog, 3 bytes

↺₉ᵒ

Try it online!

Approach stolen from ETHproductions' Japt answer.

       The input
  ᵒ    sorted by
↺      its elements rotated left
 ₉     by 9
       is the output.
\$\endgroup\$
1
\$\begingroup\$

Husk, 3 bytes

Öṙ9

Try it online!

Ported from my Brachylog answer, which rips off ETHproductions' Japt answer but isn't an exact translation since it uses rotation instead of simple accessing-the-nth-element. There, I did it because doesn't let you index past the end of the input (which is probably quite helpful in many circumstances due to the declarative nature of the language). In Husk, ! does let you index past the end of the input, with the same modular wrapping around that Japt ñg9 uses, but it's from 1 so this program in particular would end up being one byte longer: Ö!10.

Ö      Sort by
 ṙ     rotation by
  9    9.
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Ruby, 34 bytes

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

input and output as an array of strings

\$\endgroup\$
0
\$\begingroup\$

Ruby, 31 bytes

->s{s.sort_by{|i|i[1]}.reverse}
\$\endgroup\$
  • \$\begingroup\$ This will not always sort "nickel" and "dime" correctly. \$\endgroup\$ – daniero Feb 5 '17 at 1:10
0
\$\begingroup\$

Ruby, 30 bytes

->m{m.sort_by{|s|s[3].ord^16}}

Magical numbers found by trial and error. A bit clumsy, but shorter than using .reverse.

\$\endgroup\$
0
\$\begingroup\$

Perl 6,  40 36  34 bytes

*.sort: {(<q d n p>Zxx 1..*).Bag{~m/./}}

Try it

*.sort: {%(<q d n p>Z=>1..*){~m/./}}

Try it

*.sort: {%(<q d n p>Z=>^4){~m/./}}

Try it

Expanded:

*\            # WhateverCode lambda ( this is the parameter )

.sort:        # sort using the following code block

{             # bare block lambda with implicit parameter 「$_」

  %(          # treat this list as a hash

    <q d n p> # list of first characters
    Z[=>]     # zipped using pair constructor
    ^4        # Range from 0 up-to 4 ( excludes 4 )

  ){          # get the value associated with this key

    ~m/./     # regex which gets the first character ( implicitly from 「$_」 )

  }

}
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 50 bytes

Flatten@{Last@#,Most@#}&@Split@Sort@StringSplit@#&
\$\endgroup\$
0
\$\begingroup\$

RProgN, 18 bytes

~{3mtt¢\3mtt¢>}$

Explained

~               # Zero Space Segment
 {            } # Anonymous Function
  3m            # Repeat the inputted string 3 times
    tt¢         # And take the tenth character of that
       \3mtt¢   # Do the same for the entry underneith
             >  # Compare the ascii value of the two
               $# Sort the input by the anonymous function.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

java 8, 128 112 bytes

This is a lambda expression for a java.util.function.Function<String[],String[]>

s->{String r="";for(String k:"q d c p".split(" "))for(String t:s)if(t.contains(k))r+=" "+t;return r.split(" ");}

Explantion: For each of the 4 coins in order, go through the input and append the coin's name to the result every time there is a match for that coin's unique character. Split the result into an array and return it.

\$\endgroup\$
0
\$\begingroup\$

Ruby, 27 bytes

->s{s.sort_by{|x|(x*2)[5]}}
\$\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.