title: Indexize a number

text:
# Question
Title: Indexize a number
Given a string of digits or an integer as input, you will have to indexize it.

This is how you modify the input. We will use `30043376111` as an example:

First, find the sum of the indices of each occurrence of the respective digits:

```
0: 1 + 2 = 3
1: 8 + 9 + 10 = 27
3: 0 + 4 + 5 = 9
4: 3
6: 7
7: 6

```

Then, construct a new integer or string where the digits above go in the order of the sums of their indices. In the case that multiple digits yield the same sum, the smaller digit comes before the larger one:

```
047631

```

Finally, remove any leading zeroes, and return or print the result:

```
47631

```

You must write a program or function which returns or prints the input indexized.

This is , so shortest code in bytes wins!

More test cases can be added if requested.

# Answer
# k, 7 bytes

```
.<+/'=$

```

online repl

```
  $30043376111 / convert to string($)
"30043376111"
  =$30043376111 / group(=) - return a mapping (dict) from unique chars to indices
"304761"!(0 4 5
 1 2
 ,3
 ,6
 ,7
 8 9 10)
  +/'=$30043376111 / sum(+/) each(') value in the dict
"304761"!9 3 3 6 7 27
  <+/'=$30043376111 / grade(<) ascending values - return keys from the dict
"047631"
  .<+/'=$30043376111 / execute(.) the string - convert it to a number
47631

```

Juxtaposition of functions is composition, so no explicit parameter or input is required.
> 2 votes

# Answer
# , 14 bytes

```
~.".@/:1#.I.@=

```

Accepts a string, returns a number.

Attempt This Online!

```
~.".@/:1#.I.@=
          I.@=  NB. = makes a boolean table of occurrences, each row is a unique item
            @   NB. monadic atop, f@g y => f g y
          I.    NB. returns indices of 1s in each boolean list from =
       1#.      NB. sums each resulting list
~.              NB. returns unique items from input
  ".@/:         NB. /: sorts x by y
    @           NB. dyadic atop, x f@g y => f x g y
  ".            NB. eval resulting indexized string

```
> 4 votes

# Answer
## Haskell, 69 bytes

```
import Data.List
f x=0+read(nub$sortOn(\d->(sum$elemIndices d x,d))x)

```

Takes a string, returns a number. Usage example: `f "30043376111"` -\> `47631`. Try it online!

Pretty straight forward: sort the digits of the input string first on the sum of their indices and the by the digit itself (-\> pairs of (sum ...,d)), remove duplicates and convert to a number to remove leading `0`. The `0+` is needed to get the types right.
> 3 votes

# Answer
# Stacked, 59 bytes

```
:@q uniq[:q\eq q size:>*sum,]map[-1#]sortby[0#]map''#`'^0'-

```

Try it online!

This takes a character string (like `$'1231231'`) as input from the top of the stack, and leaves a string on the stack.

## Explanation

```
:@q uniq[:q\eq q size:>*sum,]map        stack: (str)
:                                       stack: (str str)
 @q                                     stack: (str)        ; store as `q`
    uniq                                stack: (str')       ; de-duplicate
        [                   ]map        map the inner over each element
         :                              stack: (chr chr)
          q\eq                          stack: (chr q')     ; `q'` is where equality occurs
               q size:>                 stack: (chr, q', k) ; `k` is range from 0, size(q')
                       *sum             stack: (chr, k')    ; `k'` is sum of indices
                           ,            stack: ((chr, k'))

```

Now we are left with pairs of (chr, sum of indices).

```
[-1#]sortby[0#]map''#`'^0'-
[   ]sortby                    sort by the inner function
 -                             vectorized subtraction of two pairs
  1#                           use the second element as the comparison
           [0#]map             get the first element of each row
                  ''#`         join by the empty string
                      '^0'-    remove all leading zeroes

```
> 3 votes

# Answer
# 05AB1E, ~~29~~ 28 bytes

*-1 thanks to Riley*

```
TFN¹SQDg<ÝsÏON‚}){vyD0å_i1è,

```

Try it online!

```
TFN            }             # Loop from 0 to 9.
   ¹SQ                       # Push 1 if index is same as `y`.
      Dg<ÝsÏ                 # Push index of the number instead of 1.
            ON‚              # Sum, combine with current `y`.
                ){           # Collect, sort 'em.
                  vyD0å_i1è, # Only print the ones with a count above 0.

```
> 3 votes

# Answer
# JavaScript (ES6), 98 bytes

```
n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``

```

Takes a string `n`, then converts it to a Set and then to an Array of distinct digits. Sorts these digits in numerical order, then sorts again according to sums of indices. Concatenates the sorted Array to a String, and finally converts to a Number to remove leading zeros.

```
f=
n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``

console.log(f('30043376111'))
```
> 3 votes

# Answer
# Jelly, 10 bytes

```
Ġ’S$ÞịDFQḌ

```

**Try it online!**

Takes and returns an integer.

### How?

```
Ġ’S$ÞịDFQḌ - Main link: n            e.g. 30043376111
Ġ          - group indices of n by value  [[2,3],[9,10,11],[1,5,6],[4],[8],[7]] (implicitly treats the number as a decimal list)
    Þ      - sort that by:
   $       -     last two links as a monad:
 ’         -         decrement (since Jelly is 1-indexed)
  S        -         sum                  [[2,3],[4],[7],[8],[1,5,6],[9,10,11]] (this leaves those indices of lower value to the left as required)
      D    - decimal list of n            [3,0,0,4,3,3,7,6,1,1,1]
     ị     - index into                   [[0,0],[4],[7],[6],[3,3,3],[1,1,1]]
       F   - flatten                      [0,0,4,7,6,3,3,3,1,1,1]
        Q  - unique                       [0,4,7,6,3,1]
         Ḍ - cast to a decimal number     47631

```
> 3 votes

# Answer
# PowerShell, 88 bytes

```
$a=@{};[char[]]"$args"|%{$a[$_]+=$i++};+-join(($a.GetEnumerator()|Sort value,name).Name)

```

Try it online!

Sets an empty hashtable `$a`, then casts the input `$args` as a `char` array, and loops through each element `|%{...}`. We set the value at "the current element" of `$a` to be incremented by `$i++`, to count up our input's indices. For example, for input `300433766111`, the first loop `$a[3]` gets `+=0`; the next loop, `$a[0]` gets `+=1`; etc.

Next, we need to `Sort` our hashtable. Unfortunately, due to an internal language quirk, this means we need to `$a.GetEnumerator()` before we can do the actual sorting. We sort by `value`, then by `name`, to satisfy the requirement of smaller digits get sorted first. We pull out the `.Name`s thereof (in sorted order), `-join` them together into a string, and cast that string as an int `+` to remove leading zeros. That's left on the pipeline and output is implicit.
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
ΣISQā<*O}Ùï

```

Try it online.

Could be 9 bytes if 1-based indexing is allowed by replacing `ā<*` with `ƶ`, in which case `4` would come before the `0` in the example, because `0: 2 + 3 = 5` and `4: 4`: try it online.

**Explanation:**

```
Σ         # Sort the digits of the (implicit) input by:
 I        #  Push the input
  S       #  Convert it to a list of digits
   Q      #  Check for each if it's equal to the current digit (resulting in 1s/0s)
    ā<*   #  Multiply each check by its 0-based index:
    ā     #   Push a list in the range [1,length] (without popping)
     <    #   Decrease each by 1 to make it the range [0,length)
      *   #   Multiply the values at the same indices in the two lists
       O  #  Sum the lists together
}Ù        # After the sort-by: uniquify the digits
  ï       # Cast it to an integer to remove potential leading 0s
          # (after which the result is output implicitly)

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 77 bytes

```
{⍎⊃{⍺[⍋⍵]}/{(⊂⊂⍋⊃⍵)⌷¨⍵}↓⍉{⍺(+/⍵-1)}⌸⍵}

```

Try it online!
> 2 votes

# Answer
# Vyxal, ~~85~~ 62 bits1, ~~10.625~~ 7.75 bytes

```
µ?f=T∑;Uṅ⌊

```

Try it Online! (link is to bitstring)

*-2.875 bytes (2 characters) thanks to @lyxal*

#### Explanation

```
µ?f=T∑;Uṅ⌊  # Implicit input (as a string)
µ     ;     # Sort input string by:
 ?f         #  List of characters of input
   =        #  Equals the current character?
    T∑      #  Sum of truthy indices
       Uṅ⌊  # Uniquify and convert to integer
            # Implicit output

```

Old:

```
fDÞzµ∑;İfU₀β  # Implicit input
fD            # Convert to digit list and duplicate
  Þz          # Group by indices
    µ∑;       # Sort by sum
       İfU    # Index in, flatten, uniquify
          ₀β  # Convert from digit list
              # Implicit output

```
> 2 votes

# Answer
# Thunno 2, 10 bytes

```
Þ$d=VS;UJN

```

Port of my Vyxal answer (suggested by @lyxal)

#### Explanation

```
Þ$d=VS;UJN  # Implicit input
Þ     ;     # Sort the input string by:
 $d=        #  Vectorised equality with the input string's characters
    VS      #  Sum of truthy indices of that list
       UJN  # Uniquify, join, and convert to integer
            # Implicit output

```
> 2 votes

# Answer
# PHP, 103 Bytes

```
for(;$i<strlen($a="$argv[1]");)$r[$a[$i]]+=$i++;ksort($r);asort($r);echo ltrim(join(array_keys($r)),0);

```
> 1 votes

# Answer
# Python 2, ~~102~~ 92 bytes

*Thanks to Ben Frankel for saving 10 bytes!*

```
a={}
for i,j in enumerate(input()):a[j]=a.get(j,0)+i
print int(''.join(sorted(a,key=a.get)))

```

Try it Online!

Takes input as a string and outputs an integer. Uses a dictionary to store the sum of indexes, then sorts it by value. Converts to an integer to strip off leading zeroes because `int` is shorter than `.lsplit('0')`.
> 1 votes

# Answer
# Python 3.5, ~~86~~ 85 bytes

Thanks @Ben Frankel for saving a byte:

```
f=lambda s:int(''.join(sorted({*s},key=lambda d:sum(i*(c==d)for i,c in enumerate(s)))))

```

Old code:

```
lambda s:int(''.join(sorted({*s},key=lambda d:sum(i for i,c in enumerate(s)if c==d))))

```

Anonymous function taking a string of digits and returning an integer
> 1 votes

# Answer
# Pip, 18 bytes

```
+J:$+(a@*_)SKSNUQa

```

Takes the number as a command-line argument. Try it online!

### Explanation

```
                    a is 1st cmdline arg (implicit)
               UQa  Get unique digits in a
             SN     Sort (numerically)
           SK       Then sort with this key function:
      a@*_           Find all indices of argument in a
   $+(    )          and sum them
 J:                 Join the resulting list back into a string (: is used to lower the
                    precedence of J)
+                   Convert to number (eliminates leading 0)
                    Print (implicit)

```
> 1 votes

# Answer
# Scala, ~~123~~ 104 bytes

```
(_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt

```

Example (using Scala REPL):

```
scala> (_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt
res0: String => Int = <function1>

scala> res0("30043376111")
res1: Int = 47631

```

Pretty straightforward, using tuple as sorting predicate for secondary sort.
> 1 votes

# Answer
# Pyth, 9 bytes

```
sosxNcQ1{

```

Try it online

Takes a string of digits as input.

```
sosxNcQ1{
sosxNcQ1{Q    Implicit variable introduction
        {Q    Unique digits
 o            Order by
     cQ1      Chop input into list of individual characters.
   xN         Find all indexes of the digit in question in the list.
  s           Sum
s             Convert string to integer.

```
> 1 votes

# Answer
# Ruby, 96 bytes

I'm sure this can be golfed more.

```
->a{(0..9).map{|n|[(0...a.size).select{a[_1]==n}.sum,n]}.select{_1[0]>0}.sort.map{_2}.join.to_i}

```

Attempt This Online!
> 1 votes

# Answer
# Japt v2.0a0 `-N`, 10 bytes

```
ñ ñ@ðX xÃâ

```

Try it

Input as a string

Explanation:

```
ñ ñ@ðX xÃâ
ñ          # Sort the digits by value
  ñ@    Ã  # Stable-sort the digits by this function:
    ðX     #  Find all indices where it appears in the input
       x   #  Sum them
         â # Remove repeated characters

-N         # Convert the string to number (removes leading 0)

```
> 1 votes

# Answer
# K (ngn/k), ~~16~~ 7 bytes

```
.<+/'=:

```

Try it online!

*Down 9 bytes thanks to ovs for the sum tip!*

A pretty literal implementation of the challenge. Takes a string and output an integer.

Explanations:

```
.<+/'=:  Main function. Takes implicit input with :
     =   Group, creates a dictionary with characters as
         the keys and their occurances position as the
         values
    '    In each of the key's values...
  +/     Sum
 <       Sort by ascending order
.        Evaluate

```
> 1 votes

# Answer
## C#, 245 bytes

```
using System.Linq;s=>{var a=new int[10];for(int i=0,l=0;i<10;i++){a[i]=-1;while((l=s.IndexOf(i+"",l+1))!=-1)a[i]+=l;}return string.Concat(a.Select((c,i)=>new{c,i}).OrderBy(o=>o.c).ThenBy(o=>o.i).Where(o=>o.c>-1).Select(o=>o.i)).TrimStart('0');};

```

Not happy with how long it ended up being and it can probably be shorter but this is what I ended up with.
> 0 votes

# Answer
# Perl 6,  ~~65 61~~  52 bytes

```
{+[~] {}.push(.comb.map:{$_=>$++}).sort({.value.sum,.key})».key}

```

Try it

```
{+[~] {}.push(.comb.antipairs).sort({.value.sum,.key})».key}

```

Try it

```
{+[~] .comb.antipairs.Bag.sort({.value,.key})».key}

```

Try it

## Expanded

```
{      # bare block lambda with implicit parameter ｢$_｣

  +    # turn the following into a Numeric
  [~]  # reduce the following using &infix:<~> (join)

    .comb              # list of digits from ｢$_｣ (implicit method call)
    .antipairs         # get a list of ｢value => index｣ pairs from above list
    .Bag               # combine them together (does the sum)
    .sort(
      { .value, .key } # sort it by the sum of indexes, then by the digit
    )».key             # get the list of digits from that
}

```
> 0 votes

# Answer
# Scala, 131 bytes

Golfed version. Try it online!

```
def f(x:String)=scala.collection.immutable.SortedSet(x:_*)(Ordering.by((d:Char)=>(x.indices.filter(x(_)==d).sum,d))).mkString.toInt

```

Ungolfed version. Try it online!

```
import scala.collection.immutable.SortedSet

object Main {
  def main(args: Array[String]): Unit = {
    println(f("30043376111"))
  }

  def f(x: String): Int = {
    val sortedUnique = SortedSet(x: _*)(Ordering.by((d: Char) => (x.indices.filter(x(_) == d).sum, d)))
    sortedUnique.mkString.toInt
  }
}

```
> 0 votes

---
Tags: code-golf, string, number
---


title: Simple String Reflection

text:
# Question
Title: Simple String Reflection
Let's start by defining a **reflection** of a character in a string:

> Given a string with distinct lowercase alphabetical letters with no spaces such as `abcdefg`, define a reflection of a letter in the string `c` as moving it (without changing the order of any other letter) to a new place in the string such that the number of letters originally to the right of it is now the number of letters to the left of it.

Thus, a reflection of the letter `c` in `abcdefg` would be `abdecfg`. *Explanation: there were 4 letters to the right of `c` and now, there are 4 letters to the left of `c`.*

Some more examples:

> Reflecting the character `e` in `myfriend` would form the string `myefrind`
>
> Reflecting the character `a` in `axyz` would form the string `xyza`.
>
> Reflecting the character `b` in `abc` would form the string `abc`.
>
> Reflecting the character `d` in `d` would form the string `d`.
>
> Reflecting the character `e` in `ef` would form the string `fe`.

For more information or to try out some test cases, here is a (somewhat long) program I wrote in C++.

## The Challenge

Given a string with distinct lowercase letters, go through each character alphabetically and "reflect" it in the string.

*Clarifications: The letters in the string are from `a-z`, there are no spaces, the letters are unique, and the string is at least 1 letter long and at most 26 letters long.*

## Examples

> Input: `dcba`. Output: `dcba`.

*Reason: First, reflect the `a` as it is the character in the string that comes earliest in the alphabet. You will get `adcb`. Then, reflect the `b` as it comes next in the alphabet, to get `badc`. Then, reflect the `c` to get `cbad`, and then the `d` to get `dcba`.*

---

> Input: `myface`. Output: `fyecma`.

*Hint: Go through the letters in the order `a, c, e, f, m, y`.*

---

> Input: `a`. Output: `a`.

---

> Input: `acb`. Output: `bac`.

---

> Input: `cwmfjordbankglyphsvextquiz`. Output: `ieabhqzugdltkfnvpjxsormycw`.

## Scoring

* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.
* Accepting ~100 hours after posting.

## Current Winner

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </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><script>var QUESTION_ID = 162891; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 8 votes
# Brain-Flak, 188 bytes

```
<>((((()()()){}){}()){}){(({}[()])<({}[(((((()()()()()){}){}){})()){}{}])<>{<>(({})<({}<>({}<>))((){[()](<{}>)}{}){{}(<({}<([]<<>{({}<>)<>}<>>){({}[()]<({}<>)<>>)}{}>)>)}{}>)<>}<>{}<>>)}<>

```

Try it online!

In addition to the reflections described in the challenge specification, this code also reverses the string exactly 26 times. This has no effect on the final output.

```
# Push 26
<>((((()()()){}){}()){})

# Do 26 times:
{(({}[()])<

  # Subtract 122 from counter to get negative lowercase letter
  ({}[(((((()()()()()){}){}){})()){}{}])

  # For each character in string:
  <>{

    # Keep a copy of pivot letter on the third stack
    <>(({})<

    # Move next letter to other stack and compare to pivot
    ({}<>({}<>))

    # If letters are equal:
    ((){[()](<{}>)}{}){

      # Keep current letter separate from this transformation
      {}(<({}<

      # While keeping a copy of current stack height:
      ([]<

        # Move all letters to one stack
        <>{({}<>)<>}<>

      >)

      # Move a number of letters equal to old stack height back
      {({}[()]<({}<>)<>>)}{}

      >)>)

    }{}>)<>

  }

  # Destroy pivot letter
  <>{}<>

>)}

# Switch stack for output
<>

```

# Answer
> 7 votes
# 05AB1E, ~~20~~ 17 bytes

```
{vð.øy¡€áÂ€gsJ£yý

```

Try it online!

**Explanation**

With example for the first iteration of `myface`

```
{v                  # for each char y in sorted input
  ð.ø               # surround current string with spaces
                    # STACK: ' myface '
     y¡             # split at current letter
                    # STACK: [' myf', 'ce ']
       €á           # remove non-letters
                    # STACK: ['myf','ce']
         Â€g        # get the length of each string in the pair, reversed
                    # STACK: ['myf','ce'], [2,3]
            sJ      # join the pair back to a string
              £     # split into 2 pieces of the calculated sizes
                    # STACK: ['my','fce']
               yý   # join on the current char y
                    # STACK: 'myafce'

```

The string is surrounded with spaces each iteration as splitting on the first or last letter of the string would result in a length-1 list otherwise and the merge wouldn't include that letter.

# Answer
> 5 votes
# Pyth, ~~18~~ ~~16~~ ~~19~~ 16 bytes

```
VSQ=QXx_QN-QNN)Q

```

Try it here

### Explanation

```
VSQ=QXx_QN-QNN)Q
VSQ           )       For each character (N) in the sorted input (Q)...
          -QN         ... remove the character from Q...
      x_QN            ... get the reflected position...
     X       N        ... insert N...
   =Q                 ... and save the result into Q.
               Q      Output the final result.

```

# Answer
> 4 votes
# Python 3, ~~80~~ 73 bytes

Thanks to Esolanging Fruit for reminding me that functions can return by modifying their argument.

```
lambda x:[x.insert(len(x)+~x.index(i),x.remove(i)or i)for i in sorted(x)]

```

Try it online!

Takes input as a list of characters.

# Answer
> 4 votes
# Python 2, 70 bytes

```
def f(t):
 for c in sorted(t):i=t.index(c);l=len(t)+~i;t[l:l]=t.pop(i)

```

Try it online!

Modifies the input list

# Answer
> 3 votes
# JavaScript, ~~85~~ ~~80~~ 79 bytes

<sup>-6 bytes thanks to @DanielIndie</sup>

```
a=>[...a].sort().map(i=>a.splice(s=a.indexOf(i),1)&&a.splice(a.length-s,0,i))&&a

```

Try it online!

# Answer
> 3 votes
# Ruby, 51 bytes

```
->s{s.sort.map{|c|s.insert~s.index(c),s.delete(c)}}

```

Try it online!

Takes an array of chars

Returns by modifying the input

# Answer
> 3 votes
# Java 8, ~~140~~ ~~96~~ ~~92~~ ~~88~~ ~~87~~ 85 bytes

```
s->{for(char c=9;++c>0;){int i=s.indexOf(c);if(i>=0)s.add(s.size()+~i,s.remove(i));}}

```

-44 bytes creating a port of *@TFeld*'s Python 2 answer.
-6 bytes thanks to *@OlivierGrégoire*.

Modifies the input List instead of creating a new one.

**Explanation:**

Try it online.

```
s->{                     // Method with ArrayList<Character> parameter and no return-type
  for(char c=9;++c>0;){  //  Loop over all characters known
                         //  (except for the first 9 unprintables)
    int i=s.indexOf(c);  //   Index of the character, or -1 of it isn't present
    if(i>=0)             //   If the current character is present in the List
      s.add(s.size()+~i,s.remove(i));}}
                         //    Change the position of this character to index `l-i-1`,
                         //    (where `l` is the size of the input-List)

```

# Answer
> 3 votes
# Retina 0.8.2, 61 bytes

```
$
a
{`(.)(.*)\1$
$2$.`$*_$1$1
+`(.)_(_*.)
$2$1
}T`_l`l!`.$
!

```

Try it online! Link includes test cases. Explanation:

```
$
a

```

Start the loop at `a`.

```
{`(.)(.*)\1$
$2$.`$*_$1$1

```

If the input contains the current letter, move it to the end, with a string of `_`s representing its original position.

```
+`(.)_(_*.)
$2$1

```

For each `_` move the letter back one character.

```
}T`_l`l!`.$

```

Increment the letter. After `z` change it to a `!` so it doesn't match anything and the loop ends.

```
!

```

Delete the `!`.

# Answer
> 2 votes
# , ~~73~~ ~~72~~ 69 bytes

```
function(s){for(x in sort(s))s=append(s[x!=s],x,match(x,rev(s))-1);s}

```

Try it online!

Inputs and outputs a vector of characters.

# Answer
> 2 votes
# Red, 96 94 bytes

2 bytes saved thanks to Kevin Cruijssen

```
func[x][foreach c sort copy x[i:(length? x)+ 1 - index? find x c insert at replace x c""i c]x]

```

Try it online!

More readable:

```
f: func[x][
    foreach c sort copy x[                  ; for each symbol in the sorted input
       i: (length? x) + 1 - index? find x c ; find its index and reflect it
       insert at replace x c "" i c         ; remove it by replacing it with an empty char
                                            ; and insert the symbol at its new index
    ]
    x                                       ; return the transformed string
]

```

# Answer
> 2 votes
# Japt, ~~23~~ 22 bytes

```
¬n rÈ+S kY iYJ-XbY)x}U
¬n                     // Split the input into chars and sort it.
   r                }U // Then reduce the result with initial value of the input.
    È+S                // Append a space for replacing edge cases and
        kY             // remove the current char from the string.
           iY          // Insert it back
             J-XbY     // at the calculated index,
                  )x   // and remove the unnecessary space once we're done.

```

Saved one byte thanks to Oliver.
Try it online!

# Answer
> 2 votes
# Jelly,  ~~12~~  11 bytes

```
W;ṢḟṁUṣ¥jʋ/

```

A monadic link accepting a list of characters and returning a list of characters.

**Try it online!**

### How?

```
W;ṢḟṁUṣ¥jʋ/ - Link: list of characters V  e.g. "myface"  ...i.e. ['m','y','f','a','c','e']
W           - wrap V in a list                 ["myface"]
  Ṣ         - sort V                           ['a','c','e','f','m','y']
 ;          - concatenate                      ["myface",'a','c','e','f','m','y']
          / - reduce with:
         ʋ  -   last four links as a dyad:
            -   (i.e. start with "myface" on the left and 'a' on the right
            -         2nd iteration has that result on the left and 'c' on the right
            -         and so-forth)            e.g. left = myface, right = 'a'
   ḟ        -     filter out (right from left)      "myfce"
       ¥    -     last two links as a dyad:
     U      -       upend left                      "ecafym"
      ṣ     -       split at occurrences of right   ["ec","fym"]
    ṁ       -     mould (ḟ(x,y)) like (Uṣ¥(x,y))    ["my","fce"]
         j  -   join with right                   "myafce"

```

# Answer
> 2 votes
# Perl 5 `-p`, 37 bytes

```
#!/usr/bin/perl -p
for$a(a..z){s/$a//&&s/.{@{-}}$/$a$&/}

```

Try it online!

# Answer
> 2 votes
# Vyxal, ~~15~~ ~~12~~ 10 bytes

```
s(n/₌ṅtLnṀ

```

Thanks to @AndrovT and @TheThonnu!

Try it Online!

# Answer
> 1 votes
# C (clang), ~~164~~ 162 bytes

```
y,n,a,b,c,p,i;f(char*s,l){for(i=0;p=0,++i<123;p<l&&(y=s[p],n=l+~p,a=p+1,b=p,n<p&&(a=n,b=n+1),c=l+~(2*(n<p?n:p)),memmove(s+b,s+a,c),s[n]=y))while(s[p]^i&&p<l)p++;}

```

Try it online!

`f()` takes char-array containing input string and length of this array as parameters and performs required reflections in place.

`callf()` does pretty-printing.

# Credits

-2 bytes. @Kevin. Thanks

# Answer
> 1 votes
# Perl, ~~74~~ 70 bytes

~~84~~ 80 bytes including invocation as unix filter

```
for$c(a..z){if($p=1+index$_,$c){substr$_,$p-1,1,"";substr$_,-$p,0,$c}}

```

```
$ echo -e 'dcba\nmyface\na\nacb\ncwmfjordbankglyphsvextquiz' |
> perl -pE'for$c(a..z){if($p=1+index$_,$c){substr$_,$p-1,1,"";substr$_,-$p,0,$c}}'
dcba
fyecma
a
bac
ieabhqzugdltkfnvpjxsormycw

```

# Answer
> 1 votes
## Haskell, 87 bytes

```
s#c|(h,_:t)<-span(/=c)s,(v,w)<-splitAt(length t)$h++t=v++c:w|1<2=s
f s=foldl(#)s['a'..]

```

Try it online!

```
f s=foldl(#)s['a'..]         -- fold the function '#' into all characters from 'a'
                              -- with the starting value of the input string s
s#c=                          -- in each step (s: result so far, c: next char)
   (h,_:t)<-span(/=c)s        -- let 'h' be the substring before 'c' and
                              -- 't' the substring after 'c'. the pattern match
                              -- fails if there's no 'c' in 's'
   (v,w)<-splitAt(length t)$h++t
                              -- split the string 'h++t' at index length of t
   =v++c:w                    -- return 'v' followed by 'c' followed by 'w'
   |1<2=s                     -- if there's no 'c' in 's', return 's' unchanged

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), ~~132~~ 128 bytes

```
	DEFINE('I(I)')
I	U =&LCASE
N	U LEN(1) . K REM . U	:F(RETURN)
	I ARB @S K	:F(N)
	I K =
	I ARB . L RPOS(S) REM . R
	I =L K R	:(N)

```

Try it online!

Straightforward implementation of the required algorithm. Saved a few bytes by switching to a function rather than a full program; the explanation remains the same, more or less.

```
	I =INPUT			;* read input
	U =&LCASE			;* alias for lowercase letters (it started out as uppercase)
N	U LEN(1) . K REM . U	:F(O)	;* set K to the next lowercase letter, and when empty, goto O
	I ARB @S K	:F(N)		;* set S to the number of letters before K, or goto N
	I K =				;* remove K
	I ARB . L RPOS(S) REM . R	;* set R to the last S characters of I and L to the others
	I =L K R	:(N)		;* recombine the string and goto N
O	OUTPUT =I			;* print new string
END

```

# Answer
> 1 votes
# APL+WIN, 63 bytes

Prompts for input string

```
l←s[⍋⎕av⍳s←,⎕]⋄⍎∊(⍴s)⍴⊂'s←(n←⌽~s=↑l)\s~↑l⋄((~n)/s)←↑l⋄l←1↓l⋄'⋄s

```

Explanation:

```
l←s[⍋⎕av⍳s←,⎕] sort characters into alphabetical order

⍎∊(⍴s)⍴⊂'....' create an implicit loop for each character

s←(n←⌽~s=↑l)\s~↑l⋄((~n)/s)←↑l do the relection for first character in l

l←1↓l drop the first character in l

s display the result

⋄ statement separator

```

---
Tags: code-golf, string
---


title: "Candy Crush" a string

text:
# Question
Title: "Candy Crush" a string
Given a non-empty string (or an integer, or a list/array if you prefer) composed exclusively of digits in the range \[1-9\], your task is to write a function (or a whole program) that applies a "Match-3 type of rule" from left to right and outputs the resulting string, like this :

```
[parameter] "12223" -> [returned value] "13"

```

Meaning, while parsing the string from left to right if you encounter **the same digit repeated 3 or more times successively**, this whole group of digits must "disappear", resulting in the concatenation of the left and right part of the remaining string.

**Each time you deal with a group, you must start again from the left end and reiterate the same process** until the string no longer changes (normally when you finally reach the right end).

If the string becomes empty at the end of the process, you should output an empty string, or the digit `0`, or an empty list/array as you prefer.

---

Test cases :

```
"1" -> "1"
"31122213" -> "33"
"44555554446" -> "6"
"1322232223222311" -> "1311"
"111" -> ""
"7789998877" -> ""

```

This is , so the shortest solution in bytes wins.

# Answer
# Python 3.8, 67 bytes

```
import re
f=lambda a:(f,str)[a==(b:=re.sub(r"(.)\1\1+","",a,1))](b)

```

Try it online!
> 10 votes

# Answer
# sed `-E`, 18 bytes

Port of Arnauld's JavaScript answer.

```
:l
s/(.)\1\1+//
tl

```

Try it online!

### Explanation

```
$ info '(sed)Programming Commands'

```

```
:l           # Specify the location of label 'l' for branch commands
s/(.)\1\1+// # Erase the first instance of 3 or more consecutive equal characters
tl           # Branch to label only if there has been a succesful 's'ubstitution

```
> 9 votes

# Answer
# Vyxal, 9 bytes

```
(Ġ:‡ḢḢǑ⟇f

```

Try it Online!

Why use fixed point when you can do too much work?

```
(         # Over each character
 Ġ        # Group identical items
  :   Ǒ   # Find the first group where...
   ‡--    # Next two as lambda
    ḢḢ    # Removing the first two items yields a truthy result
       ⟇  # Remove the group at the index
        f # Flatten the result.

```
> 8 votes

# Answer
# JavaScript (ES6), 42 bytes

Supports less digits than the more generic version below.

```
f=s=>s-(s=s.replace(/(.)\1\1+/,''))?f(s):s

```

Try it online!

---

# JavaScript (ES6), 43 bytes

```
f=s=>s==(s=s.replace(/(.)\1\1+/,''))?s:f(s)

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 12 bytes

```
ΔDγ.Δg3@}õ.;

```

Try it online or verify all test cases.

`.Δ...}` could alternatively be `D...Ïн` and/or `g3@` could alternatively be `7b@` for equal-bytes alternatives:

Try it online or verify all test cases.

**Explanation:**

```
Δ             # Loop until the result no longer changes (using the implicit input):
 D            #  Duplicate the current integer
  γ           #  Split the copy into parts of equal adjacent digits
   .Δ   }     #  Pop and find the first that's truthy for (or -1 if none are):
     g        #   Push the length of the group
      3@      #   Check whether this length is >= 3
         õ    #  Push an empty string ""
          .;  #  Replace the first occurrence of the found 3+ digits group with this ""
              # (after the loop, the result is output implicitly)

   D          #  Duplicate the list of parts of equal adjacent digits
    7b        #  Push 7, and convert it to a binary-string: "111"
      @       #  Check for each value in the copy whether it's >= 111
       Ï      #  Only keep the parts for which this is truthy
        н     #  Pop and keep the first element (or "" if none were)

```
> 6 votes

# Answer
# Jelly, 14 bytes

```
Œɠ>2i1œPŒgFµÐL

```

Try it online!

Takes input as a list of digits, outputs as a list. Outputs `[]` if the result is empty. The TIO footer converts to/from numbers to lists (and converts `[]` to `0`)

## How it works

```
Œɠ>2i1œPŒgFµÐL - Main link. Takes a list of digits D on the left
           µÐL - Until a fixed point is reached, do the following:
Œɠ             -   Run lengths of equal adjacent elements
  >2           -   Greater than 2?
    i1         -   Find the first truthy index, i
        Œg     -   Group equal adjacent elements
      œP       -   Split, removing the element at the index i
          F    -   Flatten

```
> 6 votes

# Answer
# Japt v2.0a0, 10 bytes

```
e/(.)\1\1+

```

Try it

```
e          recursively replace...
/(.)\1\1+    regex: three or more of the same character
           with empty string

```
> 5 votes

# Answer
# Retina 0.8.2, 12 bytes

```
+1`(.)\1\1+

```

Try it online! Link includes test cases. Explanation: Same regex as before naturally; the `1` executes it once (because Retina defaults to global search and replace) while the `+` repeats until the string no longer changes.
> 5 votes

# Answer
# Pip, 21 bytes

```
Wa~`(.)\1\1+`a:$`.$'a

```

Try it online!

### Explanation

```
Wa~`(.)\1\1+`a:$`.$'a
                       ; a is first command-line argument (implicit)
W                      ; While
 a~                    ;  the first match in a
   `        `          ;  of this regex:
    (.)                ;   any character
       \1\1+           ;   followed by the same character 2 or more times
                       ;  exists:
               $`      ;   Portion of the string left of the match
                  $'   ;   Portion of the string right of the match
                 .     ;   Concatenate
             a:        ;   Assign back to a
                    a  ; After the loop exits, output the final value of a

```
> 5 votes

# Answer
# Arturo, ~~56~~ 53 bytes

```
f:$[s][(=s:<=replace s{/(.)\1\1+(.*)}"$2"s)?->s->f s]

```

Try it

-3 bytes thanks to @Neil

I couldn't get the regex everyone else is using to work, because it wanted to replace all instances of three or more of the same digit at the same time.

# Arturo, 69 bytes

```
g:$[a][(=a:<=flatten filter.first chunk a=>[&]=>[2<size&]a)?->a->g a]

```

Try it

A version that works on arrays.
> 4 votes

# Answer
# Raku, 33 bytes

```
{($_,{S/(.)$0$0+//}...*eq*).tail}

```

Try it online!

This is a sequence of successive modifications to the input string, ending when the last two elements are equal (`* eq *`). Then `tail` picks off just the last element.
> 4 votes

# Answer
# Charcoal, 33 bytes

```
Ｗ⊕⌕⭆Φθλ⁼κ§θλ11≔Φθ∨‹λ⊖ι⁻✂θ⊖ι⊕λ¹κθθ

```

Try it online! Link is to verbose version of code. Explanation: Tricky without any regex or grouping primitives.

```
Ｗ⊕⌕⭆Φθλ⁼κ§θλ11

```

Map overlapping pairs of characters into `1` if equal or `0` if unequal and search for a substring match of `11`. While one is found...

```
≔Φθ∨‹λ⊖ι⁻✂θ⊖ι⊕λ¹κθ

```

... extract the characters prior to the match and all those where the substring from the match to the character contains at least two different characters.

```
θ

```

Output the final string.
> 4 votes

# Answer
# V (vim), 6 bytes

```
òíˆ±±«

```

Try it online!

If you check the V wiki on regexes there are a lot of shortcuts. This line basically expands to:

`while(match found){ :%s/\(.\)\1\1\+// }`

which removes the first 3 found matching characters and then repeats until there are none left.
> 4 votes

# Answer
# Julia 1.0, 53 bytes

```
!x=x==(y=replace(x,r"(.)\1\1+"=>"";count=1)) ? x : !y

```

Try it online!

very similar to several other answers: regex, compare, recursion
> 3 votes

# Answer
# C function, 108 bytes

Try it online with a driver program

```
char*c(char*s) {
    char *p=s,*q;
    while(*p){
        q=p;
        while(*++q==*p);
        p=q-p>=3?strcpy(p,q),c(s):q;
    }
    return s;
}

```

Here is one that hopefully meets the community standards; I'm sorry the first one didn't. I left just a few extra whitespace for clarity, hope that's OK.
> 2 votes

# Answer
# Haskell, 94 bytes

```
f xs=case break((>=3).length)$group xs of{(ys,[])->concat ys;(ys,zs)->f$concat(ys<>drop 1 zs)}

```
> 2 votes

# Answer
# Haskell, ~~68~~ 63 bytes

```
until((==)=<<f)f
f(x:r)|(_:_:_,b)<-span(==x)r=b|1<3=x:f r
f s=s

```

Attempt This Online! The function `f` recursively goes through the string and removes the first group it encounters. `until((==)=<<f)f` is short for `until(\x->f x==x)f` and applies `f` to the input string until a fixed-point is found.

#### Previous 68 bytes approach

```
(""%)
s%(x:r)|(_:_:_,b)<-span(==x)r=""%(s++b)|y<-s++[x]=y%r
s%t=s++t

```

Attempt This Online!
> 2 votes

# Answer
# Excel (ms365), 124 bytes

Formula in `B1`:

```
=LET(x,SORT(TOCOL(REPT(ROW(1:9),SEQUENCE(,LEN(A1),3))),,-1),REDUCE(A1,x,LAMBDA(y,z,SUBSTITUTE(y,@SORTBY(x,FIND(x,y),),,1))))

```

**Note:** For testing, drag this down when absolute referencing is applied to `ROW($1:$9)`. Took it of in final answer to save bytes.
> 2 votes

# Answer
# Scala, 93 bytes

Golfed version. Try it online!

```
def f(s:Q):Q={var r="""(.)\1\1+""".r.replaceFirstIn(s, "");if(s==r)s else f(r)}
type Q=String

```

Ungolfed version. Try it online!

```
import scala.annotation.tailrec
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    println(removeTriplets("31122213"))
    println(removeTriplets("44555554446"))
    println(removeTriplets("1322232223222311"))
    println(removeTriplets("7789998877"))
  }

  @tailrec
  def removeTriplets(s: String): String = {
    val tripletPattern: Regex = """(.)\1\1+""".r
    val replaced = tripletPattern.replaceFirstIn(s, "")
    if (s == replaced) s else removeTriplets(replaced)
  }
}

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Minimum number of platforms required for a railway station
## Challenge

Given daily arrival and departure times of every train that reaches a railway station, find the minimum number of platforms required for the railway station so that no train waits.

In other words, find the maximal number of trains simultaneously present in the station.

## Input

* a pair of lists of times: arrivals and departures; the two lists have same length; arrival `i` corresponds to the same train as departure `i`.
* **alternatively**, a list of pairs of times, or any equivalent.
* times are numbers between `0`, included, and `24`, excluded.
* there are no dates, only times: input is the daily schedule and repeats every day.
* the departure time of a train **can** be lower than its arrival time; in that case, the train is understood to arrive on a day and depart on the next day; that train will require a platform before midnight and after midnight.
* if the arrival time is lower than the departure time, the train is understood to arrive and depart on the same day.
* input can be restricted to integers

## Output

* one integer, the minimum required number of platforms.

## Test cases

```

arrivals   = [10, 13, 16]
departures = [12, 15, 18]
out = 1

arrivals   = [10, 11]
departures = [12, 13]
out = 2

arrivals   = [ 1, 3, 7, 9,10,10,19,23]
departures = [11, 4,11,10,11, 2, 2, 2]
out = 5

arrivals   = [1, 2]
departures = [2, 3]
out = 2

arrivals   = [1, 2]
departures = [3, 2]
out = 2

arrivals   = [2, 22]
departures = [5,  6]
out = 2

```

## Rules

* This is code-golf, the shortest code in bytes wins!

## Related challenges

# Answer
> 8 votes
# Jelly, 19 bytes

```
1ị>×24+)r/€%24ċþF§Ṁ

```

Try it online!

## How it works

If you expand the times out and lay them out as a visual aid you get something like this (3rd test case as an example):

```
1 2 3 4 5 6 7 8 9 10 11                                       1 2
    3 4     7 8 9 10 11                      19 20 21 22 23 0 1 2
                9 10                                     23 0 1 2
                  10 11
                  10 11 12 13 14 15 16 17 18 19 20 21 22 23 0 1 2

```

(Note that the `1 2` in the top right is the continuation into the next day)

From this, it's clear that the number of platforms required is equal to the maximum of the number of repeated occurrences of each time. For example, 10 appears in the ranges 5 times in this example (the maximum), so the output is 5. The only problem is with times spanning multiple days, which we fix by adding 24 to those values.

The code works as follows (out of date):

```
1ị>×24+)r/€%24ċþF§Ṁ - Main link, takes a list of pairs of times
       )            - Over each pair, map:
1ị                  -   Is the first element...
  >                 -   ...greater than each element?
                    -   This yields [0, 0] for increasing pairs and [0, 1] for decreasing
   ×24              -   Multiply each one by 24
      +             -   Add in to the original pair
                    - This replaces a pair [a, b] with [a, b+24] if b < a
          €         - Over each pair, map:
        r/          -   Convert to a range
           %24      - Modulo all values by 24
                F   - Flatten this list of pairs to get all times a train is at the station
               þ    - Pair each time up with each range, then, over the pairs:
              ċ     - Count how many times the time is in that range (either 1 or 0)
                 §  - Take the sum of all lists, giving the number of times a train is at the station for each time
                  Ṁ - Take the maximum of these sums

```

# Answer
> 8 votes
# Python, 62 bytes

```
lambda l:max(sum(a-b^b-h^h-a<1for a,b in l)for h in range(24))

```

Try it online!

Golfing Surculose Sputum's solution. The new part is `a-b^b-h^h-a<1` to check whether the time `h` lies in the interval from `a` to `b` taken cyclically, that is, their sorted ordering is a cyclic permutation of `[a,h,b]`. To do this, we check whether an odd number of the differences `a-b`, `b-h`,`h-a` are negative. I first did this with multiplication `(a-b)^(b-h)^(h-a)<1`. But, xor (`^`) lets us do the same and cuts parens with better precedence.

# Answer
> 6 votes
# , 111 bytes

Brute force - unfortunately TIO can't run it but R 4.0.2 on desktop doesn't have stack issues.

```
{f=pryr::f
`:`=f(a,b,`if`(a<b,a:b,c(a:24,0:b)))
f(a,d,max(sapply(0:24,f(x,sum(mapply(f(u,v,x%in%u:v),a,d))))))}

```

Try it online!

Much shorter version with simpler logic:

# , 72 bytes

```
function(a,d)max(sapply(0:24,function(x)sum(a<=x&x<=d|a>d&(x>=a|x<=d))))

```

Try it online!

# Answer
> 5 votes
# Python 2, 73 bytes

```
lambda l:max(sum([a<=h<=b,not b<h<a][a>b]for a,b in l)for h in range(24))

```

Try it online!

Input: A list of pairs of time.

For each hour in the day, check how many trains are in the station. Then find the max of those.

# Answer
> 4 votes
# 05AB1E (legacy), ~~19~~ 17 bytes

```
εD¬‹24*+Ÿ24%}˜D¢à

```

-2 bytes by taking inspiration from the *@cairdCoinheringaahing*'s Jelly answer for the first part (`D¬‹24*+`), so make sure to upvote him as well.

Input as a list of pairs of times.

Try it online or verify all test cases.

**Explanation:**

```
ε             # Map each pair of the (implicit) input-list to:
 D            #  Duplicate the current pair
  ¬           #  Push the first value of the pair (without popping)
   ‹          #  Check for both whether this value is larger (1 if truthy; 0 if falsey)
    24*       #  Multiply both by 24
       +      #  Add it to the pair we duplicated (at the same positions)
        Ÿ     #  Pop the pair and push a list of integers in that inclusive range
         24%  #  Take modulo-24 on each value
}˜            # After the map: flatten the list of lists of integers
  D           # Duplicate the list
   ¢          # Count how many times each value occurs in the list
    à         # Pop and push the maximum
              # (after which it is output implicitly as result)

```

Uses the legacy version of 05AB1E, where `[2,2]` with builtin `Ÿ` would result in `[2]` (as expected) instead of `[2,2]`.

# Answer
> 4 votes
# APL (Dyalog Extended), 20 bytes (SBCS)

Anonymous tacit infix function taking arrivals as left argument and departures as right argument.

```
{≢⍉⊢⌸∊⍵}24|⊣…¨⊢+24×>

```

Try it online!

`>` 1 if arrival is after departure

`24×` multiply 24 by that

`⊢+` add the right argument (the departure) to that

`⊢…¨` inclusive range for each arrival-departure pair

`24|` division remainder when divided by 24

`{``}` apply the following lambda ( is the argument, i.e. the list of ranges)

`∊⍵`**ϵ**nlist (flatten) the argument

`⊢⌸` table of indices for each unique hour

transpose (so rows, representing how many of each hour there are, become columns)

count the number of rows (i.e. the maximum number of occurrences of any hour)

# Answer
> 4 votes
# Jelly, 15 bytes

```
>/×24+Ṫr%24FĠẈṀ

```

A monadic Link accepting a list of lists, `[arrivals, departures]`, which yields the number of platforms.

**Try it online!**

### How?

```
>/×24+Ṫr%24FĠẈṀ - Link: [arrivals, departures] = X
 /              - reduce by
>               -   greater than?
  ×24           - multiply by 24
      Ṫ         - tail (this actually removes the departures from X and yields them,
                        leaving [arivals] as our left argument for the rest of the chain.)
     +          - add (adds 24 to the departures that should be on the next day)
       r        - inclusive range (vectorises)
        %24     - modulo 24 (change to 24 hour times)
           F    - flatten (gets a list of all hours trains are demanding to be at the station)
            Ġ   - group indices by their values
             Ẉ  - length of each (number of trains at the station at each of the utilised hours)
              Ṁ - maximum

```

---

Also 15 as a dyadic Link accepting `arrivals` on the left and `departures` on the right:

```
>×24+⁹r⁸%24FĠẈṀ

```

Try it online!

# Answer
> 4 votes
# x86-16 machine code, ~~40~~ 39 bytes

```
00000000: b217 32db 5156 32f6 ad3a c412 f63a e212  ..2.QV2..:...:..
00000010: f63a d012 f67a 0143 e2ec 3afb 7f02 8afb  .:...z.C..:.....
00000020: 5e59 feca 79dc c3                        ^Y..y..

```

**Listing:**

```
B2 17       MOV  DL, 23             ; loop 23 to 0 hours (h)
        HOUR_LOOP:
32 DB       XOR  BL, BL             ; reset max hour
51          PUSH CX                 ; save array length
56          PUSH SI                 ; save array pointer
        TRAIN_LOOP:
32 F6       XOR  DH, DH             ; clear negatives counter
AD          LODSW                   ; AL = arrival (a), AH = departure (b)
3A C4       CMP  AL, AH             ; is a-b negative?
12 F6       ADC  DH, DH             ; if so, bit-shift 1 into DH
3A E2       CMP  AH, DL             ; is b-h negative?
12 F6       ADC  DH, DH             ; if so, bit-shift another 1
3A D0       CMP  DL, AL             ; is h-a negative?
12 F6       ADC  DH, DH             ; if so, bit-shift another 1
7A 01       JP   NOT_AT_STATION     ; was there an odd number of negatives?
43          INC  BX                 ; if so, increment count of trains at station
        NOT_AT_STATION:
E2 EC       LOOP TRAIN_LOOP         ; go to next train
3A FB       CMP  BH, BL             ; BH = max( BL, BH )
7F 02       JG   NOT_MORE           ; if not highest number of trains, continue
8A FB       MOV  BH, BL             ; BH set to new max
        NOT_MORE:
5E          POP  SI                 ; restore array
59          POP  CX                 ; restore array length
FE CA       DEC  DL                 ; decrement hour
79 DC       JNS  HOUR_LOOP          ; if not past zero hour, keep looping
C3          RET                     ; return to caller

```

Try it online!

As a callable function. Input array as a list of pairs at `SI`, length in `CX` result in `BH`.

**Explanation:**

Loops through 24 hours and checks, for each hour, how many trains will be at the station.

Uses @xnor's formula to check cyclical time interval -- that is if `a-b`, `b-h` and `h-a` are an odd number of negative results then `h` falls within the interval. Each of these are compared and if negative the carry flag (`CF`) is set and bit-shifted as a `1` or `0` into `DH` to record the number of negative results.

The parity flag (`PF`) is then checked, which is set if the number of `1` bits is even. If odd, a counter is incremented for that hour and then compared to the previous highest counter and the max is updated for the result.

# Answer
> 3 votes
# , 42 35 33 bytes

```
[:>./[:+/(([:~:/1#~[,:]+>*[)>:)"0

```

Try it online!

### High level idea:

1. Represent each range with a 0-1 list, one slot for each hour, a `1` meaning that hour is occupied.
2. Sum the rows.
3. Take the max.

### Example

Take `1 2 23 f 5 4 2`, that is, the ranges:

```
1 5
2 4
23 2

```

We apply `(([:~:/1#~[,:]+>*[)>:)"0` (mostly J mechanics) to create the 0-1 lists:

```
0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1

```

Note how the `23 2` range extends as needed to go into the next day. This is accomplished by `]+>*[` which adds to the right arg `]+` the left arg `[` times `*` "1 if the right arg is less than the let" `>`.

Next we do the row-wise sum:

```
0 1 2 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1

```

And take the max:

```
2

```

### Bonus, 34 byte version using Adam's APL approach

```
[:>./[:#/.~@;([<@-.~&i.1+]+24*>)"0

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 75 bytes

Expects a list of pairs of times.

```
a=>(t=24,g=m=>t--?g(a.map(([a,d])=>n+=(t<a)+(t>d)<=(a>d),n=0)|n<m?m:n):m)``

```

Try it online!

# Answer
> 1 votes
# Charcoal, 24 bytes

```
Ｆ⮌θＦ⊕﹪⁻⊟ηι²⁴⊞υ⁺ικＩ⌈Ｅυ№υι

```

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

```
Ｆ⮌θ

```

Loop through the arrival times in reverse order, as it's easier to process the departure times in reverse order.

```
Ｆ⊕﹪⁻⊟ηι²⁴

```

Calculate the time that this train spends at the station...

```
⊞υ⁺ικ

```

... and loop over that to push the start, intermediate and end times to the predefined empty list.

```
Ｉ⌈Ｅυ№υι

```

For each time in the list, count how many times it appears in the list, and output the maximum of those.

# Answer
> 1 votes
# Retina 0.8.2, 117 bytes

```
\d+
$*11
(1+) (?!\1)
$&24$*
(1+) \1\b
$1
+%`^(1+) 1(1+\1)
$1 $2 1$2
1(1{24})
1
O`1+
(1+)(\s\1\b)*
$#2$*11
O^`\d+
\G\d

```

Try it online! Takes input as a list of pairs. Explanation:

```
\d+
$*11

```

Convert to unary, but increment all of the numbers as Retina has difficulty working with zero.

```
(1+) (?!\1)
$&24$*

```

Add 24 to all of the departure times that are less than the arrival times.

```
(1+) \1\b
$1

```

If the arrival and departure times are the same then delete one.

```
+%`^(1+) 1(1+\1)
$1 $2 1$2

```

Otherwise repeatedly fill in any times in between.

```
1(1{24})
1

```

Reduce all of the times "modulo 24" (allowing for the increment).

```
O`1+

```

Sort the times.

```
(1+)(\s\1\b)*
$#2$*11

```

Count (in unary) the number of occurrences of each times.

```
O^`\d+

```

Sort in descending order.

```
\G\d

```

Convert the first (i.e. maximum) to decimal.

# Answer
> 1 votes
# Arn `-fs`, ~~36~~ ~~34~~ 30 bytes

```
ö·ògT£nžú#│ä♦PüâTPF™,åé@⁻BFÏc-

```

Try it!

# Explained

Unpacked: `:<(({>:}&&[->24 0~:}]:_||=>:}}\):_:@`

```
:<                     Sorted in descending order
  (
    (
      {                Block with key of _
            _          Implied
          >            Is greater than
              _
            :}         Last entry
        &&             Boolean AND
            [          Begin array
                _
              ->       Exclusive range
                24     Literal twenty-four
              0        Literal zero
              ~        1-range
                  _
                :}
            ]          End sequence
          :_           Flatten
        ||             Boolean OR
            _
          =>           Inclusive range
              _
            :}
      }                End block
      \                Map block over...
        _              ...Variable initialized to STDIN; implied
    )                  End expression
  :_
  :@                   Group based on frequency
)
                       First entry
                       Length

```

# Answer
> 1 votes
# Scala, 113 105 bytes

Saved 8 bytes thanks to the comment of @ceilingcat

---

Golfed version. Try it online!

```
def f(a:Seq[Int],d:Seq[Int])=(0 to 24).map(x =>(a zip d).count{case(s,e)=>s<=x&x<=e|s>e&(x>=s|x<=e)}).max

```

Ungolfed version. Try it online!

```
object Main {
  def platforms(a: Array[Int], d: Array[Int]): Int = {
    (0 to 24).map(x => (a zip d).count { case (start, end) => (start <= x && x <= end) || (start > end && (x >= start || x <= end)) }).max
  }

  def main(args: Array[String]): Unit = {
    println(platforms(Array(10, 13, 16), Array(12, 15, 18)))
    println(platforms(Array(10, 11), Array(12, 13)))
    println(platforms(Array(1, 3, 7, 9, 10, 10, 19, 23), Array(11, 4, 11, 10, 11, 2, 2, 2)))
    println(platforms(Array(1, 2), Array(2, 3)))
    println(platforms(Array(1, 2), Array(3, 2)))
    println(platforms(Array(2, 22), Array(5, 6)))
  }
}

```

---
Tags: code-golf
---


title: Pairs at every distance

text:
# Question
Title: Pairs at every distance
Given a list \\$X\\$ of 2 or more integers, output whether, for all \\$n\\$ such that \\$0 \leq n \< length(X)-2\\$, there exists a pair of equal integers in \\$X\\$ separated by exactly \\$n\\$ elements.

In other words: output whether, for all overlapping slices/windows of the input, there exists at least one slice/window of each length wherein the head of the slice/window equals the tail.

For example: `[1, 1, 3, 2, 3, 1, 2, 1]` will return truthy, because

```
[1, x, x, x, x, x, x, 1]
These 1s are separated by 6 elements, the most possible in an 8 element list,

[x, 1, x, x, x, x, x, 1]
These 1s are separated by 5 elements,

[1, x, x, x, x, 1, x, x]
These 1s are separated by 4 elements,

[x, 1, x, x, x, 1, x, x]
These 1s are separated by 3 elements,

[x, x, x, 2, x, x, 2, x]
These 2s are separated by 2 elements,

[x, x, 3, x, 3, 1, x, 1]
These 3s are separated by 1 element (as are the 1s, but either pair is sufficient),

[1, 1, x, x, x, x, x, x]
And these 1s are separated by 0 elements, the least possible.

```

But `[1, 1, 2, 2, 1, 1]` will return falsy, as there is no pair of equal elements separated by exactly one element. That is, there is no length 3 slice/window with a head equal to it's tail. See all length 3 slices/windows below:

```
[1, 1, 2]
   [1, 2, 2]
      [2, 2, 1]
         [2, 1, 1]

```

Standard I/O applies, input does not have to allow negatives, or input can be a string of characters, etc.

Anything reasonable as long as you're not cheating :)

This is , so shortest code in bytes wins!

## Examples

Truthy

```
[1, 1]
[1, 1, 1]
[3, 3, 7, 3]
[2, 2, 1, 2, 2]
[2, 1, 2, 2, 2]
[1, 3, 1, 3, 1, 1]
[1, 1, 3, 2, 3, 1, 2, 1]
[1, 1, 1, 1, 1, 1, 2, 1]

```

Falsy

```
[1, 2]
[1, 2, 1]
[1, 2, 3, 4]
[3, 1, 3, 1, 3]
[3, 1, 1, 3, 1]
[1, 3, 1, 1, 3, 1]
[1, 1, 2, 2, 2, 2, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 2]

```

# Answer
# Jelly, ~~11~~ ~~8~~ 6 bytes

Uses inverted boolean output.

```
IÐƤÄPẸ

```

Try it online!

```
 ÐƤ     # Map over each suffix:
I       #   Increments (differences between adjacent elements)
   Ä    # For each list, get cumulative sums
    PẸ  # Is there a zero in each column?

```

This is basically: *Is there a zero on each diagonal of the subtraction table?*. The naive implementation would be:

```
_þ`ŒDP€Ẹ

```

Try it online!
> 9 votes

# Answer
# JavaScript (ES6), 39 bytes

Returns a Boolean value.

```
a=>a.every((_,d)=>a.some(v=>a[d++]==v))

```

Try it online!

Or **38 bytes** with an inverted output, assuming the input list does not contain any 0:

```
a=>a.some((_,d)=>a.every(v=>a[d++]^v))

```

Try it online!

### Commented

```
a =>                // given an array a[] of N entries
  a.every((_, d) => // for each distance d = 0 to N - 1:
    a.some(v =>     //   is there some value v at position i (implied) ...
      a[d++] == v   //     ... such that a[i + d] is equal to v?
                    //     (we increment d instead of storing i explicitly)
    )               //   end of some()
  )                 // end of every()

```
> 7 votes

# Answer
# Vyxal, ~~12~~ 11 bytes

```
żƛ?l'ṪǏ⁼;;A

```

Try it Online!

*-1 thanks to EmanresuA but also -10 rep thanks to EmanresuA so now I have to edit the post so the upvote can be returned*

## Explained

```
żƛ?l'ṪǏ⁼;;A
żƛ           # For every number n in the range [0, len(input)]
  ?l         #   Overlapping windows of length n of the input
    'ṪǏ⁼;    #   Get all sublists where the list is the same after appending the head of the list to the list with the tail chopped off. That is, `a[:-1] + [a[0]] == a`
         ;   # End map
          A  # Are all the items truthy?

```
> 6 votes

# Answer
# Rust, 63 bytes

```
|k:&[u8]|(0..k.len()).all(|z|(z..k.len()).any(|q|k[q-z]==k[q]))
```

Attempt This Online!
> 6 votes

# Answer
# , 18 16 bytes

```
[:*/[:+.//.@|.e.

```

Try it online!

*-2 thanks to ovs!*

Explanation slightly out of date (can't update right now), but idea is same.

Consider `3 3 7 3`:

* `-/~` Differences table:

```
0 0 _4 0
0 0 _4 0
4 4  0 4
0 0 _4 0

```
* `|.` Reversed:

```
0 0 _4 0
4 4  0 4
0 0 _4 0
0 0 _4 0

```
* `0&e./.` Is there a zero in each diagonal going this way `/`:

```
1 1 1 1 1 1 1

```
* `[:*/` Are they all 1:

```
1

```
> 5 votes

# Answer
# MATL, ~~9~~ 8 bytes

Saved one byte thanks to @Luis Mendo

```
&=T&XdaA

```

Try it online!

**Explanation:**

```
&=        # input == input'
  T       # get all diagonals from...
   &Xd    # spdiags (i.e. rotate matrix 45 degrees)
      a   # `any` applied to columns
       A  # all

```
> 5 votes

# Answer
# MATL, 9 bytes

```
fqG&=&f-m

```

Outputs a truthy or falsy value, which is allowed by default. Specifically, outputs

* a non-empty array containing only ones, which is truthy, or
* an array containing at least a zero, which is falsy.

Try it online! Or verify all test cases, including truthiness/falsihood test.

### How it works

```
     % Implicit input
f    % Find: gives indices of non-zeros. Since the input contains non-zero
     % integers, this gives [1 2 ... n] where n is the input length
q    % Subtract 1, element-wise. Gives [0 1 ... n-1]
G    % Push input again
&=   % Matrix of pairwise equality comparisons
&f   % Two-output find: gives row and column indices of nonzero (i.e. true) entries
-    % Subtract, element-wise
m    % Ismember. This gives an array containing only true (or 1) if 0, 1,... n-1
     % are all contained in the above result (note that 0 will always be contained)
     % Implicit display

```
> 4 votes

# Answer
# Husk, ~~10~~ 8 bytes

```
Πm▲∂↔´Ṫ=

```

Port of *@ovs*' second Jelly answer:

> Is there a zero on each diagonal of the subtraction table?

-2 bytes thanks to *@Steffan*, by using this instead:

> Is there a 1 on each diagonal of the equality table?

Outputs `1`/`0` for truthy/falsey respectively.

Try it online.

**Explanation:**

```
     ´    # Use the given input-argument twice,
      Ṫ   # to apply double-vectorized, creating a table
       =  # checking for each pair if they're equal
    ↔     # Reverse each inner row
   ∂      # Now pop and take all anti-diagonals of this matrix
          # (`∂↔` basically takes all diagonals of the matrix†)
 m        # Map over each diagonal-list:
  ▲       #  Maximum: check if any value in the diagonal-list is truthy
Π         # Product: check if all are truthy for each diagonal
          # (after which the result is output implicitly)

```

† Although Husk has an anti-diagonals builtin , it lacks a diagonals builtin. The reason for this is probably because the anti-diagonals can be computed on an infinite matrix, whereas this isn't the case for the diagonals, as assumed by *@MartinEnder* here.
> 3 votes

# Answer
# 05AB1E, ~~11~~ ~~9~~ 6 bytes

```
.s€αPO

```

Try it online or verify all testcases.

Returns zero if there are pairs at every distance, otherwise returns a non-zero number.

If this output format isn't allowed, it's +1 bytes for adding `_` in the end (and then it returns 1 if there are pairs at every distance and 0 otherwise). Alternatively, if you are willing to stretch the output format more you can remove the `O` in the end, and then it returns a list containing only zeros iff there are pairs at every distance

```
.s    All suffixes
€     Map each suffix to:
 α    The absolute difference of each value in the suffix from the matching value in the input
P     Product of each list - it's zero iff there's at least one pair of equal elements with distance X
O     Sum - since all values are positive, this is zero iff all values in the map are zero

```
> 3 votes

# Answer
# Knight, 91 bytes

```
;=l~1;W E++'=x'=l+1l'P'1;=aT;=wF;W<=w+1w l;=bF;=s~1;W<=s+1s-l w=b|b?E+'x'sE+'x'+s w=a&a bOa

```

Enter each number in the input list on their own line, with a trailing newline.

Try It Online!

Also made a test suite cuz I'm bored lol

(Basically equivalent Python code: Try It Online!)
> 3 votes

# Answer
# , 56 bytes

```
\(x,n=seq(x),`?`=Map)any(\(i)all(\(j)x[j]-x[i+j]?n)?n-1)
```

Attempt This Online!

Outputs `FALSE` for truthy and `NA` for falsey.
> 2 votes

# Answer
# Python NumPy, 51 bytes

```
lambda a:all(map((a==[*zip(a)]).trace,a.argsort()))
```

Attempt This Online!

Takes a numpy array.

### How?

Mostly straightforward.`zip` and `argsort` are used to avoid the direct `numpy` import. `zip` does roughly the same as transpose. The comparison with `a` creates a boolean table of pairwise incidence. The diagonals of this table are the distance groups. Taking the trace at different offsets returns a positive (hence truthy) value if there is a pair at that distance. `argsort` seems to be the cheapest way to create the offsets 0,...,n-1 not necessarily in order but we don't care.
> 2 votes

# Answer
# Clojure, ~~137~~ 136 bytes

```
(defn h[c](loop[n(count c)](if(not(contains?(set(map #(=(first %)(last %))(partition n 1 c)))true))false(if(> n 2)(recur(dec n))true))))

```

Ungolfed:

```
(defn head-eq-tail [col]
  (loop [n  (count col)]
    (if (not (contains? (set (map #(= (first %) (last %)) (partition n 1 col))) true))
      false
      (if (> n 2)
        (recur (dec n))
        true))))

```
> 2 votes

# Answer
# Desmos, 43 bytes

```
f(x)=∑_{y=1}^{x.length}abs(x[y...]-x).min

```

Uses `0` for truthy, and any other positive integer for falsey.

Try it on Desmos!
> 2 votes

# Answer
# APL (Dyalog Classic), 15 bytes

```
0∊1⊥⍳∘≢↓⍤¯1∘.=⍨

```

Try it online!

Returns `0` if there are such pairs, and `1` otherwise.
> 2 votes

# Answer
# C (clang), 78 bytes

```
h;r;d;i;f(*t,n){for(r=1,d=n;--d;r&=h)for(h=i=0;i+d<n;)h|=t[i]==t[i+++d];*t=r;}

```

Try it online!

Inputs a pointer to an array of integers and its length (because poiters in C carry no length info).
Returns, through the input pointer, \\$1\\$ if the array has pairs at every distance or \\$0\\$ otherwise.
> 1 votes

# Answer
# 05AB1E, 12 bytes

```
āsŒʒ¬Qθ}€gêQ

```

I have the feeling this can be shorter. EDIT: And it defintely can: see *@CommandMaster*'s 05AB1E answer, halve the size of mine.

I do like how this challenge can be done with a lot of different approaches, though.

Try it online or verify all test cases.

**Explanation:**

```
ā         # Push a list in the range [1, (implicit) input-length]
 s        # Swap so the input-list is at the top
  Œ       # Pop and get all its sublists
   ʒ      # Filter this list of sublists by:
    ¬Qθ   #  Check if the first and last items are the same:
    ¬     #   Get the first item (without popping the list)
     Q    #   Check for each item if it's equal to this first item
      θ   #   Then pop and push the last check
   }€     # After the filter: map over each remaining sublist:
     g    #  Pop and push the length
      ê   # Sorted-uniquify this list of lengths
       Q  # Check if it's equal to the [1,length] list we created initially
          # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Charcoal, 15 bytes

```
⊙θ⬤θ∨‹μκ⁻λ§θ⁻μκ

```

Try it online! Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` if there is a distance with no pair, nothing if there is a pair at every distance. Explanation:

```
 θ              Input array
⊙               Any distance satisfies
   θ            Input array
  ⬤             Every element satisfies
      μ         Current index
     ‹          Is less than
       κ        Current distance
    ∨           Logical Or
         λ      Current value
        ⁻       Does not equal
           θ    Input array
          §     Indexed by
             μ  Current index
            ⁻   Subtract
              κ Current distance
                Implicitly print

```
> 1 votes

# Answer
# Desmos, 63 bytes

```
k=l.length
f(l)=0^{∏_{n=2}^k∑_{i=n}^k0^{(l[i-n+1]-l[i])^2}}

```

Returns `0` if truthy, `1` if falsey.

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Pyth, ~~13~~ 12 bytes

```
*FsMqVRQ>LQU

```

Try it online! -- Truthy test suite -- Falsy test suite

Outputs zero for false, non-zero for true.

Pretty much a port of Command Master's 05AB1E answer but double the length :/

Pyth has a prefix function (`._`) but no suffix function, so building the suffixes costs a few extra bytes with `>LQU`.
> 1 votes

# Answer
# Julia

## 52 bytes

```
!X=0:length(X)-1⊆[I[1]-I[2] for I=findall(X.==X')]
```

Attempt This Online!

## 45 bytes - thanks to @MarcMush

```
!X=keys(X)⊆findall(X.==X').|>x->x[1]-x[2]+1
```

Attempt This Online!
> 1 votes

# Answer
# , 90 bytes

```
\(x,l=length,n=l(x),m=1:n)l(table(abs(outer(m,m,Vectorize(\(a,b)(x[a]==x[b])*(a-b))))))==n
```

Attempt This Online!

Just checking that all distances are represented in the matrix of distances (where elements are zeroed for non-matches).
> 1 votes

# Answer
# x86 32-bit machine code, 18 bytes

```
57 89 D7 49 AF 60 89 D6 F2 A7 61 E1 F7 0F 94 C0 5F C3

```

Try it online!

Following the `fastcall` calling convention, this takes the length of an array of 32-bit integers in ECX and its address in EDX, and returns 0 or 1 in AL.

In assembly:

```
f:  push edi      # Save EDI onto the stack.
    mov edi, edx  # Set EDI to the array address.
    dec ecx       # Subtract 1 from the length in ECX.
r:  scasd         # Advance EDI, also performing an unnecessary comparison.
    pusha         # Push all the registers onto the stack.
    mov esi, edx  # Set ESI to the array address.
                  # The distance between EDI and ESI increases each iteration.
    repne cmpsd   # Compare values at addresses EDI and ESI and advance both,
                  #  repeating ECX times but stopping if they are equal.
    popa          # Restore all registers' values from the stack.
    loopz r       # Subtract 1 from ECX, and jump back if it's nonzero
                  #  and the result of the last comparison is equal.
    setz al       # Set AL based on whether the result of the last comparison is equal.
    pop edi       # Restore the value of EDI from the stack.
    ret           # Return.

```
> 1 votes

# Answer
# PARI/GP, 41 bytes

```
a->sum(i=1,#a,prod(j=i,#a,a[j]-a[j-i+1]))
```

Attempt This Online!

Returns `0` for truthy, other integers for falsy.
> 1 votes

# Answer
# Vyxal, 7 bytes

```
v=ṘÞḋṠA

```

Try it Online!

Lyxal never posted my golf, so here goes
> 1 votes

# Answer
# Scala, 94 bytes

Golfed version. Try it online!

```
def f(a:Seq[Int])={var b=a.length;(1 to b).map{i=>(i to b).map{j=>a(j-1)-a(j-i)}.product}.sum}

```

Ungolfed version. Try it online!

```
object PariGpToScala {
  def main(args: Array[String]): Unit = {
    val testCases = List(
      List(1, 1),
      List(1, 1, 1),
      List(3, 3, 7, 3),
      List(2, 2, 1, 2, 2),
      List(2, 1, 2, 2, 2),
      List(1, 3, 1, 3, 1, 1),
      List(1, 1, 3, 2, 3, 1, 2, 1),
      List(1, 1, 1, 1, 1, 1, 2, 1),
      List(1, 2),
      List(1, 2, 1),
      List(1, 2, 3, 4),
      List(3, 1, 3, 1, 3),
      List(3, 1, 1, 3, 1),
      List(1, 3, 1, 1, 3, 1),
      List(1, 1, 2, 2, 2, 2, 1, 1),
      List(1, 1, 1, 1, 1, 1, 1, 2)
    )

    testCases.foreach { testCase =>
      println(s"${testCase.mkString("[", ", ", "]")} -> ${f(testCase)}")
    }
  }

  def f(a: List[Int]): Int = {
    (1 to a.length).map { i =>
      (i to a.length).map { j =>
        a(j - 1) - a(j - i)
      }.product
    }.sum
  }
}

```
> 1 votes

---
Tags: code-golf, array, decision-problem
---


title: Get all URLs on an HTML webpage

text:
# Question
Title: Get all URLs on an HTML webpage
This is a rewrite of the (currently closed) "Debunking Stroustrup's debunking of the myth “C++ is for large, complicated, programs only”" challenge.

## Challenge

Write the **shortest** program or function that will:

1. Download `http://www.stroustrup.com/C++.html`, and
2. List all URLs contained in the HTML document.

A "URL" for this challenge is

* some string of characters
* contained in the `href` attribute of an `<a>` tag
* that starts with `http://` or `https://`.

So `<a href="someotherpage.html">` doesn't have a URL, but `<a href="http://someotherpage.html">` does.

## Additional Rules

* You may assume the downloaded HTML is valid.
* You may not assume the input is static: you must download the page each time your code is run.
* (as a consequence of above) You may not hardcode the output URLs: this is not , this is .
* You may use either `http://www.stroustrup.com/C++.html` or `https://www.stroustrup.com/C++.html` as your source URL.

## Validation

The first 5 URLs on the page (based on a snapshot of the site on April 3, 2023) are:

```
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md
http://webhostinggeeks.com/science/programming-language-be
https://coderseye.com/stroustrup-the-c-programming-language
http://edutranslator.com/jazyk-programmirovanija-c/
https://pngset.com/uz-cplusplus

```

There are 91 URLs in this particular snapshot.

# Answer
# Windows PowerShell, ~~70~~ ~~63~~ 61 bytes

Try it in a PowerShell Console (works in PowerShell Core 7.3 on Windows as well, but not in TIO)

```
(iwr www.stroustrup.com/C++.html|% L*).href-match'^https?://'

```

Ungolfed:

```
(Invoke-WebRequest -Uri 'http://www.stroustrup.com/C++.html' | ForEach-Object -MemberName Links).href -match '^https?://'

```

Nothing remarkable (except that PS is somewhat competitive here) going on; `iwr` is an alias for Invoke-WebRequest, the object returned is passed to `%` (an Alias for `ForEach-Object`) which will call the object's member `Links` (the only one matching `L*`). `href` contains the parsed URL, and the `-match` weeds out local links as requested.

**Edit**: Removed the `http://` (-7 bytes), fixed the regex, replaced Link property with ForEach-Object; thanks to @Julian

**Edit**: -2 bytes thanks to thanks to @spookycoder: removed the quotes around the uri (d'oh).
> 7 votes

# Answer
# pup, 72, 70, 63 bytes

```
curl -sL stroustrup.com/C++.html |
pup 'a[href^=http] attr{href}'

```
> 5 votes

# Answer
# Factor 0.98 \+ `html.parser.analyzer http.client`, ~~143~~ ~~132~~ ~~128~~ ~~124~~ 93 bytes

```
[ "stroustrup.com/C++.html"http-get parse-html find-hrefs
[ protocol>> "http"head? ] filter ]

```

A function that returns a list of URLs.

* `"stroustrup.com/C++.html"http-get` push the http response and the raw html (as a string) of the url on the data stack
* `parse-html` parse the html into a sequence of tag tuples
* `find-hrefs` get all hrefs on the page as URLs
* `[ protocol>> "http"head? ] filter` select the URLs whose protocols start with `http`
> 4 votes

# Answer
# Bash, 50 48 40 bytes

```
curl -L stroustrup.com/C++.html|grep tp

```

# Bash, 64 56 bytes

(-8 thanks to Tihit)

With tags removed

```
curl -L stroustrup.com/C++.html|grep -oP '"\Khttp[^"]*'

```
> 4 votes

# Answer
# Python3 + `requests`, 109 bytes:

```
import requests as r,re
re.findall('a href="(https*[^"]+)',r.get('https://www.stroustrup.com/C++.html').text)

```
> 3 votes

# Answer
# JavaScript (ES6), ~~193 … 121~~ 117 bytes

Big port of my hyperscript answer, parsing HTML by chucking it into the `<body>`.

This program must be run from the site's root to avoid CORS issues. You can test it by pasting it into the browser console at this page. There is a snippet below that uses a CORS proxy to do the same without running on a different domain.

```
async _=>((d=document.body).innerHTML=await(await fetch`C++.html`).text(),[...d.querySelectorAll`[href*=":`].join`
`)

```

```
f=
async _=>((d=document.body).innerHTML=await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text(),[...d.querySelectorAll`[href*=":`].join`
`)

f().then(s => document.write(`<pre>${s}</pre>`))
```

```
async _ => (                            // asynchronous function
  (d=document.body)                       // alias the <body> to d
    .innerHTML =                           // put into its html:
      await (await fetch`...`).text(),    //   fetch the document
  [...d.querySelectorAll`[href*=":`]      // get all tags with href containing a “:”
    .join`\n`                             // join by newlines  (<a> stringified is its href)
)

```

# JavaScript (ES6), ~~236 … 134~~ 130 bytes

This parses HTML using the `DOMParser#parseFromString` method. Ditto for the CORS stuff.

```
async _=>[...new DOMParser().parseFromString(await(await fetch`C++.html`).text(),"text/html").querySelectorAll`[href*=":`].join`
`

```

```
f=
async _=>[...new DOMParser().parseFromString(await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text(),"text/html").querySelectorAll`[href*=":`].join`
`

f().then(s => document.write(`<pre>${s}</pre>`))
```

```
async _ =>                                // asynchronous function
  [...                                    // cast to an array:
    new DOMParser().parseFromString(      //   parse HTML from
      await (await fetch`...`).text(),    //     fetch the document
      "text/html"
    ).querySelectorAll`[href*=":`         // get all tags with href containing a “:”
  ].join`\n`                              // join by newlines (<a> stringified is its href)

```

---

Saved 7 bytes on each version thanks to a cool trick pointed out by @tsh

Saved 39 bytes by running the program from the site's root, as pointed out by @Shaggy.
> 3 votes

# Answer
# 05AB1E, 53 bytes

```
žZ.•‹Ìe¨¹w•’.ŒŒ/C++.ŠÎ’J.w'"¡ü2ʒ`žXžY‚Å?às…aØ·=Å¿*}€θ

```

`.w` is disabled on TIO, so here are two loose TIO's to verify it's working as intended:

1. `žZ.•‹Ìe¨¹w•’.ŒŒ/C++.ŠÎ’J` \- Verify the url is correct: try it online.
2. `'"¡ü2ʒ`žXžY‚Å?às…aØ·=Å¿*}€θ` \- Verify the extraction of the URLs from the HTML content and final output is correct: try it online.

**Explanation:**

```
žZ              # Push builtin constant "http://www."
.•‹Ìe¨¹w•       # Push compressed string "stroustrup"
’.ŒŒ/C++.ŠÎ’    # Push dictionary string ".com/C++.html"
J               # Join the three strings on the stack together to an URL
 .w             # Pop and download the HTML content of this URL
'"¡            '# Split it on double quotes '"'
   ü2           # Get all overlapping pairs
     ʒ          # Filter this list of pairs by:
      `         #  Pop and push the strings of the pair to the stack
       žX       #  Push builtin "http://"
         žY     #  Push builtin "https://"
           ‚    #  Pair them together
            Å?  #  Check for both whether the second string starts with these substrings
              à #  Pop and check if either of the two is truthy
      s         #  Swap so the first string is at the top of the stack
       …aØ·=    #  Push dictionary string "a href="
            Å¿  #  Check if the first string ends with this substring
      *         #  Check whether both were truthy
     }€         # After the filter: map over each overlapping pair:
       θ        #  Leave just the last/second string of each
                # (after which the list of URLs is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `’.ŒŒ/C++.ŠÎ’` is `".com/C++.html"`; `…aØ·=` is `"a href="`; and `.•‹Ìe¨¹w•` is `"stroustrup"`.
> 3 votes

# Answer
# Go, 218 bytes

```
import(."io";."net/http";."regexp")
func f(){r,_:=Get("http://www.stroustrup.com/C++.html")
b,_:=ReadAll(r.Body)
for _,e:=range MustCompile(`<a[^>]+href="(http.+?)"`).FindAllStringSubmatch(string(b),-1){println(e[1])}}

```

(you cannot) Attempt This Online!

Prints all URLs to STDERR, separated by newlines.

ATO doesn't allow web requests.
> 3 votes

# Answer
# Vyxal, ~~49~~ ~~41~~ 39 bytes

```
`s≠ĿꜝǓ≥₂.•⅛/C++.°¤`¨U`₁(ṅ•s?://[^"]+)`Ẏ

```

no point Trying it Online because web requests are disabled (if I've done things correctly - they were accidentally enabled once. Big brain)!

Example output from Crosshatch.

*-8 by remembering `https://www.` is automatically appended to links if not present when calling `¨U`*

*-2 by not including the closing `"` and `>` in the regex*

## Explained

```
`s≠ĿꜝǓ≥₂.•⅛/C++.°¤`¨U`₁(ṅ•s?://[^"]+)`Ẏ
`s≠ĿꜝǓ≥₂.•⅛/C++.°¤` # stroustrup.com/C++.html
¨U # GET request
`₁(ṅ•s?://[^"]+)` # <a href="(https?://[^"]+)
Ẏ # All regex matches

```
> 3 votes

# Answer
# hyperscript, ~~130 101~~ 62 bytes

```
def f()fetch"C++.html"put it into me return<[href^=ht/>'s@href

```

This program must be run from the site's root to avoid CORS issues. There is a snippet below that uses a CORS proxy to do the same without running on a different domain.

```
<script src="https://unpkg.com/hyperscript.org@0.9.8"></script>
<script type="text/hyperscript">
def f()fetch"//corsproxy.io/?https://stroustrup.com/C++.html"put it into me return<a[href^=ht/>'s@href

init put f().join("<br />") into <body />
</script>
```

Ungolfed:

```
def f()
  fetch "C++.html"
  put it into me
  return @href of <a [href^="http"] />
end

```

Usually hyperscript is very verbose, but it's perfect for a challenge like this. This function fetches the HTML, throws it into the `<body>`, selects all `<a>` whose `href` starts with `http`, and returns each's `href`. I was somehow able to get rid of almost every single piece of whitespace in the program because hyperscript doesn't need whitespace before or after parenthesis, string, query literal, or attribute literal tokens.
> 3 votes

# Answer
## ****C#, 221 bytes****

**Golfed**

```
using System.Text.RegularExpressions;var r=await new HttpClient().GetStringAsync("https://www.stroustrup.com/C++.html");foreach(Match m in Regex.Matches(r,"<a.\\n?href=\"(https?.*?)(?=\")"))Console.WriteLine(m.Groups[1]);

```

**Ungolfed**

```
using System.Text.RegularExpressions;

var r = await new HttpClient().GetStringAsync("https://www.stroustrup.com/C++.html");
foreach (Match m in Regex.Matches(r, "<a.\\n?href=\"(https?.*?)(?=\")"))
    Console.WriteLine(m.Groups[1]);

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 88 bytes

```
Import[s="https://www.stroustrup.com/";s<>"C++.html","Hyperlinks"]~Select~StringFreeQ@s&

```
> 2 votes

# Answer
# Ruby 3 + `nokogiri`, 152 bytes

```
require'open-uri'
require'nokogiri'
p Nokogiri::HTML.parse(URI.open("https://www.stroustrup.com/C++.html").read).css("a[href^=http]").map{_1.attr"href"}

```

Outputs an array of strings of URLs. Doesn't assume anything about the structure of `<a>`s that might be deviously crafted to fudge regular expression approaches. We cannot use `Nokogiri::XML` because it doesn't correctly parse HTML URL query parameters.

# Ruby 3, 113 bytes

```
require'open-uri'
URI.open("https://www.stroustrup.com/C++.html").read.scan(/<a[^>]+href="(http.+?)"/).map{p *_1}

```

Outputs a string on each line. Uses a regular expression approach which might be fooled in some cases (e.g. `<a style=">" ...`), although it produces the same sequene of URLs.
> 2 votes

# Answer
# JavaScript, ~~79~~ 78 bytes

Must be run from the root folder of the site (consensus), returns a `Promise` containing an array of URLs (consensus).

```
async _=>(await(await fetch`C++.html`).text()).match(/(?<=href=").+:.+(?=")/g)

```

Here's a snippet that uses a proxy to allow it to bypass the site's CORS policy:

```
f=

async _=>(await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text()).match(/(?<=href=").+:.+(?=")/g)

f().then(a=>console.log(a.join`\n`))
```
> 2 votes

# Answer
# Nim `-d:ssl`, 106 bytes

Dirty solution which might break on a different webpage.

```
import httpclient,re
echo newHttpClient().getContent"http://stroustrup.com/C++.html".findAll re"htt[^""]*"

```

Don't Attempt This Online!

# Nim `-d:ssl` \+ Nimquery, 201 bytes

Should work on any possible webpage.

```
import htmlparser,httpclient,nimquery,re,xmltree
for e in newHttpClient().getContent"http://stroustrup.com/C++.html".parseHtml.querySelectorAll"a[href^='http://'],a[href^='https://']":echo e.attr"href"

```

Don't Attempt This Online!
> 2 votes

# Answer
# Scala \+ jsoup, 220 bytes

## Golfed version(220 bytes)

```
object A{def main(args:Array[String])=org.jsoup.Jsoup.parse(scala.io.Source.fromURL("https://www.stroustrup.com/C++.html").mkString).select("a[href]").eachAttr("abs:href").toArray.toList.map(_.toString).foreach(println)}

```

## Ungolfed version

```
import java.net.URL
import scala.io.Source
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

object UrlExtractor {

  def downloadHtml(url: String): String = {
    Source.fromURL(url).mkString
  }

  def extractUrls(html: String): List[String] = {
    val doc: Document = Jsoup.parse(html)
    val elements: Elements = doc.select("a[href]")
    elements.eachAttr("abs:href").toArray.toList.map(_.toString)
  }

  def main(args: Array[String]): Unit = {
    // println("This is in UrlExtrator object.")
    val url = "https://www.stroustrup.com/C++.html"
    val html = downloadHtml(url)
    // println(html)
    val urls = extractUrls(html)

    println("List of URLs:")
    urls.foreach(println)
  }
}

```
> 1 votes

# Answer
# Bash + Retina, 40 bytes

```
curl -L stroustrup.com/C++.html|retina p

```

File `p`:

```
s`a.

S`href="
G`tp
".*

```

The tricky things are

1. `a` and `href` seperated by a newline
2. two links on the same line

Attempt This Online!
> 1 votes

# Answer
# , 122 bytes

```
u = unlist(strsplit(readLines('http://www.stroustrup.com/C++.html'),'href="'))
regmatches(u,regexpr('(https?://[^"]+)',u))

```

Try it online!

Output looks like this:

```
 [1] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md"
 [2] "http://webhostinggeeks.com/science/programming-language-be"
 [3] "https://coderseye.com/stroustrup-the-c-programming-language"
 [4] "http://edutranslator.com/jazyk-programmirovanija-c/"
 [5] "https://pngset.com/uz-cplusplus"
 [6] "https://clipartflare.com/tr-cplusplus.html"
 [7] "http://www.isocpp.org/"
 [8] "http://isocpp.org/about"
 [9] "http://isocpp.org/about"
[10] "http://www.isocpp.org/std"
[11] "https://isocpp.org/std/the-standard"
[12] "http://www.open-std.org/jtc1/sc22/wg21"
[13] "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4492.pdf"
[14] "http://www.stroustrup.com/resource-model.pdf"
[15] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md"
[16] "https://github.com/isocpp/CppCoreGuidelines"
[17] "http://www.stroustrup.com/tour2.html"
[18] "http://www.lextrait.com/vincent/implementations.html"
[19] "http://www.hboehm.info/gc/"
[20] "http://www.yl.is.s.u-tokyo.ac.jp/gc/dgc.shtml"
[21] "http://www.geodesic.com"
[22] "http://www.plumhall.com"
[23] "http://www.peren.com/pages/products.htm"
[24] "http://c-plusplus.org/index.php?option=com_mtree&Itemid=57"
[25] "http://c-plusplus.org/"
[26] "http://www.trumphurst.com/cpplibs1.html"
[27] "http://www.boost.org"
[28] "http://stlab.adobe.com/"
[29] "http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library"
[30] "https://en.cppreference.com/w/cpp/links/libs"
[31] "http://www.oonumerics.org/oon"
[32] "http://root.cern.ch/root"
[33] "https://dl.acm.org/doi/abs/10.1145/3386320"
[34] "http://www.softwarepreservation.org/projects/c_plus_plus/"
[35] "http://www.fltk.org"
[36] "http://www.gtkmm.org/"
[37] "http://www.qt-project.org"
[38] "http://www.wxwidgets.org"
[39] "https://isocpp.org/faq"
[40] "http://www.parashift.com/c++-faq-lite/"
[41] "http://www.jamesd.demon.co.uk/csc/faq.html"
[42] "http://www.faqs.org/faqs/C-faq/learn"
[43] "http://www.stroustrup.com/Tour.html"
[44] "http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html"
[45] "http://www.accu.org"
[46] "https://www.accu.org/"
[47] "http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms"
[48] "http://www.gotw.ca/"
[49] "http://curbralan.com/"
[50] "http://www.artima.com/cppsource"
[51] "https://www.youtube.com/watch?v=8aIqIBmNJyM"
[52] "https://www.youtube.com/watch?v=SwJUPeWKRHo"
[53] "https://www.youtube.com/watch?v=ERzENfQ51Ck&t=6s"
[54] "https://www.youtube.com/watch?v=ooehrkYkGdA&fbclid=IwAR3_3bgYVF_d6j6KjHBO4nmpCu-7oDk8YbSC8aYrJdlGvAvo_Al2fYY_9W4"
[55] "https://www.youtube.com/watch?v=PU-2ntDuF10&fbclid=IwAR15f5SRmmyryda7IvsgIBzDLCVXcMRz6_JRTbc766X1NQccGRe_28qmy4g"
[56] "https://www.youtube.com/watch?v=43msMqV5CVA"
[57] "https://channel9.msdn.com/Shows/C9-GoingNative/Bjarne-Stroustrup-Interview-at-CppCon-2018?fbclid=IwAR19rNUcCco2pnhCTn4AHqTbONmfQv4DKoVAV1keYPdV9VvKgzRxTIVpZMM"
[58] "https://channel9.msdn.com/Shows/C9-GoingNative/Bjarne-Stroustrup-Interview-at-CppCon-2018?term=cppcon&lang-en=true"
[59] "https://www.youtube.com/watch?v=DvUL0Y2bpyc&t=129s"
[60] "https://www.youtube.com/watch?v=e_g65LUXpBI"
[61] "http://daxue.qq.com/content/content/id/2937"
[62] "http://bss.sch.bme.hu/video/bjarne-stroustrup-type-and-resource-safe-c"
[63] "https://www.youtube.com/watch?v=aPvbxuOBQ70"
[64] "https://www.youtube.com/watch?v=ZO0PXYMVGSU"
[65] "http://www.computerhistory.org/collections/oralhistories/video/30/"
[66] "https://www.youtube.com/watch?v=xcpSLRpOMJM"
[67] "https://channel9.msdn.com/Shows/C9-GoingNative/Going-Native-42-Bjarne-Stroustrup-interview-at-cppcon"
[68] "https://channel9.msdn.com/Events/CPP/CppCon-2015/Writing-Good-C-14"
[69] "https://channel9.msdn.com/Events/CPP/CppCon-2015"
[70] "https://channel9.msdn.com/events/CPP/C-PP-Con-2014/013-Make-Simple-Tasks-Simple"
[71] "http://channel9.msdn.com/Events/CPP/C-PP-Con-2014"
[72] "https://www.youtube.com/watch?v=jDqQudbtuqo&feature=youtu.be"
[73] "http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote"
[74] "http://channel9.msdn.com/Events/GoingNative/2013/Opening-Keynote-Bjarne-Stroustrup"
[75] "http://vimeo.com/35326736"
[76] "http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style"
[77] "http://techchannel.att.com/"
[78] "http://techchannel.att.com/play-video.cfm/2011/3/7/Tech-Icons-Bjarne-Stroustrup"
[79] "http://techchannel.att.com/index.cfm?SearchTag=Tech%20Icons"
[80] "http://cdsweb.cern.ch/record/1204845?ln=en"
[81] "http://portal.acm.org/toc.cfm?id=1238844"
[82] "http://csclub.uwaterloo.ca/media/C++0x%20-%20An%20Overview.html"
[83] "http://video.google.com/videoplay?docid=-3478907067117491758"
[84] "http://video.google.com/videoplay?docid=5262479012306588324"
[85] "http://technetcast.ddj.com/tnc_catalog.html?item_id=94"
[86] "http://www.youtube.com/user/A9Videos/videos?flow=grid&view=1"
[87] "https://www.youtube.com/watch?v=69edOm889V4"
[88] "https://www.bell-labs.com/usr/dmr/www/"
[89] "http://www.computerhistory.org"
[90] "http://www.softwarepreservation.org/projects/c_plus_plus/"
[91] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md"

```
> 0 votes

---
Tags: code-golf, parsing, internet
---