title: Unique is Cheap

text:
# Question
Title: Unique is Cheap
Write a function or program that determines the *cost* of a given string, where

* the cost of each character equals the number of how many times the character has occurred up to this point in the string, and
* the cost of the string is the sum of its characters' costs.

### Example

For an input of `abaacab`, the cost is computed as follows:

```
a b a a c a b
1   2 3   4    occurrence of a
  1         2  occurrence of b
        1      occurrence of c
1+1+2+3+1+4+2 = 14

```

Thus the cost for the string `abaacab` is 14.

### Rules

* **The score of your submission is the cost of your code as defined above**, that is your submission run on its own source code, with a **lower** score being better.
* Your submission should work on strings containing printable ASCII-characters, plus all characters used in your submission.
* Characters are case-sensitive, that is `a` and `A` are different characters.

### Testcases

```
input -> output
"abaacab" -> 14
"Programming Puzzles & Code Golf" -> 47
"" -> 0
"       " -> 28
"abcdefg" -> 7
"aA" -> 2

```

### Leaderboard

```
var QUESTION_ID=127261,OVERRIDE_USER=56433;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# MATL, score 4

```
&=Rz

```

Try it online!

### Explanation

Consider input `'ABBA'` as an example.

```
&=   % Implicit input. Matrix of all equality comparisons
     % STACK: [1 0 0 1;
               0 1 1 0;
               0 1 1 0;
               1 0 0 1]
R    % Upper triangular part
     % STACK: [1 0 0 1;
               0 1 1 0;
               0 0 1 0;
               0 0 0 1]
z    % Number of nonzeros. Implicitly display
     % STACK: 6

```
> 84 votes

# Answer
# Python, score 49

```
lambda S:sum(1+S.count(C)for[C]in	S)/2

```

Try it online!

There's a tab after `in`.

Score breakdown:

* +27 for 27 unique chars
* +16 for 8 double chars: `()Camnou`
* +6 for 1 tripled char: `S`
> 17 votes

# Answer
# C (gcc), score:  ~~113~~   ~~103~~   ~~100~~   ~~96~~  91

*Thanks to @ugoren, @CalculatorFeline, @gastropner, @l4m2, and @JS1 for their tips.*

```
g(char*s){int y[238]={};while(*s)*y-=--y[*s++];*y/=1;}

```

Initializes an array of zeros, then uses the ASCII values of the characters in the string as indices to that array to keep track of the number of instances of each character in the string.

Try it online!
> 8 votes

# Answer
# T-SQL, score ~~775 579!~~ 580

```
declaRe @ char(876),@x int,@v int=0Select @=q+CHAR(9)from z X:seleCT @x=len(@),@=REPLACE(@,LEFT(@,1),''),@v+=(@x-LEN(@))*(@x-LEN(@)+1)/2IF LEN(@)>0GOTO X prINT @v-1

```

**EDIT**: Dropped a couple of variables, compacted a bit. Down to 16 `@` symbols instead of 22, that by itself reduces my score by a whopping 117 points!

Nice contest, I like the requirement to optimize for something besides total character count.

Input is via varchar field *q* in pre-existing table *z*, per our IO rules. The database containing this input table must be set to a *case-sensitive collation*.

Formatted:

```
declaRe @ char(876), @x int, @v int=0
Select @=q+CHAR(9)from z
X:
    seleCT @x=len(@)
          ,@=REPLACE(@,LEFT(@,1),'')
          ,@v+=(@x-LEN(@))*(@x-LEN(@)+1)/2
IF LEN(@)>0 GOTO X
prINT @v-1

```

SQL keywords aren't case sensitive, so I used mixed case to minimize the count of duplicate letters (*aaAA* generates a better/lower score than *aaaa*).

The main loop compares the length before and after stripping all instances of the first character out. That difference n\*(n+1)/2 is added to a running total.

The SQL `LEN()` function annoyingly ignores trailing spaces, so I had to append a control character and subtract 1 at the end.

**EDIT**: Fixed a miscalculation of my own score by 2 points (issue with quoting quotes), reduced by 1 by changing casing of one `R`. Also working on a completely different strategy, I'll be posting that as its own answer.
> 8 votes

# Answer
# Jelly, score 6

```
;\ċ"⁸S

```

Try it online!
> 7 votes

# Answer
# JavaScript (ES6), score ~~81~~ 78

*Saved 3 points thanks to @Arnauld*

```
s=>s.replace(d=/./g,z=>q+=d[z]=-~d[z],q=0)&&q

```

My original score-81 recursive solution:

```
f=([c,...s],d={})=>c?(d[c]=-~d[c])+f(s,d):0

```
> 7 votes

# Answer
# Haskell, score 42

```
f l=sum[1|c<-l,d<-c:l,d==c]/2

```

Try it online!

Anonymizing `\l->` gives the same score.
> 7 votes

# Answer
## Retina, score 34

```
s(O`.
M&!`^|(?<=(.))\1*
.

```

Try it online!

### Explanation

```
s(O`.

```

We start by sorting all the characters in the input so that identical characters are grouped together into a single run. The `s(` activates singleline mode for all stages (i.e. makes `.` match linefeeds).

```
M&!s`^|(?<=(.))\1*

```

The goal is to turn a run of **n** characters into **Tn** characters (the **n**th triangular number) because that's the score of the occurrences of this character. To do so, we find overlapping matches. In particular, for each **i** in **\[1,n\]**, we're going to include **i-1** characters in the match. We get all those matches due to the overlapping flag `&`. That gives us **n\*(n-1)/2 = Tn-1 = Tn \- n** characters just from the matches. But the match stage will join these with linefeeds, which are **n** linefeeds for **n** matches. There's only one problem. There won't be a linefeed after the last match, so the overall number of characters in the output is one less than we need. We fix this by also matching the beginning of the input, which gives us a single leading linefeed if there is at least one other match.

```
.

```

Finally, we just count how many characters there are in the string.
> 7 votes

# Answer
## Haskell, score ~~52~~ 51

```
f(a:b)=1+sum[1|c<-b,c==a]+f b;f _=0

```

There's a tab between `f` and `_`.

Try it online!

The value of the empty string is 0. The value of the string s, where `a` is the first char and `b` the rest of the string is 1 plus the occurrences of `a` in `b` plus a recursive call with b.
> 6 votes

# Answer
## , score 16

```
1#.,@(*+/\"1)&=

```

Try it online!

## Explanation

```
1#.,@(*+/\"1)&=
              =  Self-classify: bit matrix of equality between input
                 and its unique elements.
     (      )&   Apply verb in parentheses to it:
       +/\         running sums
          "1       of each row
      *            multiplied with original matrix.
                 This causes the i'th 1 on each row to be replaced by i.
   ,@            Flatten the resulting matrix
1#.              and interpret as a base-1 number, computing its sum.

```

Using `1#.` instead of `+/@` for the sum saved a few points, and `&` could be used instead of `@` in a monadic context to save one more. The repeated `1` costs me one extra point, but I haven't been able to get rid of it.
> 5 votes

# Answer
# , score: 67 ~~83~~ ~~95~~ ~~128~~

*-61 thanks to top tips from Giuseppe*

```
function(x,y=table(utf8ToInt(x)))y%*%{y+1}/2

```

Try it online!

The string is split using `utf8ToInt` and each ascii value is counted `table`. The the result is calculated using doing a matrix multiplication `%*%` over that at itself + 1 and finally halfed.
> 5 votes

# Answer
# Jelly, score 5

```
ĠJ€ẎS

```

Try it online!

Thanks to Leaky Nun for -2 (previously on his answer)
> 4 votes

# Answer
# 05AB1E, score 6

```
{γ€gLO

```

Try it online!
> 4 votes

# Answer
# Pyth, score 6

1 byte thanks to isaacg.

```
+F/V._

```

Test suite.

## How it works

```
+F/V._
+F/V._QQ  implicit input
  /V      vectorize count: for each element in the first argument,
                           count the number of occurrences of the
                           second argument:
    ._Q       all prefixes of input
       Q      input
+F        fold (reduce) on +, base case 0.

```
> 4 votes

# Answer
# , score: ~~14 12~~ 11

```
$+/@,2!1#.=

```

Try it online!
> 4 votes

# Answer
# Jelly, score of 7

```
ċÐ€QRFS

```

Explanation:

```
   Q    get unique letters
ċÐ€     count the occurences of each letter in the original string
    R   [1..n] for n in list of frequencies
     F  flatten list
      S sum
        (implicit output)

```

Try it online!
> 4 votes

# Answer
# C, 60 bytes, score 108 95

```
g(char*s){int y[256]={},z=0;while(*s)z-=--y[*s++];return z;}

```

Try it online!

Usually pre- and post-increment operators are great for code golf, but they really hurt on this challenge!

EDIT: By subtracting negative counts instead of adding positive ones, I saved a whole bunch of score. Replacing `for()` with `while()` eliminated a semicolon as well.
> 4 votes

# Answer
# Perl 6, score  ~~61 56 53 46~~  44

```
(1 X..*.comb.Bag.values).flat.sum

```

Try it

```
{sum flat 1 X.. .comb.Bag.values}

```

Try it

```
{sum flat 1 X.. values(.comb.Bag)}

```

Try it

```
{[+] flat	1	X.. values(.comb.Bag)}

```

Try it

```
{[+] flat	1	X.. values(bag
.comb)}

```

Try it
> 3 votes

# Answer
# C# (.NET Core), score ∞ (I mean, 209)

```
b=>b.Distinct().Select(z=>{var w=b.Count(p=>p==z);return w*(w+1)/2;}).Sum()

```

Try it online!

The score includes the following:

```
using System.Linq;

```
> 3 votes

# Answer
## PowerShell, score 64

```
$z=@{}
$ARGS|% getE*|%{$u+=($Z.$_+=1)};$U

```

(Score is based on a single linefeed newline, which isn't Windows standard but does work in PS).

```
PS C:\> D:\unique-is-cheap.ps1 (gc D:\unique-is-cheap.ps1 -raw)
64

```
* Hashtable counter `@{}`
* Iterate through the letters; `$args` is an array of parameters - in this case the input string makes it a single item array; `|%` does a foreach loop over the items, and uses the `getE*` shortcut to match the `GetEnumerator()` string method and call it to turn the string into a character stream.
* `|%` loop over the characters and increment their hashtable entry, add it to a running total. The `($x+=1)` form with parens both modifies the variable and outputs the new value for use.
* Output the running total.

(When I first wrote it, it was `$c=@{};$t=0;[char[]]"$args"|%{$c[$_]++;$t+=$c[$_]};$t` with a score of 128, and felt like it wouldn't go much lower. Halving it to 64 is quite pleasing).
> 3 votes

# Answer
# Java 10, score: ~~149~~ ~~138~~ ~~137~~ ~~134~~ ~~133~~ ~~130~~ ~~103~~ ~~102~~ ~~101~~ 100

(**Bytes: ~~72~~ ~~73~~ ~~74~~ ~~75~~ ~~64~~ ~~62~~ 61**) ~~Bytes go up, but score goes down. :D~~

```
x->{int j=0,q[]=new int[256];for(var    C:x)j+=++q[C];return
j;}

```

-28 score (and -11 bytes) thanks to *@Nevay*.
-1 score (and -2 bytes) thanks to *@OlivierGrégoire*.
-1 score (and -1 byte) by converting Java 8 to Java 10.

**Explanation:**

Try it here.

```
x->{                     // Method with character-array parameter and integer return-type
  int j=0,               //  Result-integer, starting at 0
      q[]=new int[256];  //  Integer-array with 256 times 0
  for(var   C:x)         //  Loop over the characters of the input array
    j+=++q[C];           //   Raise the value in the array by 1,
                         //   and then add it to the result-integer
  return                 //  Return
  j;}                    //         the result

```
> 3 votes

# Answer
# Julia 0.6, 45 bytes, Score: 77

Inspired by the MATL solution:

```
f(w)=sum(UpperTriangular([z==j for z=w,j=w]))

```

Try it online!

A less pretty solution, using counts:

Julia 0.6, score: 82

```
F(w)=sum(l->[l+1]l/2,count(x->x==i,w)for i=Set(w))

```

Try it online!

Thanks to Guiseppe for pointing out the scoring and for tips. These comments helped me loads.
> 3 votes

# Answer
## F#, score 120 118

```
let j z=Seq.countBy id z|>Seq.sumBy(fun x->List.sum[0..snd x])

```

-2 thanks to Kevin Cruijssen!

Try it online!

Takes a `string` as an input. `Seq.countBy` pairs each distinct character with its count (`id` is the identity function) so you end up with a collection like `'a' = 4, 'b' = 2` etc.

The `Seq.sumBy` takes the count for every letter and sums all the numbers from `0` to the count for that letter. So if `'a' = 4` the collection would be `0, 1, 2, 3, 4` which summed together is `10`. Then `Seq.sumBy` sums all those totals.
> 3 votes

# Answer
# BQN, Score: 4

```
≠+´⊒

```

Run online!

The *occurrence count* builtin  calculates the cost of each character decremented by 1. To adjust for that we can either add 1 to each cost or add the length  to the sum. The latter turns out to be a byte shorter.
> 3 votes

# Answer
# APL (Dyalog), score ~~27~~ ~~18~~ ~~11~~ 10

*Reduced score by 7 thanks to @Adám by using a tradfn and using `1⊥` to sum the frequencies*

*Reduced score by 1 thanks to @rabbitgrowth by using a function instead*

```
1⊥{+/⍳≢⍵}⌸

```

Try it online!
> 2 votes

# Answer
# Octave , score ~~77~~ 31 bytes

\*same as @LuisMendo 's MATL answer.

```
@(a)nnz(triu(a==a'))

```

Try it online!

Previous answer:

```
@(d,g=accumarray(+d',1)-(0:254))sum(g(g>0));

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), score 15

```
+/1 1⍉+\∘.=⍨⍞

```

Try it online!

get text input

`∘.=⍨` equality table with self

`+\` cumulative sum across

`1 1⍉` diagonal (lit. collapse both dimensions into dimension one)

`+/` sum
> 2 votes

# Answer
# Retina, score ~~68~~ ~~45~~ 43

```
s`(.)(?<=((\1)|.)+)
$#3$*
1

```

Try it online! Link shows score. Edit: Thanks to @MartinEnder who saved 20 bytes by using overlapping matches instead of lookaheads and a further three bytes by grouping the stages so that the `s` flag only needs to be applied once. Saved a further two bytes by calculating the triangular number differently, avoiding the need for a sort.
> 2 votes

# Answer
# Mathematica, score 42

```
Total[#^2+#].5&@*CharacterCounts

```

**input**

> \["abcdefg"\]

thanks to hftf
thanks to att
> 2 votes

# Answer
# Common Lisp, score ~~286~~ ~~232~~ 222

```
(loop with w =(fill(make-list 128)0)as z across(read)sum(incf(elt w(char-code z))))

```

High-valued score due to the wordy syntax of builtin operators of Common Lisp.

Try it online!

The ungolfed code:

```
(loop with w = (fill (make-list 128) 0)  ; create a list to count characters
   as z across (read)                   ; for each character of input
   sum (incf (elt w (char-code z))))     ; increase count in list and sum

```
> 2 votes

# Answer
# PHP, 45 bytes, Score 78

```
WHILE($x=ORD($argn[$v++]))$y+=$$x-=-1;echo$y;

```

Try it online!

# PHP, 46 bytes, Score 79 Bytes

```
WHILE(~$xy=$argn[$vz++])$su-=-$$xy+=1;echo$su;

```

Try it online!

# PHP, 56 bytes, Score 92

```
FOREAch(COUNT_CHARS($argn)as$z)WHILE($z)$y+=$z--;echo$y;

```

Try it online!
> 2 votes

# Answer
# Perl 5 score ~~91~~ 83

Uses the `-p` flag which adds 2 because of the p in split.

```
$x=$_;$b+=++$a{$_}for(split//,$x);$_=$b

```
> 2 votes

# Answer
# Octave, 39 bytes, Score 69

```
@(a)sum((b=hist(a,unique(1*a))).^2+b)/2

```

Try it online!

While there is another Octave answer, this one is entirely my own and a different approach, plus it scores less :).

The approach boils down to first finding the count (b) of each unique character, which is achieved using the histogram function. Then for each element we calculate the sum of 1 to b which is done using the formula `(b*(b+1))/2`. Then the individual sums are all summed into the final score.

In testing it seems brackets are really costly in the scoring because many are needed. I've optimised down from an initial score of about 88 by rearranging the questions to minimise the number of open/close brackets - hence we now do the /2 on the final total rather than individually, and also I've modified the formula to `(b^2+b)/2` as that requires fewer brackets.
> 2 votes

# Answer
# brainfuck, score 897

```
,[<<[[->+>-<<]>>[<]<[<]<[<]<[+<<]>>>>[>]>[->+>+<<]>[-<+>]<<<]<+[->>+<<]>>>[->+<]>[>]>,]<<[<]<

```

Try it online!

Ends on the cell with the correct value. Assumes a cell size larger than the score of the string, otherwise it'll wrap (got a little suspicious when the interpreter said the score was 188).
> 2 votes

# Answer
# Japt `-x`, ~~9~~ ~~7~~ 6 points

```
ü mÊcõ

```

Try it
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), score: 681

```
	s	=iNPUT
	Y	_table()
d	S	LEN(1) . x REM . S	:F(b)
	Y<X>	=y<X> + 1	:(D)
b	Z	_convert(Y,'aRrAy')
N	j	=J + 1
	G	_z[j,2]	:f(q)
	o	=o + g * G + g	:(N)
q	OUtpuT	_O / 2
end

```

Try it online!

looks a bit scary, but SNOBOL matches identifiers case-insensitively, which dropped the score by around 100 points. Note that it requires a single line of input, so I've replaced `\n` with `;` in the input field (which is still valid SNOBOL).

The SNOBOL4 implementation on TIO allows for an additional 16 point golf, as `=` and `_` are both allowable as the assignment operator. How neat!
> 2 votes

# Answer
# Rust, ~~265~~ 255 bytes. Score: ~~1459~~ 1161

```
fn main(){let mut z=String::new();std::io::stdin().read_line(&mut z);let Z=z.trim_right_matches(|x|x=='\r'||x=='\n');let mut q:Vec<u8>=Z.bytes().collect();q.sort();let(mut k,mut W,mut j)=(0,0u8,0);for Y in&q{if*Y==W{j+=1}else{j=1;W=*Y}k+=j}print!("{}",k)}

```

Ungolfed

```
fn main() {
    let mut input_string = String::new();
    std::io::stdin().read_line(&mut input_string);
    let trimmed = input_string
        .trim_right_matches(|c| c == '\r' || c == '\n');
    let mut chars: Vec<u8> = trimmed.bytes().collect();
    chars.sort();
    let (mut total_score, mut last_char, mut last_score) = (0, 0u8, 0);
    for letter in &chars {
        if *letter == last_char {
            last_score += 1;
        } else {
            last_score = 1;
            last_char = *letter;
        }
        total_score += last_score;
    }
    print!("{}", total_score);
}

```

**Edit:** improved answer by renaming variables and altering code
> 2 votes

# Answer
# Husk, Score 9

```
½§+L(Σ´×=

```

Try it online!

**Explanation:**

This calculates the score as `sum_i (n_i^2 + n_i)/2`, where `i` is indexed arbitrarily across unique character types and `n_i` is the number of characters of type i in the input. But since `sum_i n_i` is the length of the input, this reduces to `(1/2) * (L + sum_i n_i^2)`

**Code breakdown:**

```
o ½ (§ + L (o Σ (´ (× =)))        --With parentheses and two implicit compositions
                   (× =)          --1 or 0 for each equality check between elements of its first and second arguments
                (´ (× =))         --argdup, 1 or 0 for each equality check between elements of its only argument
           (o Σ (´ (× =))         --# of equalities between pairs (this will give sum_i n_i^2)
         L                        --length
    (§ + L (o Σ (´ (× =)))        --length + sum_i n_i^2
o ½ (§ + L (o Σ (´ (× =)))        --1/2 * (length + sum_i n_i^2)

```
> 2 votes

# Answer
# Python 2. Score:~~142~~ 115

```
def     f(a):
        x=0
        for y in set(a):z=a.count(y);x+=.5*z*-~z
        print x

```

EDIT:-27 thanks to @Kevin Cruijssen
> 2 votes

# Answer
# Husk, 5 bytes, score 5

```
ΣṁŀgO

```

Try it online!

Different and (so far) shorter strategy to Natte's or Sophia Lechner's Husk answers.

```
    O   # sort the input
   g    # and group equal adjacent values;
 ṁ      # now, for each group
  ŀ     # make a range 1..length of the group
 ṁ      # and flatten all the ranges into one list;
Σ       # then output the sum

```
> 2 votes

# Answer
# Python 3, score ~~89~~ 85

```
lambda	y:sum(y[:x+1].count(v)for	x,v in enumerate(y))

```

Try it online!
> 1 votes

# Answer
# Python 2, score 83

```
lambda z:sum((2*z.count(x)+1)**2/8for x in set(z))

```

**Try it online**

`1/8 (1 + 2 n)^2 -1/8` is the same as `n (n+1) / 2`. Floor division removes the need to subtract `1/8`.
> 1 votes

# Answer
# , score 23

```
$-:@+[:+/,/@(=/~)

```

Try it online!
> 1 votes

# Answer
## Clojure, score 96

```
#(apply +(for[[k j](frequencies %)](*(inc j)j 0.5)))

```

Five spaces and pairs of brackets...
> 1 votes

# Answer
# Actually, score 12

```
;╗╔⌠╜cRΣ⌡MΣ

```

Try it online!

Explanation:

```
;╗╔⌠╜cRΣ⌡MΣ  (implicit input: S)
;╗           save a copy of S in register 0
  ╔          uniquify S (call it A)
   ⌠╜cRΣ⌡M   for each unique character in A:
    ╜c         count the number of occurrences in S
      R        range(1, count+1)
       Σ       sum
          Σ  sum

```

Repeating the `Σ` is two points less than using an alternative formulation with no repeated characters (`i`+Y`).
> 1 votes

# Answer
## F#, score:~~1264~~1110

-154 points, thanks to @Laikoni

```
let x(y:bool)=System.Convert.ToInt32(y)
let rec p(k:string)q=
 let j=k.Length
 if(j=1)then(x(k.[0]=q))else p k.[0..(j-2)] q+x(k.[j-1]=q)
let rec d(a:string)=
 let z=a.Length
 if(z<2)then z else d a.[0..(z-2)]+p a (a.[z-1])

```

You need to call the d function. In a more readable form:

```
let x (y:bool)=
    System.Convert.ToInt32(y)
let rec e (c:string) b=
    let j=c.Length
    if(j=1)then
        (x(c.[0]=b))
    else
        e c.[0..(j-2)] b+x (c.[j-1]=b)
let rec d (a:string)=
    let h=a.Length
    if(h<2)then
        h
    else
        d a.[0..(h-2)]+e a (a.[h-1])

```

### Explanation

It is a recursive algorithm, the base case is, if the length of the string is less than 2 (0 or 1), the score will be the length of the string. This is because, if the length is 0 (empty string), we have no characters, so the score is 0, and if the length is 1, that means, that the string consists of only 1 character, so the score is 1.

Otherwise it trims the last character of the string, and to the score of the truncated string adds the count of the last character in the untruncated string.

The counting algorithm is also recursive. Its base case is, when the length of the string is one, then the count is 1, if the string matches with the character, and 0 otherwise. This can also be done, if we convert the bool to an int, and this results in a lower score.

Otherwise it trims the last character of the string, calculates the count of that string, and if the last character matches the character, we are calculating the count of, adds one to the count. This is again, better, if we convert that boolean to an int.
> 1 votes

# Answer
# AWK, 39 bytes, Score 54

```
BEGIN{RS="(.)"}{M+=++s[RT]}END{print M}

```

Try it online!
> 1 votes

# Answer
**FIREBIRD, score 3577**

Version to calculte the score:

```
SELECT COALESCE(SUM(C),0)FROM(WITH RECURSIVE T AS(SELECT 1 AS I,SUBSTRING(CAST(:V AS BLOB)FROM 1 FOR 1)AS S FROM RDB$DATABASE UNION ALL SELECT I+1,SUBSTRING(CAST(:V AS BLOB)FROM I+1 FOR 1)FROM T WHERE I < CHAR_LENGTH(CAST(:V AS BLOB)))SELECT T.*,(SELECT COUNT(T2.I) FROM T T2 WHERE T2.S=T.S AND T2.I<=T.I)AS C FROM T WHERE CAST(:V AS BLOB) <> '')

```

Below is the idented version of the code, in case anyone want to now. I'm sorry for any mistakes, first time here actually posting!

```
SELECT COALESCE(SUM(C), 0)
FROM (
  WITH RECURSIVE T AS (
    SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S
    FROM RDB$DATABASE

    UNION ALL

    SELECT I+1, SUBSTRING(CAST(:V AS BLOB) FROM I+1 FOR 1)
    FROM T
    WHERE I < CHAR_LENGTH(CAST(:V AS BLOB))
  )
  SELECT T.*, (SELECT COUNT(T2.I) FROM T T2 WHERE T2.S = T.S AND T2.I <= T.I) AS C
  FROM T
  WHERE CAST(:V AS BLOB) <> ''
)

```

---

**Explanation**

I start my select in a system table `SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S FROM RDB$DATABASE`, which always has only one row. Using that only one row, I return 1 as a column **I**, and the character that exists in the input in the I value.

Let's say I've passed 'abaacab' as input:

```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
╚═══╩═══╝

```

In the UNION ALL part, I start to increment the index from the first select, until it reaches the end of the input. So, in the example I would get this:

```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
║ 2 ║ b ║
║ 3 ║ a ║
║ 4 ║ a ║
║ 5 ║ c ║
║ 6 ║ a ║
║ 7 ║ b ║
╚═══╩═══╝

```

After that, I also select the count of ocurrences from the value on **S**, that has already appeared in indexes below the **I**. So, in a column **C** I now have the 'cost' of that character, which I only need to SUM after to get the value.

```
╔═══╦═══╦═══╗
║ I ║ S ║ C ║
╠═══╬═══╬═══╣
║ 1 ║ a ║ 1 ║
║ 2 ║ b ║ 1 ║
║ 3 ║ a ║ 2 ║
║ 4 ║ a ║ 3 ║
║ 5 ║ c ║ 1 ║
║ 6 ║ a ║ 4 ║
║ 7 ║ b ║ 2 ║
╚═══╩═══╩═══╝

```

I used BLOB as the type from the input, to not get limited by size.
> 1 votes

# Answer
## /Kona, score 19

```
+/,/1+!:'(#:)'=

```

Works as:

```
              = (implicitly take arg as input), group -> make dictionary of characters to their occurring indices
         (#:)'= count each of these
    1+!:'(#:)'= get a list from 0->n-1 for each of these counts, add one to each
+/,/1+!:'(#:)'= finally, reduce to single list, sum reduce this list

```

Example:

```
k)+/,/1+!:'(#:)'="+/,/1+!:'(#:)'="
19
k)+/,/1+!:'(#:)'="abaacab"
14

```

Legible q equivalent:

```
(sum/)raze 1+til count each group

```
> 1 votes

# Answer
# Pyke, score 7

```
cemSss

```

Try it here!

```
c      -    count_occurrences(input)
 e     -   values(^)
  mS   -  [range(1,i+1) for i in ^]
    ss - sum(sum(i)for i in ^)

```
> 1 votes

# Answer
# Jelly, ~~10~~ 9 bytes; Score ~~10~~ 9

```
ṢŒrzẆṪRẎS

```

Try it online!

This is the first time I use Jelly, and I didn't want to check other people's answers because I wanted to try it myself. I probably reinvented the wheel a couple times there. Suggestions and feedback are greatly appreciated.

EDIT: -1 byte for removing `ɠ` and taking the input as an argument.

Explanation:

```
ṢŒrzẆṪRẎS           #Main Link; input abaacab
Ṣ                   #sorts input; aaaabbc
 Œr                 #run-length encode, or the number of times a character appears; a4b2c1
   z                #zip; ['abc', [4, 2, 1]]
    Ẇ               #takes every contiguous sublists
     Ṫ              #Pops the last element; [4, 2, 1]
      R             #Takes the range of every element; [[1,2,3,4],[1,2],1]
       Ẏ            #Collapses every element into a single array; [1,2,3,4,1,2,1]
        S           #Sum and implicitly print; 14.

```

(no idea why, but the code doesn't work without , although it gives the exact same output as `z`)
> 1 votes

# Answer
# Japt, score 12 (+2 for `-x`) = 14

```
¬n ó¥ ËÊõÃc

```

## Explanation

```
¬n ó¥ ËÊõÃc                                             "abaacab"
¬            // Split the input into an array of chars  ["a","b","a","a","c","a","b"]
 n           // Sort                                    ["a","a","a","a","b","b","c"]
   ó¥        // Partition matching items                [["a","a","a","a"],["b","b"],["c"]]
      Ë      // map; For each array:
       Ê     //   Get the length x                      [4,2,1]
        õ    //   Create a range [1...x]                [[1,2,3,4],[1,2],[1]]
         Ã   // }
          c  // Flatten                                 [1,2,3,4,1,2,1]
-x           // Sum                                     14

```

Try it online!
> 1 votes

# Answer
# , score 14

```
1#.2!1+#/.~

```

Try it online!

Outgolfed by the other J solution, but figured I'd post this anyways since it uses a slightly different method.
> 1 votes

# Answer
# Attache, score 36

```
Sum@Map&:(Count#Last)@Prefixes

```

Try it online!

## Explanation

```
Sum@Map&:(Count#Last)@Prefixes

```

This is a composition of 3 functions:

* `Prefixes` \- this simply obtains the prefixes of the input
* `Map&:(Count#Last)` \- This is a mapped fork. This is equivalent to `arr.map { e -> e.count(e.last) }` So, for each character, this counts the occurrences of that character so far.
* `Sum` \- this sums all of these numbers.
> 1 votes

# Answer
# MS-SQL, score 308

I'm using a completely different technique from my other answer, with additional restrictions, so I'm submitting them separately:

```
SelEcT SUm(k)FROM(SELECT k=couNt(*)*(CoUNT(*)+1)/2froM spt_values,z WHERE type='P'AND number<len(q)GROUP BY sUBstring(q,number+1,1))L

```

Caveats: this must be run from the `master` database of a MS-SQL server set to a case-sensitive collation (mine is set to SQL\_Latin1\_General\_CP850\_BIN2).

Input is via varchar field *q* in pre-existing table *z*, per our IO rules. Formatted:

```
SelEcT SUm(k)
FROM
    (SELECT k=couNt(*)*(CoUNT(*)+1)/2
     froM spt_values,z
     WHERE type='P'
     AND number<len(q)
     GROUP BY sUBstring(q,number+1,1)
    )L

```

The trick here is to use a "number table" to join with the input table, which allows me to separate each character into its own row, then group by matching characters, count them up, calculate the score of each, and sum them all together. All the rest is minimizing score by playing with character case, since SQL keywords are not case sensitive.

MS-SQL has a system table in the `master` database called `spt_values` with a lot of junk in it, but I restrict it to `type='P'`, I get a nice number table with 0 through 2047.
> 1 votes

# Answer
# K4, score 15

**Solution:**

```
+/,/{1+!#x}'=

```

**Example:**

```
q)k)+/,/{1+!#x}'="Programming Puzzles & Code Golf"
47

```

**Explanation:**

```
+/,/{1+!#x}'= / the solution
            = / group
    {     }'  / apply lambda to each (')
         x    / implicit lambda input
        #     / count length
       !      / range 0..n
     1+       / add one
  ,/          / flatten list
+/            / sum up

```

**Notes:**

In **Q** this could be written as:

```
q)sum raze { 1 + til count x } each group "Programming Puzzles & Code Golf"
47

```
> 1 votes

# Answer
# JavaScript, ~~112~~ ~~95~~ 58 points

```
A=>A.map(C=>N+=A[C]=-~A[C],N=0)|N

```
* 7 points saved thanks to ETHProductions

Try it online!
> 1 votes

# Answer
# Standard ML, 66 bytes, score 113

```
fun$(a::z)=1+length(List.filter(fn y=>y=a)z)+	$z|
$_=0;$o explode;

```

This code defines an anonymous function which is bound to the implicit result identifier `it`. Try it online!

### Explanation

The ungolfed code looks like this:

```
fun f (a::z) = 1 + length (List.filter (fn y => y=a) z) + f z
  | f  _     = 0
val g = f o explode

```

The function `g` takes a string as input, converts it to a list of characters with `explode`, and passes it on to the function `f` which recurses over the list, with `a` being the current character and `z` being the remaining list. For each `a` the number of occurrences of `a` in `z` is computed by filtering `z` to contain only chars equivalent to `a` and taking the length of the resulting list. The result is incremented by one to account for the current occurrence of `a` and added to result of the recursive call of `f` on `z`.
> 1 votes

# Answer
# Stax, ~~8~~

```
ç╕┌α▒'

```

Run and debug online!

Saved 2 points by using runs per comment by @recursive.

## Explanation

Uses the unpacked version to explain.

```
o:GF:T+
o          Sort array
 :G        Run lengths
   F       For each run length `n`
    :T     The nth triangular number
      +    Add to accumulator
           Implicit output

```
> 1 votes

# Answer
# PHP, 44 bytes, score 78:

```
While($C=ORD($argn[$p++]))$s-=++$$C;EcHo-$s;

```

Almost Jörg´s solution, but one byte shorter.

---

## PHP, 51 bytes, score 80

```
ForEach(COUNT_CHARS($argn)As$p)$z-=~$p*$p/2;echo$z;

```

---

Run as pipe with `-nR` or try them online
> 1 votes

# Answer
# Perl6/Rakudo, 45 bytes, score 66

Run with `perl -ne`:

```
say [+] bag(.comb).values.map({($_+1)*$_/2});

```

Uses the essential nature of a Bag (like a set with a count per member).

Step by step:

```
.say;                      # abaacab
say .comb;                 # (a b a a c a b)
say bag(.comb);            # Bag(a(4), b(2), c)
say bag(.comb).values;     # (2 4 1)
say bag(.comb).values.map({($_+1)*$_/2});        # (3 10 1)
say [+] bag(.comb).values.map({($_+1)*$_/2});  #14

```

Also note that each character's score can be calculated from its occurrences as `(n+1)*n/2`.

Edited because I cannot evidently read.
> 1 votes

# Answer
# \>\<\>, score 33

```
0vAB;n*<
p>i:0(?^:ag1+:}r-@a

```

Try it online!

28 bytes, with 2 occurrences each of `a` and `0`, and 3 occurrences of `:`. `AB` can be replaced by any two characters which don't appear anywhere else in the code.

Works by storing the current character count in the code grid on row 10. The sum is actually a negative sum to start with, and the -1 from reaching the end of STDIN is multiplied with this to turn it back into a positive number.
> 1 votes

# Answer
# jq, score 60

(40 characters code + 3 characters command line option)

```
[./""|group_by(.)[]|range(length+1)]|add

```

Sample run:

```
bash-4.4$ jq -R '[./""|group_by(.)[]|range(length+1)]|add' <<< 'Programming Puzzles & Code Golf'
47

```

Try it online!

### jq, score 63

```
[./""|group_by(.)[]|range(length+1)]|add+0

```

In case the result for empty string must be numeric 0. There are a few other solutions that use alternative representation of nothing.
> 1 votes

# Answer
**SHELL** ( **67 bytes**)

**Last Solution :** ( **68 bytes**)

```
 f(){ bc<<<`echo -n "$1"|od -bAn|sed "s/\([^ ]\+\)/s+=++v\1;/g"`s;}

```

Old solutions :

**Old Solution 1** : by creating **function f** (**83 bytes** ) :

```
f(){ bc<<<`echo "$1"|sed "s/./ss+=++&;/g"|sed "s/[A-Z]/\L&_/g"|sed "s/ /bb/g"`ss;}

```

**Old Solution 2** : by creating **alias f** ( **81 bytes** )

```
alias f='bc<<<`cat -|sed "s/./ss+=++&;/g"|sed "s/[A-Z]/\L&_/g"|sed "s/ /bb/g"`ss'

```

**Explanations :**
I used ( **sed "s/./ss+=++&;/g"** ) to replace any char **a** by ( **ss+=++a;** ); where ss is the sum to calculate, then concatenate with ss, and calculate all expression by the command **bc** :

```
echo "a" | sed "s/./ss+=++&;/g"
ss+=++a;

```

for a string in input :

```
echo "aab" | sed "s/./ss+=++&;/g"
ss+=++a;ss+=++a;ss+=++b;

```

step by step :

```
ss+=++a;    // a=1  -->  ss=1
ss+=++a;    // a=2  -->  ss=3
ss+=++b;    // b=1  -->  ss=4

```

for lowercase only input, the simpler function need only ( **47 bytes** ) to define :

```
f(){ bc<<<`echo "$1"|sed "s/./ss+=++&;/g"`ss;}

```

to take uppercase in consideration, Without spaces ( **68 bytes**) :

```
f(){ bc<<<`echo "$1"|sed "s/./ss+=++&;/g"|sed "s/[A-Z]/\L&_/g"`ss;}

```

Complete Solution ( **83 bytes**):

```
f(){ bc<<<`echo "$1"|sed "s/./ss+=++&;/g"|sed "s/[A-Z]/\L&_/g"|sed "s/ /bb/g"`ss;}

```

**fuction tests** :

```
f "abaacab"
14

f "abcdefg"
7

f "       "
28

f "Aa"
2

```

using an alias instead the function, we can reduce code size to ( **68 bytes** )

```
alias f='bc<<<`cat -|sed "s/./ss+=++&;/g"|sed "s/[A-Z]/\L&_/g"|sed "s/ /bb/g"`ss'

```

**alias tests** :

```
echo "       " | f
28

echo "Ab" | f
2

```
> 1 votes

# Answer
# Ruby, score: 38

```
->z{z.sum{|k|z.count(k)+1}/2}

```

Try it online!
> 1 votes

# Answer
# R, 349

Here is my R solution bit of tidy

```
s=function(x) {c=0
for (i in unique(strsplit(x,"")[[1]])) {
c=c(c,sum(1:sum(charToRaw(x)==charToRaw(i))))}
sum(c)
}

```
> 1 votes

# Answer
# Kotlin, score 93

```
{it.foldIndexed(0){z,q,v->q+it.take(z+1).count{it==v}}}

```

Try it online!
> 1 votes

# Answer
# Reticular, score 56

```
iSd:A=>ddV@c~dc$:A=+:A`L0EQ6jj+1*37_$O;

```

Try it online!
> 1 votes

# Answer
# Perl 6, Score: 34

```
{sum [\+](^∞)[.comb.Bag{*}]}

```

Try it online!

Takes advantage of the unicode operator  to save on characters.

### Explanation

```
{                          }  # Anonymous code block
              .comb           # Split the input string into characters
                   .Bag{*}    # Get the count of each character
             [            ]   # And inded each into
         (^∞)                 # The infinite list of integers
     [\+]                     # Triangularly summed (0,0+1,0+1+2...)
 sum                          # And return the sum total

```
> 1 votes

# Answer
# C++ (gcc), Score: ~~209~~ ~~196~~ 193

~~98~~ 96 bytes

*-3 thanx to l4m2*

```
#include<map>
long	F(std::string	S,int I=0){for(auto&C:S){++I;for(char&D:S)I+=C==D;}return I/2;}

```

C++-specific tricks:

* `#include<map>` instead of `#include<string>`
* Returning `long` instead of `int` to use more different characters
* Using `auto` instead of `char` in one of the loops has the same effect
* References (`&`) inside range-for save whitespace

Common tricks:

* Evenly use both tabs and blanks
* Upper case variables to be distinct from keyword characters

Try it online!
> 1 votes

# Answer
# JavaScript, ~~150~~ ~~141~~ 133

```
f=(g,i=[])=>g?(i[j=g.charCodeAt()]=(i[j]|0)+1)+f(g.substr(1),i):0

```

Ungolfed:

```
f=(g,i=[])=>                                                       //function declaration, a is list of appearance of characters so far.
            g?                                                     //check if string is empty
              (i[j=g.charCodeAt()]=                                //update appearance list
                                    (i[j]|0)+1)+                   //handle undefined, then increment
                                                f(g.substr(1),i)   //next character
                                                                :0 //base case for the empty string

```

150-\>141 - -6 for renaming variables to unique characters (thanks to Ørjan Johansen), and -3 for removing implicit `0` in `charCodeAt`.

141-\>133 - -8 for using actual unique variable names(thanks again to Ørjan Johansen).
> 1 votes

# Answer
# Zsh, 36 bytes, score 52

```
for	p (${(s..)1})$[j+=++a[#p]]
<<<$j

```

Try it online!

One tab, one space, one newline. This will fill up the debug log with "command not found". If that must be avoided, 38 bytes, score 55.
> 1 votes

# Answer
# 05AB1E (legacy), score: 4 (4 bytes)

```
Ù¢LO

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
Ù     # Get all unique characters of the (implicit) input-list
 ¢    # For each, count the amount of times it occurs in the (implicit) input-list
  L   # Create a list of each of these counts
      # (which implicitly flattens in the legacy version of 05AB1E)
   O  # Take the sum of all those integers
      # (which is output implicitly as result)

```
> 1 votes

# Answer
# Haskell, ~~150~~ 133 points

(~~79~~ 75 bytes)

```
import Data.List
c=foldr(\x->	\y->y+(x*(x+1)`div`2))0.map length.group.sort

```

Try it online!

* -17 points by removing some parentheses (thanks to @Laikoni)
> 1 votes

# Answer
# Gaia, score: ~~11~~ 10

```
$uC¦ₔ┅¦_Σ

```

Try it online!

~~For some reason, `_` is necessary else this spits out garbage answers. But the language is defined by its implementation, so what are ya gonna do.~~ Without the `_`, one of the sublists generated by `┅¦`is `[1 2]` which is converted to `12` by `Σ`.

```
$		| split into characters
 		|
  u		| get unique
   C¦ₔ		| implicitly copy original input; get counts of uniques into original
      ┅¦	| sequence: 1..count
        _Σ	| flatten and sum

```
> 1 votes

# Answer
# JavaScript, 87 score

```
A=([B,...C],Z=0)=>B?C.map(D=>D!=B||Z++)^A(C)-~Z:0

```

Try it online!

`C.map(D=>D!=B||Z++)` is either empty, `0`, `true` or something with a `,`, making it never show value to `^`
> 1 votes

# Answer
# Vyxal `d`, 3 bytes

```
Ċɾ⌊

```

Try it Online!

```
Ċ   # Counts of each element within itself
 ɾ  # Convert each value to 1...n
  ⌊ # Parse each to integer, zeroes element values
    # (d flag) take the deep sum

```
> 1 votes

# Answer
# Pyth, 8 bytes, Score: 9

```
ssSM/LQ{

```

Test suite

##### Explanation

```
ssSM/LQ{  | Full code
ssSM/LQ{Q | with implicit variables filled
----------+-------------------------------
     L {Q | Map over deduplicated input:
    /LQ   |  count in input
  SM      | Map: to [1...N]
 s        | Flatten
s         | Sum

```

`ss` can be replaced with `s.n` for an identical score with no repeat bytes, at the cost of being one byte longer.
> 1 votes

# Answer
# Husk, Score: 6

```
ṁoΣ#¹u

```

Try it online!

### Explanation

```
ṁoΣ#¹u   translates to ṁoΣ#⁰u⁰
ṁ    u⁰  map following function on unique input and then sum
 o       composed function
   #⁰    count occurrences in input
  Σ      triangular number

```
> 1 votes

# Answer
# Excel, Score: 206

```
G4 =MID(B3,SEQUENCE(LEN(B3)),1)
C3 =IF(B3<>"",SUM(EXACT(G4#,TRANSPOSE(G4#))/2)+ROWS(G4#)/2,)

```

Link to Spreadsheet
> 1 votes

# Answer
# Excel VBA Immediate Window, Score ~~159~~ 141

*-18 byte thank to @TaylorRaine*

```
FOR I=1TO[len(b3)]:for J=1to i:Y=Y-(MID([B3],i,1)=mid([B3],j,1)):NEXT:next:?y

```

The mixed case reduces the score by 30.
> 1 votes

# Answer
## Python 2, score 108

```
lambda S:sum(S.count(Q)*(S.count(Q)+1)/2for Q in set(S))

```

Still golfing :)
> 0 votes

# Answer
## JavaScript (Firefox 30+), score 68

```
S=>[for(C of(T=0,S))T+=S.split(C).length]&&T/2

```

This uses array comprehensions which were originally planned for ES7, but were dropped late in the process. Firefox had implemented them anyway.
> 0 votes

# Answer
# QBIC, score: 128

```
dim x(126)[_l;||i=asc(_sA,a,1|)┘x(i)=x(i)+1][126|[x(b)|p=p+c}?p

```

Nice round score of 128.

## Explanation

```
dim x(126)      Create an array of 126 elements (one for each ASCII element)
[_l;||          Read cmd line input, loop over its length
i=asc(_sA,a,1|) Read the next char's ascii value
┘               (Syntactic linebreak)
x(i)=x(i)+1     Raise the count of this ASCII char by 1
]               NEXT
[126|           Loop over the ASCII array again
[x(b)|          Read the count and start a loop that runs from 1 to that count
p=p+c           Add to running total p the loop counter
}               Close both loops
?p              PRINT p

```
> 0 votes

# Answer
# Ruby, score ~~63~~ 60

Uses the `-n` flag which ends up adding 2 points due to the presence of another `n` within the code.

-3 points from Alexis Anderson.

```
i=x=0
gsub(/./){x+=$_[0,i+=1].count$&};p x

```

Try it online!
> 0 votes

# Answer
# Swift 3, 153 bytes, score = 637

```
var u:(String)->Int={var d = Dictionary<Character,Int>()
for c in $0.characters{d[c] = (d[c] ?? 0) + 1}
return d.values.reduce(0,{$0 + $1 * ($1 + 1) / 2})}

```

## Legible version plus explanation

```
func unique(_ string: String) -> Int {
    var dict = Dictionary<Character, Int>()
    for char in string.characters { dict[char] = (dict[char] ?? 0) + 1 }
    return dict.values.reduce(0, { $0 + $1 * ($1 + 1) / 2 })
}

```

My solution takes the string, iterates over the characters and tracks each unique character in a dictionary, counting the occurrences per character. Once that's done, it reduces the dictionary's values using the triangle number formula ( n(n+1) / 2 ) and returns the result.

## Comments

Swift obviously isn't the best language for golfing, but it was fun to see where I could save bytes despite its rigid syntax. This is my first Swift submission - be gentle!
> 0 votes

# Answer
# \>\<\> (Fish), score 133

```
!<01-0&i:2(:?&:?n?;&1+&:}}:3(00@@?.~~:{=&+&{$}8e+0.>.!06}~{

```

This code reads the input per character, adds a point and loops through all the read characters, adding an extra point for every equal character.

You can try it out here

# Explanation

```
!<01-0&         // Initialize (put -1 on the stack and 0 in the register)
i:2(:?$:?n?;    // Read the next input. If it's -1, print the register and end the program.
&1+&            // Add one to the register
:}}:            // Duplicate both the input and the check value
3(00@@?.~~      // If the check value is -1, jump the instruction pointer to 0,0 (line 0)
:{=&+&          // Compare the input to the check value and add the result to the register
{$}8e+0.        // Move the checked value to the bottom of the stack and jump to 22,0 (line 4)
>.!06}~{        // Clean up the stack and jump to 0,6 (line 2)

```
> 0 votes

# Answer
# CJam, score 18

```
q_,{)W$<}%.e=0+:+

```

Try it online!

### Explanation

```
q                  e# Read the input.
 _,                e# Copy it, get its length.
   {               e# Map over the range from 0 .. length-1:
    )              e#  Increment the current number.
     W$            e#  Push the input.
       <           e#  Get the first <current number> characters of it.
        }%         e# (end map)
          .e=      e# Count the occurrences of each character in the corresponding slice.
             0+    e# Append a 0 to the result (because you can't reduce and empty list).
               :+  e# Reduce by addition (sum).

```
> 0 votes

# Answer
# JavaScript, 49 bytes, score 88

```
b={};s=0;for(j in a=prompt())s+=b[a[j]]=-~b[a[j]]

```
> 0 votes

# Answer
# Factor, 2435

(o god my score)

`"" over [ 2dup swap in? [ drop ] [ suffix ] if ] each { } swap swapd [ dupd 0 swap swapd swap [ over = swap [ [ 1 + ] [ ] if ] dip ] each drop swap [ suffix ] dip ] each drop [ dup 1 + * 2 / ] map sum` (wrong formatting on purpose for multi-line span)

Wow, Factor is hard. Or I'm just bad. Probably a little bit of both.
> 0 votes

# Answer
# Pyt, 6 bytes

```
ĐỤ⇹ɔ△Ʃ

```

Explanation:

```
              Implicit input
Đ             Duplicate top of stack
 Ụ            Get unique characters
  ⇹           Swap top two items on stack
   ɔ          Count number of times each unique character occurs in the input
    △         Calculates the total score for each character
     Ʃ        Sum count
              Implicit output

```

Try it online!
> 0 votes

# Answer
# Factor \+ `grouping.extras math.unicode`, score: 104

```
[ head-clump
[ dup
last '[
_ =
] count
] map
Σ ]

```

Try it online!

The whitespace is a killer. In order to lessen its impact, I alternate between spaces and newlines. Tabs aren't allowed in TIO's build of Factor or I would have used them too.
> 0 votes

---
Tags: string, self-scoring
---


title: Can Jimmy hang on his rope?

text:
# Question
Title: Can Jimmy hang on his rope?
Yet another Jimmy challenge by his original father. See these other lovely challenges.

---

As you all know, recently we've been seeing challenges related to Jimmy on platforms. Now, Jimmy is an acrobat as I mentioned before, and he's got other tricks up his sleeve.

One of these tricks is hanging by ropes. Here's an example of a rope Jimmy could hang from:

```
            ||
            ||
            ||
            ||
            ||
            ||

```

When Jimmy hangs on a rope, it looks like this:

```
            ||
            ||
           /o\
            ||
            ||
            ||

```

He can hang on the left or the right of the rope, so this:

```
            ||
            ||
            ||
            /o\
            ||
            ||

```

is also valid. But he cannot hang by just one body part, so anything like this:

```
            ||
            ||
            ||
          /o\|
            ||
            ||

```

is invalid. Note that when he is hanging by one body part the other half of the rope is visible because Jimmy does not cover it up.

Also, Jimmy does not like hanging on the bottom of the rope - it scares him - so this:

```
            ||
            ||
            ||
            ||
            ||
            /o\

```

is invalid.

# The challenge

Take input of a Jimmy situation like the ones above, and output whether Jimmy will hang on to the rope or not through a truthy or falsy value.

# The specifics

* Write a program that takes input. This can be through a function or any other appropriate input method.

1. The input should be a scene of one Jimmy and a rope as exemplified above.
* The program should output a truthy or falsy value to the console based on whether Jimmy can hang on to the rope or if he would fall off the rope, respectively.
* The criteria for Jimmy being able to hang on the rope:

1. Two of his body parts are on the rope.
    2. He is not on the bottom of the rope.
    3. He is not floating in mid-air.
* You can assume the rope will be straight, made up of `||` segments, and will be longer than one character in height.
* You can assume one whole rope and one singular Jimmy will be present in your scene, no more and no less.
* You can assume there will be no trailing newlines at the bottom of the rope.
* You must cover any amount of leading or trailing spaces before and after the rope.

# Test cases

```
           ||
           ||
           ||                 TRUTHY
           /o\
           ||
           ||

            ||
            ||
          /o\|                FALSY
            ||
            ||

        ||
       /o\                    TRUTHY
        ||

            ||
           /o\                FALSY

         /o\
          ||                  TRUTHY

            ||
            ||
       /o\  ||                FALSY
            ||
            ||

```

# Scoring

This is , so lowest score in bytes wins after about a week.

# Leaderboard

You can view the leaderboard for this post by expanding the widget/snippet below. In order for your post to be included in the rankings, you need a header (`# header text`) with the following info:

* The name of the language (end it with a comma `,` or dash `-`), followed by...
* The byte count, as the last number to appear in your header.

For example, `JavaScript (ES6), 72 bytes` is valid, but `Fortran, 143 bytes (8-bit)` is invalid because the byte count is not the last number in the header (your answer will be recognized as 8 bytes - don't take advantage of this).

```
<!-- Run the snippet to see the leaderboard. Report any bugs to @ozewski on Github. -->    <iframe src="https://ozewski.github.io/ppcg-leaderboard/?id=187759" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>
```

# Answer
# Japt, 5 bytes

I *think* this is right; I've been working for 16 hours straight and barely know my own name so I wouldn't be surprised if it's not!

```
Õø|io

```

Try it

```
Õø|io     :Implicit input
Õ         :Transpose
 ø        :Contains?
  |io     :  "|" prepended with "o"

```
> 17 votes

# Answer
# Python 2 or 3,  ~~33~~  30 bytes

-3 thanks to Maxwell

```
lambda l:'o'in map(max,l[:-1])

```

An unnamed function accepting a list of lines

**Try it online!**

### How?

There needs to be a section of rope obscured by Jimmy that is not the bottom one.

```
lambda l:'o'in map(max,l[:-1])
lambda l:                      # a function taking l (the lines as strings)
                       l[:-1]  # strip off the last line
               map(max,      ) # maximum of each line (where '|'>'o'>'\'>'/'>' ')
         'o'in                 # was 'o' one of them? (hence Jimmy obscured all the rope)

```
> 25 votes

# Answer
## Python 2, 28 bytes

```
lambda x:"o', '|"in`zip(*x)`

```

Try it online!

How does it work? It takes input as a list of strings, and zip joins the string. Jimmy stays on the rope if there is a "|" below an "o", so this code joins all the lines and checks if there is an "o" followed by a "|".

Annotated code:

```
lambda x: # Creates an anonymous function that takes one argument
  "o', '|" # If this substring is in the zip object, then Jimmy's "o" is above a "|"
    in
    `    # Back quotes change the object into its string representation
    zip(*x)` # Joins the lines together

```

## (Old Answer) Python 2 or 3, 39 bytes

```
lambda x:1-all("|"in i for i in x[:-1])

```

A function that takes input as a list of strings, each string being a different line.

-11 bytes thanks to xnor! -2 bytes thanks to Jonathan Allan!

Try it online! (If you want to try more test cases, just put a "." after each set of lines in the input box.)

How does this work? Well, if Jimmy is fully on the rope, then that line will not have any "|" characters. Therefore, we can check each line, and if we find any with no "|" characters, then we know that Jimmy can stay on the rope. However, Jimmy can not hang on to the bottom of the rope; therefore, we don't include the final line in our check. If the final line is just another part of the rope, than it won't matter, because we'll still find a valid row higher up, but if the final line is the one with Jimmy, then it won't find a line without "|" anywhere, and will return False.
> 17 votes

# Answer
# Jelly,  ~~9 7~~  6 bytes

```
Ṗ<”|ṀẠ

```

A monadic Link accepting a list of lines

**Try it online!**

### How?

There needs to be a section of rope obscured by Jimmy that is not the bottom one.

```
Ṗ<”|ṀẠ - Main Link: list of lines of characters
Ṗ      - remove last line
  ”|   - pipe character
 <     - less than? (vectorises) - Note that all other characters are
    Ṁ  - maximum
     Ạ - all?

```
> 8 votes

# Answer
# Grime, 5 bytes

```
\o/\|

```

Try it online!

The right tool for the job.

```
\o        # match an "o"
  /       # above
   \|     # a "|"

```
> 8 votes

# Answer
# 05AB1E, 5 bytes

```
Çü%àθ

```

Try it online!

```
Ç         # convert the input to a 2D array of codepoints
 ü%       # pairwise modulo (vectorized)
   à      # maximum (*not* vectorized, returns a single number)
    θ     # tail (last digit)

```

The only characters that can appear in the input are `\o/ |`, with respective codepoints 92, 111, 47, 32, 124 (there are no newlines, since we chose to take input as an array of lines). The possible results by moduloing two of these numbers are 0, 13, 15, 17, 19, 28, 30, 32, 45, 47, 92, 111. 111 is the largest of those, and also the only one that ends with 1, so the code will output truthy if and only if 111 is present in the list (only 1 is truthy in 05AB1E). 111 is 111 (`o`) % 124 (`|`), and so only occurs if there's an `o` above a `|` in the input.
> 6 votes

# Answer
## brainfuck, ~~79~~ 64 bytes

```
>>+<<,[----------[<]>>[.-]+<[>-]+[---------<-->]<[<]>>[-]<[>]<,]

```

Try it online!

Outputs the 0x01 byte for truthy and nothing for falsy.

```
Z: 0
A: input
B: 0
C: has no | been found on this line?

>>+<<                       initialize C to 1
,[                          loop over each char

  ----------                set A to 0 if input was \n
  [<]>>                     move to C if input was \n; B otherwise
  [                         if input was \n and C is true
    .-                      output 1
  ]

  +                         this will reinitialize C to 1 if input was \n
                            but also clobber B with 1 if it wasn't
                            now we have { 0   0   0  (1)} if input was \n;
                                        { 0   _  (1)  _ } otherwise
  <[>-]                     clear own cell if the one to the left is positive
                            this yields { 0   0  (0)  1 } and
                                        { 0   _  (0)  _ } as desired

  +[---------<-->]          set A to 0 if input was |
  <[<]>>                    move to C if input was |; B otherwise
  [-]                       zero out current cell: clears C if input was |
  <[>]<                     realign pointer onto A

,]                          break on end of input

```
> 5 votes

# Answer
# Stax, 6 bytes

```
é¿┤4╠q

```

Run and debug it

Transposes the input, then searches for "o|".
> 4 votes

# Answer
# APL (Dyalog Unicode), 8 bytesSBCS

Anonymous tacit prefix function, taking a character matrix as argument.

```
1∊'o|'⍷⍉

```

Try it online!

transpose

`'o|'⍷` mask for everywhere `o` is immediate followed by `|`

`1∊` is one a member thereof?
> 4 votes

# Answer
# Dyalog APL Extended, ~~14~~ ~~13~~ ~~11~~ 9 bytes

```
3∊¯1+/⍤↓<

```

Try it online!
> 3 votes

# Answer
# Haskell, 19 bytes

```
any(all(<'|')).init

```

Try it online!
> 3 votes

# Answer
# JavaScript, ~~39~~ 33 bytes

Thanks @Daniil Tutubalin for golfing off 2 bytes

```
x=>!!x.match(/^( *)\/[^|]*\n/m)

```

This matches any line which is not the line where his left arm shows up and none of the rope shows.

Try it online!
> 2 votes

# Answer
# ///, ~~53~~ 50 bytes

```
/~/\/\~/\/o\\/1~1 /1~ 1/1~|1~/1|~/|~/1.~/ ~/.~/
~.

```

Try it online!

Because there is no other way to take input in ///, it is hard-coded:

```
/~/\/\~/\/o\\/1~1 /1~ 1/1~|1~/1|~/|~/1.~/ ~/.~/
~<INPUT HERE>.

```

**Explanation:**

The general approach is to replace Jimmy with a unary 1, then remove him from all situations where he is in danger. If he survives, he is outputted. If he doesn't, then nothing is. The `~` in the code are a replacement for `//`, which allow the code to be shortened by 3 bytes here. They are omitted from the explanation.

```
/{/\//
/}/\/\//

          {The top two lines allow me to leave comments without disturbing the code.}

/\/o\\/1/ {Replace Jimmy with a 1.}
/1 /1/    {Get rid of any spaces in front of Jimmy. This moves Jimmy towards the rope from the left.}
/ 1/1/    {Get rid of any spaces after Jimmy. This moves Jimmy towards the rope from the right.}

/|1//     {If Jimmy is touching the rope, remove him and the rope.}
/1|//     {This is based on the observation that in all cases where Jimmy is safe, there is no visible rope on his line.}

/|//      {Remove any remaining rope. If Jimmy was touching a rope, it's already too late for him.}
/1.//     {This handles the case where Jimmy is at the bottom of the rope (hence the period at the end).}

/ //      {The remaining lines clean up the output.}
/.//
/
//

           ||
           ||
           ||
           /o\
           ||.

```

Try it online!
> 2 votes

# Answer
# Elm 0.19, ~~68~~ 60 bytes

```
List.any(not<<String.contains"|")<<List.drop 1<<List.reverse

```

Anonymous, points-free function. Takes input as a list of lines. Disregarding the last line, it checks whether there are any with no `'|'` in them – implying the rope is fully covered by Jimmy.

Thanks to Lynn for golfing 8 bytes.

Verify all test cases here.
> 2 votes

# Answer
# Kotlin, ~~93~~ 84 bytes

```
fun j(a:List<String>){print(a.count{!it.contains("|")}==1&&!a.last().contains("o"))}

```

Try it online!
> 2 votes

# Answer
# Ruby 2.5.5, 22 bytes

```
->x{x.pop;!x.all? /\|/}

```

Expects an array of lines. Requires a minimum of version 2.5.5 because this is when `Array#all?(pattern)` was added.

Because of the constraints that the input will always be a valid scene of Jimmy and a rope, it boils down to whether any of the lines prior to the last line have the rope obscured.
> 2 votes

# Answer
## Retina, 9 bytes

```
m`^[^|]+^

```

Try it online!

Now, I've never programmed in Retina before, but as far as I can tell this works. It is a regular expression that finds a string containing (1) the beginning of the input, (2) no "|" characters, and (3) a newline.

People more familiar with either regular expressions or Retina are encouraged to offer suggestions. -2 bytes thanks to Neil!
> 1 votes

# Answer
# JavaScript, ~~38~~ 37 bytes

```
r=>r.some(x=>!~x.search`\\|`,r.pop())

```

Try it online!
> 1 votes

# Answer
# Befunge-98 (PyFunge), ~~26~~ 24 bytes

```
]~:a-!#v_' `+
^_-3q#$<
@

```

Try it online!

Exits with return code 3 if `\n` is encountered and the last line contained 3 non-space characters, otherwise exits with return code 0 on EOF. Thus, this relies on the last line not containing a trailing newline.

### Dissected

```
]~                     :a-!#v_                ' `+
 Read character,      Branch downwards if   Increment counter on
 branch up (and        equal to 10 ('\n')   the stack if greater
 loop around) if                            than 32 (' ') and
 end of stream                              implicitly loop

^_-3q#$<                    <
 Return with code 3
 if counter is equal to 3,
 otherwise reset counter
 and return to beginning

@
 Return with exit
 code 0

```
> 1 votes

# Answer
# Perl 5 `-p`, 26 bytes

```
$\||=!/\|/;$;=/o/}{$\&&=!$

```

Try it online!
> 1 votes

# Answer
# 05AB1E (legacy), 6 bytes

```
ζJ„o|å

```

Port of *@Shaggy*'s Japt answer.

Input as a list of lines.

Try it online.

**Explanation:**

```
ζ       # Zip/transpose the (implicit) strings in the input-list, with space as filler
        # (NOTE: zip/transpose doesn't work on string-list in the new version of 05AB1E,
        #  which is why we use the legacy version)
 J      # Join these zipped/transposed lines together to a single string
  „o|å  # And check if it contains the string "o|"
        # (after which the result is output implicitly)

```
> 1 votes

# Answer
# PowerShell, 26 bytes

Port of Maxwell's answer for Retina.

```
"$args"-match'(?m)^[^|]+^'

```

Try it online!

Explanation:

`true` if:

1. there is a line in a scene that does not contain the character `|`
2. and after this line there is a start of a new line.

`false` otherwise.
> 1 votes

# Answer
# Husk, 6 bytes

```
€'om▲h

```

Try it online! A port of Jonathan Allan's answer.
> 1 votes

# Answer
# Vyxal, 6 bytes

```
Ḣ\|vOA

```

Try it Online!

Takes a list of lines, returns a 1 if Jimmy can't hang on, 0 if he can.
> 1 votes

# Answer
# Pyth, 9 bytes

```
sPm!sqR\|

```

Test suite!
> 0 votes

# Answer
# Pyret, 79 bytes

```
{(l):all2({(r,n):string-char-at(n,string-index-of(r,"o") == "|")},l,link(0,l))}

```

Expects an array of lines as strings. Makes a copy in `link(0,l)` where all rows shifted down by one. Goes through each row `r` and `n` where n is the row below r. Checks that if Jimmy's body `"o"` is at some position, then the row below it has a pipe there (i.e. Jimmy's hanging on the rope and isn't at the bottom).
> 0 votes

# Answer
# SnakeEx, 7 bytes

```
j:<R>o|

```

Try it here!

### Explanation

The only necessary and sufficient condition is that Jimmy's torso has to have a rope character below it.

```
j:       Define the main snake, j (for Jimmy)
  <R>    Pivot right (i.e. downward, since the snake starts out moving to the right)
     o   Match Jimmy's torso and move down
      |  Match a rope character

```
> 0 votes

# Answer
# Rockstar, ~~147~~ ~~146~~ 137 bytes

Outputs `0` for `false` and `1` for `true`

```
listen to J
Y's 0
while J
cut J
listen to R
X's 0
while J
let S be R at X
let Y be+roll J's "o" and S's "|"
let X be+1

let J be R

say Y

```

Try it here (Code will need to be pasted in)

```
listen to J     :Read first line of input into variable J
Y's 0           :Initialise Y as 0
while J         :While J exists
cut J           :  Split J into an array
listen to R     :  Read next line of input into variable R
X's 0           :  Initialise X as 0
while J         :  While J is not empty
let S be        :    Assign to variable S
  R at X        :      The character in R at 0-based index S
let Y be+       :    Increment Y by
  roll J        :      Pop the first element from J
  's "o"        :      Eqaul to "o"?
  and           :      Logical AND with
  S's "|"       :      S is equal to "|"
let X be+1      :    Increment X
                :  End while loop
let J be R      :  Reassign R to J
                :End while loop
say Y           :Output Y

```
> 0 votes

---
Tags: code-golf, string, ascii-art, decision-problem, parsing
---


title: Output every sublist ... eventually

text:
# Question
Title: Output every sublist ... eventually
You will be given as input an infinite stream of positive integers.

Your task is to write a program which outputs an infinite sequence of lists with two requirements:

* All lists in the output are finite sub-lists of the input stream.
* Every sub-list must be output *eventually* by your program.

Sub-lists are not necessarily contiguous, so `[1,1]` *is* a sub-list of `[0,1,0,1,0,...`, and should be included in your output if your input was `[0,1,0,1,0,...`.

The empty list `[]` is a sub-list of every possible input, so it should always be output at some point.

Aside from this, you can do what you want. You can output them in whatever order suits you, you can output any sub-list any (positive) number of times. It's up to you to figure out what's best.

This is so answers will be scored in bytes with fewer bytes being the goal.

## IO

Outputting an infinite sequence is done as per the defaults of the sequence tag wiki.

Input of an infinite sequence is basically the dual of those rules. You may:

* Take the input as a black-box function which takes \\$n\\$ and outputs the \\$n\\$th term
* Take the input as a black-box function which takes \\$n\\$ and outputs all terms up to the \\$n\\$th term
* Take the input as a lazy list, generator or stream.
* Take the input by repeatedly querying STDIN each time receiving the next term of the sequence.

# Answer
> 14 votes
# Haskell, ~~31~~ 27 bytes

-4 bytes thanks to Wheat Wizard!

Takes an infinite list as input and returns each finite sublist an infinite number of times.

```
f(a:l)=[]:do x<-f l;[a:x,x]

```

Try it online!

# Answer
> 10 votes
# 05AB1E, 1 byte

```
æ

```

Try it online!

# 05AB1E no builtin, 5 bytes

```
[DNÏ,

```

Try it online!

Takes the input as an 05AB1E infinite lazy list

```
[     infinite loop
 D    create a copy of the infinite list
 N    iteration index (starting from 0)
 Ï    elements of the list for which the corresponding element of the index is 1
 ,    print

```

# Answer
> 9 votes
# Python, 43 bytes

```
lambda s,n:[s(b)for b in range(n)if n>>b&1]
```

Attempt This Online!

Outputs the `n`th sublist.

# Python, 55 bytes

```
n=0
while[print([s(b)for b in range(n)if n>>b&1])]:n+=1
```

Attempt This Online!

Takes input using a black-box function predefined under the name `s`, which takes a number and outputs the corresponding 0-indexed value of the sequence. Shown in the ATO link using the powers of 2 `[1, 2, 4, 8, ...`. Outputs infinitely to STDOUT.

Uses the binary representation of each non-negative integer `n` to produce a sub-list; `1`s in the binary representation correspond to indices where the list's value is included in the output.

A bug fix for -12 bytes (!):

By using `n` itself rather than the bit length of `n` to determine how many bits to select, we also get, pretty much for free, the ability to sometimes output sublists which don't include the first item.

Because `n` is always greater than or equal to its bit length (besides for `0`), we will effectively select some `0` bits which form part of its "padding", but which allow us to skip some of the first few elements.

When `n` is `0`, this is the only number with no `1`s in its binary. As a result, by initialising `n` to `0`, we output an empty list at the start, satisfying that requirement at no byte cost.

---

# Python, ~~63~~ 62 bytes

```
def f(s,*e):
 yield e
 for x in f(s,next(s)):yield from{x,e+x}
```

Attempt This Online!

This is a version based on @ovs' clever Haskell answer, but with some changes to make it work in Python where we don't have infinite lists. It might be improvable.

-1 thanks to Command Master

Thanks to loopy walt, this version now outputs every sub-list exactly once, for the same byte count.

# Answer
> 6 votes
# Scala, 89 bytes

```
_.scanLeft(Seq[Int]())(_:+_)flatMap(l=>l.indices.toSet.subsets.map(_.toSeq.sorted map l))

```

Try it online!

Welp, this turned out much longer than I expected. Time to reconsider this approach. Input is a `LazyList[Int]`. It outputs all the sublists up to the current integer for every integer.

```
_                            //The input (infinite list)
.scanLeft                   //Scan left over the sequence,
  (Seq[Int]())(_:+_)        //building an infinite list of subsequences
flatMap(l=>                 //Map each of those subsequences l to its sublists
 l.indices.toSet.subsets   //Get all subsets of the indices
  .map(
   _.toSeq.sorted          //Sort the indices to ensure sublists are in order
   map l)                  //Map the index to the corresponding element in l
)

```

# Answer
> 5 votes
# , ~~73~~ 68 bytes

Or **\>=4.1, 61 bytes** by replacing the word `function` with a `\`.

*Edit: -5 bytes thanks to @Giuseppe.*

```
function(g)while(T<-T+1)for(i in 1:2^T)show(g(T)[!i%/%2^(T:1-1)%%2])

```

Try it online!

Explanation:

1. Take a black-box function `g` as an argument.
2. Increment `T` in each iteration - how many numbers to read from `g`.
3. In the loop, calculate all the sub-sequences of the current vector (and some more):
    * take all numbers from `1` to `2^T`,
    * convert to binary,
    * use as logical indices, which numbers from `g(T)` to print.

# Answer
> 5 votes
# JavaScript (Node.js), 30 bytes

```
a=>n=>a(n).filter(_=>(n/=2)&1)

```

Try it online!

Input array as a function which output first n elements. Output n-th element.

# Answer
> 3 votes
# \[Ruby\], ~~64 56~~ 48 bytes

```
->g{1.step{|n|n.times{p *g[n].combination(_1)}}}
```

Attempt This Online!

* saved 8 Bucks thanks to @ovs

takes a black box function returning first *n* elements.

# Answer
> 2 votes
# Charcoal, 21 bytes

```
ＷＳ«Ｅ⌕Ａ⮌⍘Ｌυ²1§υκＤ⎚Ｄ⊞υι

```

Try it online! Link is to verbose version of code. Explanation:

```
ＷＳ«

```

Repeatedly input the next integer as a string. (This will actually stop on a blank line, which is what I use to allow the linked example to halt, but for positive integers it will keep prompting for input.)

```
Ｅ⌕Ａ⮌⍘Ｌυ²1§υκ

```

Convert the length of the predefined empty list to binary and find the positions of the `1`s counting the least significant bit as `0`. Output the elements of the predefined empty list with matching positions.

```
Ｄ⎚Ｄ

```

Output the canvas double-spaced. (Charcoal's default output format lists one element per line, so it's not easy to distinguish consecutive lists otherwise, although if you were running it interactively then the `Enter input:` prompt would do the trick.)

```
⊞υι

```

Append the next term of the input stream to the predefined empty list.

# Answer
> 2 votes
# Pari/GP, 35 bytes

```
g->i->[g(j)|j<-[0..i],bittest(i,j)]

```

Try it online!

Take the input as a black-box function which takes \\$n\\$ (0-indexed) and outputs the \\$n\\$th term.

# Answer
> 1 votes
# Julia 1.0, ~~45~~ 31 bytes

```
f\n=[f(i) for i=0:n if n&2^i>0]

```

Try it online!

Port of pxeger's answer. Outputs the n-th sublist

## Julia 1.0, 45 bytes

```
!(x,a=[[]])=for i=x a=[@show a;vcat.(a,i)]end

```

Try it online!

Input is an iterator. Output has a bit of unnecessary stuff but hopefully it's acceptable

# Answer
> 1 votes
# Vyxal, 1 byte (non-competing)

Try it Online!

Non-competing as this builtin and many others were recently given infinite list support because of this challenge.

# Answer
> 1 votes
# Haskell + hgl, 2 bytes

```
sS

```

I just finished adding builtins having to do with subsequences to hgl. `sS` gets all the subsequences of the input and works just fine on infinite lists.

It outputs subsequences in order of the index of their last element last element. That is first it outputs the empty list, then it outputs all sequences that end in the 0th element, then all sequences that end in the 1st element, then all sequences that end in the 2nd etc.

# Haskell + hgl, 21 bytes

```
jn<<mM(ap[i,p]<p)<+cg

```

Since it's no fun to just post a built-in here's one that solves the task without `sS` or related functions. First we make `jn<<mM(ap[i,p]<p)`. This takes a *finite* list and outputs all subsequences.

To do this it uses `mM`, (`mapM` or `traverse` if you are a Haskell user) which is a little complicated, but it's equivalent to `sQ<m` (`sequence.map` if your a Haskell user) so I'll explain it like that.

First `m(ap[i,p]<p)` will replace every element with a list of a singleton containing itself and an empty list:

```
>>> m(ap[i,p]<p)[1,2,3]
[[[],[1]],[[],[2]],[[],[3]]]

```

Then `sQ` basically does the generalized cartesian product. It takes n lists as input and gives all the ways to take 1 item from each list. Since we have two possibilities in each list, the integer singleton or any empty list, this gives us basically binary numbers of n digits with 0 being the empty list and 1 being the value.

```
>>> mM(ap[i,p]<p)[1,2,3]
[[[],[],[]],[[],[],[3]],[[],[2],[]],[[],[2],[3]],[[1],[],[]],[[1],[],[3]],[[1],[2],[]],[[1],[2],[3]]]

```

Now we want to get rid of the singletons so we use `m jn`

```
>>> jn<<mM(ap[i,p]<p)$[1,2,3]
[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]

```

Now we have all the subsequences of the input! However this stalls out on infinite lists.

Our fix here is to use `cg`. `cg` gives all the *contiguous* subsequences of the input, possibly infinite. So we first run `cg` and then run this finite subsequence on every result.

Unlike the first solution this

## Reflections

Nice to see that we used no 3 byte functions anywhere. Still

* `ap[i,p]<p` is a little long for my liking `(<p)<ap` could probably be it's own function. I think it would have use beyond this challenge.

# Answer
> 0 votes
# Pip `-p`, 18 bytes

```
lPBlW1P*lAL:_AEqMl

```

Reads values from stdin, outputs sublists to stdout. Each sublist will be printed infinitely many times. Attempt This Online!

### Explanation

We track every sublist of the inputs-thus-far in `l`. At each iteration, we read a new input, append it to each of the existing sublists, append that list to the list of existing sublists, and output the whole thing.

```
lPBlW1P*lAL:_AEqMl
l                   Variable preset to empty list
 PBl                Push the empty list to l; l is now [[]]
    W1              While 1 (loop forever):
                Ml   Map this function to each sublist in l:
               q      Read a line of stdin
            _AE       and append it to the sublist
        lAL:         Append those results to l in-place
      P*             Print each sublist in l

```

---
Tags: code-golf, math, sequence, subsequence, open-ended-function
---


# Question
Title: Circular shift an arbitrary byte-array bitwise
Given an arbitrary array of octets, and an offset measured in bits, the goal is to bitwise left rotate the array by the specified number of bit positions as if the entire array were a single contiguous number. Byte order is big-endian.

As an example, given the (not zero terminated) ASCII string `abcd` and a shift of 5 bits. we turn this array of bytes:

```
01100001 01100010 01100011 01100100

```

into this one:

```
00101100 01001100 01101100 10001100

```

Notice that the bits propagate to the left from byte to byte and that they wrap back around.

Now that I think you've all got the idea, the rules:

* Your program should accept an arbitrary unsigned integer (**"number of bits to shift" non-negative, possibly zero, limited only by the size of the standard integer type**) and a raw stream of octets of arbitrary length (**you may assume the length is strictly positive**). How you accept these is up to you (**file,stdin,parameter are all acceptable**). Your program should output the shifted bytes in an analogous manner (**i.e. file,stdout,return value**).
* "Cut-and-paste" style code is **not allowed**. That is, you can't rely on your user to set the value of a certain variable before calling your code.
* The byte ordering is **big-endian**.
* Shortest code wins.

**EDIT: It's clear now I should have restricted the input output format a bit more. The solutions that are using ASCII 0s and 1s directly aren't very interesting unfortunately.**

# Answer
# APL (1)

it's a builtin

```
      5⌽0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 0
0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 0 0 1 1 0 0

```
> 1 votes

# Answer
## C 89

Shifting is done in-place in `*s` array. `l` is array length and `f` is number of bits to shift.

```
void f(char*s,l,f){while(f--)for(int i=0,j,c=*s<0;s[j=i++]<<=1,s[j]+=i%l?s[i]<0:c,i<l;);}

```
> 3 votes

# Answer
# C#, ~~321~~ ~~308~~ 304 bytes

```
var y=System.Text.Encoding.UTF8.GetBytes(args[1]).ToList();int i=int.Parse(args[0]),m,j=0;for(;i>7;y.RemoveAt(0),i-=8)y.Add(y[0]);byte c=0,u;for(m=8-i;j<y.Count;j++){u=(byte)((255<<m&y[j])>>m);if(j<1)c=u;y[j]<<=i;if(j>0)y[j-1]|=u;}y[^1]|=c;Console.Write(System.Text.Encoding.UTF8.GetString(y.ToArray()));

```

Dropped 13 bytes thanks to awesome suggestions from **Kevin**, and another 4 bytes with suggestions from **ceilingcat**!

Uncompressed version below. This uses C# v9 top-level statements feature, so the program below compiles into an executable. Program expects two arguments: bits and bytes in a form of a UTF8 string (e.g., execute is as `./program 5 abcd`).

```
// get bytes from the provided provided (assumed in UTF8)
var y = System.Text.Encoding.UTF8.GetBytes(args[1]).ToList();
int i = int.Parse(args[0]), m, j = 0; // i - how many bits to shift

// rotate full bytes first if bits >= 8
for (; i > 7; y.RemoveAt(0), i -= 8) // drop the first byte
    y.Add(y[0]); // append first byte to the end

byte c = 0, u; // c keeps the bits to wrap around from first byte to the last
               // u will be used to shift bits between neighboring bytes

// now i < 8 guaranteed
for (m = 8 - i; j < y.Count; j++)
{
    u = (byte) ((255 << m & y[j]) >> m); // bits to shift
    if (j < 1) c = u; // if we are on the first byte, store them in c
    y[j] <<= i; // shift the byte
    if (j > 0) y[j - 1] |= u; // shift the cutoff bits to prev byte
                              // if current byte is not the first byte
}

y[^1] |= c; // wrap around the bits

// and output
Console.Write(System.Text.Encoding.UTF8.GetString(y.ToArray()));

```
> 3 votes

# Answer
## Sed, 35 bytes

```
:a
s/1-\(.\)\(.*\)/-\2\1/
ta
s/.//

```

Takes input on stdin, as number of bits to shift by in unary, followed by `-`, followed by the binary stream, without spaces. e.g.

```
echo 11111-01100001011000100110001101100100 | sed -f a.sed

```

outputs

```
00101100010011000110110010001100

```
> 2 votes

# Answer
## Perl, 33 (32 + 1 for `-p`)

```
1while(s/1-(.)(.*)/-$2$1/);s/.//

```

Takes input on stdin, as number of bits to shift by in unary, followed by -, followed by the binary stream, without spaces. e.g.

```
echo 11111-01100001011000100110001101100100 | perl -pe '1while(s/1-(.)(.*)/-$2$1/);s/.//'

```
> 2 votes

# Answer
## APL (23)

```
{2⊥⍉(8,⍨⍴⍵)⍴⍺⌽,⍉⍵⊤⍨8/2}

```

This is a function that takes the rotation as its left argument and the byte array as its right argument (as numbers).

```
      5{2⊥⍉(8,⍨⍴⍵)⍴⍺⌽,⍉⍵⊤⍨8/2}97 98 99 100
44 76 108 140

```
> 1 votes

# Answer
**C# (210)**

```
void r(byte[] a, int n){string s="";for(int i=0;i<a.Length;i++)s+=Convert.ToString(a[i],2).PadLeft(8,'0');s=s.Substring(n)+s.Substring(0,n);for(int i=0;i<a.Length;i++)a[i]=Convert.ToByte(s.Substring(i*8,8),2);}

```

This is a function 'r' in C# that takes a byte\[\] and an integer n. It does in-place rotation, so the original array is rotated, and nothing is returned.

I convert the byte array to string of bits, rotate, and convert back to bytes. It seems like a cheat, but the requirements does not prevent it.

The pretty code is following:

```
void r(byte[] a, int n)
{
    string s = "";
    for (int i = 0; i < a.Length; i++)
        s += Convert.ToString(a[i], 2).PadLeft(8, '0');

    s = s.Substring(n) + s.Substring(0, n);

    for (int i = 0; i < a.Length; i++)
        a[i] = Convert.ToByte(s.Substring(i * 8, 8), 2);
}

```
> 1 votes

# Answer
# C, 142 bytes

It's huge :(

Input is taken from parameters, `puts` shifted string to stdout.

```
main(int d,char**v){d=strtoul(v[1],0,10);while(d--){v[1]=v[2]+1;**v=*v[2];strcpy(v[2],v[1]);while(*(v[1]++));*v[1]--=0;*v[1]=**v;}puts(v[2]);}

```
> 1 votes

# Answer
# q (18)

depending on how picky you are about exact output format and launch, i can get it down to 18 in q:

```
$ ls -l shift*.q
-rw-r--r-- 1 daviaaro ccM504 19 Jan  8 16:05 shift1.q
-rw-r--r-- 1 daviaaro ccM504 22 Jan  8 16:07 shift2.q
-rw-r--r-- 1 daviaaro ccM504 25 Jan  8 16:07 shift3.q
$ cat shift1.q
(rotate)."I*"$.z.x
$ q shift1.q 5 "01100001011000100110001101100100" <&-
"00101100010011000110110010001100"
$ cat shift2.q
-1(rotate)."I*"$.z.x;
$ q shift2.q 5 01100001011000100110001101100100 <&-
00101100010011000110110010001100
$ cat shift3.q
-1(rotate)."I*"$.z.x;
\\
$ q shift3.q -q 5 01100001011000100110001101100100
00101100010011000110110010001100
$

```

of course, it helps that the actual function happens to be in the standard lib :)

all three interpret two command-line args as int and string and rotate the string by the int

the first case just shows the string representation of the string (a (mostly) pasteable notation)

the second and third cases print it

in the first two cases, i'm relying on q to quit itself when run without stdin

the third case has an explicit quit command (and an extra command-line arg to suppress the REPL welcome message, which is automatically suppressed in the other cases due to stdin being closed)

note btw that the byte counts from ls include newlines, even on the two one-line files, and since q is fine with code files that are missing their last newline, the actual counts are 18, 21, and 24

ETA:

how do you feel about this?

```
$ q<<<'5 rotate 01100001011000100110001101100100b'
00101100010011000110110010001100b
$

```

is it valid? how would you count it? (the `b` is q's notation for a binary vector/bitstring. if you prefer, it would also work on the string version at the cost of an extra character)
> 1 votes

# Answer
# Python, 43 42 bytes

Takes shifts and data from stdin, returns shifted data in stdout. Input format is `<shift_amount>\n<data>`

```
a=-input();b=raw_input();print b[a:]+b[:a]

```
> 1 votes

# Answer
# Python 3, 40 Bytes

```
s,n=open(0);print(n[int(s):]+n[:int(s)])

```

Try It Online!

This is basically a port of Oberons answer, and takes the same input from stdin as his Python 2 solution:

```
in:
5
01100001011000100110001101100100
out:
00101100010011000110110010001100

```

this is also my first post on this site, happy to be here!
> 1 votes

---
Tags: code-golf
---