title: Random point on a sphere

text:
# Question
Title: Random point on a sphere
## The Challenge

Write a program or function that takes no input and outputs a 3-dimensional vector of length \\$1\\$ in a **theoretically uniform** random direction.

This is equivalent to a random point on the sphere described by $$x^2+y^2+z^2=1$$

resulting in a distribution like such

### Output

Three floats from a theoretically uniform random distribution for which the equation \\$x^2+y^2+z^2=1\\$ holds true to precision limits.

## Challenge remarks

* The random distribution needs to be **theoretically uniform**. That is, if the pseudo-random number generator were to be replaced with a true RNG from the **real** numbers, it would result in a uniform random distribution of points on the sphere.
* Generating three random numbers from a uniform distribution and normalizing them is invalid: there will be a bias towards the corners of the three-dimensional space.
* Similarly, generating two random numbers from a uniform distribution and using them as spherical coordinates is invalid: there will be a bias towards the poles of the sphere.
* Proper uniformity can be achieved by algorithms including but not limited to:
    1. Generate three random numbers \\$x\\$, \\$y\\$ and \\$z\\$ from a *normal* (Gaussian) distribution around \\$0\\$ and normalize them.
    2. Generate three random numbers \\$x\\$, \\$y\\$ and \\$z\\$ from a *uniform* distribution in the range \\$(-1,1)\\$. Calculate the length of the vector by \\$l=\sqrt{x^2+y^2+z^2}\\$. Then, if \\$l\>1\\$, reject the vector and generate a new set of numbers. Else, if \\$l \leq 1\\$, normalize the vector and return the result.
    3. Generate two random numbers \\$i\\$ and \\$j\\$ from a *uniform* distribution in the range \\$(0,1)\\$ and convert them to spherical coordinates like so:\begin{align}\theta &= 2 \times \pi \times i\\\\\phi &= \cos^{-1}(2\times j -1)\end{align}so that \\$x\\$, \\$y\\$ and \\$z\\$ can be calculated by \begin{align}x &= \cos(\theta) \times \sin(\phi)\\\\y &= \sin(\theta) \times \sin(\phi)\\\\z &= \cos(\phi)\end{align}
* Provide in your answer a brief description of the algorithm that you are using.
* Read more on sphere point picking on MathWorld.

## Output examples

```
[ 0.72422852 -0.58643067  0.36275628]
[-0.79158628 -0.17595886  0.58517488]
[-0.16428481 -0.90804027  0.38532243]
[ 0.61238768  0.75123833 -0.24621596]
[-0.81111161 -0.46269121  0.35779156]

```

## General remarks

# Answer
> 43 votes
# Wolfram Language (Mathematica), 20 bytes

```
RandomPoint@Sphere[]

```

Try it online!

Does exactly what it says on the tin.

# Answer
> 24 votes
# , 23 bytes

```
x=rnorm(3)
x/(x%*%x)^.5

```

Try it online!

Generates 3 realizations of the \\$\mathcal N(0,1)\\$ distribution and normalizes the resulting vector.

Plot of 1000 realizations:

# Answer
> 24 votes
# x86-64 Machine Code - ~~63 62 55~~ 49 bytes

```
6A 4F                push        4Fh
68 00 00 80 3F       push        3F800000h
C4 E2 79 18 4C 24 05 vbroadcastss xmm1,dword ptr [rsp+5]
rand:
0F C7 F0             rdrand      eax
73 FB                jnc         rand
66 0F 6E C0          movd        xmm0,eax
greaterThanOne:
66 0F 38 DC C0       aesenc      xmm0,xmm0
0F 5B C0             cvtdq2ps    xmm0,xmm0
0F 5E C1             divps       xmm0,xmm1
C4 E3 79 40 D0 7F    vdpps       xmm2,xmm0,xmm0,7Fh
0F 2F 14 24          comiss      xmm2,dword ptr [rsp]
75 E9                jne         greaterThanOne
58                   pop         rax
58                   pop         rax
C3                   ret

```

Uses the second algorithm, modified. Returns vector of `[x, y, z, 0]` in xmm0.

Explanation:

```
push 4Fh
push 3f800000h

```

Pushes the value for 1 and 2^31 as a float to the stack. The data overlap due to the sign extension, saving a few bytes.

`vbroadcastss xmm1,dword ptr [rsp+5]` Loads the value for 2^31 into 4 positions of xmm1.

```
rdrand      eax
jnc         rand
movd        xmm0,eax

```

Generates random 32-bit integer and loads it to bottom of xmm0.

```
aesenc      xmm0,xmm0
cvtdq2ps    xmm0,xmm0
divps       xmm0,xmm1

```

Generates a random 32 bit integer, convert it to float (signed) and divide by 2^31 to get numbers between -1 and 1.

`vdpps xmm2,xmm0,xmm0,7Fh` adds the squares of the lower 3 floats using a dot product by itself, masking out the top float. This gives the length

```
comiss      xmm2,dword ptr [rsp]
jne          rand+9h (07FF7A1DE1C9Eh)

```

Compares the length squared with 1 and rejects the values if it is not equal to 1. If the length squared is one, then the length is also one. That means the vector is already normalised and saves a square root and divide.

```
pop         rax
pop         rax

```

Restore the stack.

`ret` returns value in xmm0

Try it Online.

# Answer
> 17 votes
# Python 2, 86 bytes

```
from random import*;R=random
z=R()*2-1
a=(1-z*z)**.5*1j**(4*R())
print a.real,a.imag,z

```

Try it online!

Generates the z-coordinate uniformly from -1 to 1. Then the x and y coordinates are sampled uniformly on a circle of radius `(1-z*z)**.5`.

It might not be obvious that the spherical distribution is in factor uniform over the z coordinate (and so over every coordinate). This is something special for dimension 3. See this proof that the surface area of a horizontal slice of a sphere is proportional to its height. Although slices near the equator have a bigger radius, slices near the pole are titled inward more, and it turns out these two effects exactly cancel.

To generate a random angle on this circle, we raise the imaginary unit `1j` to a uniformly random power between 0 and 4, which saves us from needing trig functions, pi, or e, any of which would need an import. We then extract the real imaginary part. If we can output a complex number for two of the coordinates, the last line could just be `print a,z`.

---

# Python 2, 85 bytes

```
from random import*
a,b,c=eval('gauss(0,1),'*3)
R=(a*a+b*b+c*c)**.5
print a/R,b/R,c/R

```

Try it online!

Generates three normals and scales the result. Thanks to ovs for saving 1 byte with `eval` in the second line.

---

**Python 2 with numpy, 57 bytes**

```
from numpy import*
a=random.randn(3)
print a/sum(a*a)**.5

```

Try it online!

`sum(a*a)**.5` is shorter than `linalg.norm(a)`. We could also do `dot(a,a)` for the same length as `sum(a*a)`. In Python 3, this can be shortened to `a@a` using the new operator `@`.

# Answer
> 13 votes
# Octave, ~~40 33~~ 22 bytes

We sample form a 3d standard normal distribution and normalize the vector:

```
(x=randn(1,3))/norm(x)

```

Try it online!

# Answer
> 12 votes
# Unity C#, 34 bytes

```
f=>UnityEngine.Random.onUnitSphere

```

Unity has a builtin for unit sphere random values, so I thought I'd post it.

# Answer
> 7 votes
# Ruby, ~~34 50~~ 49 bytes

```
->{[z=rand*2-1]+((1-z*z)**0.5*1i**(rand*4)).rect}

```

Try it online!

Returns an array of 3 numbers `[z,y,x]`.

`x` and `y` are generated by raising `i` (square root of -1) to a random power between 0 and 4. This complex number needs to be scaled appropriately according to the `z` value in accordance with Pythagoras theorem: `(x**2 + y**2) + z**2 = 1.`

The `z` coordinate (which is generated first) is simply a uniformly distributed number between -1 and 1. Though not immediately obvious, dA/dz for a slice through a sphere is constant (and equal to the perimeter of a circle of the same radius as the whole sphere.) .

This was apparently discovered by Archimedes who described it in a very non-calculus-like way, and it is known as Archimedes Hat-Box theorem. See https://brilliant.org/wiki/surface-area-sphere/

Another reference from comments on xnor's answer. A surprisingly short URL, describing a surprisingly simple formula: http://mathworld.wolfram.com/Zone.html

# Answer
> 7 votes
# MATL, 10 bytes

```
1&3Xrt2&|/

```

Try it online!

### Explanation

This uses the first approach described in the challenge.

```
1&3Xr  % Generate a 1×3 vector of i.i.d standard Gaussian variables
t      % Duplicate
2&|    % Compute the 2-norm
/      % Divide, element-wise. Implicitly display

```

# Answer
> 5 votes
# TI-BASIC, 15 bytes *

```
:randNorm(0,1,3
:Ans/√(sum(Ans²

```

Using the algorithm "generate 3 normally distributed values and normalize that vector".

Ending a program with an expression automatically prints the result on the Homescreen after the program terminates, so the result is actually shown, not just generated and blackholed.

\*: `randNorm(` is a two-byte token, the rest are one-byte tokens. I've counted the initial (unavoidable) `:`, without that it would be 14 bytes. Saved as a program with a one-letter name, it takes 24 bytes of memory, which includes the 9 bytes of file-system overhead.

# Answer
> 4 votes
# JavaScript (ES7),  ~~77 76~~  75 bytes

Implements the 3rd algorithm, using \\$\sin(\phi)=\sin(\cos^{-1}(z))=\sqrt{1-z^2}\\$.

```
with(Math)f=_=>[z=2*(r=random)()-1,cos(t=2*PI*r(q=(1-z*z)**.5))*q,sin(t)*q]

```

Try it online!

### Commented

```
with(Math)                       // use Math
f = _ =>                         //
  [ z = 2 * (r = random)() - 1,  // z = 2 * j - 1
    cos(                         //
      t =                        // θ =
        2 * PI *                 //   2 * π * i
        r(q = (1 - z * z) ** .5) // q = sin(ɸ) = sin(arccos(z)) = √(1 - z²)
                                 // NB: it is safe to compute q here because
                                 //     Math.random ignores its parameter(s)
    ) * q,                       // x = cos(θ) * sin(ɸ)
    sin(t) * q                   // y = sin(θ) * sin(ɸ)
  ]                              //

```

---

# JavaScript (ES6), 79 bytes

Implements the 2nd algorithm.

```
f=_=>(n=Math.hypot(...v=[0,0,0].map(_=>Math.random()*2-1)))>1?f():v.map(x=>x/n)

```

Try it online!

### Commented

```
f = _ =>                         // f is a recursive function taking no parameter
  ( n = Math.hypot(...           // n is the Euclidean norm of
      v =                        // the vector v consisting of:
        [0, 0, 0].map(_ =>       //
          Math.random() * 2 - 1  //   3 uniform random values in [-1, 1]
        )                        //
  )) > 1 ?                       // if n is greater than 1:
    f()                          //   try again until it's not
  :                              // else:
    v.map(x => x / n)            //   return the normalized vector

```

# Answer
> 4 votes
# 05AB1E, ~~23~~ 22 bytes

```
[тε5°x<Ýs/<Ω}DnOtDî#}/

```

Implements the 2nd algorithm.

Try it online or get a few more random outputs.

**Explanation:**

NOTE: 05AB1E doesn't have a builtin to get a random decimal value in the range \\$\[0,1)\\$. Instead, I create a list in increments of \\$0.00001\\$, and pick random values from that list. This increment could be changed to \\$0.000000001\\$ by changing the `5` to `9` in the code (although it would become rather slow..).

```
[            # Start an infinite loop:
 тε          #  Push 100, and map (basically, create a list with 3 values):
   5°        #   Push 100,000 (10**5)
     x       #   Double it to 200,000 (without popping)
      <      #   Decrease it by 1 to 199,999
       Ý     #   Create a list in the range [0, 199,999]
        s/   #   Swap to get 100,000 again, and divide each value in the list by this
          <  #   And then decrease by 1 to change the range [0,2) to [-1,1)
           Ω #   And pop and push a random value from this list
  }          #  After the map, we have our three random values
   D         #   Duplicate this list
    n        #   Square each inner value
     O       #   Take the sum of these squares
      t      #   Take the square-root of that
       D     #   Duplicate that as well
        î    #   Ceil it, and if it's now exactly 1:
         #   #    Stop the infinite loop
}/           # After the infinite loop: normalize by dividing
             # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Processing 26 bytes

Full program

```
print(PVector.random3D());

```

This is the implementation https://github.com/processing/processing/blob/master/core/src/processing/core/PVector.java

```
  static public PVector random3D(PVector target, PApplet parent) {
    float angle;
    float vz;
    if (parent == null) {
      angle = (float) (Math.random()*Math.PI*2);
      vz    = (float) (Math.random()*2-1);
    } else {
      angle = parent.random(PConstants.TWO_PI);
      vz    = parent.random(-1,1);
    }
    float vx = (float) (Math.sqrt(1-vz*vz)*Math.cos(angle));
    float vy = (float) (Math.sqrt(1-vz*vz)*Math.sin(angle));
    if (target == null) {
      target = new PVector(vx, vy, vz);
      //target.normalize(); // Should be unnecessary
    } else {
      target.set(vx,vy,vz);
    }
    return target;
  }

```

# Answer
> 2 votes
# Python 2, 86 bytes

```
from random import*
x,y,z=map(gauss,[0]*3,[1]*3);l=(x*x+y*y+z*z)**.5
print x/l,y/l,z/l

```

Try it online!

Implements the first algorithm.

---

# Python 2, ~~107~~ 103 bytes

```
from random import*
l=2
while l>1:x,y,z=map(uniform,[-1]*3,[1]*3);l=(x*x+y*y+z*z)**.5
print x/l,y/l,z/l

```

Try it online!

Implements the second algorithm.

# Answer
> 2 votes
# Java 8 (*@Arnauld*'s modified 3rd algorithm), ~~131~~ ~~126~~ ~~119~~ ~~111~~ 109 bytes

```
v->{double k=2*M.random()-1,t=M.sqrt(1-k*k),r[]={k,M.cos(k=2*M.PI*M.random())*t,M.sin(k)*t};return r;}

```

Port of *@Arnauld*'s JavaScript answer, so make sure to upvote him!
-2 bytes thanks to *@OlivierGrégoire*.

This is implemented as:

\\$k = N\cap\[-1,1)\\$
\\$t=\sqrt{1-k^2}\\$
\\$u=2\pi×(N\cap\[0,1))\\$
\\$x,y,z = \\{k, \cos(u)×t, \sin(u)×t\\}\\$

Try it online.

**Previous 3rd algorithm implementation (~~131~~ ~~126~~ 119 bytes):**

```
Math M;v->{double k=2*M.random()-1,t=2*M.PI*M.random();return k+","+M.cos(t)*M.sin(k=M.acos(k))+","+M.sin(t)*M.sin(k);}

```

Implemented as:

\\$k = N\cap\[-1,1)\\$
\\$t=2\pi×(N\cap\[0,1))\\$
\\$x,y,z = \\{k, \cos(t)×\sin(\arccos(k)), \sin(t)×\sin(\arccos(k))\\}\\$

Try it online.

### Explanation:

```
Math M;                         // Math on class-level to use for static calls to save bytes
v->{                            // Method with empty unused parameter & double-array return
  double k=2*M.random()-1,      //  Get a random value in the range [-1,1)
         t=M.sqrt(1-k*k),       //  Calculate the square-root of 1-k^2
    r[]={                       //  Create the result-array, containing:
         k,                     //   X: the random value `k`
         M.cos(k=2*M.PI         //   Y: first change `k` to TAU (2*PI)
                     *M.random()//       multiplied by a random [0,1) value
                )               //      Take the cosine of that
                 *t,            //      and multiply it by `t`
         M.sin(k)               //   Z: Also take the sine of the new `k` (TAU * random)
                  *t};          //      And multiply it by `t` as well
  return r;}                    //  Return this array as result

```

---

# Java 8 (2nd algorithm), ~~153~~ 143 bytes

```
v->{double x=2,y=2,z=2,l;for(;(l=Math.sqrt(x*x+y*y+z*z))>1;y=m(),z=m())x=m();return x/l+","+y/l+","+z/l;};double m(){return Math.random()*2-1;}

```

Try it online.

*2nd algorithm:*

```
v->{                              // Method with empty unused parameter & String return-type
  double x=2,y=2,z=2,l;           //  Start results a,b,c all at 2
  for(;(l=Math.sqrt(x*x+y*y+z*z)) //  Loop as long as the hypotenuse of x,y,z
       >1;                        //  is larger than 1
    y=m(),z=m())x=m();            //   Calculate a new x, y, and z
  return x/l+","+y/l+","+z/l;}    //  And return the normalized x,y,z as result
double m(){                       // Separated method to reduce bytes, which will:
  return Math.random()*2-1;}      //  Return a random value in the range [-1,1)

```

# Answer
> 2 votes
# Haskell, ~~125~~ ~~123~~ ~~119~~ 118 bytes

```
import System.Random
f=mapM(\_->randomRIO(-1,1))"lol">>= \a->last$f:[pure$(/n)<$>a|n<-[sqrt.sum$map(^2)a::Double],n<1]

```

Try it online!

Does three uniforms randoms and rejection sampling.

# Answer
> 2 votes
# MathGolf, ~~21~~ ~~19~~ 18 bytes

```
{╘3Éƒ∞(ß_²Σ√_1>}▲/

```

Implementation of the 2nd algorithm.

Try it online or see a few more outputs at the same time.

**Explanation:**

```
{              }▲   # Do-while true by popping the value:
 ╘                  #  Discard everything on the stack to clean up previous iterations
  3É                #  Loop 3 times, executing the following three operations:
    ƒ               #   Push a random value in the range [0,1]
     ∞              #   Double it to make the range [0,2]
      (             #   Decrease it by 1 to make the range [-1,1]
       ß            #  Wrap these three values into a list
        _           #  Duplicate the list of random values
         ²          #  Square each value in the list
          Σ         #  Sum them
           √        #  And take the square-root of that
            _       #  Duplicate it as well
             1>     #  And check if it's larger than 1
                 /  # After the do-while, divide to normalize
                    # (after which the entire stack joined together is output implicitly,
                    #  which is why we need the `╘` to cleanup after every iteration)

```

# Answer
> 2 votes
# JavaScript, 95 bytes

```
f=(a=[x,y,z]=[0,0,0].map(e=>Math.random()*2-1))=>(s=Math.sqrt(x*x+y*y+z*z))>1?f():a.map(e=>e/s)

```

You ~~don't~~ need *not* to input `a`.

# Answer
> 2 votes
# Julia 1.0, 24 bytes

```
x=randn(3)
x/hypot(x...)

```

Try it online!

Draws a vector of 3 values, drawn from a normal distribution around 0 with standard deviation 1. Then just normalizes them.

# Answer
> 2 votes
# Vyxal, ~~20~~ 19 bytes

```
{≥|3ʁƛ∆Ṙd⌐;:²∑√:1}/

```

Try it Online!

Uses the second method.

## Explanation

```
{≥|3ʁƛ∆Ṙd⌐;:²∑√:1}/
{                }  While
 ≥                    Greater or equal
  |                 do:
   3ʁ                 [0,1,2]
     ƛ    ;           Map:
      ∆Ṙ                Random number from 0 to 1
        d               Double
         ⌐              Subtract from 1
           :          Duplicate
            ²         Square
             ∑        Sum
              √       Square root
               :      Duplicate
                1     Push 1
                  / Divide [the vector by the length]

```

# Answer
> 1 votes
# Pyth, 24 bytes

```
W<1Ks^R2JmtO2.0 3;cR@K2J

```

Try it online!

Uses algorithm #2

```
W                         # while
 <1                       #   1 <
   Ks                     #       K := sum(
     ^R2                  #               map(lambda x:x**2,
        Jm      3         #                    J := map(                            , range(3))
          tO2.0           #                             lambda x: random(0, 2.0) - 1           )):
                 ;        #   pass
                   R   J  # [return] map(lambda x:            , J)
                  c @K2   #                        x / sqrt(K)

```

# Answer
> 1 votes
# Japt, 20 bytes

Port of Arnauld's implementation of the 2nd algorithm.

```
MhV=3ÆMrJ1
>1?ß:V®/U

```

Test it

```
MhV=3ÆMrJ1
Mh             :Get the hypotenuse of
  V=           :  Assign to V
    3Æ         :  Map the range [0,3)
      Mr       :    Random float
        J1     :    In range [-1,1)
>1?ß:V®/U      :Assign result to U
>1?            :If U is greater than 1
   ß           :  Run the programme again
    :V®/U      :Else map V, dividing all elements by U

```

# Answer
> 1 votes
# OCaml, ~~110~~ ~~99~~ 95 bytes

```
(fun f a c s->let t,p=f 4.*.a 0.,a(f 2.-.1.)in[c t*.s p;s t*.s p;c p])Random.float acos cos sin

```

EDIT: Shaved off some bytes by inlining \\$ i \\$ and \\$ j \\$, replacing the first `let ... in` with a `fun`, and taking advantage of operator associativity to avoid some parens `()`.

**Try it online**

---

Original solution:

```
Random.(let a,c,s,i,j=acos,cos,sin,float 4.,float 2. in let t,p=i*.(a 0.),a (j-.1.) in[c t*.s p;s t*.s p;c p])

```

First I define:

$$ a = \arccos,\ \ c = \cos,\ \ s = \sin \\ i \sim \textsf{unif}(0,4),\ \ j \sim \textsf{unif}(0,2) $$

OCaml's `Random.float` function includes the bounds. Then,

$$ t = i \cdot a(0) = \frac{i\pi}{2},\ \ p = a (j-1) $$

This is very similar to the 3rd example implementation (with \\$ \phi = p \\$ and \\$ \theta = t \\$) \\$ - \\$ except that I pick \\$ i \\$ and \\$ j \\$ within larger intervals to avoid multiplication (with 2) later on.

# Answer
> 1 votes
# Nim, 105 101 100 99 bytes

```
import math,random
randomize()
let
 t=TAU.rand
 u=2.0.rand-1
 v=sqrt 1-u*u
echo [t.cos*v,t.sin*v,u]

```

Try it online!

Uses the third method with a bit of substitution:

$$u = \cos(\phi) = 2j - 1$$ $$v = \sin(\phi) = \sqrt{1-u^2}$$

# Answer
> 1 votes
# Raku, 65 bytes

```
{(&cos,&sin,{1})».(τ.rand)Z*(&sin,&sin,&cos)».(acos 2.rand-1)}

```

Try it online!

This function uses the "convert two random numbers to spherical coordinates" method. `τ.rand` generates the first number in the range of zero to τ (tau, that is, twice pi) and `acos 2.rand - 1` generates the second with the acos argument in the range of -1 to 1.

`(&cos, &sin, {1})».(...)` applies the cosine function, the sine function, and an anonymous function that always returns `1` to the first random parameter, producing a list of the results. Similarly, `(&sin, &sin, &cos)».(...)` applies the sine, sine, and cosine functions to the second random parameter, producing a second list. Finally, `Z*` zips those two lists together using multiplication.

# Answer
> 1 votes
# Pxem, 58 bytes (filename).

Because Pxem does not handle decimal values nor negative values (negative values can be supplied via input but cannot be generated in other ways), I am representing them as integers.

Unprintables are represented as a backslash followed by three-digit octal value of its code point.

```
x\003\144.w\002.r\002.!+.+.o.v21.y.c\013.r.c.t.c.!.a.m.n.m.m.!.-.v\001.-.c.a

```

## Output format

It outputs 10x, 10y, and 10z rather than x, y, and z.

```
"%c%d%c%d%c%d\n", sign, value, sign value, sign, value

```

Sign is as either `+` or `-`; always output. Value is multiplied by 10. Thus the precision of the program is up to 0.1.

## With comments

```
XX.z
# memory layout: counter, l
# until counter is zero; do
.ax\003\144.wXX.z
  # output sign
  .a\002.r\002.!+.+.oXX.z
  # while :; do
  .a.v21.yXX.z
    # generate a random number 0<=x<=10
    .a.c\013.rXX.z
    # continue if x^2>l; otherwise break
    .a.c.t.c.!XX.z
  # done
  .a.aXX.z
  # output x
  .a.m.nXX.z
  # update l to l minus x^2
  .a.m.m.!.-XX.z
# decrement counter; done
.a.v\001.-.c.a

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Classic), 22 bytes

```
⎕←{⍵÷((+/⍵*2)*0.5)}?⍳3

```

Try it online!

---
Tags: code-golf, math, arithmetic, geometry, random
---


title: Print the Flag of the Arab Revolt!

text:
# Question
Title: Print the Flag of the Arab Revolt!
It seems flags are a trend now, so what better place to start an account? I thought bars could use a twist to them, so I found this flag.

Produce the following in the console output the fewest possible bytes:

```
+----------------------------------+
|XXXXX                             |
|XXXXXXXX                          |
|XXXXXXXXX-------------------------+
|XXXXXXXXXXX                       |
|XXXXXXXXXXX                       |
|XXXXXXXXX-------------------------+
|XXXXXXXX                          |
|XXXXX                             |
+----------------------------------+

```

This crude rendition of the flag is 36 x 10 characters. A trailing newline on the last line is optional. You may use any language you choose. If it is an obscure language, please post a link to the language in your answer.

# Answer
# CJam, 44 bytes

```
8T5@9B]_W%+{I'|'+?'XI*34"-  "I=e]"+||"I=N}fI

```

*(Thanks to @Dennis, @Jakube and @Optimizer for -1 byte each)*

```
8T5@9B]        Push [0 5 8 9 11]
_W%+           Add its reverse, to give [0 5 8 9 11 11 9 8 5 0]
{...}fI        For each I in the above array...
  I'|'+?         Push "+" if I == 0 else "|"
  'XI*             Push I "X"s
  34"-  "I=e]      Pad the "X"s to length 34 with "-" if I%3 == 0 else " "
  "+||"I=          Push "+" if I%3 == 0 else "|"
  N                Push a newline

```
> 9 votes

# Answer
# SQL (PostgreSQL flavour), ~~284~~ ~~244~~ ~~232~~ ~~210~~ 175 bytes

A HUGE Thank You to @manatwork for essentially the whole thing now.

A nice verbose language that still came in under the byte size of the flag, with a bit of a margin :)

Basically builds the half of the flag with using parameters. This is cross joined with 1 and -1 giving us both halfs of the flag and a means to order it by negating the number of #'s in the row.

```
SELECT rpad(rpad(L,X,'X'),35,P)||R FROM(VALUES('|',12,' ','|'),('|',10,'-','+'),('|',9,' ','|'),('|',6,' ','|'),('+',1,'-','+'))F(L,X,P,R),(values(-1),(1))G(O)ORDER BY(12-X)*O

```

Formatted and commented

```
SELECT rpad(rpad(L,X,'X'),35,P)||R --Build each row from parameters
FROM(VALUES           -- Parameters for each row
    ('|',12,' ','|'), -- Start Char, Num of #, Pad Char, End Char
    ('|',10,'-','+'),
    ('|',9,' ','|'),
    ('|',6,' ','|'),
    ('+',1,'-','+')
    )F(L,X,P,R),
    (values(-1),(1))G(O) -- Cross join with order modifier
ORDER BY(12-X)*O -- Order by modified number of #

```
> 14 votes

# Answer
# CJam, ~~52~~ ~~51~~ 50 bytes

```
8U5@9B]34X$f-]z87Zb"X ||X-++X-+|"4/f=..*1fm>_W%+N*

```

*Thanks to @Sp3000 for golfing off 1 byte!*

Try it online in the CJam interpreter.

### How it works

```
8U5@9B] e# Push [0 5 8 9 11] (`@` rotates on top).
34X$f-  e# Subtract each integer from 34.
]z      e# Wrap and zip. This pushes [[0 34] [5 29] [8 26] [9 25] [11 23]].
87Zb    e# Push [1 0 0 2 0] (87 in base 3).

"X ||X-++X-+|"4/

        e# Push ["X ||" "X-++" "X-+|"].

f=      e# Select for each. This pushes ["X-++" "X ||" "X ||" "X-+|" "X ||"].

..*     e# Twofold vectorized repetition.
        e# EXAMPLE: [9 25]"X-+|".* -> "XXXXXXXXX-------------------------+|"

1fm>    e# Rotate each string one character to the right.
_W%     e# Copy the resulting array and reverse the order of its lines.
+N*     e# Concatenate and join by linefeeds.

```
> 8 votes

# Answer
## Python 2, 80

```
for n in 0,5,8,9,11,11,9,8,5,0:print'|+'[n<1]+'X'*n+'-  '[n%3]*(34-n)+'+||'[n%3]

```

Instead of iterating over the row numbers, iterate over the number of `X`-symbols directly. The stripes happen where `n` is `0` or `9`, which are the only multiples of 3, and so can be checked by the value `n%3` (thanks Sp3000).

This can surely be shortened in Python 3 by converting the list of numbers to a bytes object.
> 8 votes

# Answer
## JavaScript (ES6), ~~147~~ ~~132~~  ~~127~~  ~~111~~ 106 bytes

```
[0,5,8,9,11,11,9,8,5,0].map(v=>console.log('|+'[+!v]+'X'.repeat(v)+' -'[z=+!(v%3)].repeat(36-v)+'|+'[z]))

```

### Demo

As it is ES6, it only works in Firefox at the moment.

```
// DEMO: redefine console.log to have output inside the snippet
// Taken from https://codegolf.stackexchange.com/a/52411/22867
console.log = (...x) => O.innerHTML += x + '\n';

// Actual program
[0,5,8,9,11,11,9,8,5,0].map(v=>console.log('|+'[+!v]+'X'.repeat(v)+' -'[z=+!(v%3)].repeat(36-v)+'|+'[z]))
```

```
<pre><output id=O></output></pre>
```
> 5 votes

# Answer
## C, 157 155 151 146 bytes

```
i;f(){for(char b[36];i<10;printf("%c%.34s%c\n",i++%9?124:43,b,i%3?124:43))memset(b,i%3?32:45,34),i%9?memset(b,120,35253>>((i<5?5-i:i)%4*4)&15):0;}

```

edit: I moved the string length inside of the format string and found two bytes.

edit: Added Cool Guy's recommendation and found four bytes.

edit: Removed the array and replaced it with a 4-bit packed short that's shifted to get the 'x' lengths
> 4 votes

# Answer
# CJam, ~~60~~ ~~54~~ ~~50~~ ~~48~~ 45 bytes

Compared to the previous version, I realized that one of the 5 entries in my descriptors was always the same, which was kind of pointless. Using a fixed value for it:

```
"++-0|| 5|| 8|+-9|| B"4/_W%+{1/~~'X*34@e]\N}/

```

Try it online

*Thanks to @aditsu and @Sp3000 for some related help in chat this morning.*

The basic approach here is that I have 4 character descriptors for the pattern of each line, where the characters in the descriptor are:

* First character.
* Last character.
* Right fill character.
* Repeat count for left fill character.

The left fill character, which was part of the descriptor in earlier versions of this solution, is always `X`, so it is now not part of the descriptor anymore.

These descriptors are specified for the top 5 lines, and repeated for the bottom 5 lines in reverse order.

Explanation:

```
"++-0|| 5|| 8|+-9|| B"
        Descriptors for top 5 lines, as described above.
4/      Split into 5 descriptors of 4 characters each.
_W%     Repeat the 5 descriptors in reverse order.
{       Loop over lines/descriptors.
    1/    Split descriptor string into array with 5 one-character strings.
    ~     Unwrap the array.
    ~     Evaluate last entry in descriptor, which is the count.
    'X    Left fill character.
    *     Repeat left fill character by given count.
    34@e] Pad to 34 characters using right fill character.
    \     Swap last character to top.
    N     Add a newline.
}/    End loop over lines/descriptors.

```
> 4 votes

# Answer
## Python 3, 282 bytes/characters

```
f,l,h=lambda a:a in{0,35}and '+'or'-',lambda a:a%3 and'|'or'+',lambda a:a and(a<10 and 'X'or'-')or'|';print("\n".join("".join(x)for x in[[k in{0,9}and f(j)or j==35 and l(k)or k%3 and(j==0 and'|'or j<[0,6,9,0,12,12,0,9,6][k]and'X'or' ')or h(j)for j in range(36)]for k in range(10)]))

```

Output is, of course:

```
+----------------------------------+
|XXXXX                             |
|XXXXXXXX                          |
|XXXXXXXXX-------------------------+
|XXXXXXXXXXX                       |
|XXXXXXXXXXX                       |
|XXXXXXXXX-------------------------+
|XXXXXXXX                          |
|XXXXX                             |
+----------------------------------+

```

I'm sure there's a much shorter way to do this in Python.
> 2 votes

# Answer
## Ruby, ~~156~~ 155 chars

```
h=[5,8,9,11];l=34;t=?++(?-*l)+?+;puts t;2.times{h.each{|c|if c==9 then j='-+' else j=' |';end;print(?|,((?X*c).ljust(l,j[0])),j[1],?\n)};h.reverse!};puts t

```

I used an array, `h`, with the values `[5, 8, 9, 11]`, so I can use `2.times { h.each { code }; h.reverse }` because the flag is symmetrical horizontally. I also use 34 many times in the code, so it is assigned to `l`. `?x` is shorthand for `"x"`.
> 2 votes

# Answer
# Ruby, 78

```
"@EHIKKIHE@".each_byte{|i|puts"+|"[i/65]+?X*(i-64)+" -"[i%3]*(98-i)+"|+"[i%3]}

```

A copy of Rinkattendant's / Xnor's idea of iterating over the lengths of the strings of X's. Except instead of using an array, I have compressed them into a string.

# Ruby, 96

Original plain vanilla approach

```
(0..9).each{|i|puts (i%9<1??+:?|)+(?X*("@EHIKKIHE@"[i].ord-64)).ljust(34,"-  "[i%3])+"+||"[i%3]}

```

**Ungolfed**

```
(0..9).each{|i|
   puts (i%9<1??+:?|)                                          #first character + or |
   +(?X*("@EHIKKIHE@"[i].ord-64)).ljust(34,"-  "[i%3])         #print quantity of X's according to string, then right justify with - or space
   +"+||"[i%3]}                                                #last character + or |

```
> 2 votes

# Answer
## Swift 1.2, 157 bytes

Can be run in a playground, or from a file using `swift file.swift` in Terminal.

```
let z="-----",x="XXX",y="   ",g=y+y,w=z+z+z+z+"----+",e=g+g+g+y+"  |",c="|XX"+x,d=["+"+z+z+w,c+g+e,c+x+y+e,c+x+"X-"+w,c+x+x+e]
print("\n".join(d+reverse(d)))

```
> 1 votes

# Answer
# PHP, 135 bytes

Lets play around with `printf`:

```
<?$A='|%-34s|
|%-34s|';$B="|%'--34s|";printf("+%'-34s+
$A
$B
$A
$B
$A
+%'-34s+",'',$a=XXXXX,$b=$a.XXX,$c=$b.X,$d=$b.XX,$d,$c,$b,$a,'');

```

Maybe there are some edges that I've left behind that can be cut.

But it was fun!
> 1 votes

# Answer
# Vyxal `j`, 41 bytes

```
»'ꜝ»12τƛ\X*34↲n9=[ð\-V\+|\|]+\|p;\+17-mpm

```

Try it Online!

```
    12τ                                   # Base-12 digits of...
»'ꜝ»                                      # 9119 (so 5,8,9,11)
       ƛ                        ;         # Mapped to...
        \X*                               # That many Xs
           34↲                            # Padded to width of 34
              n9=[         ]              # If it's a 9...
                  ð\-V\+                  # Replace all spaces with -s and append a +
                        |\|               # Else append a |
                            +\|p          # Prepend a |
                                 \+       # '+'
                                   17-    # Append 17 -s
                                      m   # Mirror the result
                                       p  # Prepend that to the rest
                                        m # Mirror the lot.

```
> 1 votes

# Answer
## Sed - 228

```
s/.*/eeeeee\neeeeee/
s/e/------/g
s/^-/+/
s/-$/+/
s/-\n-/+\n+/
s/\n/\nabcddcba/
s/\([a-d]\)/|XXXXX\1\1\1\1\1\1\n/g
s/\([a-d]\)/\1\1\1\1\1/g
s/Xbbb/XXXX/g
s/Xcccc/XXXXX/g
s/Xdddddd/XXXXXXX/g
y/abcd/  - /
s/ \n/|\n/g
s/-\n/+\n/g
q

```

Because of the way sed works, this requires a line of input to output the flag.
> 0 votes

# Answer
## Haskell, 233 bytes

```
putStr$uncurry((.toEnum).replicate)=<<foldl1(++)(((++)=<<reverse)$zipWith zip[[1,11,23,1,1],[1,9,25,1,1],[1,8,26,1,1],[1,5,29,1,1],[1,34,1,1]][[124,88,32,124,10],[124,88,45,43,10],[124,88,32,124,10],[124,88,32,124,10],[43,45,43,10]])

```
> 0 votes

# Answer
# Deadfish~, 558 bytes

```
{iiii}iiicii{ccc}ccccddc{ddd}c{{i}i}ic{ddd}ddddddccccc{dddddd}iiii{cc}ccccccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddcccccccc{dddddd}iiii{cc}cccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccccccc{dddd}ddd{cc}ccccc{{i}dd}dcd{{d}d}c{{i}i}ic{ddd}dddddd{c}c{dddddd}iiii{cc}ccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}dddddd{c}c{dddddd}iiii{cc}ccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccccccc{dddd}ddd{cc}ccccc{{i}dd}dcd{{d}d}c{{i}i}ic{ddd}ddddddcccccccc{dddddd}iiii{cc}cccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccc{dddddd}iiii{cc}ccccccccc{{i}d}iicd{{d}d}c{iii}cii{ccc}ccccddc

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Print this text in Scala

text:
# Question
Title: Print this text in Scala
Print the following text and nothing else:

```
<html>
  <body>

    <p>HTML is kinda annoying</p>

  </body>
</html>
I'm happy I'm not a web developer.

```

The catch? Your code must fit the template: `print(<?>)`, where `?` can be any group of characters. You can paste your completed code (with the `print(<>)` part) into this Scastie to test it. When posting an answer, please mark it as a spoiler.

Here is the sbt configuration:

```
scalaVersion := "2.13.6"
addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.13.0" cross CrossVersion.full)

scalacOptions ++= Seq(
  "-language:higherKinds",
  "-Ydelambdafy:inline",
  "-deprecation",
  "-encoding", "UTF-8",
  "-feature",
  "-unchecked",
  "-language:postfixOps"
)
libraryDependencies ++= Seq(
  "org.scala-lang.modules" %% "scala-xml" % "2.0.0",
  "org.scastie" %% "runtime-scala" % "1.0.0-SNAPSHOT"
)

```

Beware, while the configuration provides one hint, some of these are red herrings.

This is the md5 hash of my solution: `5aa91599e4a8e194b5097b36bdb3dabf`. N.B. it looks like the hash didn't work well with newlines and certain other characters - it may have skipped over them entirely.

Hints:

> Types are involved near the end, at least in the solution I had. `>` is a single token that isn't part of the XML, and it's not a method or field.

hyper-neutrino and pxeger found answers, but they use workarounds that I didn't intend to be used and should have thought of while writing the question. ~~I'll award a **500 rep bounty** to another answer, provided they meet certain criteria.~~ This is the solution.

# Answer
> 7 votes
> ```
> print(<html>
>    <body>
>
>      <p>HTML is kinda annoying</p>
>
>    </body>
>  </html>)
>  print("\nI'm happy I'm not a web developer.")
>  //>)
> ```

Probably not intended :)

# Answer
> 5 votes
> ```
> print(<html>
>    <body>
>
>      <p>HTML is kinda annoying</p>
>
>    </body>
>  </html> + "\nI'm happy I'm not a web developer.")
>  def x = (<x />)
> ```
> Try it on Scastie!

---
Tags: programming-puzzle, scala
---


title: Log Scales are for Quitters

text:
# Question
Title: Log Scales are for Quitters
Everyone knows log scales are for quitters. Therefore, you must write a program or function that *de-quitifies* a bar graph with a log scale given a base.

The bar graph input is taken as a single string which is a list of bars, where each bar of the log scale bar graph is separated by the printable (or whitespace) delimiter of your choosing (so `0x09-0x0A + 0x20-0x7E`) and composed of a printable non-whitespace (so `0x21-0x7E`) filler character of your choosing.

The program or function outputs a single string which is a list of bars, where each bar is separated by the same delimiter the input was separated by and is composed of the same filler character the input was composed of.

# Example

We choose a delimiter of `"\n"` (one newline) and a filler character of `"#"`. The input passed to our program or function is:

base=`2` and string=

```
####
##
######
###

```

The code would find that the lengths of the bars are `[4,2,6,3]`. It would compute the anti-log of each length with base `2` to get `[2^4,2^2,2^6,2^3]` = `[16,4,64,8]`. Then, the lengths are output in linear scale bar format:

```
################
####
################################################################
########

```

# Input / Output

Your program or function may input and output in any reasonable format.

The input base is guaranteed to be an integer greater than 1. You may assume the base is less than 256. The string input is guaranteed to fully match the regex `(f+s)+f+`, where `f` and `s` are replaced with your filler and delimiter respectively.

The string output must fully match the regex `(f+s)+f+`, where `f` and `s` are replaced with the same filler and delimiter respectively. The output may optionally have a trailing newline.

The output and input may also be a list of strings instead of delimited by a substring, though it must be possible to understand which bar is which.

# Testcases

(assume filler is `#` and delimiter is `\n`)

```
base
-
input string
-
output string
-----
2
-
####
##
######
###
-
################
####
################################################################
########
-----
3
-
##
#
###
#
-
#########
###
###########################
###
-----
100
-
#   I am not the delimiter
###  nor the filler
-
Anything (You do not have to handle input which does not match the regex)
-----
1
-
###
#######
###################################################
-
Anything (You do not have to handle bases less than or equal to 1).
-----
5
-
####
##
###
#
-
#################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
#########################
#############################################################################################################################
#####
-----
2
-
#
#
##
##
#
##
#
#
#
#
##
##
#
#
##
#
-
##
##
####
####
##
####
##
##
##
##
####
####
##
##
####
##

```

# Answer
## x86 32-bit machine code function, 21 bytes

## x86-64 machine code function, 22 bytes

The 1B saving in 32-bit mode requires using separator = filler-1, e.g. `fill=0` and `sep=/`. The 22-byte version can use an arbitrary choice of separator and filler.

---

**This is the 21-byte version, with input-separator = `\n` (0xa), output-filler = `0`, output-separator = `/` = filler-1. These constants can be easily changed.**

```
; see the source for more comments
; RDI points to the output buffer,  RSI points to the src string
; EDX holds the base
; This is the 32-bit version.
; The 64-bit version is the same, but the DEC is one byte longer (or we can just mov al,output_separator)
08048080 <str_exp>:
 8048080:       6a 01           push   0x1
 8048082:       59              pop    ecx           ; ecx = 1 = base**0
 8048083:       ac                      lods   al,BYTE PTR ds:[esi]  ; skip the first char so we don't do too many multiplies

; read an input row and accumulate base**n as we go.
08048084 <str_exp.read_bar>:
 8048084:       0f af ca        imul   ecx,edx       ; accumulate the exponential
 8048087:       ac              lods   al,BYTE PTR ds:[esi]
 8048088:       3c 0a           cmp    al,0xa        ; input_separator = newline
 804808a:       77 f8           ja     8048084 <str_exp.read_bar>
 ; AL = separator or terminator
 ; flags = below (CF=1) or equal (ZF=1).  Equal also implies CF=0 in this case.

 ; store the output row
 804808c:       b0 30           mov    al,0x30       ; output_filler
 804808e:       f3 aa           rep stos BYTE PTR es:[edi],al  ; ecx bytes of filler
 8048090:       48              dec    eax           ; mov al,output_separator
 8048091:       aa              stos   BYTE PTR es:[edi],al  ;append delim

 ; CF still set from the inner loop, even after DEC clobbers the other flags
 8048092:       73 ec           jnc    8048080 <str_exp>  ; new row if this is a separator, not terminator

 8048094:       c3              ret

08048095  <end_of_function>
; 0x95 - 0x80 = 0x15 = 21 bytes

```

The 64-bit version is 1 byte longer, using a 2-byte DEC or a `mov al, output_separator`. Other than that, the machine-code is the same for both versions, but some register names change (e.g. `rcx` instead of `ecx` in the `pop`).

Sample output from running the test program (base 3):

```
$ ./string-exponential $'.\n..\n...\n....' $(seq 3);echo
000/000000000/000000000000000000000000000/000000000000000000000000000000000000000000000000000000000000000000000000000000000/

```

**Algorithm**:

Loop over the input, doing `exp *= base` for every filler char. On delimiters and the terminating zero byte, append `exp` bytes of filler and then a separator to the output string and reset to `exp=1`. It's very convenient that the input is guaranteed not to end with both a newline *and* a terminator.

On input, any byte value above the separator (unsigned compare) is treated as filler, and any byte value below the separator is treated as an end-of-string marker. (Checking explicitly for a zero-byte would take an extra `test al,al` vs. branching on flags set by the inner loop).

---

The rules only allow a trailing separator when it's a trailing newline. My implementation always appends the separator. **To get the 1B saving in 32-bit mode, that rule requires separator = 0xa (`'\n'` ASCII LF = linefeed), filler = 0xb (`'\v'` ASCII VT = vertical tab).** That's not very human-friendly, but satisfies the letter of the law. (You can hexdump or
`tr $'\v' x` the output to verify that it works, or change the constant so the output separator and filler are printable. I also noticed that the rules seem to require that it can accept input with the same fill/sep it uses for output, but I don't see anything to gain from breaking that rule.).

---

NASM/YASM source. Build as 32 or 64-bit code, using the `%if` stuff included with the test program or just change rcx to ecx.

```
input_separator equ 0xa  ; `\n` in NASM syntax, but YASM doesn't do C-style escapes

output_filler equ '0'                 ; For strict rules-compliance, needs to be input_separator+1
output_separator equ output_filler-1  ; saves 1B in 32-bit vs. an arbitrary choice
    ;; Using output_filler+1 is also possible, but isn't compatible with using the same filler and separator for input and output.

global str_exp
str_exp:                        ; void str_exp(char *out /*rdi*/, const char *src /*rsi*/,
                                ;              unsigned base /*edx*/);
.new_row:
    push   1
    pop    rcx                  ; ecx=1 = base**0

    lodsb                       ; Skip the first char, since we multiply for the separator
.read_bar:
    imul   ecx, edx             ; accumulate the exponential
    lodsb
    cmp    al, input_separator
    ja .read_bar                ; anything > separator is treated as filler
    ; AL = separator or terminator
    ; flags = below (CF=1) or equal (ZF=1).  Equal also implies CF=0, since x-x doesn't produce carry.

    mov    al, output_filler
    rep stosb                   ; append ecx bytes of filler to the output string
%if output_separator == output_filler-1
    dec   eax         ; saves 1B in the 32-bit version.  Use dec even in 64-bit for easier testing
%else
    mov    al, output_separator
%endif
    stosb                       ; append the delimiter

    ; CF is still set from the .read_bar loop, even if DEC clobbered the other flags
    ; JNC/JNB here is equivalent to JE on the original flags, because we can only be here if the char was below-or-equal the separator
    jnc .new_row            ; separator means more rows, else it's a terminator
    ; (f+s)+f+ full-match guarantees that the input doesn't end with separator + terminator
    ret

```

**The function follows the x86-64 SystemV ABI, with signature<br>`void str_exp(char *out /*rdi*/, const char *src /*rsi*/, unsigned base /*edx*/);`**
It only informs the caller of the length of the output string by leaving a one-past-the-end pointer to it in `rdi`, so you could consider this the return value in a non-standard calling convention.

It would cost 1 or 2 bytes (`xchg eax,edi`) to return the end-pointer in eax or rax. (If using the x32 ABI, pointers are guaranteed to be only 32 bits, otherwise we have to use `xchg rax,rdi` in case the caller passes a pointer to a buffer outside the low 32 bits.) I didn't include this in the version I'm posting because there are workarounds the caller can use without getting the value from `rdi`, so you could call this from C with no wrapper.

We don't even null-terminate the output string or anything, so it's only newline-terminated. It would take 2 bytes to fix that: `xchg eax,ecx / stosb` (rcx is zero from `rep stosb`.)

The ways to find out the output-string length are:

* rdi points to one-past-the-end of the string on return (so the caller can do len=end-start)
* the caller can just know how many rows were in the input and count newlines
* the caller can use a large zeroed buffer and `strlen()` afterwards.

They're not pretty or efficient (except for using the RDI return value from an asm caller), but if you want that then don't call golfed asm functions from C. :P

---

**Size/range limitations**

The max output string size is only limited by virtual memory address-space limitations. (Mainly that current x86-64 hardware only supports 48 significant bits in virtual addresses, split in half because they sign-extend instead of zero-extend. See the diagram in the linked answer.)

Each row can only have a maximum of 2\**32 - 1 filler bytes, since I accumulate the exponential in a 32-bit register.

The function works correctly for bases from 0 to 2\**32 - 1. (Correct for base 0 is 0^x = 0, i.e. just blank lines with no filler bytes. Correct for base 1 is 1^x = 1, so always 1 filler per line.)

It's also blazingly fast on Intel IvyBridge and later, especially for large rows being written to aligned memory. `rep stosb` is an optimal implementation of `memset()` for large counts with aligned pointers on CPUs with the ERMSB feature. e.g. 180\**4 is 0.97GB, and takes 0.27 seconds on my i7-6700k Skylake (with ~256k soft page-faults) to write to /dev/null. (On Linux the device-driver for /dev/null doesn't copy the data anywhere, it just returns. So all of the time is in the `rep stosb` and the soft page-faults that triggers when touching the memory for the first time. It's unfortunately not using transparent hugepages for the array in the BSS. Probably an `madvise()` system call would speed it up.)

**Test program**:

Build a static binary and run as `./string-exponential $'#\n##\n###' $(seq 2)` for base 2. To avoid implementing an `atoi`, it uses `base = argc-2`. (Command-line length limits prevent testing ridiculously large bases.)

This wrapper works for output strings up to 1 GB. (It only makes a single write() system call even for gigantic strings, but Linux supports this even for writing to pipes). For counting characters, either pipe into `wc -c` or use `strace ./foo ... > /dev/null` to see the arg to the write syscall.

This takes advantage of the RDI return-value to calculate the string length as an arg for `write()`.

```
;;; Test program that calls it
;;; Assembles correctly for either x86-64 or i386, using the following %if stuff.
;;; This block of macro-stuff also lets us build the function itself as 32 or 64-bit with no source changes.

%ifidn __OUTPUT_FORMAT__, elf64
%define CPUMODE 64
%define STACKWIDTH 8    ; push / pop 8 bytes
%define PTRWIDTH 8
%elifidn __OUTPUT_FORMAT__, elfx32
%define CPUMODE 64
%define STACKWIDTH 8    ; push / pop 8 bytes
%define PTRWIDTH 4
%else
%define CPUMODE 32
%define STACKWIDTH 4    ; push / pop 4 bytes
%define PTRWIDTH 4
%define rcx ecx      ; Use the 32-bit names everywhere, even in addressing modes and push/pop, for 32-bit code
%define rsi esi
%define rdi edi
%define rsp esp
%endif

global _start
_start:
    mov  rsi, [rsp+PTRWIDTH + PTRWIDTH*1]  ; rsi = argv[1]
    mov  edx, [rsp]          ; base = argc
    sub  edx, 2              ; base = argc-2  (so it's possible to test base=0 and base=1, and so ./foo $'xxx\nxx\nx' $(seq 2) has the actual base in the arg to seq)
    mov  edi, outbuf         ; output buffer.  static data is in the low 2G of address space, so 32-bit mov is fine.  This part isn't golfed, though

    call str_exp             ; str_exp(outbuf, argv[1], argc-2)
    ;  leaves RDI pointing to one-past-the-end of the string
    mov  esi, outbuf

    mov  edx, edi
    sub  edx, esi               ; length = end - start

%if CPUMODE == 64 ; use the x86-64 ABI
    mov  edi, 1                 ; fd=1 (stdout)
    mov  eax, 1                 ; SYS_write  (Linux x86-64 ABI, from /usr/include/asm/unistd_64.h)
    syscall                     ; write(1, outbuf, length);

    xor edi,edi
    mov eax,231   ; exit_group(0)
    syscall

%else  ; Use the i386 32-bit ABI (with legacy int 0x80 instead of sysenter for convenience)
    mov ebx, 1
    mov eax, 4                  ; SYS_write (Linux i386 ABI, from /usr/include/asm/unistd_32.h)
    mov ecx, esi  ; outbuf
    ; 3rd arg goes in edx for both ABIs, conveniently enough
    int 0x80                    ; write(1, outbuf, length)

    xor ebx,ebx
    mov eax, 1
    int 0x80     ; 32-bit ABI _exit(0)
%endif

section .bss
align 2*1024*1024 ; hugepage alignment (32-bit uses 4M hugepages, but whatever)
outbuf:    resb 1024*1024*1024 * 1
; 2GB of code+data is the limit for the default 64-bit code model.
; But with -m32, a 2GB bss doesn't get mapped, so we segfault.  1GB is plenty anyway.

```

---

**This was a fun challenge that lent itself very well to asm, especially x86 string ops**. The rules are nicely designed to avoid having to handle a newline and then a terminator at the end of the input string.

An exponential with repeated multiplication is just like multiplying with repeated addition, and I needed to loop to count chars in each input row anyway.

I considered using one-operand `mul` or `imul` instead of the longer `imul r,r`, but its implicit use of EAX would conflict with LODSB.

---

**I also tried SCASB instead of load and compare**, but I needed `xchg esi,edi` before and after the inner loop, because SCASB and STOSB both use EDI. (So the 64-bit version has to use the x32 ABI to avoid truncating 64-bit pointers).

Avoiding STOSB is not an option; nothing else is anywhere near as short. And half the benefit of using SCASB is that AL=filler after leaving the inner loop, so we don't need any setup for REP STOSB.

SCASB compares in the other direction from what I had been doing, so I needed to reverse the comparisons.

My best attempt with xchg and scasb. Works, but isn't shorter. (**32-bit code, using the `inc`/`dec` trick to change filler into separator**).

```
; SCASB version, 24 bytes.  Also experimenting with a different loop structure for the inner loop, but all these ideas are break-even at best
; Using separator = filler+1 instead of filler-1 was necessary to distinguish separator from terminator from just CF.

input_filler equ '.'    ; bytes below this -> terminator.  Bytes above this -> separator
output_filler equ input_filler       ; implicit
output_separator equ input_filler+1  ; ('/') implicit

 8048080:       89 d1                   mov    ecx,edx    ; ecx=base**1
 8048082:       b0 2e                   mov    al,0x2e    ; input_filler= .
 8048084:       87 fe                   xchg   esi,edi
 8048086:       ae                      scas   al,BYTE PTR es:[edi]

08048087 <str_exp.read_bar>:
 8048087:       ae                      scas   al,BYTE PTR es:[edi]
 8048088:       75 05                   jne    804808f <str_exp.bar_end>
 804808a:       0f af ca                imul   ecx,edx           ; exit the loop before multiplying for non-filler
 804808d:       eb f8                   jmp    8048087 <str_exp.read_bar>   ; The other loop structure (ending with the conditional) would work with SCASB, too.  Just showing this for variety.
0804808f <str_exp.bar_end>:

; flags = below if CF=1 (filler<separator),  above if CF=0 (filler<terminator)
; (CF=0 is the AE condition, but we can't be here on equal)
; So CF is enough info to distinguish separator from terminator if we clobber ZF with INC

; AL = input_filler = output_filler
 804808f:       87 fe                   xchg   esi,edi
 8048091:       f3 aa                   rep stos BYTE PTR es:[edi],al
 8048093:       40                      inc    eax         ; output_separator
 8048094:       aa                      stos   BYTE PTR es:[edi],al
 8048095:       72 e9                   jc     8048080 <str_exp>   ; CF is still set from the inner loop
 8048097:       c3                      ret

```

For an input of `../.../.`, produces `..../......../../`. I'm not going to bother showing a hexdump of the version with separator=newline.
> 9 votes

# Answer
## Mathematica ~~41~~ 38 Bytes

-3 Bytes thanks to LLlAMnYP

This takes input as a list of strings followed by an integer. Output is also a list of strings.

```
""<>"#"~Table~#&/@(#2^StringLength@#)&

```

Explanation:

```
                   StringLength@# & - find length of each string in first input
                   #2^               & - raise to power of second input
                /@(                 )  - Uses each of these numbers on an inner function of ...
    "#"~Table~#&                       - Create arrys of specific length using character "#"
 ""<>                                  - Join arrays of characters together to make strings

```

Old version, 41 Bytes

```
"#"~StringRepeat~#&/@(#2^StringLength@#)&

```
> 4 votes

# Answer
# Japt, 7 bytes

Takes the graph as an array of strings with `"` as the filler, and the base as an integer.

```
£QpVpXl

```

Try it online

Add `}R` to the end in order to take the graph as a newline separated string instead. (Try it)

---

## Explanation

```
    :Implicit input of array U.
£   :Map over the array, replacing each element with ...
Q   :the " character ...
p   :repeated ...
V   :integer input ...
p   :to the power of ...
Xl  :the length of the current element times.
    :Implicit output of result.

```
> 3 votes

# Answer
# MATL, ~~14~~ 11 bytes

```
Y'iw^1HL(Y"

```

Delimiter is space. Filler is any character other than space.

Try it online!

### Explanation

```
       % Implicit input: string
       %   STACK: '## # ### #'
Y'     % Run-length encoding
       %   STACK: '# # # #', [2 1 1 1 3 1 1]
i      % Input: number
       %   STACK: '# # # #', [2 1 1 1 3 1 1], 3
w      % Swap
       %   STACK: '# # # #', 3, [2 1 1 1 3 1 1]
^      % Power, element-wise
       %   STACK: '# # # #', [9 3 3 3 9 3 3]
1      % Push 1
       %   STACK: '# # # #', [9 3 3 3 27 3 3], 1
HL     % Push [2 2 1j]. When used as an index, this means 2:2:end
       %   STACK: '# # # #', [9 3 3 3 27 3 3], 1, [2 2 1j]
(      % Write specified value at specified entries
       %   STACK: '# # # #', [9 1 3 1 27 1 3]
Y"     % Run-length decoding
       %  STACK: '######### ### ########################### ###'
       % Implicit display

```
> 3 votes

# Answer
## Haskell, ~~37~~ 33 bytes

*4 bytes shaved off thanks to sudee*

```
\b->map(\x->'#'<$[1..b^length x])

```

Description:

```
\b->                               -- take an integer b as the first input input
    map(\x->                    )  -- apply the following to every element x in the second input
            '#'<$[1..b^length x]   ---- replicate '#' (b^(length x)) times

```

Disappointingly, this is ~~2 bytes~~ much shorter than the way-harder-to-read pointfree version:

```
map.(flip replicate '#'.).(.length).(^)

```
> 3 votes

# Answer
# Haskell, 32 bytes

```
f b=map$foldr(\_->([1..b]>>))"#"

```

Try it online! Example usage: `f 3 ["##","#","###","#"]` returns `["#########","###","###########################","###"]`.

Use `mapM putStrLn $ f 3 ["##","#","###","#"]` to get a more visually pleasing output:

```
#########
###
###########################
###

```
> 3 votes

# Answer
# ReRegex, 105 bytes

```
#import math
(\d+)\n((;.*\n)*)(_+)/$1\n$2;$1^d<$4>/^\d+\n((;\d+\n?)+)$/$1/^((_*\n)*);(\d+)/$1u<$3>/#input

```

Try it online!

ReRegex is like Retina's ugly cousin that gives *all* the effort to Regular Expressions, instead of having it's own fancy operators.

Of course, it also has `#import` and `#input` to save both hardcoding input, and re-writing the same expressions over and over again.

# Explained.

Takes input in the form of:

```
2
____
__
______
___

```

on STDIN, and gives output like

```
________________
____
________________________________________________________________
________

```

Firstly, the program imports the Math Library, which of course is entirely written in ReRegex. The bulk of this is then three regular expressions.

```
(\d+)\n((;.*\n)*)(_+)   ->  $1\n$2;$1^d<$4>
^\d+\n((;\d+\n?)+)$     ->  $1
^((_*\n)*);(\d+)        ->  $1u<$3>

```

The first matches our input base, and seeks a line of unary after it. it then, replaces that line with `;$1^d<$4>`, which is the base, to the power of the (In Decimal) Unary. The Math library handles the base conversion and the exponent. A ; is placed at the start to identify it later as finished.

The second, matches the base, then many lines of ;, before ending. If this matches the entire thing, it snips off the base. leaving uf with just the answers and `;`s.

The last, matches just unary at the start, optionally, then a `;` answer. It then transforms that answer into unary again, without the `;`.

Because the output isn't matched by the first regex, it doesn't loop infinitely, and so our solution is outputted.
> 3 votes

# Answer
# Python 2, ~~52~~ 36 bytes

Input and output are taken as arrays of strings. `#` is the filler.

```
lambda s,n:['#'*n**len(l)for l in s]

```

Try it online!
> 2 votes

# Answer
# Röda, 19 bytes

```
f n,s{s|["#"*n^#_]}

```

Try it online!

Takes an array as input and returns a stream of values as output.

### Explanation

```
f n,s{s|["#"*n^#_]}              n is the number and s is the array of strings consisting of #s
      s|                         Push the each value of s to the stream
        [        ]               For each push
         "#"*                     "#" repeated
             n^#_                 n raised to the length of the string

```
> 2 votes

# Answer
# 05AB1E, 9 bytes

Bars are seperated by spaces, output character is same as input character.

```
¬Š#€gm×ðý

```

Try it online!

```
¬Š#€gm×ðý   Arguments: n, s
¬           Head, get bar character
 Š          Rearrange stack to get: s, n, bar-character
  #         Split s on spaces
   €g       Map to length
     m      n to that power
      ×     That many bar-characters
       ðý   Join on space
            Implicit output

```
> 2 votes

# Answer
# Risky, 6 bytes

```
_?_!?_?[*+?

```

Try it online!

Inputs and outputs an array like `["@@", "@@@@"]`. Unfortunately, the output is implicitly concatenated. 6 more bytes to have it joined by newlines:

# Risky, 12 bytes

```
_*+_0+_0+_0*_?_!?_?[*+?

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 7 bytes

Anonymous tacit infix function taking base as left argument and list of strings as right argument

```
*∘≢¨⍴¨⊢

```

Try it online!

`*∘≢¨` base to the power of the length of each string

`⍴¨` cyclically reshapes each

string
> 2 votes

# Answer
# Julia, 22 bytes

```
x$b="#".^b.^length.(x)

```

Try it online!

input and output are lists of strings
> 2 votes

# Answer
# JavaScript (ES8), 39 bytes

Takes the base as an integer and the graph as an array of strings with any character as the filler, using currying syntax.

```
b=>a=>a.map(x=>x.padEnd(b**x.length,x))

```

---

## Try it

```
f=
b=>a=>a.map(x=>x.padEnd(b**x.length,x))
oninput=_=>o.innerText=f(i.value)(j.value.split`\n`).join`\n`
o.innerText=f(i.value=2)((j.value=`####\n##\n######\n###`).split`\n`).join`\n`
```

```
*{box-sizing:border-box}#i,#j{margin:0 0 5px;width:200px}#j{display:block;height:100px
```

```
<input id=i type=number><textarea id=j></textarea><pre id=o>
```

---

## Alternative, 49 bytes

This version takes the graph as a newline separated string, again with any character as filler.

```
b=>s=>s.replace(/.+/g,m=>m.padEnd(b**m.length,m))

```
> 1 votes

# Answer
# PHP, 69 Bytes

```
<?foreach($_GET[1]as$l)echo str_pad("",$_GET[0]**strlen($l),"#")."
";

```

Try it online!
> 1 votes

# Answer
# Jelly, 7 bytes

```
ṁL*@¥¥€

```

A monadic link taking and returning lists of the bars (themselves lists of characters, AKA strings) the filler character is flexible.

**Try it online!** (the footer prettifies the resulting list by joining its elements with newlines.)

### How?

```
ṁL*@¥¥€ - Main link: list of list of characters, bars; number, base
     ¥€ - last two links as a dyad for €ach bar in bars:
    ¥   -   last two links as a dyad:
 L      -     length (of a bar)
  *@    -     exponentiate (swap @rguments) (base ^ length)
ṁ       -   mould like (e.g. moulding "##" like 8 yields "########")

```

---

Alternative 7-byter: `ṁ"L€*@¥` \- get length of each bar (`L€`), raise `base` to that power (`*@`), then zip (`"`) the list and that applying the mould dyad () between the two.
> 1 votes

# Answer
# Ruby, 29 bytes

```
->x,y{x.map{|z|?#*y**z.size}}

```

Try it online!

Yeah, I found out last week that `?#` produces a single-character string. I've no idea why this feature exists but I'm sure glad it does.
> 1 votes

# Answer
# Vyxal `r`, 6 bytes

```
ƛL⁰e×*

```

Try it Online! Inputs and outputs a list of strings; uses `*` as the filler character 'cuz that's easy in Vyxal.

```
ƛL⁰e×*
ƛ        # For each bar in the string
   e     # Raise...
  ⁰      # the base...
 L       # to the power of the bar's length
    ×*   # Push that many *s

```
> 1 votes

# Answer
# Jelly, 6 bytes

```
ẈƓ*ṁ@"

```

Try it online!

Takes a list of lines on the left and the base on STDIN

## How it works

```
ẈƓ*ṁ@" - Main link. Takes a list of lines L on the left
Ẉ      - Get the lengths of each line
 Ɠ     - Read the base b from STDIN
  *    - Raise b to the power of each length
     " - For each pair (length, original_line):
    @  -   Reverse the arguments as (original_line, length):
   ṁ   -     Mold the original_line to the length

```
> 1 votes

# Answer
# Pip `-rl`, ~~9~~ 8 bytes

```
0XaE#*Sg

```

Attempt This Online!

Takes the base followed by the bar graph (using any non-whitespace symbol) from stdin; outputs a bar graph of `0`s to stdout.

### Explanation

```
       g  List of lines of stdin (due to -r flag)
      S   All but the first element
    #*    Length of each
  aE      First line of stdin raised to each of those powers
0X        0 repeated that many times
          Autoprint (implicit), one element per line (due to -l flag)

```
> 1 votes

# Answer
# Excel, 24 bytes

```
=REPT("#",A1^LEN(A2:A5))
A1 is the base
A2:A5 are the input lines

```
> 1 votes

# Answer
# Knight, 21 bytes

```
;=y+0P W=xP O*"#"^yLx

```

Try it online!

Had to actually fix a bug in the interpreter on this one.

Delimiter is newline, filler is `#` (although it doesn't check this, it just checks the length)

```
# read base, coerce to int
; = base + 0 PROMPT
# read all lines
: WHILE (= line PROMPT)
    # output base ^ length(line) #'s
    OUTPUT(* "#" (^ base LENGTH(line)))

```
> 1 votes

# Answer
# Mathematica, 86 bytes

```
(s=#2^StringLength[StringSplit@#1];StringJoin/@Table[Table["#",s[[i]]],{i,Length@s}])&

```

**input**

> \["####\n##\n######\n###", 2\]
> 0 votes

# Answer
# Octave, 42 bytes

```
@(b,s)[(1:max(k=b.^sum(s'>32)')<=k)+32 '']

```

\*The string input/output doesn't fully match the regex but it is possible to understand which bar is which.

A function takes as input base `b` and a 2D array of chars `s` containing `"!"` and the output is also an array of chars.

Try it online!

Explanation:

```
                       s'>32               % logical array of input represents 1 for filler and 0 for spaces
                   sum(     )'             % an array containing length of each string
              k=b.^                        % exponentiate ( lengths of output)
        1:max(                )            % range form 1 to max of output lengths
                               <=k         % logical array of output represents 1 for filler and 0 for spaces
      [(                          )+32 ''] % convert the logical array to char array.

```
> 0 votes

# Answer
# CJam, 20 bytes

```
q~:A;N/{,A\#"#"e*N}%

```

## Input format

Input is required in the following format:

```
"##
####
######"2

```
> 0 votes

# Answer
# Charcoal, 11 bytes

```
ＮβＷＳ«ＰＸβＬι↓

```

Try it online! Link is to verbose version of code. I/O is as a list of strings of `-` characters (note that you need an empty line to terminate the list).
> 0 votes

# Answer
# , 27 bytes

The basic idea is that we add a `'` to each row (n^0), and then for each `#` we replace the `'`s in the line with `[input] * '`. At the end I swapped all of the `'` for `#` again

```
Àé'ld0ÎA'
ò/#
"_xÓ'/"òÍ'/#

```

Try it online!
> 0 votes

# Answer
# , 35 bytes

```
function(s,b)strrep('#',b^nchar(s))

```

an anonymous function which takes the strings as a list and the base, and returns a list of strings.

Try it online!
> 0 votes

# Answer
# 05AB1E, 10 bytes

```
U|v1Xygm×,

```

The filer character is `1` and the delimiter is a newline.

Try it online!

```
U          # Store the base in X
 |         # Get the rest of input as a list of lines
  v        # For each...
   1       #   Push 1
    X      #   Push the base
     y     #   Push this bar
      g    #   Get the length
       m   #   Push a**b
        ×, #   Print a string of #s with that length

```
> 0 votes

# Answer
# Retina, 62 bytes

```
ms`^(?=.*¶(.*))
#;$1$*#;
{`#(?=#*;(#+);#)
$1
}m`#$

;#+;|¶.*$

```

Try it online! After all, a bar graph is just a list of unary numbers. Takes input as the graph (using `#`s) followed by the base in decimal (to avoid confusion). Explanation: The first replacement prefixes 1 and the base to each line of the graph. The second replacement then multiplies the first number on each line by the second, as long as the third number is nonzero. The third replacement then decrements the third number on each line. These two replacements are repeated until the third number becomes zero. The last replacement deletes the base everywhere, leaving the desired result.
> 0 votes

# Answer
# Convex, 9 bytes

```
f{,#'#*N}

```

Try it online!
> 0 votes

# Answer
# Alice, 23 bytes

```
/'/dI
\I!wO&K/h.n$@?~E&

```

Try it online!

Not only am I not a quitter, but I'm so committed to making the point properly that I use `!` as the filler. That will certainly get the reader's attention.

### Explanation

Mirrors are retained in this explanation to make it more clear when the program switches between cardinal and ordinal modes.

```
/I/!/wI&/h.n$@?~E&\'!dOK

/I                        % input base
  /!/                     % store onto tape as integer
     w                    % push return address
      I                   % input next line
       &/h                % get length (by adding 1 for each character in the string)
          .n$@            % terminate if zero
              ?~E         % get base from tape and raise to power
                 &\'!     % push "!" onto the stack that many times
                     d    % combine into a single string
                      O   % output string with newline
                       K  % return to stored address (without popping it from the return address stack)

```
> 0 votes

# Answer
# Perl 6, 26 bytes

```
{map '#'x$^b** *.comb,@^a}

```

The list of input strings is in the first parameter, `@^a`. The second parameter `$^b` is the base. A list of output strings is returned.
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Jump trajectory

text:
# Question
Title: Jump trajectory
This is an challenge where you will draw ascii-art showing a person "jumping" off the top of a building.

---

## The building

Input given will be a group of rectangular buildings. You may assume buildings are not "stacked on top of each other", hence only one row of buildings. This is the standard format of a building:

```
-----
|   |
|   |
|   |
|   |

```

A row of buildings looks similar.

```
                       ------
-----    --------------|    |
|   |    |            ||    |
|   |----|            ||    |
|   ||  ||            ||    |
|   ||  ||            ||    |

```

You may choose to remove the duplicate `|` between two buildings if you would like.

Yes, buildings may be taller than the ones on their lefts, but you may assume that all buildings have a nonzero height.

This group of buildings will be given as input, in addition to the building index, which can be 0-or-1-indexed. (please specify which in your answer.)

You can also take input as an array of building characteristics or two arrays of heights and widths.

## The person

A person is represented by an `o`. The person always starts on the right of the given building, and starts jumping immediately.

## Jumping

To quote this article,

> The greatest human leapers in the world are able to jump over a bar suspended nearly 8 feet off of the ground.

Since I go by meters, this is about 3 meters (actually about 2.5, but whatever.) The person will hence jump "diagonally" for 3 meters (lines) before starting to fall, after which the person will also fall diagonally until hitting the top of a building or the ground.

Each meter should be represented by another `o` at the exact position.

## Example

Example is 1-indexed.

Given the above row of buildings and the index `1`, this would be the trajectory:

```
       o
      o o
     o   o
    o     o            ------
-----    --------------|    |
|   |    |            ||    |
|   |----|            ||    |
|   ||  ||            ||    |
|   ||  ||            ||    |

```

The person started at the right of the first building, then there were 3 `o`s going upwards before the `o`s started trending downwards. The o's stopped the moment the person hit the third building.

Given index 3:

```
                         o
                        o o
                       o   o
                      o------
-----    --------------|    |
|   |    |            ||    |
|   |----|            ||    |
|   ||  ||            ||    |
|   ||  ||            ||    |

```

Note that the person cannot be stopped by the top of a building before completing his 3-meter initial jump.

Given index 4:

```
                               o
                              o o
                             o   o
                            o     o
                       ------      o
-----    --------------|    |       o
|   |    |            ||    |        o
|   |----|            ||    |         o
|   ||  ||            ||    |          o
|   ||  ||            ||    |           o

```

The person stopped after hitting the ground.

Given index 2:

This particular case is impossible as the person is stopped by the wall of the following building. This brings another rule into the challenge: you are allowed to assume that there will never be impossible input, i.e. one where the person is stopped by another building's wall in the way, whether in his initial 3-meter jump or as he is coming down (the top of the building does *not* stop the person from jumping).

You are also permitted to use a character other than `o` as long as it is none of `|-`  (note the trailing whitespace, you may not use whitespace to denote the person.)

Macrons are permitted (the ones which look like "overscores") and if you do use them you may count them as one byte. There will never be gaps between buildings.

This is , so the shortest answer in bytes wins with standard loopholes disallowed as usual.

# Answer
> 5 votes
# Charcoal, 45 bytes

```
ＦＬθ«↑⊖§θι§ηι↙↓⊖§θι↗»Ｊ⊖Σ…η⊕ζ±§θζ↗oooＷ∧⊖ⅉ¬℅ＫＫ↘o

```

Try it online! Takes as input an array of heights, an array of widths, and a 0-indexed building. Explanation:

```
ＦＬθ«

```

Loop over each building.

```
↑⊖§θι

```

Draw the left wall.

```
§ηι↙

```

Draw the roof.

```
↓⊖§θι↗

```

Draw the right wall.

```
»Ｊ⊖Σ…η⊕ζ±§θζ

```

Jump to the corner of the building.

```
↗ooo

```

Print the leap.

```
Ｗ∧⊖ⅉ¬℅ＫＫ

```

Repeat until the ground or a roof is reached.

```
↘o

```

Print the fall.

---
Tags: code-golf, string, ascii-art
---