# Question
Title: Incrementally Increment Identical Integers
Inspired by this Stack Overflow post.

Given an ascending-sorted array of possibly duplicated integers, your goal is to increment each number by a counter, starting at 0, that resets for each group.

Spec:

* Any numbers may be negative (but if so, they'll be at the beginning, because the array is sorted),
* The array will have at least one element,
* There may be any number of integers in one group
* The groups of numbers have nothing to do with one another

To demonstrate:

```
[1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40]

```

should become this

```
[1, 2, 3, 4, 10, 11, 20, 21, 22, 30, 40, 41, 42, 43]

```

because

```
  1 1 1 1   10 10   20 20 20   30   40 40 40 40
+ 0 1 2 3    0  1    0  1  2    0    0  1  2  3
  -------   -----   --------   --   -----------
  1 2 3 4   10 11   20 21 22   30   40 41 42 43

```

## Test cases

```
input -> output
[1, 2, 3] -> [1, 2, 3]
[1, 1, 2, 2, 3, 3] -> [1, 2, 2, 3, 3, 4]
[0, 0, 0, 0, 0] -> [0, 1, 2, 3, 4]
[1, 1, 10, 10, 100, 100, 100, 100] -> [1, 2, 10, 11, 100, 101, 102, 103]
[-5, -5, -5, -5, -4, 4, 4, 4, 4, 9, 9] -> [-5, -4, -3, -2, -4, 4, 5, 6, 7, 9, 10]
[1, 1, 1, 1, 2, 2] -> [1, 2, 3, 4, 2, 3]

```

# Answer
# BQN, 3 bytesSBCS

Perfect challenge for BQN's *occurence count* builtin.

```
+⟜⊒

```

Run online!

The modifier  composes two functions. If there is a single argument (as is the case here), the right function is called on that argument, and then the left function is called with that result and the original argument:

```
(f⟜g x) ≡ (x f g x)

```

The builtin  takes a vector and returns for each element how many times the same value appeared before:

```
(⊒ 1‿1‿1‿10‿10‿100) ≡ 0‿1‿2‿0‿1‿0

```

The result of  is then added element-wise to original input by `+`:

```
(1‿1‿1‿10‿10‿100 + 0‿1‿2‿0‿1‿0) ≡ 1‿2‿3‿10‿11‿100

```

---

Ports of other more interesting answers:
> 16 votes

# Answer
# Python 3.8, ~~48~~ 46 bytes

*2-byte savings jointly contributed by Jonathan Allan and dingledooper*

```
lambda L,j=1:[n-(j:=j-1)-L.index(n)for n in L]

```

Try it online!

### Explanation

The original 48-byte solution is easier to explain:

```
lambda L:[n+i-L.index(n)for i,n in enumerate(L)]

```

Consider each number \\$n\\$ in the list together with its index \\$i\\$. Suppose that we are looking at the \\$k^{th}\\$ occurrence (0-indexed) of the number \\$n\\$. We want to add \\$k\\$ to the number. Since identical numbers are adjacent, the index of the \\$0^{th}\\$ occurrence of \\$n\\$ will be at index \\$i-k\\$. This is the result of `L.index(n)`, meaning \\$k\\$ is `i-L.index(n)`. Add that value to \\$n\\$ for each element of the list, and we're done.

To get the 46-byte solution, we track the index using a variable instead of `enumerate`, updating it in the list comprehension using Python 3.8's "walrus operator" `:=`. We could track the actual index \\$i\\$:

```
lambda L,i=-1:[n+(i:=i+1)-L.index(n)for n in L]

```

but it saves a byte to track \\$j \equiv -i\\$ instead, because we can initialize it to `1` instead of `-1`.
> 15 votes

# Answer
# , 9 bytes

```
+i.@#-i.~

```

Try it online!

Basically a port of DLosc's python answer, which fits naturally in the array paradigm.

## how

Consider `1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40`

* `i.~` Index of each element's first appearance:

```
0 0 0 0 4 4 6 6 6 9 10 10 10 10

```
* `i.@#-` Subtract that from `0 1 2 ... n`:

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

```
* `+` Add that to the original input:

```
1 2 3 4 10 11 20 21 22 30 40 41 42 43

```
> 10 votes

# Answer
# MATL, 7 bytes

```
t&=XRs+

```

Try it online! Or verify all test cases

### How it works

Consider input `[1, 1, 10, 10, 100, 100, 100, 100]` as an example.

```
t    % Implicit input. Duplicate
     % STACK: [1 1 10 10 100 100 100 100], [1 1 10 10 100 100 100 100]
&=   % Matrix of equality comparisons
     % STACK: [1 1 10 10 100 100 100 100], [1 1 0 0 0 0 0 0
                                            1 1 0 0 0 0 0 0
                                            0 0 1 1 0 0 0 0
                                            0 0 1 1 0 0 0 0
                                            0 0 0 0 1 1 1 1
                                            0 0 0 0 1 1 1 1
                                            0 0 0 0 1 1 1 1
                                            0 0 0 0 1 1 1 1]
XR   % Upper triangular part, without the diagonal
     % STACK: [1 1 10 10 100 100 100 100], [0 1 0 0 0 0 0 0
                                            0 0 0 0 0 0 0 0
                                            0 0 0 1 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 1 1
                                            0 0 0 0 0 0 0 1
                                            0 0 0 0 0 0 0 1]
s    % Sum of each column
     % STACK: [1 1 10 10 100 100 100 100], [0 1 0 1 0 1 2 3]
+    % Add, element-wise. Implicit display
     % STACK: [1 2 10 11 100 101 102 103]

```
> 7 votes

# Answer
# Jelly, 5 bytes

```
ŒɠḶF+

```

Try it online!

## How it works

```
ŒɠḶF+ - Main link. Takes a list L on the left
Œɠ    - Group run lengths
  Ḷ   - Zero based range
   F  - Flatten
    + - Add elementwise to L

```

For example, take `L = [1, 1, 2, 2, 3, 3]`:

* `Œɠ`: `[2, 2, 2]`
* : `[[0, 1], [0, 1], [0, 1]]`
* `F`: `[0, 1, 0, 1, 0, 1]`
* `+`: `[0, 1, 0, 1, 0, 1] + [1, 1, 2, 2, 3, 3] = [1, 2, 2, 3, 3, 4]`
> 6 votes

# Answer
# , ~~40~~ 33 bytes

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

```
function(a)a+sequence(rle(a)$l)-1

```

Try it online!
> 6 votes

# Answer
# Haskell + hgl, 11 bytes

```
gr+>zW(+)nn

```

## Explanation

Most of this is pretty simple

* `gr` is "group"; it groups a list into a list of equal segments.
* `zW` is "zip with"; it takes a function and uses it to combine two lists pairwise.
* `(+)` is "plus"; it adds things.
* `nn` is "the natural numbers"; an infinite list of all non-negative numbers in order.
* `zW(+)nn` combines the last 3 into a single thing which takes a list and adds every element with its index.

The last thing here that links `gr` with `zW(+)nn`. The `+>` operator. This operator has a name it's called "Kleisli composition". Regular composition takes functions `a -> b` and `b -> c` and produces a third function `a -> c`, Kleisli composition does very similar. It takes Kleisli morphisms, which are just a particular kind of function, that maps into a monad. So `a -> m b` where `m` is a monad would be an example of a function from `a` to `m b`, but is a Kleisli morphism from `a` to `b`.

So Kleisli composition takes a function `a -> m b` and a function `b -> m c` and produces a function `a -> m c` where `m` is some monad.

This is in fact sort of the fundamental essence of a monad, that Kleisli composition forms a category. So how are we using it here?

Well we have `gr :: List a -> List (List a)` and `zW(+)nn :: List a -> List a` and the thing we want is `List a -> List a`. A naive way to do it would be to group the whole thing map across each element and the concat everything back up:

```
jn<m(zW(+)nn)<gr

```

However an experienced Haskell golfer will notice that map and then concat is exactly the monad behavior of the `List`. So we could potentially get a bind to do the concat and the map in one go.

And now if we look at the types we can see they fit the shape of Kleisli morphisms. So we can actually, compose, map and concat all at once using Kleisli composition.
> 6 votes

# Answer
# Scala, 43 bytes

```
s=>s.indices.map(i=>s(i)+i-s.indexOf(s(i)))

```

Try it online!

A port of DLosc's great answer. Go upvote that!

## My original answer, 48 bytes

```
s=>s.distinct.flatMap(x=>x to x-1+s.count(x.==))

```

Try it online!

This one gets distinct elements, then for every element `x`, it makes a range from `x` to `x + n`, where `n` is the number of occurrences of `x`.
> 5 votes

# Answer
# C (tcc), ~~56~~ 54 bytes

```
c;f(int*p,int*q){for(c=0;p-q;*p+=++c)c*=!(*p-*++p-c);}

```

Try it online!

This is a rather straightforward port of my suboptimal Python answer. Takes a pointer to the beginning and end of the array.

## Explanation

```
c;  /* int c; (thanks pxeger) */
f(
    int *p,  /* pointer to the first integer */
    int *q   /* pointer to the last integer */
) {
    for (
        c=0;  /* initialise the increment */
        p-q;  /* reached the end? (if so, stop) */

        /* note: these run out of order */
                         *p+=++c)
        c*=!(*p-*++p-c);
        /*
            equivalent to:
                int original_p0 = p[0] - c;  // undo increment
                if (original_p0 != p[1]) {
                    c = 0;  // different, so reset counter
                }
                p[1] += c;
                c += 1;
                p += 1; // move to next p
        */
}

```
> 4 votes

# Answer
# , 31 bytes

```
function(a)a+seq(!a)-match(a,a)

```

Try it online!

Port of Jonah's J answer. Uses 1-based indices but it makes no difference.

Test harness taken from pajonk's answer.
> 4 votes

# Answer
# Husk, 6 bytes

```
ṁGo→Kg

```

Try it online!

```
     g  # group equal elements
ṁ       # then map the following onto each group
        # (concatenating the results):
 G      #   scan from left
        #   (arg1=result so far, arg2=next element)
  o     #   combination of 2 functions:
    K   #     constant function (= arg1)
   →    #     incremented

```
> 4 votes

# Answer
# Add++, ~~26~~ 23 bytes

```
L,dBG€bL€RbFz£+dbL1Xz£_

```

Try it online!

## Explained

```
L,dBG€bL€RbFz£+dbL1Xz£_
L,                       # create a lambda that:
  d                      # pushes two copies of the input
   BG                    # ... groups the second on consecutive items
     €bL                 # ... gets the length of each of those groups
        €R               # ... creates the range [1...n] for each of those lengths (add++ doesn't have a range [0...n) built-in for some reason dang it caird.)
          bF             # ... flattens that list
            z            # and zips it with the original input. This creates a list of items and how much to increment by
             £+          # now, reduce each item by addition
               dbL       # and push the length of the list, keeping a copy on the stack of the original list
                  1X     # push a list of length(^) 1s
                    z£_  # and subtract that from each item in the other list (this is just to account for the fact that there's no [0...n) built-in)

```
> 4 votes

# Answer
# Prolog (SWI), ~~75~~ 66 bytes

```
B+A,[C]-->[A],{C is A+B},B+1+A;[X],{C=X},1+X.
_+_-->[].
a-->0+x,!.

```

Try it online!

This program can be run by calling the grammar `a//0` to parse the input list. The remainder after parsing will be unified with the output list.
> 4 votes

# Answer
# Vyxal, 5 bytes

```
Ġvẏf+

```

Try it Online!

-1 thanks to lyxal

```
Ġ     # Group runs of identical chars
 vẏf  # 0...n each and flatten
    + # Add to input

```

Port of caird coinheringaahing's answer.
> 3 votes

# Answer
# Python 3, ~~61~~ 60 bytes

I wrote this answer to make sure my algorithm was sound, before I implemented it in C.

```
def f(a,b=.5,c=0):
 for d in a:c*=not d-b;yield d+c;c+=1;b=d

```

Try it online!

## Explanation

```
def f(
    a,     # input list
    b=.5,  # previous value
    c=0    # consecutive counter
):
    for d in a:
        c *= not d-b;  # if d and b are different, c = 0
        yield d + c;
        c += 1;
        b = d          # next loop, this'll be the previous value

```
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~22 17~~ 10 bytes

Saved 7 bytes thanks to ovs!

```
∊{⊂⍺+⍳≢⍵}⌸

```

Try it online!
> 3 votes

# Answer
# Jelly, 5 bytes

```
+ċṪ$Ƥ

```

A monadic Link accepting a sorted list of integers that yields a list of integers.

**Try it online!**

### How?

```
+ċṪ$Ƥ - Link: list of integers, A
    Ƥ - for prefixes of A:
   $  -   last two links as a monad, f(prefix):
  Ṫ   -     pop off the tail from the prefix
 ċ    -     count occurrences of that in the remaining prefix
+     - A add that (vectorises)

```
> 3 votes

# Answer
# Perl 5, 37 bytes

```
s/-?\d+/$&-$f?$i=0:$i++;$i+($f=$&)/ge

```

Try it online!
> 3 votes

# Answer
# Zsh, 38 bytes

```
p=.5
for x;echo $[(c=p-x?0:c+1)+(p=x)]
```

Attempt This Online!

I think there might a solution abusing `mv`'s backup functionality like this answer, but I can't work out how.
> 3 votes

# Answer
# Perl 5 \+ `-p`, 12 bytes

```
$_+=$h{$_}++

```

Try it online!
> 3 votes

# Answer
# Python \+ Pandas, 40 bytes

```
lambda L:S(L)+S(L).groupby(L).cumcount()

```

The code doesn't run on TIO, since it's `pandas`...

But anyway, here is the code.
> 3 votes

# Answer
# x86-64 machine code, 15 bytes

```
3b 06 74 02 31 c9 ad 29 4e fc ff cf e0 f2 c3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the array in RDI and the address of the array of 32-bit integers in RSI. The starting point is after the first 4 bytes.

Assembly:

```
.global f
repeat:
    cmp eax, [rsi]      # Compare last value and current value
    je skip             # Jump if they are equal
f:
    xor ecx, ecx        # (If not equal, or at the start) ECX = 0
skip:
    lodsd               # Put the current value in EAX, and advance the pointer
    sub [rsi-4], ecx    # Subtract ECX from the (same) value
    dec edi             # Count down from the length
    loopnz repeat       # Jump back if not finished, also reducing ECX by 1
    ret                 # Return

```

Here is another solution I found, at 16 bytes, taking the arguments in the opposite order:

```
.global f
f:
    mov eax, edx
repeat:
    cmpxchg [rdi], edx
    cmovne edx, eax
    inc edx
    scasd
    dec esi
    jnz repeat
    ret

```
> 3 votes

# Answer
# JavaScript (ES6), 51 bytes

```
x=>x.map((y,i)=>y+x.reduce((r,z,k)=>r+=z==y&k<i,0))

```
> 2 votes

# Answer
# APL+WIN, 22 bytes

Prompts for input vector

```
v+¯1++⌿p×+\p←<⍀v∘.=v←⎕

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Charcoal, 10 bytes

```
ＩＥθ⁺ι№…θκι

```

Try it online! Link is to verbose version of code. Does not require the array to be sorted or grouped. Explanation:

```
  θ         Input array
 Ｅ          Map over elements
    ι       Current element
   ⁺        Plus
     №      Count of
         ι  Current element in
      …θκ   Prefix of input
Ｉ           Cast to string
            Implicitly print

```

Alternative approach, also 10 bytes, but requires the array to be grouped:

```
ＩＥθ⁺ι⁻κ⌕θι

```

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

```
  θ         Input array
 Ｅ          Map over elements
    ι       Current element
   ⁺        Plus
      κ     Current index
     ⁻      Minus
       ⌕    First index of
         ι  Current element in
        θ   Input array
Ｉ           Cast to string
            Implicitly print

```
> 2 votes

# Answer
# Retina 0.8.2, 68 bytes

```
r(`(?<=(^|,)(\3,)*)((-)?\d+)
#$#2$*1$4$3$*
+`1-1
-
#(-)?(1*)-?
$1$.2

```

Try it online! Link includes test cases. Explanation:

```
r(`

```

Use right-to-left matching for the whole script, as that allows the matches to be specified slightly more golfily.

```
(?<=(^|,)(\3,)*)((-)?\d+)

```

Match each integer, and count how many times it's been repeated.

```
#$#2$*1$4$3$*

```

Replace each integer with a marker `#`, the repetition count in unary, and the integer in unary. Note that if the integer is positive this already adds the count to the integer.

```
+`1-1
-

```

If the integer was negative then find the difference between it and the count.

```
#(-)?(1*)-?
$1$.2

```

Convert the integer back to decimal, ignoring a trailing `-` sign, which indicates that the count was at least as large as the absolute value of the integer and therefore the result is no longer negative.

28 bytes in Retina 1 if only non-negative integers need to be supported:

```
r`(?<=(\2,)*)(\d+)
$.(*_$#1*

```

Try it online! Link includes test cases. Explanation:

```
r`(?<=(\2,)*)(\d+)

```

From right to left, match each integer, and count how many times it's been repeated.

```
$.(*_$#1*

```

Add the number of repetitions to the integer.
> 2 votes

# Answer
# Factor, 44 bytes

```
[ dup '[ over + swap _ index - ] map-index ]

```

Try it online!

Port of @Dlosc's Python answer.

`dup '[ ... _ ... ]` slots a copy of the input into the quotation at the `_`. `map-index` is like `map` except it also places the index on the stack in addition to the element.

There were a lot of other approaches and attempts; the last three are just longer versions of the above.

```
[ histogram >alist [ first2 over + 1 <range> ] map-concat ]
[ [ ] group-by values [ dup length iota v+ ] map-flat ]
[ histogram [ over + 1 <range> ] f assoc>map concat ]
[ dup '[ _ overd index -rot + - abs ] map-index ]
[| l | l [ | n i | n i + l index - ] map-index ]
[| l | l [ over + swap l index - ] map-index ]

```
> 2 votes

# Answer
# Japt, 5 bytes

```
ü ®í+

```

Try it

```
ü      - group
  ®    - for each
   í+  - zip with index then sum

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~28~~ 23 bytes

```
g[#]++&/@((g@#=#)&/@#)&

```

Try it online!

```
          (g@#=#)&/@#   initialize g[x]=x for each x in input
g[#]++&/@(           )  post-increment g[x] for each x in input

```
> 2 votes

# Answer
# J-uby, ~~66~~ 61 bytes

```
:group_by+:next|:values|:*&(:zip%(:size|:*)|:*&:sum)|:flatten

```

Try it online!

~~Surely there is a way to improve this.~~ Yep, `+` is very useful.
> 2 votes

# Answer
# Ruby, 37 bytes

Requires Ruby version 2.7 or newer.

```
->a{a.tally.flat_map{[*_1.._1+_2-1]}}

```

Attempt This Online!

##### A quick rundown:

`->a{X}` is an anonymous lambda function taking a parameter `a` and returning `X`.

`tally` returns a hash with each unique number in the input list and the number of times that number appeared in the list.

`[*1..4]` returns `[1,2,3,4]`. `flat_map` returns a flattened list from the result of the given `{code block}` being run on each number/count pair returned by `tally`, where `_1` is a placeholder for the number and `_2` is the count. So for example with an array with 5 `2`s, `[*_1.._1+_2-1]` returns `[2,3,4,5,6]`.
> 2 votes

# Answer
## Nibbles, 5 bytes

```
!$,~~+-@?_

```

That's 10 nibbles which are encoded in 0.5 bytes each. Nibbles isn't on TIO yet.

Translation:

```
!       zip
 $      the input list
 ,~     1..
 ~      (by a function, as opposed to 1 op zip) \x y->
   +
    -
     @  y
     ?  index
      _ the input list
      implicit x
    implicit y

```

Usage: pass the input in via the command line i.e.

```
nibbles filename.nbl "[1,1,1,1,10,10]"

```

Command line args used instead of stdin because input int list would still be 1 nibble in its second use (DeBruijn indicies incremented by 2 from the zip).

This is basically the same as DLosc's solution in Python (adding the difference of the index from its position)
> 2 votes

# Answer
# JavaScript (Node.js), 29 bytes

Saved 6 bytes thanks to @tsh and 2 more bytes thanks to @Shaggy!

```
a=>a.map(i=n=>i[n]=i[n]+1||n)

```

Try it online!

## Explanation

`map`s over the input (`a`) (storing the `map`ping function as `i`) and returns the value of setting index `n` in `i` to the previous value + `1`, or the input (`n`), which will increment the input each following time it's encountered.
> 1 votes

# Answer
# C (clang), 47 bytes

```
b;f(*a,n){for(b=0;n--;b+=*a-b-*++a?-b:1)*a+=b;}

```

Try it online!

Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Incrementally increments identical elements in place.
> 1 votes

# Answer
# C (gcc), 49 bytes

```
f(r,l,i)int*r;{for(i=0;--l;*r-=i*=r[i--]==*++r);}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 6 bytes

```
ÅγL<+˜

```

Try it online or verify all test cases.

```
€kā<α+

```

Try it online or verify all test cases.

```
γεεN+,

```

Outputs each item newline separated.

Try it online or verify all test cases.

I have the feeling 5 bytes should be possible, but haven't been able to find it yet. Here are three different 6-bytes approached, though.

**Explanation:**

```
Åγ      # Run-length encode the (implicit) input-list, pushing the lists of items and
        # counts separated to the stack
  L     # Transform each count to an inner list in the range [1,count]
   <    # Decrease each by 1 to make the ranges [0,count)
    +   # Add the run-length items to each inner list
     ˜  # Flatten the list of lists
        # (after which this list is output implicitly as result)

€       # Map each item in the (implicit) input-list to:
 k      #  The 0-based index of its first occurrence
  ā     # Push a list in the range [1,length] (without popping)
   <    # Decrease each by 1 to make the range [0,length)
    α   # Get the absolute difference of each with the indices
     +  # And add each to the (implicit) input-items
        # (after which the list is output implicitly as result)

γ       # Split the (implicit) input-list into parts of equal adjacent items
 ε      # Map each inner list to:
  ε     #  Map each integer to:
   N+   #   Add the 0-based (inner) map-index
     ,  #   Pop and output it with trailing newline

```
> 1 votes

# Answer
# PowerShell Core, 34 bytes

```
$args|%{if($c-$_){$c=$i=$_}($i++)}

```

Try it online!

-2 bytes thanks to mazzy!
> 1 votes

# Answer
# Java, 64 bytes

```
l->{int i=0;for(int x:l)System.out.println(x+i++-l.indexOf(x));}

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 35 bytes

```
a->b=x;[if(b-t,c=0;b=t,b+c++)|t<-a]

```

Try it online!

---

# Pari/GP, 36 bytes

```
a->p=0;[t+polcoeff(p+=x^t,t)-1|t<-a]

```

Try it online!

Based on my PARI/GP answer to another challenge.
> 0 votes

# Answer
# Pyth, 7 bytes

```
+VsUM.g

```

Test suite

#### Explanation:

```
+VsUM.g    | Full code
+VsUM.gkQQ | with implicit variables
-----------+----------------------------------
     .gkQ  | Group identical runs in the input
   UM      | Convert each run to [0..length)
  s        | Flatten
+V       Q | Vector add to input

```
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
ġıŻ+

```

Try it online!

#### Explanation

```
ġıŻ+  # Implicit input
ġ     # Group consecutive items together
 ı    # Map over each group:
  Ż   #  Push [0..length)
   +  #  Add this to the group
      # Implicit output

```
> 0 votes

---
Tags: code-golf, array
---


# Question
Title: Generate the vertices of a geodesic sphere
As in this challenge, the task is to generate the vertices of a polyhedron. The polyhedron here is the one obtained by dividing a regular icosahedron's triangular faces into smaller triangles so that each edge is divided into \\$b\\$ segments (denoted \\$\\{3,5+\\}\_{b,0}\\$ here) and projecting onto the unit sphere. Your program or function should take \\$b\\$ as input.

The vertices can be in any order (and the polyhedron can have any orientation), but each should appear exactly once, and the precision should be whatever's reasonable in your language for floating-point arithmetic.

(After typing this up, it occurred to me that a simple solution probably involves deduping points that are on the icosahedron's edges, but I'm hoping someone has a clever way of traversing the icosahedron and including exactly the right points instead.)

# Answer
# Charcoal, ~~162~~ 146 bytes

```
Ｎθ⊞υ⟦⁰¦¹⊘⊕₂⁵⟧≔⟦⟧ηＦυＦＥ²⊞ＯΦιν×⊖⊗κ§ι⁰Ｆ¬№υκＦΦ⊞Ｏυκ⁼⁴ΣＸＥμ⁻ξ§κπ²⊞η⟦κμ⟧ＦηＦ…¹θ⊞υＥ§ι⁰⁺×κλ×⁻θκ§§ι¹μＦηＦΦυ⬤ι№η⟦μκ⟧Ｆ…²θＦ…¹λ⊞υＥ§ι⁰⁺⁺×μν×⁻λμ§§ι¹ξ×⁻θλ§κξＩＥυ∕ι₂ΣＸι²

```

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

```
Ｎθ

```

Input `b`.

```
⊞υ⟦⁰¦¹⊘⊕₂⁵⟧≔⟦⟧η

```

Start with one vertex and no edges of an icosahedron of side `2`.

```
Ｆυ

```

Process all vertices as they are discovered.

```
ＦＥ²⊞ＯΦιν×⊖⊗κ§ι⁰

```

Generate more vertices by rotating about the line `x=y=z` and reflecting in the `xy` plane. (This is the same procedure as for the regular dodecahedron in the linked question.)

```
Ｆ¬№υκ

```

Ignore previously discovered vertices.

```
ＦΦ⊞Ｏυκ⁼⁴ΣＸＥμ⁻ξ§κπ²⊞η⟦κμ⟧

```

Save the new vertex and also discover any edges by checking for previously found vertices that are `2` away. (Very fortunately, `ϕ²+1²+(ϕ-1)²=2²` under floating-point arithmetic.) Since only previously found vertices are checked, each edge is only detected once, and has a specific direction.

```
Ｆη

```

Loop over the edges.

```
Ｆ…¹θ

```

Loop over the intermediate points.

```
⊞υＥ§ι⁰⁺×κλ×⁻θκ§§ι¹μ

```

Extrapolate a point along the edge. (Sadly Charcoal doesn't have a way of adding two vectors which would really simplify this. Maybe if it had octonions...)

```
Ｆη

```

Loop over the edges again.

```
ＦΦυ⬤ι№η⟦μκ⟧

```

Loop over the vertices that have edges to both vertices of that edge. (Note that because the edges have a specific direction, each face can only be detected once.)

```
Ｆ…²θＦ…¹λ

```

Loop over the interior points of the face.

```
⊞υＥ§ι⁰⁺⁺×μν×⁻λμ§§ι¹ξ×⁻θλ§κξ

```

Extrapolate a point inside the face. (Due to the normalisation, it's not necessary to interpolate.)

```
ＩＥυ∕ι₂ΣＸι²

```

Normalise all the points.
> 4 votes

# Answer
# Pyth, 99 bytes

```
mcR.add+Ksm.>L+0d3*_B1_B.n3s+mm+V*Rkhd*R-QkedStQJf&SITq.aT2^K2mmsMC.b*RlNYkdfq3lT./UQf.A}RJ>3PyT^K3

```

Try it online!

We begin with the vertices of the regular icosahedron made by all cyclic permutations and sign flips of \\$(0,1,\phi)\\$. Then we find all unordered pairs of edges that have distance 2, interpolate along the edge they specify. Then we find all unordered triplets where all the pairs are in the list of edges, and using partitions of the input we interpolate along the face they specify. Finally we normalize all points.
> 3 votes

# Answer
# Python3, 421 bytes:

```
def f(l,r=[]):
 if[]==l:yield r;return
 for i in l[0]:yield from f(l[1:],r+[i])
C=lambda n=0,b=[0,1,(1+5**.5)/2]:[]if n==3 else[*f([[[i,-i],[0]][i==0]for i in b[n:]+b[:n]])]+C(n+1)
def G(w):
 c,R=C(),[]
 for x in c:
  for y in c:
   if sum((a-b)**2 for a,b in zip(x,y))**.5==2:
    R+=[x,y]
    for v in range(1,w):R+=[[((w-v)*a+v*b)/w for a,b in zip(x,y)]]
 return{tuple(i/sum(j**2 for j in p)**.5 for i in p)for p in R}

```

Try it online!
> 2 votes

# Answer
# Ruby, ~~161 153 148~~ 146 bytes

```
->n{(n*n*10+2).times{|k|b=k/10%n
e=b-a=k/10/n
r=n*c=1i**0.4
r+=e<0?b/c-c*a:a/c-b*c+e
p 2*r*c**k/s=(r.abs*2i+z=n-e*=e<0?5**0.5-1:2).abs,z*~0**k/s}}

```

Try it online!

Golfed version of the original 175-byte concept. Now competing with the golfing languages!

* Eliminated variable `j=k/10`. Introduced new variable `e=a-b`.
* `a` & `b` are now integers (not normalised by dividing by `m=n*1.0`, with other values scaled up by `n` accordingly.)
* Conditionals used for selection instead of arrays. `d` was revised `true/false` instead of `0/1`, then eliminated completely. `e<0?` (used twice) is overall shorter than `d ?` because it doesn't require whitespace, or prior definition of `d=0>e`.
* Instead of using pythagoras (squaring then square root) to calculate scale factor `s`, multiply `r.abs` by `1i`, add `z` and take `abs` of the result. This allowed `z` to be calculated on the same line as the scale factor calculation (but means the output is now `x+yi` before `z`.)
* Moved `~0**k` to allow deletion of parentheses. Similarly redistributed calculation of `c` and `r` (Multiplying `r.abs` by `2i` instead of `1i` as previously allows movement of `2*r*c**k` and deletion of parentheses.)
* Removed `[]` around output. This alters readability because it prints each point over 2 lines instead of 1, but saves 2 bytes.

# Ruby, 175 bytes

first working version

```
->n{(n*n*10+2).times{|k|j=k/10;a=j/n/m=n*1.0;b=j%n/m
z=(1+(a-b)*[5**0.5-1,2][d=a>b ?0:1])*~0**k
r=((c=1i**0.4)+[b/c-a*c,b-b*c+a/c-a][d])*c**k*2
p [z/s=(r.abs2+z*z)**0.5,r/s]}}

```

Try it online!

A function that takes an argument `n` and prints the vertices in the format `[z,x+yi]`. One pair of opposite vertices is aligned with the `z` axis; these vertices are printed last. The code generates each vertex exactly once with no duplicates, per OP's comment in the post.

**Explanation**

According to https://mathworld.wolfram.com/RegularIcosahedron.html

`A construction for a icosahedron... places the end vertices at (0,0,+/-1) and the central vertices around two staggered circles of radii 2/sqrt(5) and heights +/- 1/sqrt(5)`

This code produces the `z`coordinates of the icosahedron at a scaled up size of `0,0,sqrt(5)` for the end vertices, which puts the other vertices at `z=+/-1`. For calculation of the x and y coordinates, the radius of the circle is conveniently set to 1, but the coordinates are doubled for compatability with the z coordinates prior to normalization.

The icosahedron is split into 10 identical diamonds as below. We include only the points marked with an `X` because the points marked with `O` are included as part of the adjacent diamond. We do however have to include the poles (marked as `?`) once.

The diamond is folded at the join of the two triangles. Looking down the `z` axis at the `x+yi` plane, the polar apex is at `0+0i`, and the other apex is at `1+0i`. The right vertex is at a 1/10th rotation, `c=i**0.4 = 0.809+0.588i`. The left vertex is at the conjugate, `0.809-0.588i`. As the absolute value of `c` is 1, the conjugate is conveniently generated by `1/c.`

```
         North Pole
                 ?  x+yi=0              z=sqrt(5)
                / \
               O   X
              / \ / \
             O   X   X
     x+yi   / \ / \ / \    x+yi
    =1/c   O---X---X---X  =c=i**0.4     z=1
    =0.809  \ / \ / \ /   =0.809
    -0.588i  O   X   X    +0.588i    Note: x,y coordinates at half
              \ / \ /                the scale of z coordinates
               O   X                 (they are doubled before normalization)
                \ /
                 O  x+yi=1              z=-1

```

We work through the `n*n` points in the diamond with increments in the value of `j`. we start at `[r=x+yi=c,z=1]`, with increasing value of `b=j%n` moving diagonally towards the bottom corner and `a=j/n` moving diagonally towards the top corner. different vectors (selected by `d=a>b`) must be added to the starting point for the upper and lower triangle.

```
                      x+yi                  z
Upper triangle a>b    a*(0-c)+b*(1/c-0)     (a-b)*(5**0.5-1)
Lower triangle a<=b   b*(1-c)+a*(1/c-1)     (a-b)*2

```

For each value of `j` we generate 10 images by 1/10 rotation of the value `r=x+yi` by multiplying by `c**k` and flipping the `z` value by multiplying by `-1**k` (due to priority of operators in Ruby, this is represented as `~0**k`)

After `n*n*10` iterations, we have covered all points up to `a=b=n-1`. It remains to add the polar vertices. This just requires another 2 iterations where the value of `j` is `n*n`, `a=n` and `b=0`.

Finally, the last line normalizes the points to a sphere and outputs them.
> 2 votes

---
Tags: code-golf, geometry, 3d
---


title: Letters in phone numbers

text:
# Question
Title: Letters in phone numbers
**Problem:**

You are making a new phone where people can type in specialized phone numbers, for example, `1-800-program`, and they would be converted automatically to a usable phone number, like `1-800-7764726` (for the previous example).

Your program will recieve a string if any length with numbers, letters and dashes, and convert all the letters to their corresponding numbers.

Here is a keypad, for reference:

**Rules:**

* Your program will receive a string
* It will process it and return/print another string
* Any language is accepted
* Since it is , the shortest code wins

# Answer
# GolfScript, 24 chars

```
{.96>{,91,'qx'+-,3/`}*}%

```

Test input:

```
0123456789-abcdefghijklmnopqrstuvwxyz

```

Test output:

```
0123456789-22233344455566677778889999

```

Explanation:

* `{ }%` applies the code between the braces to each character of the input.
* `.96>{ }*` executes the code between the inner braces if and only if the ASCII code of the character is greater than 96 (i.e. it is a lowercase letter).
* The first `,` turns the character into a list of all characters with lower ASCII codes, and `91,'qx'+-` filters out all characters with ASCII codes less than 91, as well as the letters `q` and `x`, from the list. Thus, for example, the character `a` gets turned into the 6-character list `[\]^_``, while `z` gets turned into the 29-character list `[\]^_`abcdefghijklmnoprstuvwy`.
* The second `,` counts the elements remaining in the list, and `3/` divides this count by three (rounding down). Finally, the ``` turns the resulting number (in the range 2 – 9) into a string.

Thus, as per spec, hyphens and numbers are left unchanged, while lowercase letters are mapped into numbers according to the reference keypad diagram. The code will actually cleanly pass through all printable ASCII characters except for lowercase letters (which as mapped as described) and the characters `{`, `|` and `}` (which are mapped to the two-character string `10`). Non-ASCII 8-bit input will produce all sorts of weird numeric output.

After all this, it's a bit disappointing that this only beats the trivial bash solution by just six chars.
> 9 votes

# Answer
## Bash, 30

Edit: Thank you Doorknob for eliminating 3 chars

```
tr a-z 22233344455566677778889

```

Example:
> 51 votes

# Answer
# C, ~~83~~ ~~78~~ ~~77~~ ~~65~~ ~~63~~ 62

```
main(c){for(;~(c=getchar());putchar(c>96?20-c/122+5*c/16:c));}

```

http://ideone.com/qMsIFQ
> 16 votes

# Answer
# Javascript - 103 characters

```
alert(prompt().replace(/[a-z]/g,function(y){y=y.charCodeAt(0)-91;return y>27?9:y>24?8:y>20?7:~~(y/3)}))

```
> 4 votes

# Answer
# Ruby, 75 chars

```
gets.chars{|c|$><<"22233344455566677778889999#{c}"[[*?a..?z].index(c)||-1]}

```

Uses the deprecated `chars` with block, and prints each letter individually with `$><<`. I also like `[[*?a..?z].index(c)||-1]`; it grabs the character corresponding to that letter of the alphabet if it's a letter, and the last character (which happens to be the test character unchanged) if not.

# Ruby, 43 (or 35) chars

Blatantly stealing from @ace ;)

```
puts gets.tr'a-z','22233344455566677778889'

```

Shave off 8 chars if I can run in IRB with the variable `s` as the string:

```
s.tr'a-z','22233344455566677778889'

```
> 3 votes

# Answer
# C++ - 222 chars

Longest solution so far:

```
#include<iostream>
#include<string>
#define o std::cout<<
int main(){std::string s;std::cin>>s;for(int i=0;i<s.size();i++){int j=s[i]-97;if(j<0)o s[i];if(0<=j&j<15)o 2+j/3;if(14<j&j<19)o 7;if(18<j&j<22)o 8;if(21<j&j<26)o 9;}}

```
> 3 votes

# Answer
# Frink, 92

A rather verbose language, I know. This checks 8 values instead of 26 without having to type out the compares. Can any of the above "222333444.." solutions be reduced in a similar way?

Using built in structures, 107

```
co=new OrderedList
co.insertAll[charList["cfilosv{"]]
println[input[""]=~%s/([a-z])/co.binarySearch[$1]+2/eg]

```

Using a custom recursive function, 92

```
fn[x,a]:=x<=(charList["cfilosv{"])@a?a+2:fn[x,a+1]
println[input[""]=~%s/([a-z])/fn[$1,0]/eg]

```
> 3 votes

# Answer
# Python 2.7, 66 65

### Anakata's Original

```
for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

```

### Further golfed

```
for c in input():print(ord(c)-91)/3-(c in('svyz'))if c>'`'else c,

```

I don't have enough reputation to comment on @anakata's answer, so I made a separate post here. I had the same idea (taking the ordinance modulus 3) but couldn't figure out how to print the right numbers for *s - z*.

Anyways, the golf improvements I made:

* changed `raw_input` to `input`
* removed the extraneous `'\b'` and parentheses and single quotes
* removed the `+2` offset and placed that in the original subtraction (97 - (3 * 2) = 91)

*Tested with the Python 2.7.6 interpreter. Assumes, per the rules, a string input.*
> 3 votes

# Answer
# Scala, 49 48 bytes

```
_.map(c=>if(c>96)(c/3.2+20).toChar min'9'else c)

```

Try it online!

Maps `abcdefghijklmnopqrstuvwxyz` to `22233344455566677778889999` via `(c/3.2+20).toChar min'9'`

(saved 1 byte thanks to Kevin Cruijssen)
> 3 votes

# Answer
# Smalltalk, 79 70

input is s:

```
s collect:[:c|' 22233344455566677778889999'at:1put:c;at:(($ato:$z)indexOf:c)+1]

```

probably not a candidate for being shortest - but may be of interest for an old trick to avoid a test for a not-found condition (indexOf: returns 0 in this case). So no special test for letters is needed. Some Smalltalks however, have immutable strings, and we need 4 more chars ("copy").

Oh, a better version, which even deals with immutable strings in 70 chars:

```
s collect:[:c|c,'22233344455566677778889999'at:(($ato:$z)indexOf:c)+1]

```
> 2 votes

# Answer
# Mathematica 90

This follows the logic of @ace's solution:

```
StringReplace[#,Thread[CharacterRange["A","Z"]->Characters@"22233344455566677778889999"]]&

```

Example

```
StringReplace[#1,Thread[CharacterRange["A","Z"]->
Characters@"22233344455566677778889999"]]&["VI37889"]

```

> 8437889
> 2 votes

# Answer
## Perl, 50

Another obvious copy of Ace's bash answer

```
($_)=@ARGV;y/a-z/22233344455566677778889999/;print

```
> 2 votes

# Answer
## PHP, 141

Not the shortest, but more fun:

```
<?php foreach(str_split($argv[1])as$c){$v=ord($c);if($v>114){$v--;}if($v==121){$v--;}if($v<123&$v>96){echo chr(ceil($v/3+17));}else{echo$c;}}

```

More readable:

```
<?php
foreach (str_split($argv[1]) as $c) {
  $v=ord($c);
  if ($v>114) {$v--;}
  if ($v==121){$v--;}
  if ($v<123 & $v>96){
    echo chr(ceil($v/3+17));
    } else {echo $c;}
}

```
> 2 votes

# Answer
## R, very long but fun

```
foo <- '1-800-splurghazquieaobuer57'
oof <- unlist(strsplit(foo,''))
#don't count that part - it's input formatting :-)
digout <- unlist(strsplit('22233344455566677778889999',''))
oof[oof%in%letters[1:26]] <- unlist(sapply(oof[oof%in%letters[1:26]], function(j) digout[which(letters[1:26]==j)] ))

```
> 2 votes

# Answer
# k \[32 Chars\]

```
{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}

```

### Usage

```
{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}"stack exchange"
"78225 39242643"

```
> 2 votes

# Answer
# JavaScript, 85

JavaScript is never going to win the golf wars, but I like it and I wanted to do something different than jump on the @ace bandwagon.

```
alert(prompt().replace(/[a-z]/g,function(a){for(i=7;a<"dgjmptw{"[i--];);return i+4}))

```
> 2 votes

# Answer
**Python 2.7, 80**

```
for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

```

I am new to python, so **I'm sure there must be a way to golf this even further**, it's a different aproach, hope you guys like it, ***my god, is python pretty!***

Run example:

* input: 01-800-abcdefghijklmnopqrstuvwxyz
* output: 01-800-22233344455566677778889999
> 2 votes

# Answer
# T-SQL, 216 bytes

I spent quite some time over the past couple of nights painstakingly creating a mathematical sequence function that would round correctly to generate the proper ASCII codes for the numbers from the alphabetical ASCII codes. It had a ridiculous number of decimal places in the coefficients, but it worked.

However, mattnewport's rational approach works in SQL as well, at a much lower cost of bytes, so I am shamelessly scrapping my own math in favor of his. Go up-vote him, it's an elegant solution!

Here's mine:

```
DECLARE @p VARCHAR(MAX)='';WITH t AS(SELECT ASCII(LEFT(@s,1))c,2 i UNION ALL SELECT ASCII(SUBSTRING(@s,i,1)),i+1FROM t WHERE i<=LEN(@s))SELECT @p=@p+CHAR(CASE WHEN c>96THEN 20-c/122+5*c/16 ELSE c END)FROM t;SELECT @p

```

This uses a recursive CTE to make an impromptu stack of the characters in the phone number and translate the letters on the fly, then a bit of SQL trickery (SELECT @p=@p+columnValue) to recompose the string from the CTE without requiring another recursion construct.

Output:

```
DECLARE @s VARCHAR(MAX)='1-800-abcdefghijklmnopqrstuvwxyz'
--above code runs here
1-800-22233344455566677778889999

```
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
Aā6+žq÷T9:‡

```

Try it online!

```
A                 # alphabet: "abcdefghijklmnoqrstuvwxyz"
 ā                # length range: [1..26]
  6+              # add 6 to each: [7..32]
    žq÷           # divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10]
       T9:        # replace 10 with 9
          ‡       # transliterate the input (a => 2, ..., z => 9)

```
> 2 votes

# Answer
# Vyxal, 14 bytes

```
ka:ż6+kiḭṪ9JṅĿ

```

Try it Online!

```
ka:ż6+kiḭṪ9JṅĿ
ka:            # Push the alphabet twice
   ż           # Length range: [1..26]
    6+         # Add 6: [7..32]
      kiḭ      # Floor divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10]
         Ṫ9J   # Remove the last item and append 10
            ṅ  # Join by nothing to make a string
             Ŀ # Transliterate the input from the alphabet to this

```
> 2 votes

# Answer
## PHP, 87

```
echo str_ireplace(range('a','z'),str_split('22233344455566677778889999'),fgets(STDIN));

```
> 1 votes

# Answer
# q \[38 Chars\]

```
{(.Q.a!"22233344455566677778889999")x}

```

Inspired by @ace's solution

Example

```
{(.Q.a!"22233344455566677778889999")x}"stack exchange"
"78225 39242643"

```
> 1 votes

# Answer
# C# 140

```
using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Concat(a[0].Select(d=>(char)(d>96?20-d/122+5*d/16:d))));}}

```
> 1 votes

# Answer
### XQuery, 71

BaseX was used as XQuery processor. `$i` is input.

```
translate($i,"abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")

```

Not the shortest answer, but quite short and very readable.
> 1 votes

# Answer
## Python, very ungolfed

Since everyone is copying ace, i decided to post the code i made up before i submitted the question:

```
def phonekeypad(text):
    c = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
    st = ""
    for i in list(text):
        a = False
        for t in range(len(c)):
            if i in c[t]:
                st += str(t)
                a=True
        if a == False:
            st += str(i)
    return st

```
> 1 votes

# Answer
# EcmaScript 6 (103 bytes):

```
i.replace(/[a-z]/g,x=>keys(a='00abc0def0ghi0jkl0mno0pqrs0tuv0wxyz'.split(0)).find(X=>a[X].contains(x)))

```

*Expects `i` to contain the string.*

Try it in any recent version of Firefox. I've not tried Google Chrome.
> 1 votes

# Answer
## Python 3, 121

```
print("".join((lambda x:"22233344455566677778889999"[ord(x)-97] if ord(x)>96 and ord(x)<123 else x)(i) for i in input()))

```
> 1 votes

# Answer
# Haskell, 93C

```
t[]_ a=a
t(b:c)(d:e)a
 |a==b=d
 |True=t c e a
y=map(t['a'..'z']"22233344455566677778889999")

```

Usage

```
y "1-800-program"

```
> 1 votes

# Answer
# Perl, 54

```
print map{/[a-y]/?int(5/16*ord)-28:/z/?9:$_}<>=~/./gs

```

Shoot, @RobHoare still beat me by 4 characters. :)
> 1 votes

# Answer
# C++ (clang), 50 bytes

```
[](auto&s){for(auto&c:s)c=c>96?20-c/122+5*c/16:c;}

```

this is a port of mattnewport's C solution.

Try it online!
> 1 votes

# Answer
Python

```
import string
trans = str.maketrans(string.ascii_lowercase,
                      '22233344455566677778889999')
print("1-800-ask-usps".translate(trans))

```
> 0 votes

# Answer
**ECMASCRIPT, 101 (with input)**

```
"1-800-PROGRAM".replace(/./g,function(c){
return "22233344455566677778889999"[c.charCodeAt(0)-65]||c})

```

Newline added for clarity. 85 characters if the input is in a variable.
> 0 votes

# Answer
# QBasic, 155

Ah, the memories...

```
INPUT n$
FOR i=1 TO LEN(n$)
c$=MID$(n$,i,1)
a=ASC(c$)
IF 97>a THEN
PRINT c$;
ELSE IF 122>a THEN
PRINT STR$(a\3.2-28);
ELSE
PRINT 9;
END IF
NEXT i

```

This should have been shorter, but I was testing with repl.it, which doesn't allow single-line `IF` statements and behaves strangely if you leave the variable off of `NEXT i`. It also doesn't recognize the `ASC` function, so to run the code you'll need to add this workaround at the beginning:

```
DECLARE FUNCTION ASC(s$)
FUNCTION ASC(s$)
FOR j=1 TO 255
IF CHR$(j)=LEFT$(s$,1) THEN
ASC=j
END IF
NEXT j
END FUNCTION

```

(The second time you run it, the interpreter will complain unless you remove the `DECLARE FUNCTION` line, go figure.)
> 0 votes

# Answer
## R, 110

```
s=strsplit(scan(,""),"")[[1]];i=grep("[a-z]",s);s[i]=sort(c(1:24%%8+2,7,9))[match(s[i],letters)];cat(s,sep="")

```

Example:

```
> s=strsplit(scan(,""),"")[[1]];i=grep("[a-z]",s);s[i]=sort(c(1:24%%8+2,7,9))[match(s[i],letters)];cat(s,sep="")
1: 1-800-program
2:
Read 1 item
1-800-7764726

```
> 0 votes

# Answer
## VB.net (61c)

*Excludes the 45c min for a valid vb.net program*.

```
Module P
Sub Main(A()As string)
For Each x In A(0).ToUpper
Console.Write(If(x<"A"or x>"Z",x,Chr(Asc(x)\4+35)))
Next
End Sub
End Module

```
> 0 votes

# Answer
# Rust, 196 bytes

```
x.iter().map(|x|match x{'a'|'b'|'c'=>'2','d'|'e'|'f'=>'3','g'|'h'|'i'=>'4','j'|'k'|'l'=>'5','m'|'n'|'o'=>'6','p'|'q'|'r'|'s'=>'7','t'|'u'|'v'=>'8','w'|'x'|'y'|'z'=>'9',_=>*x}).collect::<Vec<_>>();

```

Try it online!

Power of `match`. Yet match for every letter feels unnecessarily tedious. Still trying to grasp `iter()` and subsequent functions
> 0 votes

# Answer
# brainfuck, 326 bytes

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

```

Try it online!

For each character:

* Check if it's a letter. If not, print it and go to the next character.
* Check if it's 'z'. If it is, subtract 1 to make it 'y'
* Check if it's after 'r'. If it is, subtract 1 to realign it with the number grid.
* Divide the letter number by 3.
* Add the result to 50 ('2') and print it.

```
stage0 memory layout:
| input x | input backup | compare result z | compare val y | compare t0 | compare t1 |
stage1:
| else flag | input backup | prev compare result / letter index y | inv letter index / compare t0 | compare t1 | compare val x |
stage2:
| else flag | letter index backup | letter index x | compare result z | compare t0 | compare t1 | compare val y |

,[ Read first character
    >+[-[---<]>>-]<-- Check if input is greater than 96 (a lowercase letter)
    <<<[>>>>+
        <[->[-]>+<<]
        >[-<<+>>]
        >[-<<+>>]
        <<-<<+<-
    ]

    + Set else flag
    >>[ If input is a letter:
        ((stage1))
        <<->[-]>- Clear the result/else flags
        >[<+>+]<- Invert the letter index

        >>+++++[>+++++<-]> Check if letter 25 (z)
        [<+>-]+
        <<<[>>-<+<-]
        >[<+>-]
        >[>-<[-]]
        >[<<<->>>-] If it is subtract 1 to change it to y

        ((stage2))
        ++++[>++++<-]>+ Check if greater than letter 17 (r)
        <<<<[>>+
            >>[-<<[-]>+>]
            <<[-<+>]
            >[->+<]
            >-<<<<<+>-
        ]
        >>>>[-] Clear y
        <<<[<<->>-] If it is subtract 1 to normalize indices
        <+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<] Divide normalized index by 3
        >[-]>[-] Clear tempvars from division
        +++++[>++++++++++<-]>. Add 50 ('2') to result and print it
        [-]<< Clear letter index

        ((stage0))
    ]<<[ If input isn't a letter:
        - Clear the result flag
        >. Just print the character
        >>[-]<<< Clear the letter index
    ]
    >[-]<, Next input
]

```
> 0 votes

# Answer
# Retina, 27 bytes

```
T`l`22233344455566677778889

```

Try it online!

Port of the Bash solution. `T`ransliterates each `l`owercase letter to a digit between `2` and `9`. The list is implicitly padded with 3 additional `9`s
> 0 votes

# Answer
# Haskell, 80 bytes

```
d c|elem c['a'..'z']="22233344455566677778889999"!!(fromEnum c-97)|1>0=c
l=map d

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 11 bytes

```
Ạż6+kP÷T9vṆ

```

Try it online!

#### Explanation

```
Ạż6+kP÷T9vṆ  # Implicit input
Ạ            # Push the lowercase alphabet
 ż           # Without popping, push [1..26]
  6+         # Add 6 to make it [7..26]
    kP÷      # Floor divide each by pi
       T9v   # Replace the 10 with a 9
          Ṇ  # Transliterate the input
             # Implicit output

```
> 0 votes

# Answer
# Python 3, 130 bytes

```
d=lambda x:str(int((ord(x)-96)*.31769+1.76715))
def f(s,c=''):
	for i in s:c+=(d(i)if i!='z'else'9')if i.isalpha()else i
	print(c)

```

Try it online!

Uses the formula `y = (x * .31769) + 1.76715` to approximate the given relation. Sadly this formula gives wring value for `z` hence requires one additional check
> -1 votes

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


title: Disappearing Elements

text:
# Question
Title: Disappearing Elements
Given a string `S` and a list of indices `X`, modify `S` by removing the element at each index of `S` while using that result as the new value of `S`.

For example, given `S = 'codegolf'` and `X = [1, 4, 4, 0, 2]`,

```
0 1 2 3 4 5 6 7  |
c o d e g o l f  |  Remove 1
c d e g o l f    |  Remove 4
c d e g l f      |  Remove 4
c d e g f        |  Remove 0
d e g f          |  Remove 2
d e f

```

Your task is to perform this process, collect the values of `S` after each operation, and display each on a newline in order. The final answer would be

```
S = 'codegolf'
X = [1, 4, 4, 0, 2]

Answer:

codegolf
cdegolf
cdeglf
cdegf
degf
def

```
* This is so make your code as short as possible.
* You may assume that the values in `X` are always valid indices for `S`, and you may use either 0-based or 1-based indexing.
* The string will only contain `[A-Za-z0-9]`
* Either `S` or `x` may by empty. If `S` is empty, it follows that `x` must also be empty.
* You may also take `S` as a list of characters instead of a string.
* You may either print the output or return a list of strings. Leading and trailing whitespace is acceptable. Any form of output is fine as long as it is easily readable.

## Test Cases

```
S = 'abc', x = [0]
'abc'
'bc'

S = 'abc', x = []
'abc'

S = 'abc', x = [2, 0, 0]
'abc'
'ab'
'b'
''

S = '', x = []
''

S = 'codegolfing', x = [10, 9, 8, 3, 2, 1, 0]
'codegolfing'
'codegolfin'
'codegolfi'
'codegolf'
'codgolf'
'cogolf'
'cgolf'
'golf'

```

# Answer
# JavaScript (ES6), ~~57~~ ~~50~~ ~~48~~ ~~45~~ 42 bytes

Takes the string as an array of individual characters, outputs an array containing a comma separated string of the original followed by a subarray of comma separated strings for each step.

```
s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]

```
* 3 bytes saved thanks to Arnauld suggesting I abuse the loose output spec more than I already was, which led me to abusing it even more for another 3 byte saving.

---

## Test it

```
o.innerText=JSON.stringify((f=

s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]

)([...i.value="codegolf"])(j.value=[1,4,4,0,2]));oninput=_=>o.innerText=JSON.stringify(f([...i.value])(j.value.split`,`))
```

```
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
```

```
<label for=i>String: </label><input id=i><label for=j>Indices: </label><input id=j><pre id=o>
```

---

## Explanation

We take the two inputs via parameters `s` (the string array) and `a` (the integer array) in currying syntax, meaning we call the function with `f(s)(a)`.

We build a new array and start it off with the original `s`. However, as the `splice` method we'll be using later on modifies an array, we need to make a copy of it, which we can do by converting it to a string (simply append an empty string).

To generate the subarray, we `map` over the integer array `a` (where `x` is the current integer) and, for each element, we `splice` 1 element from `s`, beginning at index `x`. We return the modified `s`, again making a copy of it by converting it to a string.
> 8 votes

# Answer
## Haskell, ~~38~~ 33 bytes

```
s#i=take i s++drop(i+1)s
scanl(#)

```

Straight forward: repeatedly take the elements before and after index i, rejoin them and collect the results.

Try it online!

Edit: @Lynn saved 5 bytes. Thanks!
> 8 votes

# Answer
# Python 2, 43 bytes

```
s,i=input()
for i in i+[0]:print s;s.pop(i)

```

Try it online!

> Any form of output is fine as long as it is easily readable.

So this prints as lists of chars.
> 6 votes

# Answer
# Japt, 6 bytes

```
åjV uV

```

Test it online!

### Explanation

```
UåjV uV   Implicit: U = array of integers, V = string
Uå        Cumulatively reduce U by
  j         removing the item at that index in the previous value,
   V        with an initial value of V.
     uV   Push V to the beginning of the result.

```

Alternatively:

```
uQ åjV

UuQ       Push a quotation mark to the beginning of U.
    å     Cumulatively reduce by
     j      removing the item at that index in the previous value,
      V     with an initial value of V.

```

This works because removing the item at index `"` does nothing and so returns the original string.
> 6 votes

# Answer
## Husk, 7 bytes

```
G§+oh↑↓

```

Takes first the string, then (1-based) indices. Try it online!

## Explanation

```
G§+oh↑↓
G        Scan from left by function:
           Arguments are string, say s = "abcde", and index, say i = 3.
      ↓    Drop i elements: "de"
     ↑     Take i elements
   oh      and drop the last one: "ab"
 §+        Concatenate: "abde"
         Implicitly print list of strings on separate lines.

```
> 6 votes

# Answer
# Python 2, 47 bytes

This could be shortened to 43 bytes, as @LuisMendo pointed out, but that's already @ErktheOutgolfer's solution.

```
a,b=input();print a
for i in b:a.pop(i);print a

```

Try it online!
> 5 votes

# Answer
# Java 8, 78 bytes

This is a curried lambda, from `int[]` to a consumer of `StringBuilder` or `StringBuffer`. Output is printed to standard out.

```
l->s->{System.out.println(s);for(int i:l)System.out.println(s.delete(i,i+1));}

```

Try It Online
> 4 votes

# Answer
# 05AB1E, 11 bytes

```
v=ā0m0yǝÏ},

```

Try it online!

```
v           # For each index:
 =          #   Print without popping
  ā         #   Push range(1, len(a) + 1)
   0m       #   Raise each to the power of 0.
            #   This gives a list of equal length containing all 1s
     0yǝ    #   Put a 0 at the location that we want to remove
        Ï   #   Keep only the characters that correspond to a 1 in the new list
         }, # Print the last step

```
> 3 votes

# Answer
# Mathematica, 70 bytes

```
(s=#;For[t=1,t<=Length@#2,Print@s;s=StringDrop[s,{#2[[t]]+1}];t++];s)&

```

Try it online!
> 3 votes

# Answer
# , ~~46~~ 32 bytes

```
function(S,X)Reduce(`[`,-X,S,,T)

```

Try it online!

Takes input as a list of characters and `X` is 1-based. `Reduce` is the R equivalent of `fold`, the function in this case is `[` which is subset. Iterates over `-X` because negative indexing in R removes the element, and `init` is set to `S`, with `accum=TRUE` so we accumulate the intermediate results.

# , 80 bytes

```
function(S,X,g=substring)Reduce(function(s,i)paste0(g(s,0,i-1),g(s,i+1)),X,S,,T)

```

2-argument function, takes `X` 1-indexed. Takes `S` as a string.

Try it online!
> 3 votes

# Answer
# q/kdb+, ~~27~~ 10 bytes

**Solution:**

```
{x _\0N,y}

```

**Examples:**

```
q){x _\0N,y}["codegolf";1 4 4 0 2]
"codegolf"
"cdegolf"
"cdeglf"
"cdegf"
"degf"
"def"
q){x _\0N,y}["abc";0]
"abc"
"bc"
q){x _\0N,y}["abc";()]
"abc"
q){x _\0N,y}["abc";2 0 0]
"abc"
"ab"
,"b"
""
q){x _\0N,y}["";()]
""

```

**Explanation:**

Takes advantage of the converge functionality `\` as well as drop `_`.

```
{x _\0N,y}
{        } / lambda function, x and y are implicit variables
     0N,y  / join null to the front of list (y), drop null does nothing
   _\      / drop over (until result converges) printing each stage
 x         / the string (need the space as x_ could be a variable name)

```

**Notes:**

If we didn't need to print the original result, this would be **2** bytes in `q`:

```
q)_\["codegolfing";10 9 8 3 2 1 0]
"codegolfin"
"codegolfi"
"codegolf"
"codgolf"
"cogolf"
"cgolf"
"golf"

```
> 3 votes

# Answer
# PowerShell, ~~94~~ 84 bytes

```
param($s,$x)$a=[Collections.Generic.list[char]]$s;$x|%{-join$a;,$a|% r*t $_};-join$a

```

Try it online!

Takes input `$s` as a string and `$x` as an explicit array. We then create `$a` based on `$s` as a list.

Arrays in PowerShell are fixed size (for our purposes here), so we need to use the lengthy `[System.Collections.Generic.list]` type in order to get access to the `.removeAt()` function, which does exactly what it says on the tin.

I sacrificed 10 bytes to include two `-join` statements to make the output pretty. OP has stated that outputting a list of chars is fine, so I could output just `$a` rather than `-join$a`, but that's really ugly in my opinion.

*Saved 10 bytes thanks to briantist.*
> 3 votes

# Answer
# Haskell, 33 bytes

```
scanl(\s i->take i s++drop(i+1)s)

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~9~~ 7 bytes

```
=svõyǝ=

```

Try it online!

---

```
=s        # Print original string, swap with indices.
  v       # Loop through indices...
   õyǝ    # Replace current index with empty string.

```

-2 thanks to idea from @ETHProductions.
> 2 votes

# Answer
# Python 2, 50 bytes

* Takes in string and list of indices

```
s,i=input()
for j in i+[0]:print s;s=s[:j]+s[j+1:]

```

Try it online!
> 2 votes

# Answer
# C (gcc), 99 bytes

```
j;f(s,a,i)char*s;int*a;{puts(s);for(j=0;j<i;j++){memmove(s+a[j],s+a[j]+1,strlen(s)-a[j]);puts(s);}}

```

Try it online!

Takes the string, array, and the length of the array.
> 2 votes

# Answer
# MATL, 8 bytes

```
ii"t[]@(

```

Indexing is 1-based.

Try it online! Or verify the test cases.

### Explanation

```
i      % Input string. Input has to be done explicitly so that the string
       % will be displayed even if the row vector of indices is empty
i      % Input row vector of indices
"      % For each
  t    %   Duplicate current string
  []   %   Push empty array
  @    %   Push current index
  (    %   Assignment indexing: write [] to string at specified index
       % End (implicit). Display stack (implicit)

```
> 2 votes

# Answer
# Retina, 58 bytes

```
¶\d+
¶¶1$&$*
+1`(?=.*¶¶.(.)*)(((?<-1>.)*).(.*)¶)¶.*
$2$3$4

```

Try it online! Explanation:

```
¶\d+

```

Match the indices (which are never on the first line, so are always preceded by a newline).

```
¶¶1$&$*

```

Double-space the indices, convert to unary, and add 1 (because zeros are hard in Retina).

```
+1`

```

Repeatedly change the first match, which is always the current value of the string.

```
   (?=.*¶¶.(.)*)

```

Retrieve the next index in `$#1`.

```
                (           .    ¶)

```

Capture the string, including the `$#1`th character and one newline.

```
                 ((?<-1>.)*) (.*)

```

Separately capture the prefix and suffix of the `$#1`th character of the string.

```
                                   ¶.*

```

Match the index.

```
$2$3$4

```

Replace the string with itself and the index with the prefix and suffix of the `$#1`th character.
> 2 votes

# Answer
# C# (.NET Core), ~~87~~ ~~87~~ ~~74~~ 70 bytes

```
S=>I=>{for(int i=0;;S=S.Remove(I[i++],1))System.Console.WriteLine(S);}

```

Try it online!

Just goes to show that recursion isn't always the best solution. This is actually shorter than my original invalid answer. Still prints to STDOUT rather than returning, which is necessary because it ends with an error.

-4 bytes thanks to TheLethalCoder
> 2 votes

# Answer
# Pyth, 8 bytes

```
.u.DNYEz

```

Demonstration

Reduce, starting with the string and iterating over the list of indices, on the deletion function.
> 2 votes

# Answer
# PowerShell, ~~54~~ 58 bytes

```
param($s,$x),-1+$x|%{$z=$_;$i=0;-join($s=$s|?{$z-ne$i++})}

```

Try it online!

## Explanation

Takes input as a char array (`[char[]]`).

Iterates through the array of indices (`$x`) plus an injected first element of `-1`, then for each one, assigns the current element to `$z`, initializes `$i` to `0`, then iterates through the array of characters (`$s`), returning a new array of only the characters whose index (`$i`) does not equal (`-ne`) the current index to exclude (`$z`). This new array is assigned back to `$s`, while simultaneously being returned (this happens when the assignment is done in parentheses). That returned result is `-join`ed to form a string which is sent out to the pipeline.

Injecting `-1` at the beginning ensures that the original string will be printed, since it's the first element and an index will never match `-1`.
> 2 votes

# Answer
# Perl 5, 55 bytes (54 + "`-l`")

```
sub{print($s=shift);for(@_){substr$s,$_,1,"";print$s}}

```

Try it online!
> 2 votes

# Answer
# , 23 bytes

```
>@({&.>/\.&.|.@;<^:4"0)

```

Try it online!
> 2 votes

# Answer
# Vyxal `o`, 4 bytes

```
(…n⟇

```

Try it Online!

Prints lists of chars

```
(…n⟇ # 'o' flag forces output of the last value
(    # For every number in the list...
 …   # Print the string without popping
  n  # Get the current value
   ⟇ # Remove the char at the index
     # The result is printed on next iteration

```
> 2 votes

# Answer
# Pyth, 10 bytes

Rule changes saved me 1 byte:

```
V+E0Q .(QN

```

Try it online!

# Pyth, 11 bytes

```
V+E0sQ .(QN

```

**Try it online!**
> 1 votes

# Answer
# Python 2, 54

```
X,S=input()
for a in X:
    print S
    S=S[:a]+S[a+1:]
print S

```

Try It Online
> 1 votes

# Answer
# , 12 bytes

```
òdt,GÙ@-|xHx

```

Try it online!

This is 1-indexed, input is like:

```
11,10,9,4,3,2,1,
codegolfing

```

### Explanation

```
ò              ' <M-r>ecursively until error
 dt,           ' (d)elete (t)o the next , (errors when no more commas)
    G          ' (G)oto the last line
     Ù         ' Duplicate it down
        |      ' Goto column ...
      @-       ' (deleted number from the short register)
         x     ' And delete the character there
          H    ' Go back home
           x   ' And delete the comma that I missed

```
> 1 votes

# Answer
# Gaia, 9 bytes

```
+⟪Seḥ+⟫⊣ṣ

```

I should really add a "delete at index" function...

Try it online!

### Explanation

```
+          Add the string to the list
 ⟪Seḥ+⟫⊣   Cumulatively reduce by this block:
  S         Split around index n
   e        Dump the list
    ḥ       Remove the first char of the second part
     +      Concatenate back together
        ṣ  Join the result with newlines

```
> 1 votes

# Answer
# Swift 3, 80 bytes

```
func f(l:[String],c:[Int]){var t=l;for i in c{print(t);t.remove(at:i)};print(t)}

```

**Try it online!**
> 1 votes

# Answer
# Pyth, 8 bytes

```
+zm=z.Dz

```

Test suite!

# explanation

```
+zm=z.DzdQ    # implicit: input and iteration variable
  m      Q    # for each of the elements of the first input (the array of numbers, Q)
     .Dzd     # remove that index from the second input (the string, z)
   =z         # Store that new value in z
+z            # prepend the starting value

```
> 1 votes

# Answer
# APL, ~~31~~ ~~30~~ 28 bytes

```
{⎕←⍺⋄⍵≡⍬:⍬⋄⍺[(⍳⍴⍺)~⊃⍵]∇1↓⍵}

```

Try it online!
> 1 votes

# Answer
# C++ (gcc), ~~70~~ 65 bytes

As generic unnamed lambda, requiring `s` to be like `std::string` but `x` can be any iterable container of `int`, even an array. Returns via reference parameter into the input string.

```
[](auto&s,auto&x){auto t=s;for(int i:x)t+="\n"+s.erase(i,1);s=t;}

```

no trailing newline: -5 byte

### previous 70 byte solution

```
[](auto&s,auto&x){auto t=s+'\n';for(int i:x)t+=s.erase(i,1)+'\n';s=t;}

```

Try it online!

The result is a single newline-seperated string.
> 1 votes

# Answer
# C# (Mono), 85 bytes

```
s=>a=>{for(int i=-2;++i<a.Count;)System.Console.WriteLine(s=i<0?s:s.Remove(a[i],1));}

```

Try it online!
> 1 votes

# Answer
# Factor, 36 bytes

```
[ [ swap dup . remove-nth ] each . ]

```

Try it online!
> 1 votes

# Answer
# Ruby, 40 bytes

```
F=->s,(a,*b){a&&(s[a]=""
puts s
F[s,b])}

```

Attempt This Online!
> 1 votes

# Answer
# \>\<\>, 32 bytes

**X** is takes as 1-indexed charcodes.

```
l:?!v1-{:o$!
ob0.>~ri:0(?;[{~]ra

```

Try it online!
> 1 votes

# Answer
# R (+pryr), 45 bytes

Different (and longer) solution than @Guiseppe's.

```
f=pryr::f(`if`(sum(x|1),f(s[-x[1]],x[-1]),s))

```

which evaluates to the function:

```
function (s, x)
if (sum(x | 1)) f(s[-x[1]], x[-1]) else s

```

Takes input as a list of characters and a list of 1-indexed indices. As long as `x` is not empty, recursively calls `f` with the first element from `x` removed, as well as its corresponding value in `s`.
> 0 votes

# Answer
# Tampio, 173 bytes

```
l miinus tyhjyys on l
l miinus a on l lisättynä l:ään avattuna a:lla
l avattuna a:lla lisättynä b:hen on l katkaistuna a:sta plus l jatkettuna a:n seuraajasta miinus b

```

Explanation:

```
l miinus tyhjyys on l
l -      []      =  l

l miinus a on l lisättynä l:ään avattuna a:lla
l -      a =  l :        (l     `avattu` a)

l avattuna  a:lla lisättynä b:hen on
l `avattu` (a     :         b)    =

  l katkaistuna a:sta plus l jatkettuna  a:n seuraajasta miinus b
((l `katkaistu` a)    ++  (l `jatkettu` (a   +1)     ) ) -      b

```

`katkaistu` and `jatkettu` are equivalent to `take` and `drop` of Haskell, respectively.
> 0 votes

# Answer
# Röda, 29 bytes

```
f l{[l[:]];[l[:]]if del l[_]}

```

Try it online!
> 0 votes

# Answer
# Go, 69 bytes

```
func f(S string,X[]int){for _,i:=range X{S=S[:i]+S[i+1:];println(S)}}

```

Attempt This Online!

Prints to STDERR.
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
£{Ɗß

```

Try it online!

#### Explanation

```
£{Ɗß  # Implicit input
£     # Print the first input
 {    # For each number in the second input:
  Ɗ   #   Drop the item at that index in the
      #   top of stack (initially first input)
   ß  #   Print this new string without popping
      #   (so we leave it for the next iteration)

```
> 0 votes

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


title: Index and return 3 characters

text:
# Question
Title: Index and return 3 characters
The challenge is simple: Read 3 letters from a system input¹ and convert them to numbers (`A-1, B-2, C-3...Z-26`)². Print each of those numbers in the order the letters were inputted in, each on a new line and then the sum of all 3 numbers, on its own line as well.

NOTE: There will be no extra input characters, only 3 letters. However, the code must be case insensitive.

This follows the standard rules of code golf, and the shortest byte count wins.

¹If your language does not support input, you may use from a file, or predefined variable instead. However, the program should be able to run any and all possibilities.

²The program should be able to take lowercase AND uppercase, and allow for a mix of lowercase and uppercase (e.g `wOq` or `ZNu`)

# Answer
> 4 votes
# Vyxal `so`, 4 bytes

```
øA⟑,

```

Try it Online!

Inspired by a -1 from @TheThunno

## Explained

```
øA⟑,
øA    # Char to alphabet index
  ⟑,  # print each on newlines
      # the s flag sums the list and the o flag prints it even though implicit output gets disabled from the map

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
O%32Ṅ€S

```

A full program that accepts a string of three letters and prints their alphabetic indices followed by their sum on four lines.

**Try it online!**

### How?

```
O%32Ṅ€S - Main Link: list of characters, C
O       - cast to ordinals  A:65 ... Z:90 / a:97 ... z:122
 %32    - modulo 32         A:1  ... Z:26 / a:1  ... z:26
    Ṅ€  - print each followed by a new line
      S - sum
        - implicit print

```

---

9 if it had to be the *first* three of a string of letters (Try it online!):

```
ḣ3O%32Ṅ€S

```

...or 12 if it had to both handle non-alphabetic characters, and take the *first* three *letters* (Try it online!):

```
fØẠḣ3O%32Ṅ€S

```

# Answer
> 4 votes
# Factor \+ `combinators.extras`, ~~42~~ 35 bytes

```
0 [ read1 32 mod dup . + ] thrice .

```

Try it online!

*-7 bytes thanks to @MarcMush*

* `0` Push `0`, our sum, to the data stack.
* `[ ... ] thrice` Call a quotation three times.
* `read1` Read one code point from standard input.
* `32 mod` Modulo 32.
* `dup .` Output on its own line non-destructively.
* `+` Add it to the sum.
* `.` Print the sum.

# Answer
> 4 votes
# Google Sheets, ~~56~~ 53

Ending parens discounted.

* Input is in A1
* B1

```
=ArrayFormula(-64+CODE(UPPER(MID(A1,{1;2;3},1))))
or
=ArrayFormula(-9+DECIMAL(MID(A1,{1;2;3},1),36))

```
* C1

```
=SUM(B:B)

```

# Answer
> 3 votes
# APL (Dyalog Extended), 10 bytes

Full program. Prompts via stdin and prints to stdout

```
+⌿⎕←⍪⎕A⍳⌈⍞

```

Try it online!

prompt via stdin

uppercase

`⎕A⍳` **i**ndices in uppercase **A**lphabet

make into column

`⎕←` send to stdout

`+⌿` sum (and implicitly print to stdout)

# Answer
> 3 votes
# Elixir, 70 bytes

```
&(IO.puts Enum.reduce &1,0,fn b,c->IO.puts b=b-(b>91&&96||64)
c+b
end)

```

Try it online!

# Answer
> 3 votes
# Perl 5 \+ `-pF`, 27 bytes

-6 bytes thanks to @Sisyphus!

```
$\+=$;*say$;=31&ord for@F}{

```

Try it online!

# Answer
> 3 votes
# TI-BASIC, 135 132 bytes (on-calc) / 145 135 bytes (as text)

-3 bytes thanks to MarcMush!

```
Input Str1
For(I,1,3
int(.5inString(" AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz",sub(Str1,I,1
Disp Ans
A+Ans→A
End
A

```

## Explanation

* `Input Str1`: Take text input into string variable `Str1`.
* `For(I,1,3`: Start a for-loop with variable I from 1 to 3 (TI-BASIC strings and lists are 1-indexed).
* `int(.5inString(" AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz",sub(Str1,I,1`: Find the position of the current character of `Str1` in the alphabet string, divide it by 2 and find the floor of it to get the number of the uppercase or lowercase letter. Parentheses at the end of a line in TI-BASIC don't need to be closed, so using `.5` in front of `inString(` rather than `/2` behind it saves a couple bytes' worth of parentheses.
* `Disp Ans`: Display what the previous line returned (`Ans`).
* `A+Ans→A`: Add `Ans` to the sum (`Disp` doesn't return anything so `Ans` remains the same).
* `End`: End of `For(` loop.
* `A`: Implicitly print the sum (variable `A`) at the end of the program.

# Answer
> 3 votes
# Python 3, ~~67~~ ~~63~~ 53 bytes

*-10 bytes by dingledooper*

```
i=[ord(c)%32for c in input()]
*map(print,i+[sum(i)]),

```

Try it online!

# Answer
> 3 votes
# brainfuck, 38 bytes

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

```

Try it online!

## Explanation:

The first 13 plus signs put the 'newline' character into cell 0. Then, I initialize cell 1 as a counter with a value of 3. Then there's the main loop. This loop will get a character in cell 2, display it, display the 'newline' character in cell 0, add cell 2 to cell 3, which holds the running sum, and repeat until cell 1 has a value of zero. When the loop is done, it displays the value in cell 3, which, if you've been following, holds the running sum of the characters. However, there is a problem with this last part: it displays the sum of the three characters as an ascii character, not an integer. I don't know if this is actually an issue since I technically displayed the sum, but just in case, I added a (long) routine to the end of the code that displays the sum as an integer.

# brainfuck, 242 bytes

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

```

Try it online!

But wait, there's more. The routine I used only supports displaying eight bit numbers. This means that if I input 'abc' into the program, it displays:

```
a
b
c
39

```

If you didn't catch it, the sum of the ascii values of 'a','b', and 'c' is not 39. However, it's equivalent if you add 255. This is because the value of the cell was only calculated to 8 bits by the routine I used. At this point, brainfuck had had its effect on my brain, and I didn't really feel like rewriting any more code in it. If I need to change my submission because of this issue or any other issue, let me know in the comments.

# Answer
> 3 votes
# Nibbles, ~~5.5~~ 4.5 bytes

```
;.@%$32+

```

Attempt This Online!

~~Shorter than the Vyxal answer~~ not anymore but still doesn't cheat by storing information in flags. Nibbles is an awesome language.

```
;.@%$32+
 .       For each character
  @       in the input:
   %       Modulo
    $       the character
     32     by 32
;        Take the result
       + and append its sum

```

*-1 byte by borrowing the modulo 32 trick from other answers*

# Answer
> 2 votes
# Jelly, 9 bytes

```
ŒuO_64Ṅ€S

```

Try it online!

Full program which takes a three-character string of letters as the first command line argument. 10 bytes to read from STDIN

## How it works

```
ŒuO_64Ṅ€S - Main link. Takes [a,b,c] (a string) on the left
Œu        - Convert to uppercase
  O       - Ordinal
   _64    - Subtract 64 (A -> 1, B - 2 etc.)
       €  - Over each:
      Ṅ   -   Print with a trailing newline
        S - Take the sum, and print implicitly

```

# Answer
> 2 votes
# Keg, 20 bytes

```
0&(3|?84*%:.
,&+&)&.

```

Try it online!

Why....why did I do this to myself?

## Explained

```
0&

```

First of all, we put `0` into the register, because it is intialised as `None`. The register will be used to track the sum of the three letters.

```
(3|

```

Three times:

```
?84*%

```

Take the next letter and modulo its ASCII value by 32. This trick is stolen from Jonathan Allen's Jelly answer, so go upvote that too.

```
:.
,

```

Print the result of that modulo, followed by a newline (yes, newlines really do push newlines in Keg. This entire language is cursed, what did you expect?)

```
&+&

```

Push the value of the register, add the modulo'd index and then place that back in the register

```
)&.

```

Close the for loop and print the register raw.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 38 bytes

```
(Print@Column[y=LetterNumber@#];Tr@y)&

```

Doesn't seem to run in Try it online!, so here are some screenshots:

*And here is a superior 32-byte approach given by att in the comments:*

```
Print/@##@*+##&@@LetterNumber@#&

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 61 bytes

```
x=>[...[a,b,c]=[...x].map(z=>parseInt(z,36)-9),a+b+c].join`
`

```

Try it online!

```
x=>[                   // Define a function taking a parameter x, returning an array of...
  ...                  // Iterating over...
    [a,b,c]=           // assign a, b and c to...
    [...x].map(z=>     // x mapped to...
      parseInt(z,36)-9 // parse as base36, -9 to get charcode
    ),
  a+b+c                // and the sum of all three
].join`\n`             // Joined by newline

```

The trick is that parseInt is case-insensitive, saving a lot of bytes.

# Answer
> 2 votes
# Ruby, 36 Bytes

```
p $*.map{|c|p c.downcase.ord-96}.sum

```

# Answer
> 2 votes
# Julia 1.0, 38 bytes

```
r=read(stdin).%32
println.([r;sum(r)])

```

Try it online!

# Answer
> 2 votes
# SimpleTemplate 0.84, ~~107~~ 77 bytes

This code expects 1 argument passed to the compiler, with the 3 characters used for input.

Outputs the text directly and doesn't return anything.

```
{@eachargv.0}{@callord intoZ _}{@set%A.[__]Z 32}{@/}{@set+Y A}{@echoj"\n"A,Y}

```

This is quite a messy mess...

But you can try it on http://sandbox.onlinephpfunctions.com/code/825bbd653f036fce8cc12f639c982ec5eed793ea (Please don't use PHP 8.0.0)

Thanks MarcMush for the idea that saved me 30 bytes.

---

**Ungolfed:**

This should be a lot easier to read.

```
{@set numbers as 0, 0, 0}

{@each argv.0 as letter key key}
    {@call ord into tmp letter}
    {@set% numbers.[key] tmp 32}
{@/}

{@set+ sum numbers}
{@echo separator "\n" numbers, sum}

```

---

**Explanation:**

I will explain how the golfed version works.

* `{@eachargv.0}` \- loops through the first argument. `argv` is an array with all passed arguments.
The ungolfed version defines variables for the key as value: `{@each argv.0 as letter key key}`.
The default names are `_` for the value and `__` for the key.
* `{@callord intoZ _}` \- calls the function `ord` passing `_` as a value and storing into `Z`.
`Z` is the same as `tmp` in the ungolfed version.
* `{@set%A.[__]Z 32}` \- `set` is used to define a variable, and you can pass it a value.
If you add a `%` before the variable, it calculates the remainder of the values (in this case, `Z` divided by 32). By magic, this handles letters A-Z and a-z, and maps them to A\>1, B\>2 ... Z\>26.
The result is stored into `A.[__]` (`numbers.[key]` in the ungolfed version).
* `{@/}` \- closes the `@each` loop
* `{@set+Y A}` \- `set` is used to define a variable, and you can pass it a value. If you add a `+` after, it indicates that it will receive the sum of all the passed values.
In this case, it will sum all the numbers (`A`) and store into `Y`. The ungolfed version has `{@set+ sum numbers}`, which demonstrates a lot better the way it works.
* `{@echoj"\n"A,Y}` \- Outputs `A` and `Y`, joined by `"\n"`.
The ungolfed version has `{@echo separator "\n" numbers, sum}`.
`@echoj` is just a shorthand for `@echo separator`.
All values are separated by `"\n"`, regardless of their type. This doesn't output a newline at the end!

# Answer
> 2 votes
# PHP -F, 55 bytes

```
for(;$c=ord($argn[$i++])%32;$r+=$c)echo"$c
";echo"$r
";

```

Try it online!

Quite straightforward solution..

# Answer
> 2 votes
# Grok, 35 bytes

```
j
:zhq
hx{y1py1pw*25xxY+zPY%*48py1p

```

Try it Online!

Gets input, then starts moving left through the main program, which juggles the register, where the running sum is stored, and the stack, where the input and some calculations are stored. Once all letters are printed and added, execution moves up to the middle row, where the sum is printed and execution ends.

# Answer
> 2 votes
# jq, 22 bytes

```
[explode[]%32]|.[],add

```

Try it online!

quite useful that `.[]` prints numbers with newlines.

# Answer
> 2 votes
# , ~~32~~ 24 bytes

```
echo,.(,+/)32|3 u:1!:1[3

```

Full program, -8 bytes thanks to Conor.

Attempt This Online!

```
echo,.(,+/)32|3 u:1!:1[3
                  1!:1[3  NB. read from stdin
              3 u:        NB. convert to char codes
           32|            NB. mod 32
      (,+/)               NB. monadic hook
        +/                NB. sum nums
       ,                  NB. append sum to nums
    ,.                    NB. make a column
echo                      NB. print

```

# Answer
> 2 votes
# PowerShell, 53 ~~60~~ bytes

*-7 bytes thanks to @Julian*

> By encapsulating the first command in parenthesis, I was able to skip the second command which just printed $t and saved 1 byte. The other 6 bytes were from replacing ***$t='a','b','c'*** with ***$t=$args***.

```
($t=$args|%{[byte][char]$_%32});($t|measure -sum).sum

```

Try it online!

**Explanation**

```
($t=               # $t will be set to an array of ints returned
$args              # 'a','b','c' is passed through aka $args
|                  # pipes into the next command
%{                 # for loop
[byte][char]$_     # accepts char and returns int (ie. [byte][char]'a' returns 97)
%32                # x mod 32 returns position in alphabet
})                 # completes for loop and encapsulation
;                  # divider between commands
($t                # passes the ints returned from the command above
|                  # pipe into next command
measure -sum       # measures the array and adds the sum property
).sum              # only returns the sum property

```

# Answer
> 1 votes
# C (gcc), 60 bytes

```
i,j;f(char*s){for(i=0;printf("%d\n",j=*s&31?:i),*s++;i+=j);}

```

Try it online!

# Answer
> 1 votes
# Pyth, 11 bytes

```
j+=%R32CMQs

```

Try it here!

# Answer
> 1 votes
# Red, ~~58~~ 57 bytes

-1 byte thanks to dingledooper!

```
func[a][s: 0 foreach c a[s: s + probe 1 * c % 32]print s]

```

Try it online!

Takes a 3-letter string as input. Iterates over the string, converts each character to an integer `(1 * c)` and maps it to `1-26` by `% 32`. Prints this at each step using `probe` (it returns a value) and updates the sum, which is printed at the end.

## Full program (works in Red console), ~~53~~ 52 bytes

-1 byte thanks to dingledooper!

```
s: 0 foreach c input[s: s + probe 1 * c % 32]print s

```

# Answer
> 1 votes
# Charcoal, 15 bytes

```
≔ＥＳ﹪℅ι³²θ⊞θΣθＩθ

```

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

```
≔ＥＳ﹪℅ι³²θ

```

Map the input string into ASCII ordinals and reduce modulo 32.

```
⊞θΣθ

```

Append the sum.

```
Ｉθ

```

Output everything in decimal.

# Answer
> 1 votes
# Excel, 65 bytes

```
=LET(n,ROW(1:4),a,MOD(CODE(MID(A1&" ",n,1)),32),IF(n=4,SUM(a),a))

```

Link to Spreadsheet

# Answer
> 1 votes
# Japt `-R`, 9 bytes

```
Ëc %H
pUx

```

Try it

```
Ëc %H\npUx     :Implicit input of character array
Ë              :Map
 c             :  Charcode
   %H          :  Mod 32
     \n        :Assign to variable U
       p       :Push
        Ux     :  U reduced by addition
               :Implicit output joined with newlines

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
Ç32%€=O?

```

Try it online or verify the entire alphabet at once.

**Explanation:**

```
Ç         # Get the ASCII values of the characters in the (implicit) input-string
 32%      # Modulo each by 32
    €     # For-each over these integers:
     =    #  Print the integer with trailing newline (without popping)
      O   # Take the sum of the list
       ?  # And output it (without newline) as well

```

# Answer
> 1 votes
# MathGolf, 7 bytes

```
$♥%_Σ▐n

```

Input as a list of characters.

Try it online.

**Explanation:**

```
$        # Get the ordinal value of each character in the (implicit) input-list
 ♥%      # Modulo-32
   _     # Duplicate this list of integers
    Σ    # Sum the duplicated list
     ▐   # Append it to the original list
      n  # Join this list by newlines
         # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
Using 3 inividual chars as input: (Not sure if allowed)

# Java (JDK), 73 bytes

```
(a,b,c)->System.out.print(a%32+"\n"+b%32+"\n"+c%32+"\n"+(a%32+b%32+c%32))

```

Try it online!

Using a string as input:

# Java (JDK), 110 bytes

```
s->{byte[]a=s.getBytes();System.out.print(a[0]%32+"\n"+a[1]%32+"\n"+a[2]%32+"\n"+(a[0]%32+a[1]%32+a[2]%32));};

```

Try it online!

# Answer
> 1 votes
# *Acc!!*, 122 bytes

```
Count i while i-4 {
(_/80+_%80)*80+N%32
_/80^(i/3)
Count t while _%80/10*0^t {
Write _%80/10+48
}
Write _%10+48
Write 10
}

```

Try it online!

### Explanation

We conceptually partition the accumulator into two sections, `_/80` and `_%80`. The latter holds each letter's index; the former holds the running sum of letter indices. (The number 80 is chosen because it's both divisible by 10 and larger than any number we'll have to handle.) We loop four times: each time, we read a new character into `_%80` and add the previous character's index to `_/80`, but on the fourth iteration we then divide the accumulator by 80, effectively moving the sum into the `_%80` slot. We then output the one-or-two-digit number in `_%80`, followed by a newline.

```
# Loop four times
Count i while i - 4 {
    # Set _ to: sum of _/80 and _%80, times 80, plus character code from stdin mod 32
    (_ / 80 + _ % 80) * 80 + (N % 32)
    # If i = 3, divide _ by 80; if i < 3, no-op
    _ / 80 ^ (i / 3)
    # Loop once if _%80 >= 10
    Count t while (_ % 80) / 10 * (1 - t) {
        # Print the tens digit of _%80
        Write (_ % 80) / 10 + 48
    }
    # Print the ones digit of _%80
    Write (_ % 80) % 10 + 48
    # Print a newline
    Write 10
}

```

# Answer
> 1 votes
# Zsh, 38 bytes

```
for i;echo $[j=##$i:u-64,k+=j,j]
<<<$k

```

Try it online!

# Answer
> 1 votes
# Thunno `N`, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
O32%DST

```

Attempt This Online!

#### Explanation

```
O32%DST  # Implicit input
O        # Ordinals
 32%     # Mod 32
    D    # Duplicate
     ST  # Append sum
         # N flag joins by newlines
         # Implicit output

```

# Answer
> 1 votes
# Fig, \\$8\log\_{256}(96)\approx\\$ 6.585 bytes

```
SM',%32C

```

Try it online!

Sorta-port of 05AB1E.

```
SM',%32C # Takes input as a list of chars
 M'      # Map each char
       C # Get the charcode
    %32  # Modulo 32
   ,     # And print (returning the thing printed)
S        # Sum the resulting list
         # Which gets implicitly printed

```

# Answer
> 1 votes
# Java 8 (OpenJDK 8), 75 ~~107~~ bytes

> *-32 bytes.
I don't know why i didn't think sooner of using `peek` even though it has been invented specifically for this kind of case!*

Using only a single inline Java Stream, takes String as parameter.

```
s->System.out.print(s.chars().map(e->e%32).peek(System.out::println).sum())

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 51 ~~55~~ bytes

*-4 bytes thanks to @xigoi !*

For the first time, i got the shortest JS answer!

```
s=>Buffer(s).map(e=>(a+=e%=32,e),a=0).join`
`+`
`+a

```

Try it online!

---

Alternative solution using an accumulator for the resulting string to try to get rid of the join and the double newline (**56 bytes**, improved with @xigoi's tip too) :

```
s=>Buffer(s).map(e=>(a+=(e%=32)+`
`,b+=e),a="",b=0)&&a+b

```

---

Alternative way to calculate the sum and regroup before joining (**56 bytes**. I wonder if the 2 join could be declared only once and called 2 times with different parameters) :

```
s=>[...r=Buffer(s).map(e=>e%32),eval(r.join`+`)].join`
`

```

# Answer
> 0 votes
# CSASM v2.5.1, 155 bytes

```
func main:
in ""
conv ~arr:char
dup
dup
lda 0
sta $1
.lbl a
ldelem $1
conv i32
push 31
and
dup
print.n
push $a
add
pop $a
inc $1
push $1
push 3
sub
brtrue a
push $a
print.n
ret
end

```

A simple loop which goes over each character.

**Explanation:**

```
func main:
    ; Get the input as a string, then convert it to an array of characters
    in ""
    conv ~arr:char

    ; Duplicate the array twice
    dup
    dup

    ; Initialize $a and $1 to 0
    lda 0
    sta $1

.lbl a
    ; Load the character at index $1, convert it to an integer, bitwise-AND it with 31, duplicate it, then print it
    ldelem $1
    conv i32
    push 31
    and
    dup
    print.n

    ; Add the duplicated value to $a
    push $a
    add
    pop $a

    ; Increment $1 and break from the loop when $1 == 3
    inc $1
    push $1
    push 3
    sub
    brtrue a

    ; Print $a, which now contains the sum of the characters
    push $a
    print.n

    ret
end

```

# Answer
> 0 votes
# Alice, 28 bytes

```
!3wi' %.?+!/ O \t.$K?/ O \@

```

Try it online!

The trailing new line is required for the ordinal mode to work.

```
!          Initialises the sum to 0
3w         Main loop with 3 iterations
i' %       Reads one character from the input as its ascii code, modulus 32 (32 is the ascii code of <space>)
.?+!       Adds the index of the character to the sum
/ O \      Prints the current character index
t.$K       End of the loop
?/ O \@    Prints the sum and exits

```

# Answer
> 0 votes
# Thunno 2 `N`, 4 bytes

```
ÄDSa

```

Try it online!

#### Explanation

```
ÄDSa  # Implicit input
Ä     # Num to alphabet
 DS   # Sum without popping
   a  # Append the sum
      # Join on newlines
      # Implicit output

```

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