title: Von Neumann Neighborhood

text:
# Question
Title: Von Neumann Neighborhood
Your goal is to make a function that takes the coordinates of a cell in 2D space and a distance \\$r\\$ and returns the coordinates of all cells in the input coordinate's von Neumann neighborhood of radius \\$r\\$. That is, all cells at most \\$r\\$ away in Manhattan distance. For example, given the following cell coordinates and radius pairs:

```
[1, 1], 1 -> [0, 1], [1, 0], [1, 1], [1, 2], [2, 1]
[2, 2], 2 -> [0, 2], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [4, 2]

```

This is what the von Neumann neighborhood looks like:

More information about the von Neumann neighborhood can be found here.

This is , so shortest amount of bytes wins!

# Answer
> 3 votes
# Vyxal, 11 bytes

```
k□0zJẋΠṠUMṠ

```

Try it online! Takes \\$r\\$ then the coordinate.

```
k□          # cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
  0z        # 0 zipped into self  [[0,0]]
    J       # join                [[0,1],[1,0],[0,-1],[-1,0],[0,0]]
     ẋ      # repeated into a list r times
      Π     # reduce by cartesian product
       Ṡ    # vectorising sum
        U   # remove duplicates
         M  # pair each direction into the input coordinate
          Ṡ # and sum to it

```

# Answer
> 5 votes
# APL (Dyalog Extended), 23 bytes

-4 thanks to ovs.

Anonymous tacit infix function, taking coordinates of a cell and radius as left and right arguments. Requires 0-based indexing.

```
{⍺∘+¨⍵-⍸⍵≥+/¨|∘.,⍨⍵…-⍵}

```

Try it online!

`{``}` "dfn"; left argument is  and right argument is :

`⍵…-⍵` inclusive integer range from radius to negative radius

`∘.,⍨` Cartesian selfie product

`⊢m←` assign to `m` and pass that

`|` absolute values

`+/¨` sum each (gives matrix of Manhattan distances)

`⍵≥` indicate which ones are less than or equal to the radius

**ɩ**ndices where true

`⍵-` subtract from radius

`⍺∘+¨` add the cell coordinates to each

# Answer
> 3 votes
# Perl 5, 64 bytes

```
sub n($x,$y,$d){map{//;map[$x+$',$y+$_],-$d+abs..$d-abs}-$d..$d}

```

Try it online!

Saved 4 bytes, thanks to Xcali.

# Answer
> 2 votes
# 05AB1E, ~~14~~ 13 bytes

-1 thanks to ovs

```
D(ŸãʒÄO¹s@}€+

```

Try it online!

Takes input as range, coordinates

Explanation:

```
D duplicate the range in the stack
( negate
Ÿ push the range [-range..range]
ã Cartesian power
 ʒ filter
  Ä absolute value, vectorizes over each of the coordinates
   O sum - distance from 0,0
    ¹s@ less than or equals to the range
 } end filter
€ map
+ add, with the implicit center coordinate

```

# Answer
> 2 votes
# Jelly, 12 bytes

```
ŒRṗ2AS>³ƲÐḟ+

```

Try it online!

A dyadic link that accepts the radius and the point.

## Explanation

```
ŒRṗ2AS>³ƲÐḟ+   Main dyadic link accepting r, [x,y]
ŒR             [-r..r]
  ṗ2           [-r..r]^2 (Cartesian product)
         Ðḟ    Filter out by
        Ʋ      (
    A            Absolute value (of both)
     S           Sum
      >³         Greater than r
        Ʋ      )
           +   Add [x,y] to each

```

# Jelly, 13 bytes

```
ŒRAạ³ŒR;€Ʋ€Ẏ+

```

Try it online!

A dyadic link that accepts the radius and the point.

## Explanation

```
ŒRAạ³ŒR;€Ʋ€Ẏ+   Main dyadic link accepting r, [x,y]
ŒR              [-r..r]
          €     For each i in [-r..r]
         Ʋ      (
  A               |i|
   ạ³             |(|i| - r)|
     ŒR           [-|(|i| - r)| .. |(|i| - r)|]
       ;€         Join each with i
         Ʋ      )
           Ẏ    Tighten (flatten by one level)
            +   Add [x,y] to each

```

# Answer
> 2 votes
# , 75 bytes

```
function(c,r)(d=t(expand.grid(c[1]+-r:r,c[2]+-r:r)))[,colSums(abs(d-c))<=r]

```

Try it online!

**How? Un-golfed code**

```
vnn=function(c,r)                       # c = (x,y) coordinates; r = radius
d=expand.grid(c[1]+(-r:r),c[2]+(-r:r))) # d = all combinations of coordinates from x-r to x+r, y-r to y+r
d=t(d)                                  # transpose d so that (x,y) coordinates are rows instead of columns
d[,colSums(abs(d-c))<=r]                # select the columns for which the sum of absolute differences to
                                        # the given (x,y) are less than or equal to r
                                        # (note that R recycles c to subtract it from every pair of elements
                                        # by row in d, so 'd-c' produces all the differences in x,y coordinates)

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 41 bytes

```
oo+#&/@DiamondMatrix@#~Position~1-#-1&

```

Try it online!

# Answer
> 1 votes
# Haskell, 52 bytes

```
(a,b)!r=[(a+k,b+j)|k<-[-r..r],j<-[abs k-r..r-abs k]]

```

Try it online!

I'm sure someone will figure out a more clever way to do this that isn't nearly so long. But for now I am stumped.

# Answer
> 1 votes
# , 28 bytes

```
+"1](]#~(>:1#.|))>@,@{@;~@i:

```

Try it online!

* `+"1...` Add the left argument (the center point) to each element of the right argument (the width) after transforming the right argument by `...`
* `i:` The first part of that transformation is the "both direction" integers of the width. Eg, `i: 2` produces `_2 _1 0 1 2`.
* `>@,@{@;~@` Take the Cartesian product of that bi-directional integer list with itself `{@;~`, flatten the result `,` and unbox `>@`.
* `](]#~...)` Now filter that Cartesian product result by the following...
* `(>:1#.|)` For each point on the list, is the sum `1#.` of the absolute values `|` of the `x` and `y` coordinates greater than or equal to `>:` the original right arg (the width)?

# Answer
> 1 votes
# Python 3, 81 bytes

```
lambda x,y,d:[(x+i,y+j)for i in range(-d,d+1)for j in range(abs(i)-d,d+1-abs(i))]

```

Try it online!

Three bytes saved, thanks to ovs.

# Answer
> 1 votes
# Python 3, 79 bytes

```
f=lambda s,r:{s}|{(a+x,b+d-x)for d in(1,-1)*r for a,b in f(s,r-1)for x in(0,d)}

```

Try it online!

# Answer
> 1 votes
# Scala, 61 bytes

```
(x,y,r)=>for(a<- -r to r;d=r-a.abs;b<-y-d to y+d)yield(x+a,b)

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 146 bytes

```
int[][]f(int x,int y,int d){int i=~d,r[][]=new int[1-2*d*i][],p=0,a,j;for(;i++<d;)for(j=a=i<0?d+i:d-i;j>~a;)r[p++]=new int[]{x+i,y+j--};return r;}

```

Try it online!

minus 6 bytes, thanks to ceilingcat

minus 2 bytes, thanks to ceilingcat

# Answer
> 1 votes
# PowerShell, 82 bytes

```
$x,$y,$r=$args;-$r..$r|%{$i=$_;($d=($i-replace'-')-$r)..-$d|%{,(($x+$i),($y+$_))}}

```

Try it online!

# Answer
> 1 votes
# Python 3, 75 bytes

```
f=lambda s,r:{s}|{(a+x//3,b-1+x%3)for x in(-2,4,0,2)*r for a,b in f(s,r-1)}

```

Try it online!

# Answer
> 1 votes
# Scala, 59 bytes

```
(x,y,r)=>for(a<- -r to r;d=a.abs-r;b<-d to-d)yield(x+a,y+b)

```

Try it online!

# Answer
> 1 votes
# JavaScript (V8), 75 bytes

```
p=>n=>{for(i=-n;i<=n;++i)for(j=k=n-(i*i)**.5;j>=-k;)print(p[0]+i,p[1]+j--)}

```

Try it online!

# Answer
> 0 votes
# Pyth, 38 bytes

```
AQf!>+ahThGaeTeGH*r-hGHh+hGHr-eGHh+eGH

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 58 bytes

```
(x,y,d)->[(x+i,y+j) for i=-d:d,j=-d:d if abs(i)+abs(j)<=d]

```

Try it online!

---
Tags: code-golf, cellular-automata
---


title: Shift distance of number

text:
# Question
Title: Shift distance of number
Given two non-zero 16-bit integers `a` and `b`, decide the smallest number of shift operations needed to turn `a` into `b`. A shift is one of the following (big-endian) operations:

* `shl` (shift left): move all bits to the left, adding a `0x0` bit to the right.
* `shr` (shift right): move all bytes to the right, adding a `0x0` bit to the left.
* `sar` (arithmetic shift right): move all bits to the right, duplicating the leftmost bit.
* `rol` (rotate left): move all bits to the left, replacing the rightmost bit with the leftmost bit.
* `ror` (rotate right): move all bits to the right, replacing the leftmost bit with the rightmost bit.

Or, if the number is expressed in 16-bit big-endian binary x15x14...x1x0, then allowed operations are listed as following:

```
(original)  x15 x14 x13 x12 x11 x10  x9 x8 x7 x6 x5 x4 x3 x2 x1  x0
shl         x14 x13 x12 x11 x10  x9  x8 x7 x6 x5 x4 x3 x2 x1 x0   0
shr           0 x15 x14 x13 x12 x11 x10 x9 x8 x7 x6 x5 x4 x3 x2  x1
sar         x15 x15 x14 x13 x12 x11 x10 x9 x8 x7 x6 x5 x4 x3 x2  x1
rol         x14 x13 x12 x11 x10  x9  x8 x7 x6 x5 x4 x3 x2 x1 x0 x15
ror          x0 x15 x14 x13 x12 x11 x10 x9 x8 x7 x6 x5 x4 x3 x2  x1

```

Test cases:

```
1, 4 => 2 # shl, shl
10, 8 => 4 # shr, shr, shl, shl
1, 65535 => 16 # ror, sar*15

```

Shortest code wins.

# Answer
> 4 votes
# JavaScript (ES6), 107 bytes

*-5 thanks to @l4m2*

Expects `(a)(b)`.

```
p=>g=q=>g[g[p]=q]?0:1+g(q,(_=>{for(v in g)[v*2,h=v/2,v<<15|h,v>>15|v*2,v&1<<15|h].map(v=>g[v&65535]=1)})())

```

Try it online!

### Commented

```
p =>                     // p = initial value
g = q =>                 // q = target value
g[g[p] = q]              // mark p as already found
?                        // if q was found:
  0                      //   stop the recursion
:                        // else:
  1 +                    //   increment the final result
  g(                     //   do a recursive call:
    q,                   //     pass q
    ( _ => {             //     dummy function to process a for
      for(v in g) [      //     for each value v found so far:
        v * 2,           //       compute shl
        h = v / 2,       //       compute shr
        v << 15 | h,     //       compute ror
        v >> 15 | v * 2, //       compute rol
        v & 1 << 15 | h  //       compute sar
      ]                  //
      .map(v =>          //       and for each of them:
        g[v & 65535]     //         keep the 16 lower bits
        = 1              //         and mark the result as found
      )                  //       end of map()
    })()                 //     end of for
  )                      //   end of recursive call

```

# Answer
> 2 votes
# Python 3, 255 bytes

```
def f(x,y,i=0):
 while 1:
  for p in product(*[[lambda n:n[1:]+'0',lambda n:n[:-1],lambda n:n[0]+n[:-1],lambda n:n[1:]+n[0],lambda n:n[-1]+n[:-1]]]*i):
   r=x
   for q in p:r=int(q(bin(r)[2:].zfill(16)),2)
   if r==y:return i
  i+=1
from itertools import*

```

Try it online!

Brute force method (very slow). It goes through every single possibility. The last test case times out on TIO.

Takes in two integers and returns an integer.

---

**Explanation:**

```
def f(x,y,i=0):                                 # Create a function, f, which takes in x and y. Define i as 0
 while 1:                                       # Forever:
  for p in product(*[...]*i):                   #   Go through every combination of length i. (Five functions have been defined here, each corresponding to one of the shifts/rotations)
   r=x                                          #     Set r to x
   for q in p:r=int(q(bin(r)[2:].zfill(16)),2)  #     Apply each function in p to r
   if r==y:return i                             #     If r equals y, return i (the number of functions we applied)
  i+=1                                          #   Add one to i
from itertools import*                          # Import the itertools library

```

# Answer
> 1 votes
# Charcoal, 61 bytes

```
≔⟦Ｎ⟧θＮη≔Ｘ⁸¦⁵ζＷ¬№θη«≔ΣＥθ⟦⊗﹪κζ÷κ²⁺＆κζ÷κ²⁺⊗﹪κζ÷κζ⁺×﹪κ²ζ÷κ²⟧θ→»Ｉⅈ

```

Attempt This Online! Link is to verbose version of code. Explanation: Lots of brute force, so times out for anything interesting.

```
≔⟦Ｎ⟧θ

```

Start with having discovered `a`.

```
Ｎη

```

Input `b`.

```
≔Ｘ⁸¦⁵ζ

```

Precompute `32768`.

```
Ｗ¬№θη«

```

Repeat until `b` is discovered.

```
≔ΣＥθ⟦⊗﹪κζ÷κ²⁺＆κζ÷κ²⁺⊗﹪κζ÷κζ⁺×﹪κ²ζ÷κ²⟧θ

```

Replace each discovered value with the results of its five shifts.

Keep track of the number of shifts taken.

```
»Ｉⅈ

```

Output the required number of shifts.

106 bytes for a less inefficient version that also outputs the list of shifts required:

```
≔Ｘ⁸¦⁵ζ≔Ｅ⊗ζ⟦⟧η⊞υＮＮθＦυＦ¬§ηθＦ⁵«≔§⟦⊗﹪ιζ÷ι²⁺＆ιζ÷ι²⁺⊗﹪ιζ÷ιζ⁺×﹪ι²ζ÷ι²⟧λκＦ¬§ηκ«§≔ηκ⁺§ηι⟦§⪪”&→∧¡?kiNⅉ｜Ｍ”³λ⟧⊞υκ»»§ηθ

```

Try it online! Link is to verbose version of code. Requires `a` and `b` to be different. Explanation:

```
≔Ｘ⁸¦⁵ζ

```

Precompute 32768.

```
≔Ｅ⊗ζ⟦⟧η

```

Start with not having discovered anything.

```
⊞υＮ

```

Start a breadth-first search at `a`.

```
Ｎθ

```

Input `b`.

```
ＦυＦ¬§ηθ

```

Loop over the discovered numbers until `b` has been discovered.

```
Ｆ⁵«≔§⟦⊗﹪ιζ÷ι²⁺＆ιζ÷ι²⁺⊗﹪ιζ÷ιζ⁺×﹪ι²ζ÷ι²⟧λκ

```

Loop over the five shifts and compute the current shift's value.

```
Ｆ¬§ηκ«

```

If this value has not yet been discovered, then...

```
§≔ηκ⁺§ηι⟦§⪪”&→∧¡?kiNⅉ｜Ｍ”³λ⟧

```

... record the shifts needed to reach it, and...

```
⊞υκ

```

... add it to the list of discovered values.

```
»»§ηθ

```

Output the shifts needed to reach `b`.

---
Tags: code-golf, bitwise
---


# Question
Title: Find The Sum of the First n Bouncy Numbers
**Terminology**

An increasing number is one where each digit is greater than or equal to all the digits to the left of it (ex. 12239)

A decreasing number is one where each digit is less than or equal to all the digits to the left of it (ex. 95531)

A bouncy number is any number that is not increasing or decreasing. Since this requires at least 3 digits, the first bouncy number is 101

**The task**

Given an integer n greater than or equal to 1, find the sum of the first n bouncy numbers

**Rules**

* This is code golf, so the answer with the shortest amount of bytes wins
* If your language has limits on integer size (ex. 2^32-1) n will be small enough that the sum will fit in the integer
* Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc)
* Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc)

**Test cases**

```
1 > 101
10 > 1065
44701 > 1096472981

```

# Answer
# Jelly, ~~10~~ 8 bytes

```
ṢeṚƬ¬µ#S

```

Try it online!

### How it works

```
ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.

```
> 8 votes

# Answer
# Pyth, 10 bytes

```
s.f!SI#_B`

```

Try it here!

### How it works?

```
s.f!SI#_B` – Full program. Takes an integer Q from STDIN and outputs to STDOUT.
 .f        – Find the first Q positive integers that satisfy a certain condition.
   !SI#_B  – The condition. Returns true for bouncy numbers only.
       _B` – Cast the number to a string and bifurcate (pair) it with its reverse.
      #    – Filter-keep those...
     I     – That are invariant under...
    S      – Sorting.
           – To clarify, I (invariant) is a Pyth operator that takes two inputs, a
             function and a value and checks whether function(value) == value, so
             this is technically not a built-in.
   !       – Logical not. The empty list gets mapped to true, other values to false.
s          – Sum.

```
> 6 votes

# Answer
# K (ngn/k), 37 bytes

```
{+/x{{(a~&\a)|a~|\a:10\x}(1+)/x+1}\0}

```

Try it online!

`{` `}` is a function with argument `x`

`x{` `}\0` applies the `{}` on `0` `x` times, preserving the intermediate results

`(1+)` is the successor function

`{` `}(1+)/x+1` applies the successor function starting from `x+1` until the `{}` returns true

`10\x` are the decimal digits of `x`

`a:` assign to `a`

`|\` is the max-scan (partial maxima) of `a`

`&\` analogously, is the min-scan

`a~|\a` does `a` match its max-scan?

`|` or

`a~&\a` its min-scan?

`+/` sum
> 4 votes

# Answer
# JavaScript (ES6), 77 bytes

```
f=(i,n=0,k,p)=>i&&([...n+''].map(x=>k|=x<p|2*(p<(p=x)))|k>2&&i--&&n)+f(i,n+1)

```

Try it online!

### Commented

```
f = (                     // f = recursive function taking:
  i,                      //   i = number of bouncy numbers to find
  n = 0,                  //   n = current value
  k,                      //   k = bitmask to flag increasing/decreasing sequences
  p                       //   p = previous value while iterating over the digits
) =>                      //
  i && (                  // if there's still at least one number to find:
    [...n + '']           //   turn n into a string and split it
    .map(x =>             //   for each digit x in n:
      k |=                //     update k:
        x < p |           //       set bit #0 if x is less than the previous digit
        2 * (p < (p = x)) //       set bit #1 if x is greater than the previous digit
                          //       and update p
    )                     //   end of map()
    | k > 2               //   if both bits are set (n is bouncy):
    && i--                //     decrement i
    && n                  //     and add n to the total
  ) + f(i, n + 1)         //   add the result of a recursive call with n + 1

```
> 4 votes

# Answer
# Python 2, 84 bytes

```
i=s=0
n=input()
while n:b=`i`>`sorted(`i`)`[2::5]<`i`[::-1];n-=b;s+=b*i;i+=1
print s

```

**Try it online!** Or see a test-suite.
> 4 votes

# Answer
# Python 2, ~~110~~ ~~92~~ 89 bytes

```
n=input()
x=s=0
while n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1
print s

```

**Try it online**

This function determines if a number is bouncy:

```
lambda x:{-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]))

```
> 3 votes

# Answer
# Retina, 93 bytes

```
K`:
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(#*).*
:$1#;$.($1#
)`\d
*_;
)`:(#+).*
$1:$1
\G#

```

Try it online! Explanation:

```
K`:

```

Initialise `s=i=0`. (`s` is the number of `#`s before the `:`, `i` the number of `#`s after.)

```
"$+"{
...
)`

```

Repeat `n` times.

```
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)`

```

Repeat while `i` is not bouncy.

```
:(#*).*
:$1#;$.($1#

```

Increment `i` and make a copy in decimal.

```
\d
*_;

```

Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once `i` has been incremented at least once.

```
:(#+).*
$1:$1

```

Add `i` to `s` and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and `i` gets incremented at least once.

```
\G#

```

Convert `s` to decimal.

121 byte version calculates in decimal, so might work for larger values of `n`:

```
K`0:0
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(\d+).*
:$.($1*__);$.($1*__)
)+`;\d
;$&*_;
)`\d+:(\d+).*
$.(*_$1*):$1
:.*

```

Try it online! Explanation:

```
K`0:0

```

Initialise `s=i=0`.

```
"$+"{
...
)`

```

Repeat `n` times.

```
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)

```

Repeat while `i` is not bouncy.

```
:(\d+).*
:$.($1*__);$.($1*__)

```

Increment `i` and make a copy.

```
+`;\d
;$&*_;

```

Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once `i` has been incremented at least once.

```
\d+:(\d+).*
$.(*_$1*):$1

```

Add `i` to `s` and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and `i` gets incremented at least once.

```
:.*

```

Delete `i`.
> 3 votes

# Answer
# 05AB1E, 12 bytes

```
µN{Â‚Nå_iNO¼

```

Try it online!

**Explanation**

```
µ              # loop over increasing N until counter equals input
     Nå_i      # if N is not in
 N{Â‚          # the pair of N sorted and N sorted and reversed
         NO    # sum N with the rest of the stack
           ¼   # and increment the counter

```
> 3 votes

# Answer
# Java 8, ~~114~~ 112 bytes

```
n->{int i=0,s=0;for(;n>0;++i)s+=(""+i).matches("0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*")?0:--n*0+i;return s;}

```

Uses a regular expression to check if the number is increasing or decreasing. Try it online here.

Ungolfed:

```
n -> { // lambda
    int i = 0, // the next number to check for bounciness
        s = 0; // the sum of all bouncy numbers so far
    for(; n > 0; ++i) // iterate until we have summed n bouncy numbers, check a new number each iteration
        s += ("" + i) // convert to a String
             .matches("0*1*2*3*4*5*6*7*8*9*" // if it's not an increasing  number ...
             + "|9*8*7*6*5*4*3*2*1*0*") ? 0 // ... and it's not a decreasing number ...
             : --n*0 // ... we have found another bouncy number ...
               + i; // ... add it to the total.
    return s; // return the sum
}

```
> 3 votes

# Answer
# Python 2, 250 bytes

```
n=input()
a=0
b=0
s=0
while a<n:
    v=str(b)
    h=len(v)
    g=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]>=v[f-1]]
    d=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]<=v[f-1]]
    if len(g)!=h-1 and len(d)!=h-1:
       a+=1
       s+=b
    b+=1
print s

```
> 2 votes

# Answer
# Nibbles, 9 bytes

```
+<$|,~~?`.`<;`p$\

```

(it would be 8.5 bytes if filesystems could store half bytes)

Similar to the Jelly answer.

```
+                # sum of
 <               # first n elements of
  $              # first input integer
   |  ~          # filter.not
    ,~           # range from 1 to infinity
       ?         # index of (begin of filter body)
        `.       # iterate while uniq
        `<       # sort
          ;`p$   # int to str of filter arg, also save value
              \  # reverse
                 # implicit $ (arg of iterate while uniq)
                 # implicit $ (saved value from `p)

```
> 2 votes

# Answer
# Stax, 14 bytes

```
Ö²àDæ▲☼Ty≡°lû↕

```

Run and debug it
> 1 votes

# Answer
# Vyxal, 7 bytes

```
fÞȮ¬)ȯ∑

```

Try it Online!

```
      ∑ # Sum of...
     ȯ  # First n integers...
----)   # Where...
f       # Digits
   ¬    # Are not
 ÞȮ     # Sorted

```
> 1 votes

# Answer
# Red, 108 bytes

```
func[n][i: s: 0 until[t: form i
if(t > u: sort copy t)and(t < reverse u)[s: s + i n: n - 1]i: i + 1
0 = n]s]

```

Try it online!

## More readable:

```
f: func [ n ] [
    i: s: 0
    until [
       t: form i
       if ( t > u: sort copy t ) and ( t < reverse u ) [
            s: s + i
            n: n - 1
       ]
       i: i + 1
       0 = n
    ]
    s
]

```

A good opportunity to use `form` \- `form i` is 5 bytes shorter than `to-string i`
> 0 votes

# Answer
# , 96 bytes

```
function(n){while(n){y=diff(T%/%10^(0:log10(T))%%10);g=any(y<0)&any(y>0);F=F+T*g;n=n-g;T=T+1};F}

```

Try it online!

**Explanation :**

```
while(n){                         # while n > 0

        T%/%10^(0:log10(T))%%10   # split T into digits(T==TRUE==1 at the 1st loop)
y=diff(                         ) # compute the diff of digits i.e. digits[i] - digits[i+1]

g=any(y<0)&any(y>0)               # if at least one of the diff is < 0 and
                                  # at least one is > 0 then T is "bouncy"

F=F+T*g                           # if bouncy increment F (F==FALSE==0 at the 1st loop)

n=n-g                             # decrement n by 1 if bouncy

T=T+1}                            # increment T by 1 and loop

F}                                # return F

```
> 0 votes

# Answer
# MATL, ~~31~~ 30 bytes

```
l9`tVdZS&*0<a?wQtG>?.]y]QT]xvs

```

Try it online!

```
l       % Initialize counter to 1
9       % First value to check for being bouncy
`       % Start do-while loop
  tV    % duplicate the current number and convert to string
        % (let's use the iteration where the number is 1411)
        % stack: [1, 1411, '1411']
  d     % compute differences between the characters
        %  For non-bouncy numbers, this would be either all
        %  positive values and 0, or all negative values and 0
        % stack: [1, 1411, [3 -3 0]]
  ZS    % keep only the signs of those differences
        % stack: [1, 1411, [1 -1 0]]
  &*    % multiply that array by its own transpose, so that
        %  each value is multiplied by every other value
        %  for non-bouncy numbers, all products will be >=0
        %  since it would have had only all -1s or all 1 (other than 0s)
        % stack: [1, 1411, [1 -1  0
                            -1  1 0
                            0  0  0]]
  0<a?  % if any value in the matrix is less than 0
    wQ    % switch the counter to top, increment it
          % stack: [1411, 2]
    tG>?  % duplicate it, check if it's gotten greater than the input limit
      .]    % if so, break out of loop
  y]    % else, duplicate bouncy number from inside stack,
        %  keeping a copy to be used for summing later
        % stack: [1411, 2, 1411]
  QT    % increment number, push True to continue loop
]     % loop end marker
x     % if we've broken out of loop, remove counter from stack
v     % concatenate the bouncy numbers we've collected in stack and
s     % sum them

```
> 0 votes

# Answer
## Ruby (123 106 bytes)

```
o=0
x=[?0]
(z=(x=(x.join.to_i+1).to_s.chars).sort)!=x&&z!=x.reverse ? (n-=1;o+=x.join.to_i):1while n>0
p o

```

Looks pretty ugly to me. Bounciness is defined in this block `x.sort!=x&&x.sort!=x.reverse`
> 0 votes

# Answer
# C (gcc), 104 bytes

```
f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}

```

Try it online here.

Ungolfed:

```
f(n, // function: return type and type of arguments defaults to int;
     // abusing extra arguments to declare variables
  i,   // number currently being checked for bounciness
  s,   // sum of the bouncy numbers
  j,   // copy of i to be used for checking bounciness in a loop
  p,   // used for investigating the last digit of j
  b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
    for(i = s = 0; // check numbers from zero up; initial sum is zero
        n; // continue until we have n bouncy numbers
        s += b ? 0 // not bouncy, no change to the sum
        : i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
        ++i) // either way, move to the next number
        for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
        // bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
            p = j % 10, // get the last digit
            j /= 10, // truncate one digit from the right
            b &= // adjust bounciness:
                 (p -= j % 10) // compare current digit to the next
                 < 0 ? // not an increasing number, clear second to least significant bit
                 : p ? 2 // not a decreasing number, clear least significant bit
                 : b; // keep it the same
    n = s; // gcc shortcut for return s
}

```
> 0 votes

# Answer
# Ruby, 76 bytes

```
->n,s=i=0{[d=(i+=1).digits,d.reverse].index(d.sort)||(s+=i;n-=1);n<1?s:redo}

```

Try it online!
> 0 votes

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


title: Hello, World! (Every other character)

text:
# Question
Title: Hello, World! (Every other character)
Write a program that prints "Hello, World!". But also, if you take only the first, third, fifth, etc. characters of your program, the resulting program should still print "Hello, World!".

If your program is:

```
abc
def

```

It should output "Hello, World!", but so should

```
acdf

```

No solutions with fewer than 2 characters.

# Answer
> 213 votes
# Python 3, 61 bytes

```
rant="partisn't"
print(("HHeelllloo,,  WWoorrlldd!!"""[::2]))

```

Try it online!

Abusing the fact that `print` is a function in Python 3 :)

The least partisan solution you'll find here on PPCG.

Becomes

```
rn=print
rn("Hello, World!"[:])

```

# Answer
> 62 votes
## Cardinal, 29 bytes

```
%
"
H
e
l
l
o
,

W
o
r
l
d
!

```

Try it online!

Removing every other character removes all the linefeeds, which still results in `Hello, World!`:

```
%"Hello, World!

```

Try it online!

The reason this works is that `%` creates four instruction pointers, moving in each of the four cardinal directions. IPs that leave the source code are simply removed. So in the first case, only the south-going IP remains and in the second case, only the east-going IP remains, all the others are simply dropped. In either case, the executed program is then just `"Hello, World!`. The `"` toggles to string mode where each cell is simply printed to STDOUT. We don't need to terminate the string, because leaving the source code still terminates the program.

Note that the same idea works in Beeswax, using `*` instead of `%` and ``` instead of `"` (this is because Beeswax was largely inspired by Cardinal but uses a hexagonal grid).

Try it online! (vertical) | | Try it online! (horizontal)

# Answer
> 52 votes
# C, 125 bytes

```
xpxuxtxs( ) { }xuxs ( ) { } main( ) {puts ( "Hello, World!" ) ; } mxaxixn ( ) {xpxuxtxs ( " H e l l o ,   W o r l d ! " ) ; }

```

Try it online!

**With even characters removed:**

```
xxxx(){}us(){}mi(){us("el,Wrd");}main(){puts("Hello, World!");}

```

Try it online!

# Answer
> 36 votes
# Actually, 2 bytes

```
HH

```

Explanation:

`H`, as you might expect, pushes `Hello, World!` to the stack.

The main program (`HH`) will encounter the first `H` and push `Hello, World!` to the stack. On the second `H`, however, it will try to use two arguments (as the stack needs to be empty to push `Hello, World!`) and fail. However, this error will be ignored and then `Hello, World!` will be implicitly printed.

The second program (`H`) will push `Hello, World!` once, and that will be impliclty printed.

This is similar to Fatalize's 2-byte answer, but this doesn't really "cheat".

Try it online!

# Answer
> 24 votes
# Lua, 89 bytes

```
--- [ [
print("Hello, World!")
--[[ ] ]
pCrAiLnCtU(L"AHTeOlRlFoE,L IWNoEr:lDd !:"D)
---]]

```

Try it online! As the syntax highlighting shows, this is massive comment abuse.

Alternate:

```
--[[pit"el,Wrd"
-[]]print("Hello, World!")--]

```

Try it online!

And for convenience, a program to convert a program into every other character form: Try it online!

# Answer
> 21 votes
# Retina, 39 bytes

```

HHeelllloo,,  WWoorrlldd!!

(.).x?
$1

```

Try it online!

Taking every other character gives:

```

Hello, World!
()x
1

```

Try it online!

The first program creates a string with the greeting duplicated. Then it replaces each pair of characters with the first character. There is also an empty stage that replaces all empty strings with empty strings in between, but that doesn't do anything. The second program fails to match the letter "x" so it doesn't replace anything after creating the greeting.

Perhaps more amusingly, if the third stage is changed slightly the first set of characters doesn't have to be the same message. This could lead to many identical length solutions such as full and halved.

# Answer
> 19 votes
# Charcoal, 25 bytes

```
H→e→l→l→o→,→ →W→o→r→l→d→!

```

Try it online!

If you remove the even characters, you just remove the arrow commands that indicate the direction of the next text, and that leaves the following code:

```
Hello, World!

```

Try it online!

That also prints the greeting.

# Answer
> 17 votes
# Haskell, 85 bytes

```
{--}main=putStr"Hello, World!"--} m a i n = p u t S t r " H e l l o ,   W o r l d ! "

```

Try it online!

Every second character removed:

```
{-mi=uSrHlo ol!-}main=putStr"Hello, World!"

```

Try it online!

This exploits the two comment formats in Haskell: `{- -}` for in-line or multi-line comments and `--` to comment the rest of the line.

# Answer
> 17 votes
# Javascript, 67 bytes

```
/**/alert`Hello, World`// * / a l e r t ` H e l l o ,   W o r l d `

```

Every second letter removed:

```
/*aetHlo ol`/*/alert`Hello, World`

```

Just like many other answers, this exploits comments.

# Answer
> 15 votes
# Brachylog, 4 bytes

```
Ḥ~wḤ

```

Try it online!

### Explanation

`~w` writes its right variable to `STDOUT`, and ignores its left argument.  is `"Hello, World!"`, so this prints `Hello, World!`.

If we only take the first and third chars, we get `Ḥw`. In that case `w` writes its left variable and ignores its right variable, so it also prints `Hello, World!`.

### 2 bytes

```
ḤḤ

```

Try it online!

This is technically a valid answer, but this unifies the output variable of the program instead of printing to `STDOUT`, so I guess the 4 bytes program is more in the spirit of the challenge.

# Answer
> 14 votes
# x86 machine code, 162 bytes

**PROG.COM** Download and run it in **MS-DOS** emulator, DOSBox for example.

```
90 B3 B4 B4 02 90 90 B3 B2 B2 48 90 90 B3 CD CD 21 90 90 B3 B2 B2 65 90
90 B3 CD CD 21 90 90 B3 B2 B2 6C 90 90 B3 CD CD 21 90 90 B3 CD CD 21 90
90 B3 B2 B2 6F 90 90 B3 CD CD 21 90 90 B3 B2 B2 2C 90 90 B3 CD CD 21 90
90 B3 B2 B2 20 90 90 B3 CD CD 21 90 90 B3 B2 B2 77 90 90 B3 CD CD 21 90
90 B3 B2 B2 6F 90 90 B3 CD CD 21 90 90 B3 B2 B2 72 90 90 B3 CD CD 21 90
90 B3 B2 B2 6C 90 90 B3 CD CD 21 90 90 B3 B2 B2 64 90 90 B3 CD CD 21 90
90 B3 B2 B2 21 90 90 B3 CD CD 21 90 90 B3 CD CD 20 90

```

after removal **MINI.COM** Download

```
90 B4 02 90 B2 48 90 CD 21 90 B2 65 90 CD 21 90 B2 6C 90 CD 21 90 CD 21
90 B2 6F 90 CD 21 90 B2 2C 90 CD 21 90 B2 20 90 CD 21 90 B2 77 90 CD 21
90 B2 6F 90 CD 21 90 B2 72 90 CD 21 90 B2 6C 90 CD 21 90 B2 64 90 CD 21
90 B2 21 90 CD 21 90 CD 20

```

## How to run?

Install DOSBox, for Ubuntu/Debian

```
sudo apt install dosbox

```

Run it

```
dosbox

```

**In DOSBOX**

```
mount c /home/user/path/to/your/directory
c:
PROG.COM
MINI.COM

```

## How does it works?

Machine **operation codes** represents **assembly** language **instructions**.

In MS-DOS to **print char** you will set registers and make interrupt. AH register will be 0x02, DL register contains your char. Interrupt vector is 0x21.

```
mov ah,0x2  ;AH register to 0x2 (B4 02)
mov dl,0x48 ;DL register to "H" (B2 48)
int 0x21    ;0x21 interrupt     (CD 21)

```

MS-DOS COM file tiny model is good choise, because it **doesn't have any headers**. It is limited by 64K, but in our case it doesn't matters.

To stop program use 0x20 interrupt

```
int 0x20    ;0x20 interrupt     (CD 20)

```

## Magic

If you want to execute **0xAB** opcode command with one parameter **0xCD**, you write

```
AB CD

```

In **PROG.COM**

```
90 B3 AB AB CD 90
nop         ; No operation (90)
mov bl,0xb4 ; BL register to AB (B3 AB)
AB CD command (AB CD)
nop         ; No operation (90)

```

In **MINI.COM**

```
90 AB CD
nop         ; No operation (90)
AB CD command (AB CD)

```

It is **equal** machine codes, if you don't use **BL register**.

## Generator

Convert text file with hex to hex binary

```
cat hex_file | xxd -r -p > exec.com

```

```
function byte2hex(byte){
 var ret=byte.toString(16).toUpperCase();
 return ret.length==1 ? "0"+ret : ret;
}

function str2hex(str){
 var ret = [];
 for(var i=0;i<str.length;i++){
  ret.push(byte2hex(str.charCodeAt(i)));
 }
 return ret;
}

function genCode(hexArr){
 var ret = [["B4","02"]];
 for(var i=0;i<hexArr.length;i++){
  if(hexArr[i]!=hexArr[i-1]){
   ret.push(["B2",hexArr[i]]);
  }
  ret.push(["CD","21"]);
 }
 ret.push(["CD","20"]);

 return ret;
}

function magicCode(str){
 var ret=[""];
 var code=genCode(str2hex(str));

 for(var i=0;i<code.length;i++){
  ret.push("90 B3 "+code[i][0]+" "+code[i][0]+" "+code[i][1]+" 90");
  if(i%4==3){ret.push("\n");}
 }
 return ret.join(" ");
}

function magicCodeMinified(str){
 var ret=[""];
 var code=genCode(str2hex(str));

 for(var i=0;i<code.length;i++){
  ret.push("90 "+code[i][0]+" "+code[i][1]);
  if(i%8==7){ret.push("\n");}
 }
 return ret.join(" ");
}

var str=prompt("string","Hello, world!");
var out="PROG.COM\n" + magicCode(str)+"\n\nMINI.COM\n"+magicCodeMinified(str);

document.write(out.replace("\n","<br>"));
alert(out);
```

# Answer
> 11 votes
# Haskell, 102 bytes

The full program:

```
main= putStr"Hello, World!";;
putSt   x ="p u t S t r  \" H e l l o ,   W o r l d !\"";
mmaaiin = main

```

and with every other character removed:

```
mi=ptt"el,Wrd";ptt x=putStr "Hello, World!";main=mi

```

# Answer
> 10 votes
# Pyth, 31 bytes

```
p% 2"HHeelllloo,,  WWoorrlldd!!

```

Try it online!

Becomes

```
p "Hello, World!

```

Thanks to @CalculatorFeline for pointing out an error and removing one byte.

# Answer
> 8 votes
# , 32 bytes

```
i;H;e;l;l;o;,; ;w;o;r;l;d;!;<esc>;Ó;

```

Note that `<esc>` is a single character, e.g. `0x1b`

Try it online!

Removing every other character gives:

```
iHello, world!<esc>Ó

```

Try it online!

# Answer
> 8 votes
# Jelly, ~~26~~ 25 bytes

```
““3ḅaė;œ»ḷ“ 3 ḅ a ė ; œ »

```

Try it online!

After removing every second character, we're left with the following code.

```
“3a;»“3ḅaė;œ»

```

Try it online!

### How it works

```
““3ḅaė;œ»ḷ“ 3 ḅ a ė ; œ »  Main link.

““3ḅaė;œ»                  Index into Jelly's dictionary to yield
                           ["", "Hello, World!"].
          “ 3 ḅ a ė ; œ »  Index into Jelly's dictionary to yield.
                          " FullERebitingBEfluffiest adoptable".
         ḷ                 Take the left result.

```

```
“3a;»“3ḅaė;œ»  Main link.

“3a;»          Index into Jelly's dicrionary to yield " N-".
               Set the argument and the return value to the result.
     “3ḅaė;œ»  Index into Jelly's dicrionary to yield "Hello, World!".
               Set the return value to the result.

```

# Answer
> 8 votes
# PHP, 53 bytes

```
#
echo date(
$e_c_h_o='\H\e\l\l\o\,\ \W\o\r\l\d\!
');

```

With every other character removed:

```
#eh ae
echo'Hello, World!';

```

# Answer
> 8 votes
# 05AB1E, 29 bytes

```
”ïŸŸ™ ,ï‚‚ï ! ”# ¦2 ä ø¨øJð ý

```

Try it online!

**Explanation**

```
”ïŸŸ™ ,ï‚‚ï ! ”                # push the string "Weekly Hello , Changed World ! "
               #               # split on spaces
                               # RESULT: ['Weekly','Hello',',','Changed','World','!','']
                ¦              # remove the first element (Weekly)
                 2ä            # split in 2 parts
                               # RESULT: [['Hello', ',', 'Changed'], ['World', '!', '']]
                   ø           # zip
                               # RESULT: [['Hello', 'World'], [',', '!'], ['Changed', '']]
                    ¨          # remove the last element
                     ø         # zip
                               # RESULT: [['Hello', ','], ['World', '!']]
                      J        # join each inner list
                       ðý      # join on space

```

After removing every other character we are left with the code

```
”Ÿ™,‚ï!” 2äøøðý

```

Try it online!

**Explanation**

```
”Ÿ™,‚ï!”       # push the string "Hello, World!"
        2ä     # split in 2 parts
               # RESULT: ['Hello, ', 'World!']
          ø    # zip, as the string has an odd length the space is lost
               # RESULT: ['HW', 'eo', 'lr', 'll', 'od', ',!']
           ø   # zip again
               # RESULT: ['Hello,', 'World!']
            ðý # join on space

```

# Answer
> 8 votes
# Cubically v2.1, 222 bytes

```
+0503 @@6 :22 //1 +050501 @@6 :55 +0502 @@6@6 :33 //1 +050502 @@6 :55 +03 //1 +04 @@6 :55 //1 +03 @@6 :55 +01 //1 +0504 @@6 :33 //1 +050502 @@6 :55 +01 //1 +050502 @@6 :55 +0502 @@6 :11 //1 +050501 @@6 :55 +01 //1 +03 @@6

```

Try it online!

Every other letter:

```
+53@6:2/1+551@6:5+52@66:3/1+552@6:5+3/1+4@6:5/1+3@6:5+1/1+54@6:3/1+552@6:5+1/1+552@6:5+52@6:1/1+551@6:5+1/1+3@6

```

Try it online!

# Answer
> 8 votes
# Befunge-93, ~~43~~ 41 bytes

Coming back to this a few years later, I found a way to avoid running those unsupported instructions, meaning this can even be run on implementations that treat those differently.

```
"!!ddllrrooWW  ,,oolllleeHH"""> :$# ,#__@

```

Try it online!

Second version

```
"!dlroW ,olleH">:#,_@

```

is the shortest possible "Hello World!". This therefore is the shortest possible answer to this question for Befunge-93.

Try It Online

# Answer
> 7 votes
# Octave, ~~49~~ 45 bytes

Saved 4 bytes since Octave doesn't require brackets to do indexing.

```
'HHeelllloo,,  WWoorrlldd!! ' (1:2 : 3 ^ 3)''

```

Try it online!

And the reduced one:

```
'Hello, World!'(:    )'

```

Try it online!

## Explanation:

The initial code has the letters in the string duplicated, so that we're left with `Hello, World!` when every second is removed. Some spaces are added to ensure the brackets and apostrophes are kept.

The indexing is really `1:2:end`. There are 27 characters, and we can't use `end` or `27` since we must remove a character, so we go with `3 ^ 3` instead. When we remove every third character, the indexing becomes `(:)` (and some additional spaces).

`(:)` means *"flatten and turn into a vertical vector"*. So, we need to transpose it, using `'`. We don't need to transpose the string in the original code, but double transposing works, so the first string is transposed twice using `''`, and the second is transposed just once.

# Answer
> 7 votes
# ///, 25 bytes

```
H\e\l\l\o\,\ \W\o\r\l\d\!

```

Try it online!

With every other character removed:

```
Hello, World!

```

# Answer
> 7 votes
# Mathematica, 62 bytes

```
P0r0i0n0t0@0"0H0e0l0l0o0,0 0W0o0r0l0d0!0"Print@"Hello, World!"

```

It returns `"0H0e0l0l0o0,0 0W0o0r0l0d0!0" Null P0r0i0n0t0[0]`, and prints `Hello, World!` as a side effect. When run as a program (not in the REPL), the return value will not be printed.

After removing every other character:

```
Print@"Hello, World!"rn@Hlo ol!

```

It returns `Null ol! rn[Hlo]`, and prints `Hello, World!`.

# Answer
> 6 votes
# CJam, 32 bytes

```
"HHeelllloo,,  WWoorrlldd!! "2 %

```

Try it online!

Taking every other character gives:

```
"Hello, World!"

```

Try it online!

# Answer
> 6 votes
# ,,,, 34 bytes

```
 2"Hteoltlaol,l yWhourmladn!! "⟛

```

On removing the even numbered characters...

```
 "Hello, World!"

```

## Explanation

With all the characters:

```
 2"..."⟛

               no-op
 2             push 2 to the stack
  "..."        push "Hteoltlaol,l yWhourmladn!! " to the stack
       ⟛      pop 2 and the string and push every 2nd character of the string
               implicit output

```

Without the even numbered characters:

```
 "..."

               no-op
 "..."         push "Hello, World!" to the stack
               implicit output

```

# Answer
> 6 votes
# Help, WarDoq!, 2 bytes

```
Hi

```

Try it online!

`H` prints `Hello, World!`, `i` is a no-op.

<sub>Help, WarDoq! can add two numbers and test for primes, so it is considered as a valid programming language per this meta post.</sub>

# Answer
> 6 votes
# APL (Dyalog), ~~35~~ 34 bytes

-1 thanks to Martin Ender.

```
'0H0e0l0l0o0,0 0W0o0r0l0d0!0'~ ⍕ 0

```

Try it online!

`'0H0e0l0l0o0,0 0W0o0r0l0d0!0'` the message with zeros as removable filler characters

`~` except

formatted (stringified)

`0` number zero

Leaving just the odd characters, this becomes `'Hello, World!'` .

# Answer
> 6 votes
## \>\<\>, 47 bytes

Original:

```
| v~" H e l l o ,   W o r l d ! "

~o<< ;!!!? l

```

With every second character removed:

```
|v"Hello, World!"
o<;!?l

```

Try them online: original, modified

The original program pushes the characters of "Hello, World!" to the stack (in reverse order) interspersed with spaces, then alternately prints a character and deletes one until the length of the stack is zero. The second program does the same, except the deletion instructions `~` are gone.

If you don't mind halting with an error, we can take a leaf out of Martin Ender's Cardinal book: the modified code is

```
\"!dlroW ,olleH"!#o#

```

and the original is the same but with newlines inserted between all the characters, for 39 bytes. Try them online: original, modified.

# Answer
> 6 votes
# JavaScript, 138 bytes

A lot of people used comments and I found it too easy so here's one entry **without comments**:

```
c_n_o_e_l_g ="c o n s o l e . l o g"; console.log ( "_H_e_l_l_o_,_ _W_o_r_l_d_!".replaceAll( "_","") ) ;[ ' s l i c e ' ]+( 0 , - 9 )+ ")"

```

Taking every other character out:

```
cnoelg=console.log;cnoelg("Hello, World!.elcAl _,"  ['slice'](0,-9) )

```

## Important

This code uses `String.prototype.replaceAll()`, which is a fairly recent feature, and thus wont work in older browsers/NodeJS versions (**NodeJS v15.0.0 and above** is required, for example).

## Explanation

1. First it create an alias of `console.log` named `c_n_o_e_l_g` which returns the same as `console.log` when every other character is removed.
2. Then `console.log` is called (being replaced with `cnoelg` when converted).
3. Inside `console.log` there's `"_H_e_l_l_o_,_ _W_o_r_l_d_!"` in which every underscore (`_`) is removed, but not in the converted version (they will be removed anyway because in even position); because of the clever placement of the last double quote (`"`), the string will look like `"Hello, World!.elcAl _,"`.
4. Since `"Hello, World!.elcAl _,"` needs to be cleaned up, a `slice()` is applied with the brackets notations (`[]`), removing the last 9 characters (`".elcAl _,"`).
5. But we don't want any modification to happen to the not converted version, so a `)` closes the `console.log` being removed when converted alongside a `;` (since in even position). Then it will apply correctly to the converted version but nothing will happen to the not converted one, since it's a value not assigned to anything.
6. This consist of `[ ' s l i c e ' ]`, `( 0 , - 9 )` and `")"`, concatenated with a `+` sign (removed during conversion), so that the script stays valid. The last `")"` is there to close the `console.log` in the converted version.

# Answer
> 5 votes
# Brainfuck, 155 bytes

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

```

Try it online!

Every second character removed:

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

```

# Answer
> 5 votes
# T-SQL, 75 bytes

```
---
PRINT 'Hello, World!'
/*
-P-R-I-N-T-'-H-e-l-l-o-,- -W-o-r-l-d-!-'
---*/

```

Single- and multi-line comment abuse, inspired by CalculatorFeline's LUA version.

After removal of all even-numbered characters, some of which are line breaks:

```
--PIT'el,Wrd'/
PRINT'Hello, World!'--/

```

# Answer
> 5 votes
# Javascript, 73 bytes

```
a ='a0l0e0r0t0`0H0e0l0l0o0,0 0W0o0r0l0d0!0`0/0/';eval(a.replace(/0/g,''))

```

Constructs a string `a` with the content `a0l0e0r0t0`0H0e0l0l0o0,0 0W0o0r0l0d0!0`0/0/`, then removes all `0`'s to give `alert`Hello, World!`//`, which is `eval`'d.

Taking every other character of the program gives

```
a=alert`Hello, World!`//;vlarpae//,')

```

which alerts `Hello, World` using template string syntax the same way as what was eval'd in the full program, then stores the result of the call in `a` and includes the insightful comment `//;vlarpae//,')`.

# Answer
> 5 votes
My naive solution

# C/C++, ~~111 105 byes~~ 97 bytes

(6 bytes saved using "puts", inspired by Hawkings)

```
///
f(){puts("Hello, World!");}
#define x\
_f_(_)_{_p_u_t_s_(_"_H_e_l_l_o_,_ _W_o_r_l_d_!_"_)_;_}

```

After takeaway

```
//f)pt(Hlo ol!)}#eiex
f(){puts("Hello, World!");}

```

# Answer
> 4 votes
# Befunge-98, 39 bytes

```
"" '!'d'l'r'o'W' ','o'l'l'e'H ""c k , @

```

Try it online!

Every second character removed:

```
" !dlroW ,olleH"ck,@

```

Try it online!

# Answer
> 4 votes
# Jelly, 32 bytes

```
 2“HHeelllloo,,  WWoorrlldd!! ”m

```

Try it online!

-2 bytes thanks to @totallyhuman's answer

Now mine is a dupe \>.\<

Go upvote that one too :D

# Answer
> 4 votes
# dc, 112

```
 6   C * P
A d * 1 + d P
7 + d P
d P
3 + d P
B   4 * d P
C - P
F   6 * 3 - P
d P
3 + d P
6 - d P
8 - P
B   3 * P

```

All odd-indexed characters are whitespace that don't affect the output of the program. Character values are built arithmetically from single digits

Try it online.

# Answer
> 4 votes
# Java 8, ~~245~~ ~~243~~ ~~241~~ ~~239~~ ~~238~~ 237 bytes (full program)

```
/**/interface M{static void main(String[]a){System.out.print("Hello, World!");}}//**/ iinntteerrffaaccee  MM{{ssttaattiicc  vvooiidd  mmaaiinn((SSttrriinngg[[]]aa)){{SSyysstteemm..oouutt..pprriinntt((""HHeelllloo,,  WWoorrlldd!!""));;}}}

```

Try it online.

After removing every other character:

```
/*itraeMsai odmi(tig])Sse.u.rn(Hlo ol!)}/*/interface M{static void main(String[]a){System.out.print("Hello, World!");}}

```

Try it online.

-2 bytes (243 → 241) thanks to *@OlivierGrégoire*.
-2 bytes (241 → 239) by creating a port of *@SuperStormer*'s JavaScript answer.

---

# Java 8, 63 bytes (lambda function)

```
/**/v->"Hello, World!"//**/vv-->>""HHeelllloo,,  WWoorrlldd!!""

```

Try it online.

After removing every other character:

```
/*v>Hlo ol!/*/v->"Hello, World!"

```

Try it online.

**Explanation:**

Utilizes `//abc` single-line comments and `/*abc*/` multi-line comments.
See the Java-highlighting of the two programs/functions to see how these type of comments are used.

# Answer
> 4 votes
## JavaScript (ES6), 65 bytes

Latecomer to the game...

```
01?alert`Hello, World!` : a_l_e_r_t ` H e l l o ,   W o r l d ! `

```

Becomes:

```
0?lr`el,Wrd`:alert`Hello, World!`

```

Obviously, neither the `a_l_e_r_t` function nor the `lr` function does exist. That's OK, because their respective code paths are never executed.

### Demo

```
let code0 = "01?alert`Hello, World!` : a_l_e_r_t ` H e l l o ,   W o r l d ! `";
let code1 = code0.replace(/../g, s => s[0]);

console.log(code0);
eval(code0);
console.log(code1);
eval(code1);
```

# Answer
> 4 votes
# C (MSVC), 60 bytes

As Stack Exchange doesn't like me posting null bytes, here is an `xxd -g1`:

```
00000000: 6d 00 61 00 69 00 6e 00 28 00 29 00 7b 00 70 00  m.a.i.n.(.).{.p.
00000010: 75 00 74 00 73 00 28 00 22 00 48 00 65 00 6c 00  u.t.s.(.".H.e.l.
00000020: 6c 00 6f 00 2c 00 20 00 57 00 6f 00 72 00 6c 00  l.o.,. .W.o.r.l.
00000030: 64 00 21 00 22 00 29 00 3b 00 7d 00              d.!.".).;.}.

```

For an infinitely less readable textual version, with `0` representing a raw `0x00` byte:

```
m0a0i0n0(0)0{0p0u0t0s0(0"0H0e0l0l0o0,0 0W0o0r0l0d0!0"0)0;0}0

```

### Explanation

I'll see your small brain comment abuse and raise you one cosmic brain text encoding abuse.

Unlike GCC and Clang, MSVC supports files encoded in UTF-16.

That is what we abuse. MSVC will """incorrectly""" auto-detect this file as-is as UTF-16LE, causing it to """incorrectly""" read it as this, encoded in UTF-16LE:

```
main(){puts("Hello, World!");}

```

If we remove every other character (a.k.a. removing every `00` byte), it treats it as UTF-8 (well, technically, the current SBCS/MBCS codepage), and it is compiled as you would probably expect, as the codepoints are now the same as they were in UTF-16LE:

```
main(){puts("Hello, World!");}

```

You may say "but this is UTF-16, it should be `mi({us"el,Wrd";`", but I say that U+0000 is a valid UTF-8 codepoint, and it just *looks* like UTF-16 by """coincidence""".

# Answer
> 3 votes
# PHP, 63 bytes

```
#
echo"Hello, World!";
#eecchhoo""HHeelllloo,,  WWoorrlldd!!"";

```

Try it online!

# PHP, 32 bytes

```
#eh"el,Wrd"
echo"Hello, World!";

```

Try it online!

# Answer
> 3 votes
# Standard ML (MLton), 75 bytes

```
(*p r i n t " H e l l o ,   w o r l d ! " ( *)print"Hello, world!"(*  * )*)

```

Try it online!

After removing every other character, we have:

```
(print"Hello, world!"(*pitHlo ol!( *))

```

Try it online!

Just exploits the fact that comments are a digraph.

# Answer
> 3 votes
# Pip, 33 bytes

```
"0H0e0l0l0o0,0 0W0o0r0l0d0!0"RM 0

```

Removes the `0`s from the string, leaving just `Hello, World!`. Try it online!

The every-other-character version:

```
"Hello, World!"M0

```

Uses the map operator to replace each character in `0` with the string `"Hello, World!"`. Try it online!

# Answer
> 3 votes
# TeX, 54 bytes

Full version:

```
 %H e l l o ,   W o r l d ! \ e n d%
Hello, World!\end

```

Every other character:

```
 Hello, World!\end
el,Wrd\n

```

A bit boring, but for completeness.

# Answer
> 3 votes
## Alice, 37 bytes

```
"_!_d_l_r_o_W_ _,_o_l_l_e_H_"_d_&_o_@

```

Try it online!

Removing every other character gives:

```
"!dlroW ,olleH"d&o@

```

Try it online!

The way this works is that Alice's string mode doesn't push *all* cell values directly to the stack. Some characters have a special meaning. In particular, `_` is a wall which retains it's control flow meaning even when in string mode. But a horizontal wall is a no-op when the IP moves horizontally, so none of those `_` do anything. Hence, they can be safely removed.

# Answer
> 3 votes
# Self-modifying Brainfuck, 39 bytes

```
< - [ . <<- ] " e m s p X ! - p m m f I

```

Try it online!

### Explanation

For anyone that is not familir with self-modifying brainfuck: The program itself gets put into registers directly left to where you start out from. This allows for some cool stuff you can't do with regular brainfuck.

This program will move back two registers (one with every second char removed) increment it and output in until the loop stops. The loop will stop once you increment the char that ends the loop itself thus making brainfuck ignore it.

**Version without every second character:**

```
 <-[.<-]"emspX!-pmmfI

```

# Answer
> 3 votes
# Japt, ~~25~~ 23 bytes

*Saved 2 bytes thanks to @Shaggy*

```
`\H\e\¥\o\,\ \W\Ž\l\d\!

```

Try it online!

This seems to be the optimal compressed string that would output `Hello, World!` while ignoring every other `\`.

# Answer
> 3 votes
# Ruby, 58 bytes

```
$/>%< <> > ;puts a= %w( H e l l o ,\  W o r l d ! )* "#{}"

```

Which becomes:

```
$><<  pt =%(Hello, World!) #}

```

I borrowed the puts/assignment trick from @G B's solution

Explanation:

The first version compares the ruby global `$/` which evaluates to `\n` to the string `" <> "` and does nothing with it. Then it creates an array of all the characters in `"Hello, World!"` and joins them by multiplying by empty string

The second pushes the return value of assignment of the string `"Hello, World!"` (which happens to be `"Hello, World!"` directly to `$>` which is the global for standard out.

Try it online!

# Answer
> 3 votes
# Bash, 36 bytes

```
e\c\h\o  "H"e"l"l"o"," "W"o"r"l"d"!"

```

With every other character removed:

```
echo Hello, World!

```

Invalid escape sequences will be ignored, so `\c\h\o` makes no difference from `cho`.

# Answer
> 3 votes
# Rust, 85 bytes

```
| | /**/print!("Hello, World!")//___*//_p_r_i_n_t_!_(_"_H_e_l_l_o_,_ _W_o_r_l_d_!_"_)

```

Try it online

Every other character:

```
||/*pit(Hlo ol!)/_*/print!("Hello, World!")

```

Try it online

### Full program, 113 bytes

```
/**/fn main(){print!("Hello, World!")}//__*//_f_n_ _m_a_i_n_(_)_{_p_r_i_n_t_!_(_"_H_e_l_l_o_,_ _W_o_r_l_d_!_"_)_}

```

Try it online

Every other character:

```
/*f an)pit(Hlo ol!)/_*/fn main(){print!("Hello, World!")}

```

Try it online

# Answer
> 2 votes
# 05AB1E, 32 bytes

```
"
H
e
l
l
o
,

W
o
r
l
d
!
"¶ K

```

Basically the `"`s make a string, and the `¶ K` removes all newlines.

Try it online!

Version with even characters removed, 16 bytes.

```
"Hello, World!"

```

Try it online!

# Answer
> 2 votes
# Ruby, 63 bytes

```
puts a= 'Hello, World!'#; p u t s ' H e l l o ,   W o r l d ! '

```

Which becomes:

```
pt ='el,Wrd';puts'Hello, World!'

```

(Abusing comments like a lot of people do)

Try it online!

# Answer
> 2 votes
# Python 2, 63 bytes

```
#
print'Hello, World!'
#p r i n t ' H e l l o ,   W o r l d ! '

```

Try it online!

After transformation, this becomes:

```
#pitHlo ol!
print'Hello, World!'

```

# Answer
> 2 votes
# Braingolf, ~~42~~ 40 bytes

```
#"#H#e#l#l#o#,# #W#o#r#l#d#!#" $_ <$_& @

```

Try it online!

After removing odd characters:

```
"Hello, World!"$ $&@

```

Try it online!

## Explanation

Full program:

```
#"#H#e#l#l#o#,# #w#o#r#l#d#!#" pushes "Hello, World!" (including quotes)

$ adds the silent modifier to the next operator
space does nothing
_ Pops and prints the last item on the stack, but due to silent mode, does not print
< moves the first item on the stack to the end of the stack

This means that $_ <$_ will remove both quotes from the stack

& adds the greedy modifier to the next operator
@ pops and prints the last item on the stack as an ASCII character
  greedy modifier means it prints the entire stack.

```

With characters removed:

```
"Hello, World!" Pushes Hello, World!
Spaces are no-ops
&@ Prints entire stack as ASCII
@ is not affected by the silent modifier (apparently)

```

It feels really cheap using no-ops for this, but it's better than the Java/Python comment solutions imo

# Answer
> 2 votes
# Noodel, 25 bytes

```
Hðeðlðlðoð,ð¤ðWðoðrðlðdð!

```

Try it:)

---

## How it works

```
Hðeðlðlðoð,ð¤ðWðoðrðlðdð! # The ð character breaks the string into an array and pushes the array ["H", "e", "l", "l", "o", ",", "¤", "W", "o", "r", "l", "d", "!"].
                          # Implicitly printed to the screen (¤ is the space).

```

Without every other character gives you :

```
Hello,¤World!

```

```
<div id="noodel" code="Hðeðlðlðoð,ð¤ðWðoðrðlðdð" input="" cols="12" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```

# Answer
> 2 votes
# Lua, 85 bytes

I decided to try making a function copying Lua answer. It's slightly shorter than the comment abuse submission.

```
paints= p_r_i_n_t----
print("Hello, World!")

paints( " H e l l o ,   W o r l d ! " )

```

Try it online!

Alternated:

```
pit=print--pit"el,Wrd"
pit("Hello, World!")

```

Try it online!

Alternator script is in my other answer.

# Answer
> 2 votes
# C, ~~111~~ 101 bytes

10 bytes saved thanks to Jasen

Full version:

```
//*
main(){puts("Hello, World!");}
//**// m a i n ( ) { p u t s ( " H e l l o ,   W o r l d ! " ) ; }

```

Every other character

```
/*mi({us"el,Wrd";
/*/main(){puts("Hello, World!");}

```

# Answer
> 2 votes
## shell (ksh), 58 bytes

```
 #e c h o   H e l l o ,   W o r l d ! #
echo Hello World!

```

(in interactive bash, you'd need to add '\\' before the '!')

# Answer
> 2 votes
# JavaScript (ES6), 66 bytes

```
/ /;alert`Hello, World!`
'a l e r t ` H e l l o ,   W o r l d ! `'
```

```
//aetHlo ol!
alert`Hello, World!`
```

# Answer
> 2 votes
# Python 2, 73 bytes

```
print"=#0##Hello, World!"[5:]
#portionate ""IHeeelallof,A TWookralade!?"

```

Try it online!

Python 2, unfortunately doesn't have that nifty trick the Python 3 answer used :( So I did the obvious comment trickery. "Try it online" code provides the halved version and execs it to make checking easier.

Halved version:

```
pit=0#el,Wrd"5]
print "Hello, World!"

```

# Answer
> 2 votes
# Ly, 38 bytes

```
"""!!ddllrrooWW  ,,oolllleeHH" [po ]

```

Try it online!

Explanation:

```
"""HHeelllloo,,  WWoorrlldd!!" [po ]

"""           # open a string literal, close it, then open one again
   ...        # push "HHeelloo,,  WWoorrlldd!!" backwards
      "       # close string literal
         [    # until the stack is empty
          po  # pop off the stack, then output
            ] # end loop

```

Every other character:

```
"!dlroW ,olleH"[o]

```

Try it online!

Explanation:

```
"!dlroW ,olleH"[o]

"!dlroW ,olleH"    # push "Hello, World!" backwards
               [o] # output until the stack is empty

```

# Answer
> 2 votes
# Befunge-93, 51 bytes

Inspired by Martin's Cardinal solution, I thought it might be fun to try and do something vertical in Befunge as well. It's a little more complicated in Befunge though.

```
?
"
!
d
l
r
o
W

,
o
l
l
e
H
" :
>>:v$
#^,__@@
v >

```

Try it online!

We start with a `?`(random direction) command, which can potentially send the instruction pointer in any direction. Left and right will just wrap around back to the start, and going up will hit the `v` at the bottom of the program and reflect back to the start as well. So while we may bounce around for a while, we'll eventually be forced down at some point, pushing the "Hello, World!" string (in reverse) onto the stack. Which brings us to this sequence:

```
>>:v
 ^,__@

```

This is just a simple output loop that writes out the string on the stack. The only thing out of the ordinary is the extra `_` (branch) when the loop terminates. But because there are only zeros on the stack at that point, the second test will safely continue on to to the right, finishing with the `@` (exit) command.

---

Once we remove every second character, the code looks like this:

```
?"!dlroW ,olleH":>:$#,_@v>

```

Try it online!

Again we start with a `?`(random direction) command, and again most directions will just end up wrapping back to the start. So eventually we're forced to go to the right, pushing "Hello, World!" (in reverse) onto the stack. Which then brings us to this sequence:

```
:>:$#,_@

```

Again this is just a loop outputting the string on the stack. It's very similar to the classic inline print loop, but we've got an extra `:` (dup) command, and thus require a `$` (drop) to cancel it out.

# Answer
> 2 votes
# Cubically, 155 bytes

```
R U + 4 3 2 @ 6 + 5 0 - 4 @ 6 + 3 - 4 @ 6 @ 6 + 1 - 0 0 @ 6 - 3 3 1 @ 6 - 0 0 @ 6 + 4 1 1 0 @ 6 + 0 0 0 0 @ 6 + 1 - 0 0 @ 6 - 0 @ 6 - 2 + 4 @ 6 - 3 3 1 @ 6

```

The new parser strips out all spaces ¯\\\_(ツ)\_/¯ so either way the code is interpreted like this:

```
RU+432@6+50-4@6+3-4@6@6+1-00@6-331@6-00@6+4110@6+0000@6+1-00@6-0@6-2+4@6-331@6

```

Try it online! (spaced)

Try it online! (every other character)

# Answer
> 2 votes
# Stax, 33 bytes

```
"zHzezlzlzoz,z zWzozrzlzdz!z"'z -

```

Run and debug it

Every other character, 17 bytes

```
"Hello, World!"z-

```

Run and debug it

In the first version, `'z -` remove all `z`s from the string. In the second version, `z` by itself is empty set, and `z-` is noop.

# Answer
> 2 votes
# Lost, 113 bytes

```
v<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>.%?"Hello, worldvU"-+@
v>v%v?v"vHvevlvlvov,v
wvovrvlvdvvvUv"v-v+v@

```

Try it online!

# With removal, 57 bytes

```
v<<<<<<<<<<<<<<<<<<<<<
.?Hlo olv"+
>%?"Hello, worldvU"-+@

```

Try it online!

# Answer
> 2 votes
# Vyxal, 7 bytes

```
ka`a`kH

```

Try it Online!

Pretty straightforward: The `kH` at the end is a builtin for `Hello, World!`, and that's the only thing that gets implicitly printed.

#### With characters removed:

```
k``H

```

Try it Online!

This makes use of a quirk in Vyxal where you can put a string in the middle of a constant diagraph, and the constant will be pushed after the string, making this equivalent to ```kH`, which pushes the same builtin as before and prints it.

# Answer
> 2 votes
# Vyxal, 29 bytes

```
`HHeelllloo,,  WWoorrlldd!!`√

```

Try it Online!

```
`Hello, World!√

```

Try it Online!

Without using the `kH` builtin, which returns "Hello, World!"

```
`HHeelllloo,,  WWoorrlldd!!`  # String
                            √ # Get every second character

```

```
`Hello, World!  # String (unterminated)
              √ # Ignored due to parsing bug

```

# Answer
> 1 votes
# Pyth, 31 bytes

```
%y1t"pHEeGlGlhoz,e QwjolrDlBdJ!

```

eh

# Answer
> 1 votes
# Forth, 61 bytes

This uses the fact that `\` makes the rest of the line a comment.

```
 \  . (   H e l l o ,   W o r l d ! )   \
 .( Hello, World! )

```

**Full program**

Remove every other byte to get:

```
  .( Hello, World!) \ (Hlo ol!)

```

**Every other**

# Answer
> 1 votes
# Japt, ~~32~~ 28 bytes

Wrote this up and then noticed Oliver beat me to it with the same method in 05AB1E.

Note: The empty line after the comma contains a space character and the empty line after the "W" contains an unprintable.

```
`
H
e
¥
o
,

W

l
d
!
` rR

```

Test it

With every second character removed, it becomes (with the unprintable still present between the "W" and the "l"):

```
`He¥o, Wld!`r

```

Test it

# Answer
> 1 votes
# Swift, 77 bytes

```
/**/print("Hello, World!")//  * / p r i n t ( " H e l l o ,   W o r l d ! " )

```

Every other character:

```
/*pit"el,Wrd"/ */print("Hello, World!")

```

# Answer
> 1 votes
# Java 8, ~~123~~ 122 bytes

Here is the full code

```
/**/()->System.out.print("Hello, World!")//_*_/_(_)_-_>_S_y_s_t_e_m_._o_u_t_._p_r_i_n_t_(_"_H_e_l_l_o_,_ _W_o_r_l_d_!_"_)_

```

Try it online here

---

Here is the 'every other' code

```
/*(-Sse.u.rn(Hlo ol!)/*/()->System.out.print("Hello, World!")

```

Try it online here

# Answer
> 1 votes
## LOGO, 63 bytes

```
 ;p r [ H e l l o ,   W o r l d ! ] e r [
 pr[Hello, World!] ;]

```

With characters at even index removed

```
 pr[Hello, World!]er[ rHlo ol! ]

```

Explanation:

`;` starts an inline comment in Logo. Therefore the first program is equivalent to

```
 pr[Hello, World!]

```

which obviously `pr`int "Hello, World!".

In the second program, a function `er` is invoked. `er` stands for `erase`, receive a list in a suitable format as input, and erase some contents specified in the list (the details does not matter). The key point is that `er` does not return anything, so it is a shorter alternative to `ignore`, which ignores its contents.

# Answer
> 1 votes
## x86 machine code, 73 bytes

Inspired by *Евгений Новиков*'s solution, I thought it should be doable with less tricks, i.e., just jumping around to otherwise "disjoint" codes for all three variants. I'm still trying with a smart variant that uses `lodsb; lodsb` as central point (so only one string constant is needed for all variants)

```
EB 14 00 00 8A 8A 17 16 01 01 B4 B4 09 09 CD CD
21 21 CD CD 20 20 8A 1f 01 B4 09 CD 21 CD 20 48
65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 48 48 65
65 6c 6c 6c 6c 6f 6f 2c 2c 20 20 57 57 6f 6f 72
72 6c 6c 64 64 21 21 00 00

```

If I recall correctly from my childhood days, COM's tiny model starts with `DS=CS=SS` and the code is loaded beginning from `CS:0100h`. I do not assume it is guaranteed that the code is loaded into a zeroed memory block (if it were guaranteed, I could drop two bytes).

Disassembly of the long code should be

```
  JMP *+14h
  ; 20 irrelevant bytes
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
message:
  DB "Hello, World!\0"
  DB "HHeelllloo,,  WWoorrlldd!!\0\0"

```

Disassembly of odd code

```
  JMP *+00h
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
  ; some irrelevant bytes
message:
  DB "Hello, World!\0"

```

Disassembly of even code:

```
  ADC AL,00h
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
  ; some irrelevant bytes
message:
  DB "Hello, World!\0"

```

# Answer
> 1 votes
# dc, 52 bytes

```
0#[#H#e#l#l#o#,# #W#o#r#l#d#!#]#P#q
[Hello, World!]P

```

Try it online!

The first line puts a zero on the stack, and then the rest of the line is commented out. The second line prints 'Hello, World!'

With every even character removed, all the `#`s in the first line disappear, and the line is no longer commented out. It then prints 'Hello, World!' and quits before hitting the second line.

# Answer
> 1 votes
# Brainfuck 156 bytes

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

```

# Answer
> 1 votes
# Powershell, 46 bytes

Full version:

```
#
"Hello, World"
#" H e l l o ,   W o r l d "

```

Try it online here

Every other character

```
#"el,Wrd
"Hello, World"

```

Try it online here

# Answer
> 1 votes
# MAWP, 169 bytes

```
9/8/W/;/5/5/W/4/W/1/M/;/9/3/W/4/W/;/9/3/W/4/W/;/9/4/W/1/M/3/W/;/5/8/W/4/M/;/8/4/W/;/9/8/M/5/W/2/M/;/9/4/W/1/M/3/W/;/9/9/M/1/M/6/W/;/9/3/W/4/W/;/5/5/W/4/W/;/9/2/M/3/W/;/.

```

Try it!

Code with every other character removed:

```
98W;55W4W1M;93W4W;93W4W;94W1M3W;58W4M;84W;98M5W2M;94W1M3W;99M1M6W;93W4W;55W4W;92M3W;.

```

Try It!

# Answer
> 1 votes
# Java (JDK), 123 bytes

```
/*/ */System.out.print("Hello, world!"); ///\ u 0 0 0 d S y s t e m . o u t . p r i n t ( " H e l l o_,_ _w o r l d ! " ) ;

```

Try it online!

This isn't a full program - you'll have to paste it into a method somewhere.

---

# Every other character, 62 bytes

```
//*Sse.u.rn(Hlo ol!) /\u000dSystem.out.print("Hello, world!");

```

Try it online!

It takes advantage of the way the compiler turns unicode escapes into their corresponding characters.

# Answer
> 1 votes
# Julia, 59 bytes

```
".H.e.l.l.o. .W.o.r.l.d.!\" | > p r i n t #"[2:2:24]|>print

```

### Shortened version :

```
"Hello World!"|>print#[::4|pit

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 25 bytes

```
”Ÿ™,‚ï!”,””q”
Ÿ
™
,
‚
ï
!

```

Try it online!

```
”Ÿ™,‚ï!”,””q”Ÿ™,‚ï!  # full program (newlines aren't important here)
        ,            # output...
”Ÿ™,‚ï!”             # "Hello, World!"
         ””          # push empty string
           q         # exit program
            ”Ÿ™,‚ï!  # push "\nŸ\n™\n,\n‚\nï\n!" (never executed)

```

## Every other character, 13 bytes

```
”™‚!,””Ÿ™,‚ï!

```

Try it online!

```
”™‚!,””Ÿ™,‚ï!  # full program
”™‚!,”         # push "Situation!,"
      ”Ÿ™,‚ï!  # push "Hello, World!"
               # implicit output

```

# Answer
> 1 votes
# Zsh, 35 bytes

```
e\c\h\o  \H\e\l\l\o\,\ \W\o\r\l\d\!
```

Attempt This Online!

AtmtTi nie

# Answer
> 1 votes
# AWK, 87 bytes

```
BEGIN {print"Hello, World!" }
B#E#G#I#N# #{#p#r#i#n#t#"#H#e#l#l#o#,# #W#o#r#l#d#!#"# #}

```

Try it online!

The resulting code is:

```
BGN{rn"el,Wrd"}BEGIN {print"Hello, World!" }

```

Because the `BGN` variable is false (not assigned), the first part of the code has no effect.

# dc, 49 bytes

```
[Hello, World!]p #[[HHeelllloo,,  WWoorrlldd!!]]p

```

Try it online!

# Answer
> 1 votes
# Ly, 39 ~~\[40\]~~ bytes

```
"x!xdxlxrxoxWx x,xoxlxlxexHx"'_p_p[xop]

```

Try it online!

*Thanks to Aaroneous Miller for the -1 improvement hint in the comments.*

The alternate code, with all the odd number characters deleted is,

```
"!dlroW ,olleH"__[o]

```

Which is straightforward. The only trick used is relying on Ly's willingness to ignore any character is doesn't recognize. So the `_` characters (and the `x` characters in the longer code) can be replaced by any character that's undefined in the language.

The longer code works because the loop running through the stack and printing things, meaning

```
 [xop]

```

deleted one character for every one it prints.

# Answer
> 1 votes
# Backhand, 33 bytes

```
>'l"o'"'l','!'e' 'd'H'WHl'"'o.r'H

```

Try it online!

Only works in the latest interpreter, so the entire interpreter is copied into the TIO link (TIO's Backhand seems to not have `'` implemented).

This one has only one copy of "Hello, World!" in the entire code.

```
>'l"o'"'l','!'e' 'd'H'WHl'"'o.r'H   Full program
>  "  "                             Push empty string (no-op)
         '  !  '  d  '  l  '  r     Push "!dlr" (`'` pushes next char)
    o  '  ,  '     '  W  '  o  '    Bounce off and push "oW ,o"
 'l  '  l  '  e  '  H               Bounce off and push "lleH"
                       H            Halt and print entire stack

>lo"l,!e dHWl"orH   Halved program
>  "                Start string mode
      !  d  l  r    Push "!dlr"
  o  ,     W  o     Bounce off and push "oW ,o"
 l  l  e  H  "      Bounce off and push "lleH" and end string mode
                H   Halt and print entire stack

```

# Backhand, 34 bytes

```
>>lvo""!ld,l!reo Wd H,Woll"loerHH"

```

Try it online!

Halved:

```
>lo"l,!e dHWl"orH

```

Try it online!

This one works in the TIO version, and has two disjoint program paths. The full program has its step size reduced at an odd position, which makes the rest of its path totally invisible to the halved program. (Bonus points for looking totally jumbled, I guess.)

```
>>lvo""!ld,l!reo Wd H,Woll"loerHH"   Full program
>  v                                 Reduce step size to 2
     " ! d l r o W   , o l l e H "   Push the string
                               H     Halt and print

>lo"l,!e dHWl"orH   Halved program
>  "  !  d  l  r    →
  o  ,     W  o     ←
 l  l  e  H  "      →  Push the string
                H   Halt and print

```

# Answer
> 0 votes
# Stacked, 60 bytes

```
'Hello, World!'  '''H e l l o ,   W o r l d !''' @oouutt out

```

Try it online!

I generated the second code with this snippet. Second code is:

```
'el,Wrd' 'Hello, World!' out u

```

The first one generates two strings, `Hello, World!` and `'H e l l o , W o r l d !'`. The latter is saved to variable `oouutt`, and the former is printed.

The second one generates two strings, outputs the second, then errors after encountering `u`.

# Answer
> 0 votes
# BotEngine, 91 bytes

```
 vv
 v <
 eHH
 eee
 ell
 ell
 eoo
 e,,
 e
 eWW
 eoo
 err
 ell
 edd
 e!!
 P

```

# Answer
> 0 votes
# Keg, ~~47~~ ~~39~~ 35 bytes

```
`1H1%1;1,1 1c1¡1;1!1`_`H%;, c¡;!` $

```

Try it online!

And, unless I've somehow misread the challenge, the program with alternating characters:

## `-hd`, 18 bytes

```
`H%;, c¡;!``%,c;`$

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 47 bytes

```
p r i n t ( H e l l o "\,\ """W o r l d "\!""")

```

Try it online!

```
print(Hello", "World"!")

```

Try it online!

A boring answer. In PARI/GP, all spaces not contained in a string are simply ignored. `Hello` and `World` are variables that can be used in polynomials.

# Answer
> 0 votes
# Python 3, 60 bytes

```
#
exec(#
'p_r_i_n_t_(_"_H_e_l_l_o_,_ _W_o_r_l_d_!_"_)'[::2])

```

Try it online!

The `[::2]` slice the string to have `'print("Hello, World!")'`. Then we execute it with `exec`

## Every other char :

```
#ee(
print("Hello, World!")[:]

```

This prints `Hello, World!` and then error due to the slice on a `None` object

# Answer
> 0 votes
# x86 machine code (DOS), 53 bytes

Full:

```
00000000: ba 00 0d b0 01 b0 b4 b0 09 b0 cd b0 21 b0 c3 be  ............!...
00000010: 1a 01 ad cd 29 3c 21 75 f9 c3 48 00 65 00 6c 00  ....)<!u..H.e.l.
00000020: 6c 00 6f 00 2c 00 20 00 57 00 6f 00 72 00 6c 00  l.o.,. .W.o.r.l.
00000030: 64 00 21 00 24                                   d.!.$

```

Even bytes only, 27 bytes

```
00000000: ba 0d 01 b4 09 cd 21 c3 1a ad 29 21 f9 48 65 6c  ......!...)!.Hel
00000010: 6c 6f 2c 20 57 6f 72 6c 64 21 24                 lo, World!$

```

Assembly (NASM syntax)

```
    [org 0x100]
start:
    ; Encode the half version using the defacto hello world with some
    ; harmless mov instructions. I haven't found a good use for these bytes
    ; yet (point of interest: get 13 in CX or (hello - start) in AX.
    ; mov dx, hello
    ; The offset is halved, then shifted left 8 to get it to encode in the
    ; upper byte.
    ;
    ; As a 3 byte opcode, this jumps the full variant to an odd address,
    ; causing a desync.
    mov dx, ((hello - start) / 2) << 8
    mov al, 0x01
    ; mov ah, 0x09
    mov al, 0xB4
    mov al, 0x09
    ; int 0x21
    mov al, 0xCD
    mov al, 0x21
    ; ret
    mov al, 0xC3

    ; Now for the thicc code. Instead of INT 21:09H, which expects a byte
    ; string terminated with '$', I print each char manually using INT 29H
    ; since I can do that with LODSW.

    ; Get the address of str into SI
    mov si, hello
.loop:
    ; Load one padded UTF-16 character into AX, and advance SI.
    lodsw
    ; Print AL using INT 29H.
    int 0x29
    ; Check for the last character
    cmp al, '!'
    jne .loop
    ; Return to exit
    ret
    ; On the minified version, this is a $-terminated string for INT 21:09H.
    ; db "Hello, World!$"
    ; On the non-minified version it is just dummy thicc.
hello:
    dw __UTF16__("Hello, World!") ; Unicode strings are proof that nasm > gas
    ; this one doesn't need padding
    db '$'

```

The full variant does this:

```
    [org 0x100]
start:
    ; bunch of pointless mov instructions

    mov si, str
.loop:
    lodsw
    int 0x29
    cmp al, '!'
    jne .loop
    ret
str:
    dw __UTF16__("Hello, World!")

```

while the small variant does this

```
    [org 0x100]
start:
    mov dx, str
    mov ah, 0x09
    int 0x21
    ret
    ; Unexecuted nonsense here
str:
    db "Hello, World!$"

```

This does not attempt to do even bytes only, unlike Hagen von Eitzen's solution. This allows me to simplify it greatly.

As the comments say, I use two methods for printing the string. For the larger code, I loop over the padded string with `LODSB; INT 29H`, and for the shorter code I use `INT 21:09H` to just print the string directly from memory. This means I don't need to use any complex tricks.

I feel like there is some improvement possible, as I think I could take better advantage of the nops and padding.

# Answer
> 0 votes
# JavaScript (V8), 66 bytes

```
"";alert`Hello, World`; " ; a l e r t ` H e l l o ,   W o r l d `"

```

Try it online!

String as comment, nothing wrong

---
Tags: code-golf, string, source-layout, hello-world
---


title: Rotation summation

text:
# Question
Title: Rotation summation
Take a square matrix containing positive integers as input, and calculate the "rotated sum" of the matrix.

**Rotated sum:**

Take the sum of the original matrix and the same matrix rotated 90, 180 and 270 degrees.

Suppose the matrix is:

```
 2    5    8
 3   12    8
 6    6   10

```

then the rotated sum will be:

```
2    5    8     8    8   10    10    6    6     6    3    2
3   12    8  +  5   12    6  +  8   12    3  +  6   12    5  =
6    6   10     2    3    6     8    5    2    10    8    8

26   22   26
22   48   22
26   22   26

```

### Test cases:

Input and output separated by dashes, different test cases separated by a newline. Test cases in more convenient formats can be found here.

```
1
-------------
4

1 3
2 4
-------------
10   10
10   10

14    6    7   14
 6   12   13   13
 6    2    3   10
 5    1   12   12
-------------
45   37   24   45
24   30   30   37
37   30   30   24
45   24   37   45

14    2    5   10    2
18    9   12    1    9
 3    1    5   11   14
13   20    7   19   12
 2    1    9    5    6
-------------
24   29   31   41   24
41   49   31   49   29
31   31   20   31   31
29   49   31   49   41
24   41   31   29   24

```

### Shortest code in bytes in each language wins. Explanations are highly encouraged!

# Answer
> 8 votes
# Python 2, 78 bytes

Thanks to Dennis for golfing two bytes off my previous recursive approach.

```
f=lambda*l:l[3:]and[map(sum,zip(*d))for d in zip(*l)]or f(zip(*l[0][::-1]),*l)

```

Try it online! or See a test suite.

---

### Python 2, 80 ~~81 83 85~~ bytes (non-recursive)

Takes input as a singleton list.

```
l=input()
exec"l+=zip(*l[-1][::-1]),;"*3
print[map(sum,zip(*d))for d in zip(*l)]

```

Try it online!

### Code functionality

Since this is quite length-ish to analyse it as a whole, let's check it out piece-by-piece:

```
f = lambda *l:                # This defines a lambda-function that can accept any number
                              # of arguments (the matrix) using starred expressions.
l[3:] and ...X... or ...Y...  # If l[3:] is truthy (that is, the length of the list is
                              # higher than 3), return X, otherwise Y.

[map(sum,zip(*d))for d in zip(*l)]     # The first expression, X.
[                                ]     # Start a list comprehension, that:
                 for d in              # ... Iterates using a variable d on:
                          zip(*l)      # ... The "input", l, transposed.
         zip(*d)                       # ... And for each d, transpose it...
 map(sum,       )                      # ... And compute the sum of its rows.
                                       # The last two steps sum the columns of d.

f(zip(*l[0][::-1]),*l)     # The second expression, Y. This is where the magic happens.
f(                   )     # Call the function, f with the following arguments:
  zip(*          )         # ... The transpose of:
       l[0][::-1]          # ...... The first element of l (the first arg.), reversed.
                  ,        # And:
                   *l      # ... l splatted. Basically turns each element of l
                           # into a separate argument to the function.

```

And for the second program:

```
l=input()                                # Take input and assign it to a variable l.
                                         # Note that input is taken as a singleton list.

exec"l+=zip(*l[-1][::-1]),;"*3           # Part 1. Create the list of rotations.
exec"                     ;"*3           # Execute (Do) the following 3 times:
     l+=                 ,               # ... Append to l the singleton tuple:
        zip(*           )                # ...... The transpose of:
             l[-1][::-1]                 # ......... The last element of l, reversed.

print[map(sum,zip(*d))for d in zip(*l)]  # Part 2. Generate the matrix of sums.
print                                    # Output the result of this expression:
     [                for d in        ]  # Create a list comprehension, that iterates
                                         # with a variable called "d" over:
                               zip(*l)   # ... The transpose of l.
      map(sum,       )                   # ... And computes the sum:
              zip(*d)                    # ... Of each row in d's transpose.
                                         # The last 2 steps generate the column sums.

```

**TL;DR:** Generate the list of matrices needed by rotating the input 3 times by 90-degrees and collecting the results. Then, get the sums of the columns of each matrix in the result's transpose.

# Answer
> 8 votes
# Octave, 29 bytes

```
@(x)(y=x+rot90(x))+rot90(y,2)

```

Try it online!

### Explanation

This adds the input matrix with a 90-degree rotated version of itself. The result is then added with a 180-degree rotated version of itself.

# Answer
> 5 votes
# Clean, 110 bytes

```
import StdEnv,StdLib
r=reverse
t=transpose
z=zipWith(+)
$m=[z(z(r b)a)(z(r c)d)\\a<-m&b<-r m&c<-t m&d<-r(t m)]

```

Try it online!

From the matricies:

* `X = transpose(reverse M)`: 90-degree rotation
* `Y = reverse(map reverse M)`: 180-degree rotation
* `Z = reverse(transpose M)`: 270-degree rotation

This zips the addition operator over `M` and `X`, as well as `Y` and `Z`, and then over the results.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 28 bytes

```
Sum[a=Reverse@a,{a=#;4}]&

```

is `\[Transpose]`.

Try it online!

# Answer
> 5 votes
# Julia 0.6, ~~28~~ 24 bytes

```
~A=sum(rotr90.([A],0:3))

```

Try it online!

```
~A=sum(rotr90.([A],0:3)) #
~                        # redefine unary operator ~
 A                       # function argument
               [A]       # put input matrix A into a list with one element
                   0:3   # integer range from 0 to 3
       rotr90.(   ,   )  # apply function rotr90 elementwise, expand singleton dimensions
       rotr90.([A],0:3)  # yields list of rotated matrices:
                         # [rotr90(A,0), rotr90(A,1), rotr90(A,2), rotr90(A,3)]
  sum(                )  # sum

```

# Answer
> 5 votes
# Julia 0.6, 29 bytes

```
x*y=rotr90(y,x)
!x=x+1x+2x+3x

```

Try it online!

I couldn't get below LukeS's solution

But in trying I did come up with this, which I think is kinda cute.

First we redefine multiplication to be the rotate operation, where there first time is the number of times to rotate. So since julia multipes by juxtaposition then: `1x` becomes `rotr90(x,1)` and `3x` becomes `rotr90(x,3)` etc.

Then we write out the sum.

# Answer
> 4 votes
# Jelly, 7 bytes

```
ZU+µUṚ+

```

Try it online!

# Answer
> 4 votes
# Octave, 33 bytes

```
@(a)a+(r=@rot90)(a)+r(a,2)+r(a,3)

```

Try it online!

## Explanation:

`(r=@rot90)` in an inline way of creating a function handle `r` used to rotate the matrix 90 degrees. If a second argument, `k` is given to `r` then it will rotate the matrix `k*90` degrees. So this is equivalent to the pseudo code:

```
a + rot90(a) + rot180(a) + rot270(a)

```

# Answer
> 4 votes
# MATL, 9 bytes

```
i3:"G@X!+

```

Try it at MATL Online

**Explanation**

```
i       # Explicitly grab the input matrix
3:"     # Loop through the values [1, 2, 3], and for each value, N:
  G     # Grab the input again
  @X!   # Rotate the value by 90 degrees N times
  +     # Add it to the previous value on the stack
        # Implicitly end the for loop and display the resulting matrix

```

# Answer
> 4 votes
# APL (Dyalog Classic), 8 bytes

```
(⌽+⍉)⊖+⌽

```

Try it online!

# Answer
> 3 votes
# Pyth, 13 bytes

```
m+MCdC.u_CN3Q

```

Try it online!

# Answer
> 3 votes
# , ~~16~~ 15 bytes

```
[:+/|.@|:^:(<4)

```

Try it online!

# Answer
> 3 votes
# MATL, 7 bytes

```
,t@QX!+

```

Try it at MATL Online!

### Explanation

Port of my Octave answer.

```
,        % Do twice
  t      %   Duplicate. Takes input (implicit) the first time
  @Q     %   Push 1 in the first iteration, and 2 in the second
  X!     %   Rotate by that many 90-degree steps
  +      %   Add
         % End (implicit). Display (implicit)

```

# Answer
> 3 votes
# , ~~69~~ 64 bytes

```
function(x,a=function(y)apply(y,1,rev))x+a(x)+a(a(x))+a(a(a(x)))

```

Try it online!

---

Attempt number three at codegolf. From 69 to 64 bytes thanks to Giuseppe!

# Answer
> 2 votes
# Jelly, 7 bytes

```
ṚZ$3Ð¡S

```

Try it online!

Saved 1 byte thanks to Erik the Outgolfer (also thanks to a suggestion for fixing a bug).

### How?

```
ṚZ$3Ð¡S || Full program (monadic).

   3Ð¡  || Do this 3 times and collect results in a list
  $     || –> Apply the last two links as a monad
Ṛ       || –––> Reverse,
 Z      || –––> Transpose.
      S || Summation.

```

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

```
a->sum(i=1,4,a=Mat(Vecrev(a))~)

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 77 bytes

```
a=>a.map((b,i)=>b.map((c,j)=>c+a[j][c=l+~i]+a[c][c=l+~j]+a[c][i]),l=a.length)

```

# Answer
> 2 votes
# Python 2, 76 bytes

```
f=lambda x,k=-2:k*x or[map(sum,zip(*r))for r in zip(x,f(zip(*x)[::-1],k+1))]

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 12 bytes

```
3FÂø}3F‚øε`+

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Classic), 17 bytes

```
{⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵}

```

Try it online!

# APL NARS 34bytes ~~21~~17 chars

```
{⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵}

```

-2 chars thanks to ngn

-2 chars because operator composite ∘ seems to have precedence on +

it seems ⌽⍉a rotate a from 90°,⌽⊖a rotate a from 180°,⌽⍉⌽⊖a rotate a from 270° as ⍉⌽

If exist the operator p as:

```
∇r←(g p)n;a;i;k
   a←⌽,n⋄r←⍬⋄i←0⋄k←⍴a⋄→C
A: →B×⍳r≡⍬⋄r←g¨r
B: r←r,⊂i⊃a
C: →A×⍳k≥i+←1
   r←⌽r
∇

```

The operator p above would be such that if g is a 1 argument function (monadic?) it should be:

```
"g f a a a a" is "a ga gga ggga"

```

the solution would be pheraps 15 chars

```
  g←{⊃+/⌽∘⍉ p 4⍴⊂⍵}
  a←2 2⍴1 3 2 4
  g a
10 10
10 10
  g 1
4

```

But could be better one operator "composed n time" d such that "3 d f w" is f(f(f(w))).

Now I wrote something but it is too much fragile without the need type checking.

But i like more the operator q that repeat compose of f with argument m (it is not complete because the error cases of the types are not written)

```
∇r←(n q f)m;i;k;l
   r←⍬⋄k←⍴,n⋄→A×⍳k≤1⋄i←0⋄→D
C: r←r,⊂(i⊃n)q f m
D: →C×⍳k≥i+←1
   →0
A: l←n⋄r←m⋄→0×⍳n≤0
B: l-←1⋄r←f r⋄→B×⍳l≥1
∇

```

the solution would be 17 chars but i prefer it

```
  g←{⊃+/(0..3)q(⌽⍉)⍵}
  ⎕fmt g a
┌2─────┐
2 10 10│
│ 10 10│
└~─────┘
  ⎕fmt g 1
4
~

```

# Answer
> 2 votes
# Ruby, ~~74 72~~ 66 bytes

```
->a{r=0...a.size;r.map{|i|r.map{|j|(0..3).sum{i,j=j,~i;a[i][j]}}}}

```

Try it online!

This works on an element-by-element basis, finding the associated elements mathematically, instead of rotating the array. The key part is `i,j=j,~i`, which turns (i, j) clockwise 90 degrees.

-2 bytes thanks to Mr. Xcoder

-6 bytes because of `sum`

# Answer
> 2 votes
# K4 / K (oK), ~~23~~ 8 bytes

**Solution:**

```
+/(|+:)\

```

Try it online!

**Example:**

```
+/(|+:)\5 5#14 2 5 10 2 18 9 12 1 9 3 1 5 11 14 13 20 7 19 12 2 1 9 5 6
24 29 31 41 24
41 49 31 49 29
31 31 20 31 31
29 49 31 49 41
24 41 31 29 24

```

**Explanation:**

Thanks to ngn for the simplified transformation technique.

```
+/(|+:)\ / the solution
       \ / converge
  (   )  / function to converge
    +:   / flip
   |     / reverse
+/       / sum over the result

```

**Extra:**

In Q this could be written as

```
sum (reverse flip @) scan

```

# Answer
> 2 votes
# Attache, 20 bytes

```
Sum@MatrixRotate&0:3

```

Try it online!

## Explanation

```
Sum@MatrixRotate&0:3

```

`MatrixRotate&0:3` expands to, with input `x`, `MatrixRotate[x, 0:3]`, which in turn exapnds to `[MatrixRotate[x, 0], MatrixRotate[x, 1], MatrixRotate[x, 2], MatrixRotate[x, 3]]`. That is to say, it vectorizes over the RHS. Then, `Sum` takes the sum of all of these matrices by one level. This gives the desired result.

# Answer
> 1 votes
# Python 3, ~~105~~ 102 bytes

3 bytes thanks to Mr. Xcoder.

```
def f(a):l=len(a)-1;r=range(l+1);return[[a[i][j]+a[l-j][i]+a[l-i][l-j]+a[j][l-i]for j in r]for i in r]

```

Try it online!

# Answer
> 1 votes
# Ruby 89 79 bytes

-10 bytes thanks to Unihedron

```
->m{n=m;3.times{n=n.zip(m=m.transpose.reverse).map{|i,j|i.zip(j).map &:sum}};n}

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~84 83~~ 67 bytes

```
z=zipWith
e=[]:e
f l=foldr(\_->z(z(+))l.foldr(z(:).reverse)e)l"123"

```

Try it online!

Thanks to Laikoni and totallyhuman for saving a lot of bytes!

# Answer
> 1 votes
# Husk, 9 bytes

```
F‡+↑4¡(↔T

```

Try it online!

### Explanation

```
F‡+↑4¡(↔T)  -- implicit input M, for example: [[1,0,1],[2,3,4],[0,0,2]]
     ¡(  )  -- repeat infinitely times starting with M
        T   -- | transpose: [[1,2,0],[0,3,0],[1,4,2]]
       ↔    -- | reverse: [[1,4,2],[0,3,0],[1,2,0]]
            -- : [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]],[[1,0,1],[2,3,4],[0,0,2]],…
   ↑4       -- take 4: [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]]]
F           -- fold (reduce) the elements (example with [[1,0,1],[2,3,4],[0,0,2]] [[1,4,2],[0,3,0],[1,2,0]])
 ‡+         -- | deep-zip addition (elementwise addition): [[2,4,3],[2,6,4],[1,2,2]]
            -- : [[4,6,4],[6,12,6],[4,6,4]]

```

# Answer
> 1 votes
# tinylisp, 132 bytes

Let's take the recently added library function `transpose` for a spin!

```
(load library
(d T transpose
(d R(q((m #)(i #(c m(R(reverse(T m))(dec #)))(
(q((m)(foldl(q(p(map(q((r)(map sum(T r))))(T p))))(R m 4

```

The last line is an unnamed lambda function that performs rotation summation. To actually use it, you'll want to use `d` to bind it to a name. Try it online!

### Ungolfed, with comments

```
(load library) (comment Get functions from the standard library)

(comment Rotating a matrix by 90 degrees is just transpose + reverse)
(def rotate
 (lambda (matrix)
  (reverse (transpose matrix))))

(comment This function recursively generates a list of (count) successive rotations
          of (matrix))
(def rotations
 (lambda (matrix count)
  (if count
   (cons matrix
    (rotations (rotate matrix) (dec count)))
   nil)))

(comment To add two matrices, we zip them together and add the pairs of rows)
(def matrix-add
 (lambda two-matrices
  (map row-sum (transpose two-matrices))))

(comment To add two rows of a matrix, we zip them together and add the pairs of numbers)
(def row-sum
 (lambda (two-rows)
  (map sum (transpose two-rows))))

(comment Our final function: generate a list containing four rotations of the argument
          and fold them using matrix-add)
(def rotated-sum
 (lambda (matrix)
  (foldl matrix-add (rotations matrix 4))))

```

# Answer
> 1 votes
# Java 8, ~~135~~ ~~133~~ 131 bytes

```
a->{int l=a.length,r[][]=new int[l][l],i,j,k=0;for(;k<l*l;)r[i=k/l][j=k++%l]=a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i];return r;}

```

-4 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
a->{                       // Method with integer-matrix as both parameter and return-type
  int l=a.length,          //  Dimensions of the input-matrix
      r[][]=new int[l][l], //  Result-matrix of same size
      i,j,k=0;             //  Index-integers
  for(;k<l*l;)             //  Loop over the cells
    r[i=k/l][j=k++%l]=     //    Set the cell of the result-matrix to:
      a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i];
                           //     The four linked cells of the input-matrix
  return r;}               //  Return the result-matrix

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 8 bytesSBCS

```
+∘⍉∘⊖⍣3⍨

```

Try it online!

### How it works

```
+∘⍉∘⊖⍣3⍨  ⍝ Input: matrix m
  ⍉∘⊖     ⍝ Rotate 90 degrees clockwise
+∘        ⍝ Add the original matrix m
     ⍣3⍨  ⍝ Repeat 3 times, starting with m

```

---

# , 12 bytes

```
(+|:@|.)^:3~

```

Try it online!

Straightforward port of the APL answer above.

# Answer
> 1 votes
# Factor \+ `combinators.extras math.matrices`, ~~49~~ 48 bytes

```
[ [ dup flip [ reverse ] map ] thrice m+ m+ m+ ]

```

Try it online!

* `[ ... ] thrice` Call `[ ... ]` 3 times.
* `dup` Make a copy of the top of the stack.
* `flip [ reverse ] map` Rotate a matrix 90 degrees.
* `m+ m+ m+` Add 4 matrices together.

# Answer
> 0 votes
# Perl 5, 92 bytes

```
sub f{@t=@_;map{//;[map$t[$'-1][$_-1]+$t[$_-1][-$']+$t[-$'][-$_]+$t[-$_][$'-1],1..@t]}1..@t}

```

Try it online!

# Answer
> 0 votes
# Burlesque, 38 bytes

```
SP{{}{tp<-}{<-)<-}{tp)<-}}M-r{q?+Z]}sp

```

Try it online!

```
SP        # Read input as array
{
 {}       # Original
 {tp<-}   # 90deg
 {<-)<-}  # 180deg
 {tp)<-}  # 270deg
}
M-        # Return an array of maps
r{        # Reduce by
 q?+      # Vectorised addition
 Z]       # Zip, push, map
}
sp        # Pretty print as array

```

# Answer
> 0 votes
# GolfScript, 64 bytes

```
4/{.(,\;[]:w;{[]:t;{(t\+:t;}%t{+}*w\+:w;}\*; w.,(!!3*)*.4/,/~}%`

```

I cheated, I cheated. Kinda. Though there are typical, standardized ways to take in Matrix input, I decided to take it in a... less conventional method. GolfScript is fucking *terrible* at rotational mathematics, so I knew I *had* to try. Below is the array-matrix method I used.

So yeah. You might notice a bit of convenient symmetry in this format, and I abused the hell out of it.

Input is taken in as an array of circular-ordered arrays, such as

\[ \[1 2 3 4\]\[5 6 7 8\]\[9 10 11 12\]\[13 14 15 16\]\[17 18\]\[19 20\]\[21 22\]\[23 24\]\[25\] \]

for a 5x5 array.

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

```

It returns in identical output.

Teehee.

Maybe one day I'll make a program that takes an array of this format and turns it into nice formatting and vice-versa.

Then my program will no longer be an abomination.

I mean, it still *would* be, the I/O would just be more conventional.

God, should I even write an explanation for this *hot garbage*?

Try it online, if you dare.

# Answer
> 0 votes
# Haskell, 84 bytes

```
import Data.List
s=foldl1(zipWith(zipWith(+))).take 4.iterate(transpose.map reverse)

```

Try it online!

---
Tags: code-golf, math, number, array, matrix
---