Count My Change

21

1

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.

ckjbgames

Posted 2017-02-03T18:26:34.040

Reputation: 1 287

1

Let us continue this discussion in chat.

– ckjbgames – 2017-02-03T19:24:03.010

1All 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 – 2017-02-03T19:33:32.097

4i'm canadian, can i assume the input has no pennies? ;) – undergroundmonorail – 2017-02-03T21:48:01.017

1@undergroundmonorail Sadly, no. – ckjbgames – 2017-02-05T13:46:06.773

1What happened to loonies and half-dollars? – Adám – 2017-02-06T06:29:23.587

1@Adám This is not Canadian currency. – ckjbgames – 2017-02-06T16:04:39.343

1

@ckjbgames I assumed that much. US coins come in 50¢, and $1, while Canada issues $2 instead of 1¢ and 50¢.

– Adám – 2017-02-06T16:46:23.683

1@Adám This is just coins that you would normally have on you as change. – ckjbgames – 2017-02-06T18:02:17.190

Answers

26

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

ETHproductions

Posted 2017-02-03T18:26:34.040

Reputation: 47 880

It should also work with 5, i think. – FlipTack – 2017-02-03T19:08:07.817

@FlipTack Yeah, I just noticed that myself. Not that it makes a difference ;-) – ETHproductions – 2017-02-03T19:09:14.330

This. Cannot. Be. Defeated. – ckjbgames – 2017-03-19T21:28:04.463

You outgolfed Dennis! Congrats! – ckjbgames – 2017-04-26T16:54:41.550

1@ckjbgames Dennis didn't post any answers ;-) – ETHproductions – 2017-04-26T16:55:23.213

1@ETHproductions He probably will. Just show him this question. – ckjbgames – 2017-04-26T17:03:02.583

8

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.

James

Posted 2017-02-03T18:26:34.040

Reputation: 54 537

8

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.

Jonathan Allan

Posted 2017-02-03T18:26:34.040

Reputation: 67 804

Oh oops - if I don't get the el the wrong way around I miss the c :p – Jonathan Allan – 2017-02-03T19:52:44.223

7

Bash + coreutils, 18

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

Try it online.

Digital Trauma

Posted 2017-02-03T18:26:34.040

Reputation: 64 644

6

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)

FlipTack

Posted 2017-02-03T18:26:34.040

Reputation: 13 242

5

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.

Jonathan Allan

Posted 2017-02-03T18:26:34.040

Reputation: 67 804

5

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.

briantist

Posted 2017-02-03T18:26:34.040

Reputation: 3 110

What is $_ in PowerShell? – ckjbgames – 2017-02-03T19:15:56.343

@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 – 2017-02-03T19:18:48.640

That makes sense. – ckjbgames – 2017-02-03T19:31:02.613

5

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 !

zeppelin

Posted 2017-02-03T18:26:34.040

Reputation: 7 884

5

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.

xnor

Posted 2017-02-03T18:26:34.040

Reputation: 115 687

4

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

Business Cat

Posted 2017-02-03T18:26:34.040

Reputation: 8 927

3

Pyke, 9 7 5 bytes

.#5R@

Try it here!

.#5R@ - sort_by:
  5R@ -  i[5]

Blue

Posted 2017-02-03T18:26:34.040

Reputation: 26 661

3

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.

Digital Trauma

Posted 2017-02-03T18:26:34.040

Reputation: 64 644

@ETHproductions Great - thanks! – Digital Trauma – 2017-02-03T19:57:54.727

3

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

user41805

Posted 2017-02-03T18:26:34.040

Reputation: 16 320

You can do :m0 on your alternate solution to save a byte (and tie me) Úçq/:m0 – James – 2017-02-03T21:38:20.813

@DJMcMayhem Thanks, TIL about :move – user41805 – 2017-02-04T08:30:06.210

3

Japt, 3 bytes

ñé5

Try it online!


A couple other 3-byte solutions:

üÅw

Try it online!


ü é

Try it onlin!

Oliver

Posted 2017-02-03T18:26:34.040

Reputation: 7 160

1

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.

Brian J

Posted 2017-02-03T18:26:34.040

Reputation: 653

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 – 2017-02-03T19:46:31.703

@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 – 2017-02-03T19:50:19.030

1

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

Arnauld

Posted 2017-02-03T18:26:34.040

Reputation: 111 334

1

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.

James Holderness

Posted 2017-02-03T18:26:34.040

Reputation: 8 298

1

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

isaacg

Posted 2017-02-03T18:26:34.040

Reputation: 39 268

1

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

}

Adám

Posted 2017-02-03T18:26:34.040

Reputation: 37 779

1

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.

Unrelated String

Posted 2017-02-03T18:26:34.040

Reputation: 5 300

1

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.

Unrelated String

Posted 2017-02-03T18:26:34.040

Reputation: 5 300

0

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.

Neil

Posted 2017-02-03T18:26:34.040

Reputation: 95 035

0

Ruby, 34 bytes

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

input and output as an array of strings

Alexis Andersen

Posted 2017-02-03T18:26:34.040

Reputation: 591

0

Ruby, 31 bytes

->s{s.sort_by{|i|i[1]}.reverse}

dkudriavtsev

Posted 2017-02-03T18:26:34.040

Reputation: 5 781

This will not always sort "nickel" and "dime" correctly. – daniero – 2017-02-05T01:10:15.100

0

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.

daniero

Posted 2017-02-03T18:26:34.040

Reputation: 17 193

0

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 「$_」 )

  }

}

Brad Gilbert b2gills

Posted 2017-02-03T18:26:34.040

Reputation: 12 713

0

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.

Jack Ammo

Posted 2017-02-03T18:26:34.040

Reputation: 430

0

Mathematica, 50 bytes

Flatten@{Last@#,Most@#}&@Split@Sort@StringSplit@#&

martin

Posted 2017-02-03T18:26:34.040

Reputation: 1 335

0

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!

ATaco

Posted 2017-02-03T18:26:34.040

Reputation: 7 898

0

Ruby, 27 bytes

->s{s.sort_by{|x|(x*2)[5]}}

G B

Posted 2017-02-03T18:26:34.040

Reputation: 11 099

0

Smalltalk, 42 bytes

a sort:[:s :t|s allButFirst>t allButFirst]

Explanation

a              input array
sort:          sort message, criterion in the block
[:s :t |       block arguments, represent entries of the input array
allButFirst    copy the receiving string without its first character
>              alphabetic comparison

Leandro Caniglia

Posted 2017-02-03T18:26:34.040

Reputation: 181

0

Perl 6 (19 bytes)

Takes a list of strings.

*.sort(*.comb[5%*])

In action:

my &f = *.sort(*.comb[5%*]);
say f(<quarter dime nickel nickel quarter dime penny penny>);

bb94

Posted 2017-02-03T18:26:34.040

Reputation: 1 831