39
\$\begingroup\$

Don't you love those exploded-view diagrams in which a machine or object is taken apart into its smallest pieces?

enter image description here

Let's do that to a string!

The challenge

Write a program or function that

  1. inputs a string containing only printable ASCII characters;
  2. dissects the string into groups of non-space equal characters (the "pieces" of the string);
  3. outputs those groups in any convenient format, with some separator between groups.

For example, given the string

Ah, abracadabra!

the output would be the following groups:

!
,
A
aaaaa
bb
c
d
h
rr

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

  • The groups may be strings separated by newlines, as shown above.

  • The groups may be separated by any non-ASCII character, such as ¬. The output for the above input would be the string:

    !¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
    
  • The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

    !  ,    A   a a a a a    b b  c       d   h  r r
    
  • The output may also be an array or list of strings returned by a function:

    ['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
    
  • Or an array of char arrays:

    [['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
    

Examples of formats that are not allowed, according to the rules:

  • A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.
  • It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

  • Test case 1:

    Ah, abracadabra!
    !
    ,
    A
    aaaaa
    bb
    c
    d
    h
    rr
    
  • Test case 2:

    \o/\o/\o/
    ///
    \\\
    ooo
    
  • Test case 3:

    A man, a plan, a canal: Panama!
    !
    ,,
    :
    A
    P
    aaaaaaaaa
    c
    ll
    mm
    nnnn
    p
    
  • Test case 4:

    "Show me how you do that trick, the one that makes me scream" she said
    ""
    ,
    S
    aaaaa
    cc
    dd
    eeeeeee
    hhhhhh
    ii
    kk
    mmmm
    n
    ooooo
    rr
    ssss
    tttttt
    u
    ww
    y
    
\$\endgroup\$
  • 1
    \$\begingroup\$ If we use non-ASCII symbols like "¬" as separator, can it be counted as 1 byte? \$\endgroup\$ – Leaky Nun Aug 24 '16 at 22:39
  • 5
    \$\begingroup\$ @LeakyNun No, it will be counted as it corresponds depending on the encoding used for the source code, as usual \$\endgroup\$ – Luis Mendo Aug 24 '16 at 22:40
  • \$\begingroup\$ Is a trailing newline after the last group acceptable? \$\endgroup\$ – JustinM - Reinstate Monica Aug 24 '16 at 23:10
  • \$\begingroup\$ Is a leading newline of output acceptable? \$\endgroup\$ – DJMcMayhem Aug 24 '16 at 23:16
  • 1
    \$\begingroup\$ @RohanJhunjhunwala Well done! :-) Yes, several newlines as separators is fine \$\endgroup\$ – Luis Mendo Aug 25 '16 at 21:35

49 Answers 49

11
\$\begingroup\$

Jelly, 5 bytes

ḟ⁶ṢŒg

Try it online!

It does return an array, just that when it is printed to STDOUT, the separator is gone.

This is indeed a function that can be called as such (in Jelly, each line is a function).

ḟ⁶ṢŒg
ḟ⁶      filter out spaces
  Ṣ     sort
   Œg   group
\$\endgroup\$
23
\$\begingroup\$

Python 3.5+, 77 46 44 41 bytes

lambda s:[a*s.count(a)for a in{*s}-{' '}]

Pretty simple. Goes through the unique characters in the string by converting it to a set (using Python 3.5's extended iterable unpacking), then uses a list comprehension to construct the exploded diagrams by counting the number of times each character occurs in the string with str.count. We filter out spaces by removing them from the set.

The order of the output may vary from run to run; sets are unordered, so the order in which their items are processed, and thus this answer outputs, cannot be guaranteed.

This is a lambda expression; to use it, prefix lambda with f=.

Try it on Ideone! Ideone uses Python 3.4, which isn't sufficient.

Usage example:

>>> f=lambda s:[a*s.count(a)for a in{*s}-{' '}]
>>> f('Ah, abracadabra!')
[',', 'A', 'aaaaa', 'd', '!', 'bb', 'h', 'c', 'rr']

Saved 3 bytes thanks to @shooqie!

\$\endgroup\$
  • 3
    \$\begingroup\$ Congrats on 1k! \$\endgroup\$ – Luis Mendo Aug 25 '16 at 0:11
  • 2
    \$\begingroup\$ In Python >3.5 you can do {*s} for set(s). \$\endgroup\$ – shooqie Aug 25 '16 at 16:44
11
\$\begingroup\$

Retina, 13 bytes

O`.
!`(\S)\1*

The sorting is very easy (it's a builtin), it's separating the letters that takes 9 bytes. Try it online!

The first line sOrts all matches of the regex . (which is every character), giving us !,Aaaaaabbcdhrr.

Match is the default stage for the last line of a program, and ! makes it print a linefeed-separated list of matches of the regex. The regex looks for one or more instances of a non-space character in a row.

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

Perl 6, 28 bytes

*.comb(/\S/).Bag.kv.map(*x*)

Note that Bag like a Hash or Set is unordered so the order of results is not guaranteed.

Explanation:

# Whatever lambda 「*」


# grab the characters
*.comb(
  # that aren't white-space characters
  /\S/
)
# ("A","h",",","a","b","r","a","c","a","d","a","b","r","a","!")


# Turn into a Bag ( weighted Set )
.Bag
# {"!"=>1,","=>1,"A"=>1,"a"=>5,"b"=>2,"c"=>1,"d"=>1,"h"=>1,"r"=>2}


# turn into a list of characters and counts
.kv
# ("!",1,",",1,"A",1,"a",5,"b",2,"c",1,"d",1,"h",1,"r",2)


# map over them 2 at a time
.map(
  # string repeat the character by the count
  * x *
)
# ("!",",","A","aaaaa","bb","c","d","h","rr")
\$\endgroup\$
7
\$\begingroup\$

Vim, 50, 46 bytes

i <esc>:s/./&\r/g
:sor
qq:%s/\v(.)\n\1/\1\1
@qq@qD

Explanation/gif will come later.

\$\endgroup\$
  • 1
    \$\begingroup\$ For once, Emacs & vim solutions look alike. \$\endgroup\$ – YSC Aug 25 '16 at 11:26
7
\$\begingroup\$

Pyth, 6

.gk-zd

Try it here or run a Test Suite.

Pretty simple, -zd removes spaces from the input, and .gk groups each remaining element by its value. Unfortunately, I haven't found a way to make use of auto-fill variables. Note that the output is shown as Python strings, so certain characters (read: backslashes) are escaped. If you want it to be more readable, add a j to the beginning of the code.

\$\endgroup\$
7
\$\begingroup\$

Haskell, 38 bytes

f s=[filter(==c)s|c<-['!'..],elem c s]

Basically nimi's solution, but explicitly checking only letters appearing in the string.

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

2sable, 7 bytes

Code:

Úð-vyÃ,

Explanation:

Ú       # Uniquify the string, aabbcc would result into abc
 ð-     # Remove spaces
   vy   # For each character...
     Ã  #   Keep those in the string, e.g. 'aabbcc', 'a' would result into 'aa'
      , #   Pop and print with a newline

Uses the CP-1252 encoding. Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ That doesn't sound like Dennis at all :-P \$\endgroup\$ – Luis Mendo Aug 24 '16 at 22:57
6
\$\begingroup\$

JavaScript (ES6), 41 bytes

s=>[...s].sort().join``.match(/(\S)\1*/g)
\$\endgroup\$
  • \$\begingroup\$ Wouldn't this also cause an entry " " to exist in the returned array, as well? Not sure if that's allowed \$\endgroup\$ – Value Ink Aug 24 '16 at 23:46
  • \$\begingroup\$ @ValueInk Bah, I thought about that when I started, but promptly forgot. Fixed now. \$\endgroup\$ – Neil Aug 25 '16 at 0:21
  • \$\begingroup\$ Umm, how is join() being called with those double backkticks ? \$\endgroup\$ – Tejas Kale Aug 28 '16 at 9:01
  • 1
    \$\begingroup\$ @TejasKale That's an ES6 template string. When you prefix a method to a template string, it passes the template as an array to the method, so in this case, it ends up calling .join(['']). join then converts that to the (empty) string and uses that to join the array elements. Not all methods convert their parameter to string, but this technique is handy on those that do. \$\endgroup\$ – Neil Aug 28 '16 at 9:04
6
\$\begingroup\$

Brachylog, 14 7 bytes

7 bytes thanks to Fatalize.

:@Sxo@b

Try it online!

:@Sxo@b
:@Sx     remove spaces
    o    sort
     @b  group
\$\endgroup\$
5
\$\begingroup\$

Haskell, 40 bytes

f x=[v:w|d<-['!'..],v:w<-[filter(==d)x]]

Usage example: f "Ah, abracadabra!"-> ["!",",","A","aaaaa","bb","c","d","h","rr"].

The pattern v:w matches only list with at least one element, so all characters not in the input are ignored.

Also 40 bytes:

import Data.List
group.sort.filter(>' ')
\$\endgroup\$
  • \$\begingroup\$ @ThreeFx: But group is from Data.List, too. Anyway, I think this syntax is ghci only and needs the REPL, so it's a language of it's own. I want to stick with standard Haskell. \$\endgroup\$ – nimi Aug 25 '16 at 5:59
4
\$\begingroup\$

Ruby, 41 + 1 = 42 bytes

+1 byte for -n flag.

gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)}

Takes input on stdin, e.g.:

$ echo 'Ah, abracadabra!' | ruby -ne 'gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)}'
A
h
,
c
d
bb
rr
aaaaa
!
\$\endgroup\$
4
\$\begingroup\$

C# 125 98 Bytes

using System.Linq;s=>s.GroupBy(c=>c).Where(g=>g.Key!=' ').Select(g=>new string(g.Key,g.Count())));

Explanation

//Using anonymous function to remove the need for a full signature 
//And also allow the implicit return of an IEnumerable
s =>

    //Create the groupings
    s.GroupBy(c => c)

    //Remove spaces
    .Where(g=> g.Key!=' ')

    //Generate a new string using the grouping key (the character) and repeating it the correct number of times
    .Select(g => new string(g.Key, g.Count()));
  • Thanks to @TheLethalCoder who suggested the use of an anonymous function, which also allowed me to remove the ToArray call and just implicitly return an IEnumerable which collectively saves 27 bytes
\$\endgroup\$
  • \$\begingroup\$ You can save 18 bytes (if I counted correctly) by compiling it to a Func<string, string[]> i.e. s=>s.GroupBy.... \$\endgroup\$ – TheLethalCoder Aug 25 '16 at 10:21
  • \$\begingroup\$ @TheLethalCoder are you sure that is acceptable in place of a function, I've always been wary of that because it adds quite a bit of extra boilerplate to be able to execute it, and with the argument for requiring the Linq using it just seems... well wrong. \$\endgroup\$ – JustinM - Reinstate Monica Aug 25 '16 at 14:47
  • \$\begingroup\$ Heres a recent example where I do it... codegolf.stackexchange.com/a/91075/38550 it'll remove all your boilerplate, as long as functions are allowed \$\endgroup\$ – TheLethalCoder Aug 25 '16 at 14:57
  • \$\begingroup\$ @TheLethalCoder OK thats good enough for me. :) It also allowed me to remove the ToArray call \$\endgroup\$ – JustinM - Reinstate Monica Aug 25 '16 at 17:55
4
\$\begingroup\$

R, 198 189 96 95 bytes

for(i in unique(a<-strsplit(gsub(" ","",readline()),"")[[1]]))cat(rep(i,sum(a==i)),"\n",sep="")

Ungolfed :

a<-strsplit(gsub(" ","",readline()),"")[[1]] #Takes the input from the console

for(i in unique(a)) #loop over unique characters found in variable a

cat(rep(i,sum(a==i)),"\n",sep="") # print that character n times, where n was the number of times it appeared

This solution is currently not entirely working, when \ are involved.
Now it is !

Thank a lot you to @JDL for golfing out 102 bytes !

\$\endgroup\$
  • \$\begingroup\$ @JDL : Please suggest edits in the comments. Your changes are really interesting, but it's kinda rude to change someone else's code like that. \$\endgroup\$ – Frédéric Aug 25 '16 at 9:01
  • 1
    \$\begingroup\$ apologies for that, but I didn't have 50 reputation at the time and couldn't make comments. Will do in future though! \$\endgroup\$ – JDL Aug 26 '16 at 8:03
  • \$\begingroup\$ @JDL : Fair enough ! \$\endgroup\$ – Frédéric Aug 26 '16 at 10:15
  • \$\begingroup\$ Try assigning the variable inside a function: for(i in unique(a=strsplit(gsub(" ","",readline()),"")[[1]]))cat(rep(i,sum(a==i)),"\n",sep="") — saves 2 bytes. \$\endgroup\$ – Andreï Kostyrka Aug 26 '16 at 12:36
  • \$\begingroup\$ @AndreïKostyrka : It doesn't save bytes in this form because you have to put the whole a=strsplit(...) part between brackets: basically does a -2+2 difference. However, using <- will save 1 byte ! \$\endgroup\$ – Frédéric Aug 26 '16 at 13:19
4
\$\begingroup\$

Swift, 105 91 bytes

Thanks to @NobodyNada for 14 bytes :)

Yeah, I'm pretty new to Swift...

func f(a:[Character]){for c in Set(a){for d in a{if c==d && c != " "{print(c)}}
print("")}}

Characters within a group are separated by a single newline. Groups are separated by two newlines.

\$\endgroup\$
  • \$\begingroup\$ You can save 13 bytes by taking input as a [Character] instead of a String, since the rules say "The input should be a string or an array of chars." Also, print("") can be replaced with just print(). \$\endgroup\$ – NobodyNada - Reinstate Monica Aug 26 '16 at 3:50
  • \$\begingroup\$ @NobodyNada print without arguments didn't work for some reason but the [Character] suggestion was solid. Thanks! \$\endgroup\$ – jrich Aug 26 '16 at 21:54
3
\$\begingroup\$

Octave, 61 bytes

@(x)mat2cell(y=strtrim(sort(x)),1,diff(find([1 diff(+y) 1])))

This is an anoymous function that takes a string as input and outputs a cell arrray of strings.

Try at Ideone.

How it works

  • sort sorts the input string. In particular, spaces will be at the beginning.
  • strtrim removes leading spaces.
  • diff(+y) computes consecutive differences between characters (to detect group boundaries)...
  • ... so diff(find([1 diff(+y) 1]) gives a vector of group sizes.
  • mat2cell then splits the sorted string into chunks with those sizes.
\$\endgroup\$
3
\$\begingroup\$

Mathematica, 36 bytes

Built-in functions Gather and Characters do most of the work here.

Gather@Select[Characters@#,#!=" "&]&
\$\endgroup\$
3
\$\begingroup\$

><>, 49 bytes

i:0(?v
84}0~/&{!*
v!?: <}/?=&:&:<
>&1+&}aol1-?!;^

Very spaciously wasteful in the output, but i assume is still allowed given the lenience of the rules

Explanation:

i:0(?v           Collects text from input
84}0~/&{!*       adds 32 (first ascii starting at space) to register and 0 to stack
v!?: <}/?=&:&:<  checks all characters to the current register, if equal:
       o         prints the character and continues looping
>&1+&}aol1-?!;^  when all characters are checked, adds 1 to register, prints a newline,
                 checks the stack length to halt the program if 0, and starts looping again

fit some things in pretty tight, even using jumps to get around some functions so i could run the pointer vertically.

Basically this puts each ASCII character on its own newline, and if none of that character exists, the line will be blank

Try it online

Edit: i was wrong there was an error in the code what would cause it to never complete if there was a space in the input

\$\endgroup\$
3
\$\begingroup\$

Pyth, 5 bytes

.gksc

Try it here!

Takes input as a Python string (i.e. wrapped in quotes, escaped quotes and slashes as necessary).

Explanation:

    c    Split (implied) input on whitespace
   s     Sum together
.gk      Group by value

If you guarantee at least one space in the input, there's a 4-byte solution:

t.gk

Try it here!

Explanation:

 .gk (Q)  groups the characters in the string by their value
           this sorts them by their value, which guarantees that spaces are first
t         Remove the first element (the spaces)
\$\endgroup\$
3
\$\begingroup\$

PowerShell v2+, 44 bytes

[char[]]$args[0]-ne32|group|%{-join$_.Group}

Takes input $args[0] as a command-line argument literal string. Casts that as a char-array, and uses the -not equal operator to pull out spaces (ASCII 32). This works because casting has a higher order precedence, and when an array is used as the left-hand operator with a scalar as the right-hand, it acts like a filter.

We pass that array of characters to Group-Object, which does exactly what it says. Note that since we're passing characters, not strings, this properly groups with case-sensitivity.

Now, we've got a custom object(s) that has group names, counts, etc. If we just print that we'll have a host of extraneous output. So, we need to pipe those into a loop |%{...} and each iteration -join the .Group together into a single string. Those resultant strings are left on the pipeline, and output is implicit at program completion.

Example

PS C:\Tools\Scripts\golfing> .\exploded-view-of-substrings.ps1 'Programming Puzzles and Code Golf'
PP
rr
ooo
gg
aa
mm
i
nn
u
zz
ll
ee
s
dd
C
G
f
\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 11 bytes

Function returning list of strings.

(⊂∩¨∪)~∘' '

(⊂∩¨∪) the intersection of the entirety and its unique characters

~∘' ' except spaces

TryAPL online!

\$\endgroup\$
2
\$\begingroup\$

Processing, 109 bytes

void s(char[] x){x=sort(x);char l=0;for(char c:x){if(c!=l)println();if(c!=' '&&c!='\n'&&c!='\t')print(c);l=c;}}

Its the brute force approach, sort the array, then loop through it. If it doesn't match the last character printed, print a newline first. If it is whitespace, skip the printing step.

\$\endgroup\$
2
\$\begingroup\$

Javascript (using external Library - Enumerable) (78 67 bytes)

 n=>_.From(n).Where(y=>y!=' ').GroupBy(x=>x).WriteLine(y=>y.Write())

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: This is what Enumerable was made to do! Load the string into the library, which converts it to a char array. Filter out the white space entries. Group by char. Write each group to a line, according to the specified predicate. That predicate says to join all the elements of the current group into a string, without a delimiter.

enter image description here

\$\endgroup\$
2
\$\begingroup\$

MATL, 7 bytes

Xz!t7XQ

MATL Online Demo

\$\endgroup\$
2
\$\begingroup\$

Perl6, 48 47 45

slurp.comb.Bag.kv.map:{$^a.trim&&say $a x$^b}

Thanks to manatwork for the improvements.

\$\endgroup\$
  • 1
    \$\begingroup\$ Not a big improvement, but $a.trim seems to do it for the condition. \$\endgroup\$ – manatwork Jan 4 '17 at 18:09
  • \$\begingroup\$ Seems the logical operators still not need spaces around them, so $^a.trim&&say $a x$^b works. (Sorry for adding the hints byte by byte, but this is my first try on Perl6.) \$\endgroup\$ – manatwork Jan 5 '17 at 9:28
  • \$\begingroup\$ Little typo, you accidentally removed the opening {. \$\endgroup\$ – manatwork Jan 5 '17 at 13:27
1
\$\begingroup\$

Ruby, 46 bytes

Try it online!

->s{(s.chars-[' ']).uniq.map{|c|c*s.count(c)}}

My original full program version, 48 bytes after adding the n flag:

p gsub(/\s/){}.chars.uniq.map{|c|c*$_.count(c)}
\$\endgroup\$
  • \$\begingroup\$ Can you replace .count(c) with .count c ? \$\endgroup\$ – Cyoce Aug 26 '16 at 1:02
  • \$\begingroup\$ @Cyoce no, because the * operator is present nearby so the parser will complain. \$\endgroup\$ – Value Ink Aug 26 '16 at 1:06
  • \$\begingroup\$ s.chars-[' ']|[] inside the brackets would avoid the uniq \$\endgroup\$ – G B Jan 5 '17 at 7:56
  • \$\begingroup\$ @GB It would, but if we're chaining it to map then it needs extra parens, and ((s.chars-[' '])|[]).map has the same number of characters as (s.chars-[' ']).uniq.map. And the other, shorter way to check unique characters (via regex) is already covered by @Jordan in another answer \$\endgroup\$ – Value Ink Jan 5 '17 at 9:20
  • \$\begingroup\$ It works inside the brackets, you don't need extra brackets because precedence of '-' is higher. \$\endgroup\$ – G B Jan 5 '17 at 9:29
1
\$\begingroup\$

Python, 107

Could be shortened by lambda, but later

x=sorted(input())
i=0
while i<len(x):x[i:]=['  '*(x[i]!=x[i-1])]+x[i:];i-=~(x[i]!=x[i-1])
print("".join(x))
\$\endgroup\$
1
\$\begingroup\$

CJam, 10 bytes

{S-$e`::*}

An unnamed block that expects the string on top of the stack and replaces it with a list of strings.

Try it online!

Explanation

S-  Remove spaces.
$   Sort.
e`  Run-length encode, gives pairs [R C], where R is the run-length and
    C is the character.
::* Repeat the C in each pair R times.
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 123

(lambda(s &aux(w(string-trim" "(sort s'char<))))(princ(elt w 0))(reduce(lambda(x y)(unless(char= x y)(terpri))(princ y))w))

Ungolfed:

(lambda (s &aux (w (string-trim " " (sort s 'char<))))
  (princ (elt w 0))
  (reduce
    (lambda (x y) 
      (unless (char= x y) (terpri))
      (princ y))
  w))

Not the most golf friendly language. This could probably be modified to return list of lists instead of printing string.

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

Emacs, 36 keystrokes

C-SPACE C-EM-xsort-rTABRETURN.RETURN.RETURNC-AC-M-S-%\(\(.\)\2*\)RETURN\1C-QC-JRETURN!

Result

A man, a plan, a canal: Panama! -->

!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p

Explanation

  1. C-SPACE C-E
  2. M-x sort-rTAB RETURN .RETURN .RETURN
  3. C-A
  4. C-M-S-% \(\(.\)\2*\)RETURN\1 C-Q C-JRETURN !

  1. Select the input line;
  2. Call sort-regexp-fields with arguments . and .;
    • Argument #1: Regexp scpecifying records to sort
    • Argument #2: Regexp scpecifying key within records
  3. Return at line start;
  4. Apply regexp substitution \(\(.\)\2*\) -> \1\n on all matches.
\$\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.