It is very hard to remember my password, so I came up with a way to generate a password.

The way I generate my password is from a word or a sentence, following these steps:

1. Start from left to right

2. Find the count of each letter

3. Put letter with its count in an order

• Letters with higher repetition will be in the end

• Letters with the same repetition will be ordered alphabetically

4. Numbers and special letters will be ignored including whitespace (e.g. 9, 4, @, (, *, etc. are ignored)

5. Group letters ignoring case. In the output, use the case of the last occurrence in the input

6. The count of the letter can be any number e.g. 5H17M345K
7. If input is all numbers or special letters then output will be empty string e.g. Input "12$*34^!" then output "" 8. when order for the same occurrence alphabetically case does not matter e.g. 1a1B1c Example: Input: Kitkat Tango (2k / 1i / 3T / 2a / 1n / 1g / 1o) Output: 1g1i1n1o2a2k3T  Another example: Input: Database Partitions Task (1D / 5a / 4T / 1b / 3s / 1e / 1P / 1r / 2i / 1o / 1n / 3s / 1k) Output: 1b1D1e1k1n1o1P1r2i3s4T5a  Note: the letters with 1 repeat are in the beginning ordered alphabetically then the letters with more reps This is , the shortest code wins. • Can a letter appear more than 9 times? Commented Jan 18, 2019 at 7:58 • @manatwork: But that's not unclear (note, their answer didn't assume that letters appear less than 10 times), it's just trying to loosen the input restrictions. Commented Jan 18, 2019 at 16:36 • make sure to add these clarifications to the actual question body, so answerers don't have to hunt through the comments – Jo King Commented Jan 20, 2019 at 4:04 • Comments do not a specification make. You need to update the challenge to 1. add at least 1 test case that includes more than 9 occurrences of one or more letters, 2. specify that output must be a string (although I'd strongly recommend against being that strict; it adds nothing to the challenge), 3. specify that we must be able to handle inputs containing no letters, and, 4. clarify whether or not we need to handle an empty string as input. Commented Jan 22, 2019 at 19:51 • Once you've done that then you will then have to test all existing solutions and inform them if they need to make any changes. I've already found quite a number of solutions that fail on point 1. Also, in the future you might consider using our Sandbox to try to iron out issues like these before posting a challenge. Commented Jan 22, 2019 at 19:54 ## 26 Answers # 05AB1E, 1917 16 bytes Saved 1 byte thanks to Kevin Cruijssen áΣl}.γl}éεgyθJ}J  Try it online! or as a Test Suite Explanation á # keep only letters in input Σl} # sort by lower-case .γl} # group by lower-case é # sort by length (stable) ε } # map each to g # its length J # joined with yθ # the last letter J # join to string  • You can save a byte by changing the ‚ (pair with) to a « (concat/merge), so one of the two Js (joins) can be removed. Commented Jan 18, 2019 at 12:27 • @KevinCruijssen: Wow. I feel stupid now :) Why didn't I just move a J inside? Edit: Actually, I needed them as a pair in the 19-byte version and I didn't think to change it when I made the 17 one :P Commented Jan 18, 2019 at 13:25 • You might be able to drop the second Join, depending on the answer to this question Commented Jan 18, 2019 at 17:13 • -1 by changing εgyθJ}J to vygyθJ. And another -3 by changing Σl}.γl} to .¡l} (we now have an actual group-by builtin, yay). Commented Feb 24, 2020 at 13:28 # Perl 6, 66 63 bytes {[~] map {+$_~.tail},sort {+$_,.lc},m:g/<:L>/.classify(&lc){*}}  Try it online! ### Explanation { } # Anon block m:g/<:L>/ # Match all letters .classify(&lc) # Group by lowercase {*} # Get hash values sort {+$_,.lc},  # Sort by array length and lowercase
map {         },  # Map to
+$_~.tail # Concat array length and last letter [~] # Join  # C# (Visual C# Interactive Compiler), 105 bytes x=>x.Where(char.IsLetter).GroupBy(a=>a%32).OrderBy(a=>(a.Count(),a.Key)).Select(a=>a.Count()+""+a.Last())  Try it online! Thanks to dana for bringing it down to 105 bytes from 138 bytes. • why not just .OrderBy(a=>a) ? Commented Jan 19, 2019 at 19:34 • 105? – dana Commented Jan 23, 2019 at 14:56 # Japt v2.0a0 -P, 14 bytes f\l üv ñÊ®ÌiZÊ  Try it f\l üv ñÊ®ÌiZÊ :Implicit input of string > e.g., "Kitkat Tango" f :Split to an array of characters \l : Matching RegEx /[a-z]/gi > ["K","i","t","k","a","t","T","a","n","g","o"] ü :Sort & group (Preserves original order within each group) v : By lowercase > [["a","a"],["g"],["i"],["K","k"],["n"],["o"],["t","t","T"]] ñ :Sort Ê : By length > [["g"],["i"],["n"],["o"],["a","a"],["K","k"],["t","t","T"]] ® :Map each Z Ì : Last element of Z > ["g","i","n","o","a","k","T"] i : Prepend ZÊ : Length of Z > ["1g","1i","1n","1o","2a","2k","3T"] :Implicitly join & output > "1g1i1n1o2a2k3T"  # Retina, 676641 39 bytes \P{L} O$.
$l$0
ir\1*(.)
$.0$1
N\d+.


-25 bytes and a minor bug-fix thanks to @Neil.
-2 bytes thanks to @Neil and @Shaggy together.

Explanation:

Remove everything except for upper- and lowercase letters:
i.e. Kitkat Tango 123!KitkatTango

\P{L}



Sort the individual letters case-insensitive (thanks to @MartinEnder for this):
i.e. KitkatTangoaagiKknottT

O$.$l$0  Capture every chunk of case-insensitive repeated adjacent letters: i.e. aagiKknottT → [aa,g,i,Kk,n,o,ttT] ir\1*(.)  Prepend the length of every match, and only keep the last letter of every chunk: i.e. [aa,g,i,Kk,n,o,ttT] → 2a1g1i2k1n1o3T $.0$1  Sort the numbers and letter groups based on the numbers: 2a1g1i2k1n1o3T1g1i1n1o2a2k3T N\d+.  After which the result is output implicitly. • Are you sure that's a bug? Is it not just sorting lexicographically? ("aA" < "aa") Commented Jan 18, 2019 at 9:48 • @Shaggy I'm not sure if it can. Because the \w and . in the O\w. were used to indicate that we're sorting pairs of characters. Not sure if we can sort every pair of characters, but only sort it based on the first character. But ah well, Martin's suggestion to sort each character based on a substitution (which is the lowercase variant of the match) works like a charm. :) Commented Jan 18, 2019 at 10:26 • Can it be done in 41 bytes or am I missing something? – Neil Commented Jan 18, 2019 at 12:32 • github.com/m-ender/retina/wiki/The-Language#regex-modifiers – Neil Commented Jan 18, 2019 at 13:29 • @Shaggy Actually reading further, \P{L} might work, which saves 2 bytes. – Neil Commented Jan 18, 2019 at 20:58 # Python 3, 105 bytes s=input() t=s.upper() for n,c in sorted((t.count(i),i)for i in{*t}if'@'<i<'['):print(n,end=s[t.rfind(c)])  Try it online! -1 thanks to ArBo. # Wolfram Language (Mathematica), 1029693 87 bytes ""<>Map@ToString/@Sort[(r=Reverse)/@Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]]&  Try it online! Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&] Start with a char list #/." "->Nothing Remove spaces r@ Reverse the result Tally[ ,Equal@@ToLowerCase@{##}&] Make a list of letters and multiplicities, where two letters are considered the same if their lowercase values are equal. Then: ""<>Map@ToString/@Sort[(r=Reverse)/@ ... ]& (r=Reverse) Reverse each {letter, freq} to {freq,letter}. Then the standard Wolfram order function sorts lower frequencies first, with ties broken by by letters earlier in the alphabet, Sort[ ] exactly what we want. Map@ToString/@ @ has higher precedence than /@, so this effectively does Map[Map[ToString]]. ""<> StringJoin the nested list into a single string.  # Pyth, 2724 22 bytes ssrD0m,lded.gr0k@+Gr1G  Try it online here. ssrD0m,lded.gr0k@+Gr1GQ Implicit: Q=eval(input()), G=lowercase alphabet Trailing Q inferred r1G Uppercase alphabet +G Concatenate with lowercase alphabet @ Q Keep those characters in Q which are also in the above .g Group the remaining characters, as k, using: r0k Convert k to lowercase (Grouping preserves relative order) m Map the sorted groups, as d, using: ld Length of d , Pair the above with... ed ... last element of d D Sort the above... r 0 ... by their lowercase values ss Flatten, then concatenate the result of the above into a string, implicit print  Edit: Golfed 3 bytes by ordering by character before group, previous version: sm+ldedo,lNr0eN.gr0kf}r0TGQ Edit 2: Golfed off another 2 bytes by formatting output before any ordering, previous version: sm+ldedlD.gr0krD0f}r0TGQ Edit 3: Golfed off another byte by changing the filter, thanks to @FryAmTheEggman. Also had to fix a bug when OP clarified that a single letter can appear more than 9 times, which added a byte back on :o( Previous version: srD0m+lded.gr0kf}r0TGQ # Perl 5 (-n), 74, 68, 66, 65 bytes -6 bytes changing -p to -n and using say instead of $_=join"",
-2 bytes thanks to Abigail using \pL instead of [a-z]
-1 byte thanks to Kjetil S. removing i flag no more necessary after using \pL

s/\pL/($h{lc$&}+=1).=$&/ge;say sort{$a-$b||lc$a cmp lc$b}values%h  TIO 58 bytes, in case there is no more than 9 occurence of each character s/\pL/($h{lc$&}+=1).=$&/ge;say sort{lc$a cmp lc$b}values%h

• @Abigail, thank you, in the second program it was an oversight a after update Commented Jan 18, 2019 at 22:04
• Shave a byte by replacing /gie with /ge. Since \pL is case insensitive. Commented May 4, 2021 at 14:42
• @KjetilS. thank you, updated Commented May 4, 2021 at 17:58

# Python 2, 116 bytes

def f(s):a=s.lower();return''.join(n+s[a.rfind(c)] for n,c in sorted((a.count(c),c)for c in set(a)if c.isalpha()))


Try it online!

• The output for Database Partitions Task is not equal to 1b1D1e1k1n1o1P1r2i3s4T5a Commented Jan 18, 2019 at 16:12
• @mdahmoune thanks, should be fixed. Commented Jan 18, 2019 at 21:50
• In the output, use the case of the last occurrence in the input you'll need rfind instead of find for this. ...] for can become ...]for to offset that though.
– ArBo
Commented Jan 18, 2019 at 22:18

-9 bytes thanks to Laikoni (using list-comprehension and (||) instead of filter with elem & shorten length to get rid of ugly zip)!

f s=id=<<[show(h r)++[last r]|l<-[1..h s],a<-['A'..'Z'],r<-[[x|x<-s,x==a||x==[a..]!!32]],h r==l]
h=length


Try it online!

• 107 bytes: Try it online! Commented Jan 19, 2019 at 15:32
• 105: Try it online! Commented Jan 19, 2019 at 15:44
• @Laikoni: Now shorter than with imports, very nice!! Commented Jan 19, 2019 at 16:20

# Red, 220196 206 bytes

func[s][a: charset[#"a"-#"z"#"A"-#"Z"]trim/all form sort/skip collect[foreach c sort
unique reverse rejoin parse s[collect[any[keep[a]| skip]]][i: 0
foreach d s[if(c% 32)=(d% 32)[i: i + 1]]keep i keep c]]2]


Try it online!

Thanks to Shaggy for finding a bug.

# Scala, 103 bytes

_.filter(_.isLetter).groupBy(_%32).values.map(l=>l.size+""+l.last).toSeq.sortBy(_.toLowerCase).mkString


Try it online!

# Jelly, 15 bytes

fØẠµŒlĠLÞịµL,Ṫ)


A full program printing the password as specified (as a monadic Link it yields a list of lists each containing an integer and a character).

Try it online!

# Husk, 15 bytes

No problems with imports when using Husk, therefore we can make use of the various handy functions such as groupOn, sortOn, toLower etc:

ṁ§:osL→ÖLSġÖ_f√


## Explanation

ṁ§:(sL)→ÖLSġÖ_f√  -- example input: "Kitkat Tango"
f√  -- filter isAlpha: "KitkatTango"
S  _    -- apply _ to .. then ..
Ö     -- | sortOn: sortOn toLower
ġ      -- | groupOn: groupOn toLower
-- .. compose: groupOn toLower . sortOn toLower
-- sortOn toLower (stable): "aagiKknottT"
-- groupOn toLower: ["aa","g","i","Kk","n","o","ttT"]
ÖL        -- sortOn length (stable): ["g","i","n","o","aa","Kk","ttT"]
ṁ                 -- map and flatten (concatMap)
§                -- | fork argument ..
→          -- | | last: ['g','i','n','o','a','k','T']
(sL)           -- | | show . length: ["1","1","1","1","2","2","3"]
:               -- | .. and snoc: ["1g","1i","1n","1o","2a","2k","3T"]
-- : "1g1i1n1o2a2k3T"


# APL (Dyalog Extended), 28 bytesSBCS

Anonymous tacit prefix function.

(∊⍤∧⌊(⊂⍕⍤≢,⊢/)⍤⊢⌸⊢)'\PL'⎕R''


Try it online!

'\PL' non-letters
⎕R PCRE Replaced with
'' empty strings

() apply the following tacit function:

⌊ with the lowercase as keys,
…⌸ apply the below tacit function to each key and its corresponding set of values, namely
⊢ the argument:

() apply the following tacit function
⍤ to
⊢ the list of values:

⊢/ the last value

…, prepend the following to that:

⍕ the stringification
⍤ of
≢ the tally

⊂ enclose (to treat character list as single string)

∊ϵnlist (flatten)
⍤ the
∧ sorted-ascending version of that

# JavaScript (Node.js), 127 bytes

s=>[...s].sort(o=(x,y)=>p(0+x,36)-p(0+y,36),p=parseInt).join.match(/([a-z])\1*/ig).map(x=>(l=x.length)+x[l-1]).sort(o).join


Try it online!

• parseInt(numberAsString, radix) will try to parse integer in the beginning of string. For example, parseInt('120px', 10) will output 120. When parsing failed, it returns NaN instead. We connect an '0' to the beginning of each character so it will return 0 for any non numeric-alpha characters. And we can sort same letters together and non-alpha character to the beginning by this algorithm.
• After sort and join, "Hello world!123" would become " !123deHllloorw". An matching against /([a-z])\1*/ig will ignore any non-alpha character and split the string into chunks with same letters. .
• map convert "aaa" to "3a" as required in the question.
• The second sort use same function as the first one. Thanks to the number system, "3b" would be less than "12a" in base 36 just as we expect: It compare counts first (n div 36), and compare the letter later (n mod 36).
• Finally join them together.

# JavaScript (Node.js), 146 bytes

f=(s,...a)=>(s=s.replace(/[^a-z]/ig,''))?f(s.replace(RegExp(s[c=0],'ig'),x=>(l=++c+x,'')),...a,l):a.sort((x,y)=>p(x,36)-p(y,36),p=parseInt).join


Try it online!

• Why not submit the shorter solution as your main solution? Also, it can be 2 bytes shorter as it's not recursive. Commented Jan 22, 2019 at 19:27
• @Shaggy Ah, totally forgot to remove f=. The first one used to be shorter. But it gets 4 bytes more since OP asked the output may be empty string. And I just kept them there...
– tsh
Commented Jan 23, 2019 at 2:24
• @Shaggy OK, just find out the second one may be even more shorter. And I placed it as first.
– tsh
Commented Jan 23, 2019 at 3:22

# Java 10, 223209 301 bytes

s->{int i=32,t;String M[]=new String[i],r,R="";for(var c:s)M[c%32]+=c>64&c<91|c>96&c<123?c:R;for(;i-->0;M[i]=(t=r.length()-4)>0?t+r.split(R)[t+3]:R)r=M[i]+R;java.util.Arrays.sort(M);for(var p:M)R+=p;return R;}


+92 bytes as a fix for inputs with more than 9 of a single letter.. Will see if I can bring that down again with a different approach.

Try it online.

Explanation:

s->{                        // Method with character-array parameter and String return-type
int i=32,                 //  Index-integer, starting at 32
t;                    //  Temp-integer, uninitialized
String M[]=new String[i], //  Create a String-array of size 32, filled with null by default
R="",              //  Result-String, starting empty
r;                 //  Temp-String, uninitialized
for(var c:s)              //  Loop over the characters of the input-array:
M[c%32]+=               //   Append the string at index code-point of c modulo-32 with:
c>64&c<91|c>96&c<123?  //    If the character is a letter:
c                     //     Append the character
:                      //    Else:
R;                    //     Append an empty String
for(;i-->0                //  Loop i in the range (32, 0]:
;                     //    After every iteration:
M[i]=                //     Replace the String at index i with:
(t=r.length()-4)    //      Set t to the length of String r minus 4
//      (the minus 4 is for the prepended "null")
>0?                //      If this length minus 4 is larger than 0:
t                 //       Set the String to this length minus 4
+r.split(R)[t+3]  //       Appended with the last character of r as String
:                  //      Else:
R)                //       Make the String at index i empty
r=M[i]                  //   Set r to the i'th String
+R;               //  Converted to String
// (null becomes "null", to prevent NullPointerException-errors)
java.util.Arrays.sort(M,  //  Now sort the array of Strings on:
(a,b)->                  //   For each pair of two Strings:
new Byte(              //    Convert the first String to a number
(0+a).replaceAll("\\D",""))
.compareTo(             //   And compare it to:
new Byte(              //    The second String converted to a number
(0+b).replaceAll("\\D",""))));
for(var p:M)              //  Loop over the Strings of the array:
R+=p;                   //   And append each to the result-String R
return R;}                //  And finally return the result-String R

• @Shaggy Dang.. fixed at the cost of 92 bytes.. >.< Will see if I can golf it down again by not using a Comparator to sort but sort manually myself later on.. Commented Jan 23, 2019 at 14:38
• Ouch! Sorry about that! Commented Jan 23, 2019 at 15:51

s.map{String($0)}.filter{$0.rangeOfCharacter(from:.letters) != nil}.reversed().reduce(into:[String:Int]()){d,s in if let l=[s.uppercased(),s.lowercased()].first(where:{d[$0] != nil}){d[l]=d[l]!+1}else{d[s]=1}}.sorted{let c=$0.value-$1.value;return c==0 ?$0.key.compare($1.key,options:.caseInsensitive) == .orderedAscending:c<0}.map{"\($0.value)\($0.key)"}.joined()  Try it online! @KevinCruijssen also removed some spaces. • Hi, welcome to PPCG! I don't know Swift, but it seems you forgot to remove some spaces, and you can also golf all false to 0>1 and true to 1>0. Try it online 1027 bytes. Probably loads more can be golfed, like the duplicated if let v=$0.key.escaped(asASCII:0>1).lowercased().unicodeScalars.first?.value{return v<$1.key.value}else{return 0>1} you have, but I'll leave that to someone who actually knows Swift. Commented Jan 25, 2019 at 13:00 • Also, if you haven't seen it yet: Tips for golfing in <all languages> and Tips for golfing in Swift might be interesting to read through. Again welcome, and enjoy your stay! :) Commented Jan 25, 2019 at 13:01 • Hello @KevinCruijssen. Thanks for tips, I removed true and false from my answer. Commented Jan 27, 2019 at 12:10 • Nice, you've golfed it quite a lot from your initial 1000+ bytes. :) I see 6 more spaces that can be removed after/before all =-assigns: Try it online 364 bytes. Enjoy your stay! :) Commented Jan 27, 2019 at 12:12 # Charcoal, 30 bytes Ｆ⌈Ｅβ№↧θιＦβ¿⁼№↧θκ⊕ι⁺⊕ι§Φθ⁼↧λκ±¹  Try it online! Link is to verbose version of code. Explanation: Ｆ⌈Ｅβ№↧θι  Run through the lowercase alphabet and find the highest character count in the lowercased input. Loop over the implicit range. (The loop actually goes from 0 to n-1 so I have to increment the loop variable at each use.) Ｆβ  Loop over the lowercase alphabet again. ¿⁼№↧θκ⊕ι  If the count of the current letter is equal to the outer loop value... ⁺⊕ι§Φθ⁼↧λκ±¹  Concatenate the current count with the last occurrence of the current letter and implicitly print. # Jelly, 14 bytes fØẠŒuL,ṪƊƙ$ŒuÞ


Try it online!

Full program.

## NodeJS, 299 bytes, -6 bytes thank to @tsh

Not so beauty but it work!

(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).join[R](/,/g,'')[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())


## Javascript (ES8) (Firefox or Chrome), 294 bytes, -1 byte thank to @tsh

With new .flat method, I can save 10 bytes:

(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).flat().join[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())


Try this online: https://repl.it/repls/ConcernedHorribleHypothesis

• Hello and welcome to PPCG. It would be nice if you provided a way to test your submission, like linking to an online interpreter. Commented Jan 19, 2019 at 15:04
• @JonathanFrech I just added test cases, thank you! Commented Jan 19, 2019 at 15:45
• .replace x 3 times -> [R='replace] and [R] x 2 times
– tsh
Commented Jan 20, 2019 at 7:24
• .charCodeAt(0) -> .charCodeAt() (0 is default)
– tsh
Commented Jan 20, 2019 at 7:30
• @tsh Thank you a lot for all your good tips, I just updated my answer! Commented Jan 20, 2019 at 13:58

# R, 131 129 bytes

cat(paste0(N<-by(X<-utf8ToInt(gsub('[^a-z]','',scan(,''),T)),G<-X%%32,length),L<-intToUtf8(by(X,G,tail,1),T))[order(N,L)],sep='')


Try it online!

# Julia 1.0, 158 bytes

¬t=(c=Dict();C=Dict();for i=eachmatch(r"\w",t);l=i.match;k=lowercase(l);c[k]=get(c,k,0)+1;C[k]=l;end;*(["$v$(C[k])" for (v,k)=sort([(v,k) for (k,v)=c])]...))


Original ungolfed version with same logic:

function password(text)
letter_counts = Dict()
cases = Dict()

for i in eachmatch(r"\w", text)
letter = i.match[1]
letter_key = lowercase(letter)
letter_counts[letter_key] = get(letter_counts, letter_key, 0) + 1
cases[letter_key] = letter
end

sorted_counts = sort([(value, key) for (key, value) in letter_counts])

return string(["$v$(cases[k])" for (v,k) in sorted_counts]...)
end


Try it online!

# Perl 6, 86 82 bytes

{[~] flat map *[0,2],sort map {+$^b,$^a,$b[*-1]},kv classify &lc,.comb: /<alpha>/}  ## Rebol, 149, 146 bytes f: func[s][l: charset[#"a"- #"z"#"A"- #"Z"]rejoin sort/skip collect[parse sort s[any[copy t[copy o l any o](keep length? t keep last t)| skip]]]2]  Try it online! Ungolfed: f: func [s] [ l: charset[#"a" - #"z" #"A" - #"Z"] rejoin sort/skip collect [ parse sort s [ any [ copy t [copy o l any o] (keep length? t keep last t) | skip ] ] ] 2 ]  Example usage in Rebol console: >> f "Kitkat Tango" == "1g1i1n1o2a2k3T" >> f "Database Partitions Task" == "1b1D1e1k1n1o1P1r2i3s4T5a" >> f "12$*34^!"
== ""