[Question]
  [
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](https://github.com/lmendo/MATL), score 4
```
&=Rz
```
[Try it online!](https://tio.run/##y00syfn/X802qOr/f/XEpMTE5MQkdQA "MATL – 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
```
[Answer]
# [Python](https://docs.python.org/2/), score 49
```
lambda S:sum(1+S.count(C)for[C]in	S)/2
```
[Try it online!](https://tio.run/##JYu9CoMwFEZnfYrLHUrE0lJHwSmDq5DROqQxsYH8SKLQ@vJppGf7ON9Zv9vbuyYJP8vumdBw@5o5sDbuljxqdhN@dxuhlfJhpJN2BavuDSb5kQJVh/UZlllCBO1gPOcVcAh@Cdxa7RYY9uMwMsIFaJbQe6MwX@APTm1ZrEG7DRSJVfoB "Python 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`
[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](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). 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.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 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!](https://tio.run/##nY2xDoIwFEV3vuKFRNMWG6MuRsJgHFxJHIGhlFKaQDFFYwrh2xFwMjEM3vHe887jVHI@DBLxghnS4E7pB9hofzgmQdf7r0KVAo09sTSg1Eak8bzEJ3Yb7Px@mOCKKY2w0zkw5m7GKkfujddGnGCVxTrW7gYkcv974WLsO1/qyfkxspQxztIZ@U2EppaGVZXSEsJn25aigTVc6kzAtS7zhcuFCT5ZIFjKM5HLJeI8j/3wBg)
[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
```
[Answer]
# [Haskell](https://www.haskell.org/), score 42
```
f l=sum[1|c<-l,d<-c:l,d==c]/2
```
[Try it online!](https://tio.run/##fYuxDoIwFEV/5aYxTBAjo6GTgys7YXiUFhvfa0kLC/Hfq/yA0znDOS/Kb8tcigPrvMtw@5iu4XruGnP/QWszXtsi5AM01uTDhguEVjgM6u@kaiiaiAxNp/YpLolEfFjQ78fBNqPCI84Wz8juTNRYvg "Haskell – Try It Online")
Anonymizing `\l->` gives the same score.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 6
```
;\ċ"⁸S
```
[Try it online!](https://tio.run/##y0rNyan8/9865ki30qPGHcH/kdgA "Jelly – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), score 34
```
s(O`.
M&!`^|(?<=(.))\1*
.
```
[Try it online!](https://tio.run/##K0otycxL/P@/WMM/QY/LV00xIa5Gw97GVkNPUzPGUItLD48UAA "Retina – 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.
[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!](https://tio.run/##hY49C8IwGAZn/RUPQUSpgl3VTA5du6vImzRpg/koSbsU/3t0zuJ4xw03UHora3PWOzqLPa@rNLt7/ZHXozhIzulZaYiLXr34KTsyHhxdwBrAGI2fsIEGI0EkSbBCtzH0kZwzvkc7L4tVCVvcQqfQBKvLvOQ/S4/p98TyFw "Haskell – 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.
[Answer]
## [J](http://jsoftware.com/), score 16
```
1#.,@(*+/\"1)&=
```
[Try it online!](https://tio.run/##y/r/P03B1krBUFlPx0FDS1s/RslQU832f2pyRr5CmoJ6YlJiYnJikjoXTABNofp/AA "J – 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.
[Answer]
# [R](https://www.r-project.org/), 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!](https://tio.run/##jZFNa8MwDIbv@xUmrIvUFkp6Gowcxg5jh0EPu5Ue7MTODI4dbAfqlv72zIn3wTpoJ4yNhJ5XL7IdlGSW2gB5y/27qV2ON6IcRK8rL42G/TKUnjLFoffi/s28aA97RAyz@ewYFsVptR4E5JRRWlE2wpBvrGksbVupG7LpDwfFHbkjT6bm5NkokZrSTVKkhLKq5qL5TB7T@yqdG0/XyamQ/VhD17cAurTRnTPWA1fgvHWdktHkMo6IcatwtZ6DXhSI2bnA8Sr8MM7Q3wqnixK/@e222O3@p/G14zMDExgiOG36L3j9bzIcPgA "R – 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.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score 6
```
{γ€gLO
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@tzmR01r0n38kZgA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 5
```
ĠJ€ẎS
```
[Try it online!](https://tio.run/##y0rNyan8///IAq9HTWse7uoL/o/MAQA "Jelly – Try It Online")
Thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for -2 (previously on [his answer](https://codegolf.stackexchange.com/a/127265/41024))
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score 6
1 byte thanks to isaacg.
```
+F/V._
```
[Test suite.](http://pyth.herokuapp.com/?code=%2BF%2FV._&test_suite=1&test_suite_input=%22s%2B0%2FV._%22%0A%22abaacab%22%0A%22Programming+Puzzles+%26+Code+Golf%22%0A%22%22%0A%22+++++++%22%0A%22abcdefg%22%0A%22aA%22&debug=0)
## 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.
```
[Answer]
# [J](http://jsoftware.com/), score: ~~14 12~~ 11
```
$+/@,2!1#.=
```
[Try it online!](https://tio.run/##y/pfZmulUGtloGBl8F9FW99Bx0jRUFnP9r8mV0q@gnqarZ66ThlXanJGvkKagnpiUmJicmKSOlwgoCg/vSgxNzczL10hoLSqKie1WEFNwTk/JVXBPT8nDaEQwVKAALhA2X8A)
[Answer]
# [Jelly](https://github.com/DennisMitchell/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!](https://tio.run/##y0rNyan8//9I9@EJj5rWBAa5Bf9H4QEA "Jelly – Try It Online")
[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!](https://tio.run/##pY3dDoIgAIVfhdnaAKFlW92Qvohx4QCBTakh2sT57AbP0N3Z@fmOoFqI42SdGGapwHMK0r4vpjk0FKbzeEKbdQGs7e3@4PW2k1hf2dfYQcGURVpTurZ4KkvOvAqzdyCy/Rg762DedV4LkkEA46SXROthNpsKfXxq9LA4y5criM720lYcoQT46/4H "C (gcc) – 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.
[Answer]
# [Perl 6](https://perl6.org), score ~~61 56 53 46~~ 44
```
(1 X..*.comb.Bag.values).flat.sum
```
[Try it](https://tio.run/##hY9PT8MwDMXv@RRPY1o2NEUMTQMp4gAcuO7AgdvkpklXKSFV3UzaEJ@99I@gXBC@2P7p2c@ubO13bWKL004ZLcIZCxO5wUO73OBNqWtlYsjUExXqRD5ZXinnqVGcQqsF0xny9WhhYm5RNmy9w5EYhGFLdJDrsZT/7pNaVKkTdllwypCXXPnOYIn5ASt8CKD3U1V38xryD5/5QYtPIb6HJWVEhjKpcYXN9ofP9nUsagqhfC@wT5eLt4wFnvs/XqJ3s16/vZv0A7iZeowx4Nv7iVNmcuuKgf8ap8dR2X4B "Perl 6 – Try It Online")
```
{sum flat 1 X.. .comb.Bag.values}
```
[Try it](https://tio.run/##hY9Pa8MwDMXv/hSPrtQbFLOO0g7CDtsOu/aww25Fduw0YM8higtt6WfP8octu4zpIunHk55U2dpv2sQWx40ymQgnLEzkBk/thVOA89RghQ@loEwMWr1QoY7kk@Vry3SCfD9YmJhblA1b73AgBmHYER3kcizlv9tkJqrUCbssOGnkJVe@M7jFfI87XATQ@6mqu3gJ@YfPfJ@JqxDfw5I0kSEtM9xgtf7hs10di5pCKD8L7NL57C1jgdf@j7fo3azXr7eTfgD3U48xBvzwOHHSJreuGPivcXoele0X "Perl 6 – Try It Online")
```
{sum flat 1 X.. values(.comb.Bag)}
```
[Try it](https://tio.run/##hY9Pa8MwDMXv/hSPrtQtFLOO0g5CD9sOu/aww25Fcew0YNchigtt6WfP8octu4zpIunHk55UmsptmsgG543SifAXzHTgGrvmxtHDOqqxwqdSOJOLhudKB5@qV8oX94bpAvlxNNAhMyhqNs7iSAxCvyRYyOVQyv/XyUSUsVW2WXBMkRVcutZhjukBC9wE0Bmqsr15CfmH0fSQiLsQ38OSUiJNqUzwgNX6h0/2Vcgr8r445djH69UZxgxv3SPvwdlJp19vR30PHsceQ/T46XnklOrM2Lznv8bpZVA2Xw "Perl 6 – Try It Online")
```
{[+] flat	1	X.. values(.comb.Bag)}
```
[Try it](https://tio.run/##hY9PawIxEMXP5lM8VIyihFrEFhYP2kOvHnoolCKTbLIuZM2y2Qgqfvbt/qHdXkrnMjM/3sybyXVh11XwGue1UBHLLpgo50tsqtvH/BPGUjlYDt6FwJls0H4qlMuk2FEyu1eeLuBvRw3lYo209NoaHMmD0C5xBnzRlfz/dTxieaiVdWY@SMSpz23tMMX4gBluDGgMRV7fvAD/w2h8iNidse9hTpJIkeQRRliufvhwX7ikoCxLTwn24Xq12mOCl@aRV2fNsNGvnnp9Cx76Hl20@PG55yRVrE3S8l/jtO2U1Rc "Perl 6 – Try It Online")
```
{[+] flat	1	X.. values(bag
.comb)}
```
[Try it](https://tio.run/##hY9PawIxEMXP5lM8rBilEmoRW1g8lB569dCDIEUm2WRdyJplsxFU/Ozr/qFdL9K5zMyPN/Nmcl3YZRW8xnEpVMSyE8bK@RKr6rJ9/oGxVA7mg40QOJIN2k8kJUwol8nptfJ0Av/eaygXa6Sl19ZgTx6Edokz4LOu5P@v4xHLQ62sM/NBIk59bmuHCUY7THFhQGMo8vrmGfgDo9EuYlfGfoc5SSJFkkd4wnzxx4frwiUFZVl6SLAO57PVHmN8No98OWuGjX7x1utb8NL36KLFr@89J6libZKW343TR6esbg "Perl 6 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 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!](https://tio.run/##rVA9a8MwEN39K44MQeqHTEqggysvLu3SQiBDZ1mRg0CWEn3E1MG/3ZWMm0K7ZOgbjuM@3r173N1zY8UIEcFJvYftp/OiJW9SH4ssS3WumHOwsWZvWTtVzlNMcJ55yeFk5A7emdQIX1o/Qwkz7UvQ/Ml5Gy/dgdS@hAZoNta0rMmzdF5q7hEmW6FETHpank/MQkdrUpmgPTrQ8kBpjwsrfLAauhvU3a5w/lAMcSu0CI@z6l@HK6OdUYJ8WOlFfE6gBi1YzRhn9QLjAvIcVuurN2c32uTYJvS9Eg6WUJmdgFejmm/G9ePVjH/d/0dTkp6LkmHKhvEL "C# (.NET Core) – Try It Online")
The score includes the following:
```
using System.Linq;
```
[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).
[Answer]
# [Julia 0.6](http://julialang.org/), 45 bytes, Score: 77
Inspired by the MATL solution:
```
f(w)=sum(UpperTriangular([z==j for z=w,j=w]))
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/TaNc07a4NFcjtKAgtSikKDMxL700J7FII7rK1jZLIS2/SKHKtlwny7Y8VlPzf3ByflGqgq1CQVFmXolGmoYSSdqVgCYAAA "Julia 0.6 – Try It Online")
A less pretty solution, using counts:
[Julia 0.6](http://julialang.org/), score: 82
```
F(w)=sum(l->[l+1]l/2,count(x->x==i,w)for i=Set(w))
```
[Try it online!](https://tio.run/##yyrNyUw0@//fTaNc07a4NFcjR9cuOkfbMDZH30gnOb80r0SjQteuwtY2U6dcMy2/SCHTNji1BKhY839BUSZQ1k1DiXS9SkDtAA "Julia 0.6 – Try It Online")
Thanks to Guiseppe for pointing out the scoring and for tips.
These comments helped me loads.
[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.](https://tio.run/##lZE/b4MwEMXn8ilOGSojGlRVaociKkUMnRpFykgYDmMoFOzkbGj@iM9OTeiYSsWyhzvfe/eTXoUdLqvsa@A1ag0fWMqLA1BKIyhHLmA9ltcGcMY/keIEtBvYZm@fvdqgKTmsQUIIw3H5dhlnq/Dx4RAnoRTfozZ@en5JglwR65DuotejW3mh5x3iKAlImJakUwX9EEyW@zatreWvc6fKDBoLxraGSllYAHQnqu1JG9H4qjX@3n6ZWjLpc7bAFJFjuvCNiizyighPzHWv2H@rNqQKwqaxO2DTns@10HAPkcoEvKs6n@k2cxymM1OFKc9EXsxVrWYK/pPqztyKdSdtrje39U4//AA)
```
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
```
[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](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
[Try it online!](https://tio.run/##pc/NioMwFAXgvU9xCLQojNL9TLPoMHQzC6FL6yLVKBlMYvMzVOm720RhXmB2h8vHufd2Nm@04csycIcfzMcLvxeN9sqdJogW85PGifXyNKWdV3jk9FtYFyfVoSisavGos6X6@FLOTKUWytE6iW2SCQVm@l8cE1SEvIOwG2MNu8VYGt0bJqVQPUo/zwO32ONTtxxnPXSR/O8kUid4UkQq2YhVCjV6h5wiXdNbqF9Dlv1Z4bjZ8MiEsQEnwGjCW50C2dmr2wkSgHUbyJDGhVsONYflBQ)
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.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), Score: 4
```
≠+´⊒
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omgK8K04oqSCgo+4ouI4p+cRsKoIOKfqCLiiaArwrTiipIiCiJhYmFhY2FiIgoiUHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZiIKIiIKIiAgICAgICAiCiJhYmNkZWZnIgoiYUEi4p+p)
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.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), score 15
```
+/1 1⍉+\∘.=⍨⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOb@45L@2vqGC4aPeTu2YRx0z9Gwf9a541DsPJPtfAQxAirgSkxITkxOTuJCEsOoDAA "APL (Dyalog Unicode) – Try It Online")
`⍞` get text input
`∘.=⍨` equality table with self
`+\` cumulative sum across
`1 1⍉` diagonal (lit. collapse both dimensions into dimension one)
`+/` sum
[Answer]
# [Retina](https://github.com/m-ender/retina), score ~~68~~ ~~45~~ 43
```
s`(.)(?<=((\1)|.)+)
$#3$*
1
```
[Try it online!](https://tio.run/##K0otycxL/P@/OEFDT1PD3sZWQyPGULNGT1Nbk0tF2VhFi8sQryQA "Retina – 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.
[Answer]
# [PHP](https://php.net/), 45 bytes, Score 78
```
WHILE($x=ORD($argn[$v++]))$y+=$$x-=-1;echo$y;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nqx7u4enjqqFSYesf5KIBFotWKdPWjtXUVKnUtlVRqdC11TW0Tk3OyFeptFa3/k@S@v//AQ "PHP – Try It Online")
# [PHP](https://php.net/), 46 bytes, Score 79 Bytes
```
WHILE(~$xy=$argn[$vz++])$su-=-$$xy+=1;echo$su;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nqx7u4enjqlGnUlFpCxaJVimr0taO1VQpLtW11VUBimvbGlqnJmfkA0Ws1a3/k6bh/38A "PHP – Try It Online")
# [PHP](https://php.net/), 56 bytes, Score 92
```
FOREAch(COUNT_CHARS($argn)as$z)WHILE($z)$y+=$z--;echo$y;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nq@7mH@TqmJyh4ewf6hcS7@zhGBSsAZbSTCxWqdIM9/D0cdUAMlQqtW1VqnR1rVOTM/JVKq3Vrf@Tq/X//695@brJickZqQA "PHP – Try It Online")
[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
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 39 bytes, Score 69
```
@(a)sum((b=hist(a,unique(1*a))).^2+b)/2
```
[Try it online!](https://tio.run/##jc0xCgIxEEDRq0wjk9FVcVsRBI@gpQiT7AQDmrjJZGFPHxttrOw/7yenPElrR8NU6tMYe7iHooa7GsNYxeyWTESbW7@ytO3beOBY9v6VQ1RvcDHAGs4uZQGfMpzSINeI3WjwTxCJfrSLFAXHRQCRLbNjiwiaYJIc/Ay@RqchRX4EnT@zb0fU3g "Octave – 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.
[Answer]
# Octave , score ~~77~~ 31 bytes
\*same as @LuisMendo 's [MATL answer](https://codegolf.stackexchange.com/a/127290/62451).
```
@(a)nnz(triu(a==a'))
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRMy@vSqOkKLNUI9HWNlFdU/N/mm1iXrE1V5qGEjZpJU2QTGJSYmJyYpKS5n8A "Octave – Try It Online")
Previous answer:
```
@(d,g=accumarray(+d',1)-(0:254))sum(g(g>0));
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNFJ902MTm5NDexqCixUkM7RV3HUFNXw8DKyNREU7O4NFcjXSPdzkBT0/p/mm1iXrE1V5qGEinalDRBOhKTEhOTE5OUNP8DAA "Octave – Try It Online")
]