# Question
Title: ASCII-art polygons to GeoJSON coordinates
We're going to turn ascii art versions of polygons into their equivalent GeoJSON.

# The ASCII shape language

The input ASCII language only has 3 possible characters:

* `*` signifies a vertex
* `-` signifies a horizontal line
* `|` signifies a vertical line

A `*` will never be directly adjacent to another `*` (but may be diagonal to one). A `*` shall have exactly two lines adjacent to it, either a `-` to the left or right of it, or a `|` to the top or bottom. There will never be a `|` to the left or right of a `*`, and consequently, never a `-` directly above or below a `*`. It is possible to have a vertex along a line, e.g. `-*-`.

Each input only contains one "ring". There are no multi-part polygons, or polygons with holes.

The input is minimal. For example, there are no extra leading or trailing blank lines or trailing white spaces.

For example, some valid shapes are:

```
*--*
|  |
*--*

*--*
|  |
|  *--*
|     |
*-----*

  *--*
  |  |
*-*  |
|  *-*
|  |
*--*

```

# The coordinate language

The above shapes shall be converted into their equivalent coordinates. The top left corner of the ASCII art is `(0,0)`. The first coordinate is the x-axis.

For example, the 3 shapes above would turn into the following coordinates:

```
[[0,0],[3,0],[3,2],[0,2],[0,0]]

[[0,0],[3,0],[3,2],[6,2],[6,4],[0,4],[0,0]]

[[2,0],[5,0],[5,3],[3,3],[3,5],[0,5],[0,2],[2,2],[2,0]]

```

Note that other representations are possible too, depending on which coordinate you start with. Continuing with GeoJSON convention, the coordinate ring shall be clockwise.

# Input/output

Take your input via any of the standard methods. The input may be:

* A string containing only the characters `*`, `-`, `|`, `\n` or
* or an array of strings where each string represents a line.

Output shall be via any standard format. The output shall be an `n`-by-2 dimensional JSON array. Any amount and type of whitespace is allowed in the resulting JSON.

---

This is , so fewest bytes wins.

# Answer
# Jelly, 23 bytes

```
n⁶ŒṪŒ!ạƝ§$ÞḢfœẹ”*$ṭ@Ṃ$’

```

Try it online!

This is a monadic link that accepts an array of lines as input and produces a 2D array (which the interpreter prints in the correct format) as output. The solution always starts with the first non-space character, which must be an asterisk.

Note that this solution is very slow, so the only valid input that will terminate within a minute on TIO is a 3x3 square. However, this program should work for any input where the non-space characters form a Hamiltonian cycle and the first non-space is an asterisk.

## Explanation

List all permutations of the non-space characters' coordinates:

`ŒṪ` and `Œ!` order their results lexicographically (according to the input's order in `Œ!`'s case), so this step's output is ordered lexicographically.

```
n      # Not equal
 ⁶     # " "
  ŒṪ   # Multidimensional indices of truthy values
    Œ! # Permutations (ordered lexicographically according to the input)

```

Find the valid permutation starting with the first non-space character:

Listing all permutations and then finding a valid one is a similar idea to step 4 in @KevinCruijssen's answer, although the details are very different.

Consider the list of Manhattan distances of adjacent elements of a permutation. (The Manhattan distance from (a, b) to (c, d) is |a-b| + |c-d|). No coordinate is repeated, so each distance is positive. Thus, the lexicographically minimum possible distance list is \[1, 1, ..., 1\]. This distance list means two adjacent points in the permutation have distance 1, so this permutation is valid or reverse-valid (i.e. the counterclockwise version of a valid permutation). Thus, sorting the permutations by their distance lists puts all of the (reverse-)valid permutations at the beginning.

`Þ` is implemented using Python's `sorted` function, which is guaranteed to be stable, so among the (reverse-)valid permutations, the lexicographically minimum one still comes first. This will be one that starts with the first two non-space characters in order. These characters are the first and second non-space characters on the top row (excluding space-only rows), so the first permutation must be clockwise, making it valid.

```
ạƝ§$ÞḢ
ạ      # Absolute-value difference
 Ɲ     # Apply to each adjacent pair
  §    # Sum
   $   # Group ạƝ§ as a monad
    Þ  # Sort
     Ḣ # First item

```

Filter non-asterisk coordinates:

```
fœẹ”*$
f      # Filter
 œẹ    # Multidimensional indices of
   ”*  # "*"
     $ # Group œẹ”* as a monad

```

Repeat the first coordinate (which is also the minimum coordinate in lexicographic order) and switch to 0-based indexing:

```
ṭ@Ṃ$’
ṭ     # Tack
 @    # Transpose arguments
  Ṃ   # Minimum
   $  # Group ṭ@Ṃ as a monad
    ’ # Decrement

```
> 2 votes

# Answer
# Charcoal, 52 bytes

```
ＷＳ⟦ι⟧⊞υ⟦⌕θ*⁰⟧Ｊ⊕⌕θ*⁰ＷΦ⁴‹ ⊟ＫＤ²✳⊗κ«✳⊗⌊ι ≡ＫＫ*⊞υ⟦ⅈⅉ⟧»⎚⭆¹υ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
ＷＳ⟦ι⟧

```

Copy the input to the canvas.

```
⊞υ⟦⌕θ*⁰⟧

```

Start at the top left corner of the shape.

```
Ｊ⊕⌕θ*⁰

```

Jump to the top edge of the shape.

```
ＷΦ⁴‹ ⊟ＫＤ²✳⊗κ«

```

Repeat while there's at least one orthogonally adjacent shape part.

```
✳⊗⌊ι

```

Overwrite the current shape part, moving to the next one.

```
≡ＫＫ*

```

If this is a `*`, then...

```
⊞υ⟦ⅈⅉ⟧

```

... record the current coordinates.

```
»⎚⭆¹υ

```

Clear the canvas and pretty-print the final list of coordinates.
> 7 votes

# Answer
# 05AB1E, ~~45~~ 43 bytes (non-competing†)

† My approach assumed `-*-` vectors weren't a thing, since I look for pairs of corner-vectors, making my entire solution worthless once that was added in as a (new) rule of the challenge.. :/

```
εNUεNX)]Dζ«€`ʒ'*å}€¦2ôœ.Δðý©À`åθ®üåOP*}€`ÙĆ

```

-2 bytes by using 2x `€``  and `θ` instead of 2x `í€``  and `н`.

Input as a list of lists of characters.

Try it online or verify all test cases. (Will time out for test cases with 10 or more vertices due to the `œ` builtin.)

**Explanation:**

Step 1: Pair each character with it's coordinate:

```
ε          # Map over each row of the (implicit) input:
 NU        #  Store the 0-based index of the current row in variable `X`
 ε         #  Inner map over each inner cell of the current row:
  N        #   Push the cell's index
   X       #   Push the row's index from variable `X`
    )      #   Wrap the cell-value, cell-index, and row-index into a triplet-list
]          # Close the nested maps

```

Try just step 1 online.

Step 2: Merge the transposed result, since we want to check all `*-*` and `*|*` connections separately:

```
D          # Duplicate the result
 ζ         # Zip/transpose; with " " as implicit filler if the input isn't a rectangle
           # (which will be removed again with the filter later on)
  «        # Merge the regular and transposed lists together

```

Try just the first 2 steps online.

Step 3: Convert it to a flattened list of all pairs of coordinates for the vertices `*`, first for all `*-*` and then also for all `*|*`:

```
€`         # Flatten it one level down
           # (implicitly reverses the values of each row, but we'll fix this later)
ʒ          # Filter this list of triplets by:
 '*å      '#  Does the triplet contain "*"
}€¦        # After the filter: remove all first items (the "*") of the triplets
   2ô      # Split this list of pairs into pairs

```

Try just the first 3 steps online.

Step 4: Find the first valid permutation of this list of pairs:

```
œ          # Get all permutations of this list of pairs of coordinates
 .Δ        # Find the first which is truthy for:
   ðý      #  Join each inner-most coordinate with a space delimiter to a string
           #  (necessary because 05AB1E lacks a contains for pairs)
     ©     #  Store this in variable `®` (without popping)
      À    #  Rotate it once towards the right
       `   #  Pop and push all pairs of strings separated to the stack
        å  #  Check for both values inside the top pair of strings whether they're in
           #  the pair below it
         θ #  Only keep the last truthy/falsey check of this
     ®     #  Push list `®` again
      ü    #  For each overlapping pair of pairs of strings:
       å   #  Check for the values in the second pair if they're in the first pair
        O  #  Sum each pair of truthy/falsey values
         P #  Take the product, to check whether just one in each was truthy
     *     #  Check that both checks were truthy
 }         # Close the find-first

```

Try just the first 4 steps online.

Format it to the intended output:

```
€`         # Flatten it one level down (in reversed order again)
  Ù        # Uniquify this list of pairs
   Ć       # Enclose; append its own head
           # (after which the resulting list of pairs is output implicitly as result)

```

Try the entire program online.
> 3 votes

# Answer
# , 92 90 85 75 67 bytes

```
[:(-.~{.,~{.,((]~.@,[#~1=(|@-{:))^:_{.)@}.)&($j./@#:I.@,)/'* '~:"{]

```

Try it online!

## idea

1. Get positions of all non-space characters in "reading" order (left to right, top to bottom). This is easy using a standard idiom, and returns the positions as complex numbers.
2. Next, we need to get them in "ring" order. To do that, seed a list with the upper-leftmost position and re-build the list from step 1 as follows:
    * Add to the most recently added list element the four compass directions, as complex numbers, giving 4 new candidates for "next" list element.
    * Remove any candidates not in the list from step 1
    * Remove any candidates that would result in a repeat in the list we're building
    * The first seeded element will result in 2 candidates (we pick the first arbitrarily), but all subsequent elements will have only one "next" candidate.
    * Repeat this process "list length - 1" times. We now have the list from step 1 in ring order. We add the first element to the tail.
3. Remove all elements from step 2's list associated with `-|` positions, resulting in a list of just the `*` positions, but in "ring" order. This is our answer.
> 3 votes

# Answer
# jq -Rn, 166 bytes

```
[inputs|explode]|[tostream|select(.[1]>32)]
|reduce keys[]as$k(.;.[$k]as[[$y,$x]]|.[$k+1:]
|=sort_by(.[0]|hypot(.[0]-$y;.[1]-$x)))+.[:1]
|map(select(.[1]<45)[0]|reverse)

```

(newlines added for ~~readability~~ aesthetic pleasure)

Try it online!

### Explanation:

```
[ inputs                             #  read each input line as raw string
| explode                            #  make them an array of ascii codes
]                                    #  collect line arrays into row array
| [ tostream                         #  convert items into path and value
  | select(.[1] > 32)                #  only keep non-empty cell values
  ]                                  #  collect them into a cell array
| reduce keys[] as $k (.             #  iterate over pivot cell indices
    ; .[$k] as [ [$y,$x] ]           #    destructure pivot cell into coords
    | .[$k+1:] |= sort_by(.[0]       #    sort remaining slice of cells wrt
        | hypot(.[0]-$y; .[1]-$x)    #      Euclidean distance to pivot cell
      )                              #    (hor or ver adjacency always wins)
  ) + .[:1]                          #  repeat the initial cell at the end
| map(                               #  prepare some cell items for output
    select(.[1] < 45)[0]             #    only keep paths of vertex cells
    | reverse                        #    turn row/col path into x/y coords
  )

```
> 1 votes

# Answer
# Python 3, 244 233 bytes

Different approach, actually works

```
def g(a,o=[]):
 b=c=(0,0)
 while[b]!=o[1:2]:x,y=b;s=[(q,r)for q,r in((x+1,y),(x,y+1),(x-1,y),(x,y-1))if(len(a)>r>=0<=q<len(a[r])and a[r][q]or' ')in'-|*'and (q,r)!=c];o=a[y][x]=="*"and o+[(x,y)]or o;c=b;b=s and s[0]or(x+1,y)
 print(o)

```

Try it online!

### Ungolfed

```
def g(a,o=[]):
 b=c=(0,0)                         # set starting point b and previous point c to (0,0)
 while[b]!=o[1:2]:                 # continue until we have passed the first point a second time
  x,y=b;
  s=[
   (q,r) for q,r in (
    (x+1,y),                        # east point
    (x,y+1),                        # south point
    (x-1,y),                        # west point
    (x,y-1)                         # north point
   )
   if (
    len(a)>r>=0                     # point is in y bounds of array
    and len(a[r])>q>=0              # point is in x bounds of row
    and a[r][q]                     # then character at point
    or ' '                          # else ' '
   ) in '-|*'                       # only include points where the character is "*", "-", or "|";
   and (q,r)!=c                     # exclude the point we just came from
  ];
  o=a[y][x]=="*"and o+[(x,y)]or o;  # if the current character is "*", add to output list
  c=b;                              # set previous point (c) to current point
  b=s and s[0]or(x+1,y)             # if we found "*", "-", or "|", move to that point; else, stay in row and move forward one place on the x-axis
 print(o)                           # return the output list

```
> 0 votes

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


title: How to weight loss easily?

text:
# Question
Title: How to weight loss easily?
In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight.

Different sports burn different amount of calories.

For example, playing billiards for an hour can burn 102 calories\[1\], while playing basketball for 15 minutes can already burn 119 calories \[1\], which make weight loss by playing basketball easier, at least from some perspectives.

The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI).

For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15.

You will be given a list in this format:

```
[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

```

or other format that you want.

Then, you will output the sports which have the highest EI.

### TL;DR

Given a list of tuples `[name,value1,value2]` output the `name` where `value2/value1` is the highest.

### Constraints

* You may **not** produce any real number that is not integer in the process.
* You may **not** use any fraction built-in.

### Specifications (Specs)

* If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them.
* The name will match the regex `/^[a-z]+$/`, meaning that it will only consist of lowercase Latin standard alphabet.
* The list will not be empty.

### Testcase

Input:

```
[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

```

Output:

```
basketball

```

### References

1. http://calorielab.com/burned/

# Answer
> 14 votes
## Python 2, 51 bytes

```
lambda l:max((10**len(`l`)*a/b,s)for s,b,a in l)[1]

```

Does the obvious thing of finding the entry with the biggest ratio, but sidesteps the prohibition against floats by first multiplying the numerator by a huge input-dependent power of 10 before floor-dividing.

I'll prove this coefficient is big enough to make floor-division act the same difference as non-floor division.

**Claim:** If a1/b1 \> a2/b2, then floor(Na1/b1) \> floor(Na2/b2) for any N≥b1b2.

**Proof:** Note that a1/b1 \- a2/b2 is a multiple of 1/b1b2, so a1/b1 \- a2/b2 \> 0 implies that

> a1/b1 \- a2/b2 ≥ 1/b1b2

Then, multiplying both sides by N,

> Na1/b1 \- Na2/b2 ≥ N/b1b2 ≥ 1

So, since Na1/b1 and Na2/b2 differ by at least 1, their respective floors are distinct. ∎

Now, note that the product b1b2 has digit length at most their total digit length, which is less than the string length of the input. Since the input is in base 10, its suffices to use 10 to the power of its length `N=10**len(`l`)` to produce a number with more digits than it, guaranteeing the condition.

# Answer
> 8 votes
## JavaScript (ES6), 43 bytes

```
a=>a.sort(([p,q,r],[s,t,u])=>q*u-r*t)[0][0]

```

Or alternatively

```
a=>a.sort((v,w)=>v[1]*w[2]-v[2]*w[1])[0][0]

```

Sort is of course overkill for this, but `reduce` would take 46 bytes:

```
a=>a.reduce((v,w)=>v[1]*w[2]-v[2]*w[1]?v:w)[0]

```

# Answer
> 7 votes
# MATL, 8 bytes

```
pG/*&X<)

```

All computed numbers are integer values. First, the product of the denominators is computed (this is an integer). This product is divided by each denominator (which gives an integer too). Each result is then multiplied by the corresponding numerator. This gives an integer value proportional to the original fraction.

Input format is: numeric array with denominators, numeric array with numerators, cell array of strings with sport names:

```
[85, 102, 119]
[15, 60, 15]
{'fencing', 'billiards', 'basketball'}

```

If there are several minimizers the first one is output.

**Try it online!**

```
p     % Take first input. Compute the product of its entries
G/    % Divide by first input element-wise
*     % Take second input. Multiply by previous array element-wise
&X<   % Argmax
)     % Take third input. Index into it using previous result. Display

```

# Answer
> 5 votes
# Brachylog, 42 bytes

```
:{bh.}a*g:?z:2aott.
[D:[S:I:J]]tt:D*:I/:S.

```

Try it online!

`/` above is integer division because both `J*D` and `I` are integers (`D` is a multiple of `I` in fact).

### Explanation

* Main predicate: `Input = [["string":mins:cals]:...]`

```
:{bh.}a*                Multiply all mins in the Input together
        g:?z            Zip that number with the Input
            :2a         Apply predicate 2 to that zipped list
               ott.     Sort the list of lists on the values of the first element of
                          sublists, Output is the string of the last sublist

```
* Predicate 1:

```
[D:[S:I:J]]             Input = [D:[S:I:J]]
           tt:D*        Multiply J by D
                :I/     Divide the result by I
                   :S.  Output = [That number:S]

```

# Answer
> 5 votes
# Dyalog APL, 18 bytes

```
⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕

```

Prompts for times, then for calories, then for activity names.

prompt (for times)

`(∧/÷⊢)` LCM `∧/` of the times divided by `÷` the times  (so no floats)

`⎕×` prompt (for calories) and multiply by them

`(⊢⍳⌈/)` in that , get the position  of the maximum value `⌈/`

`⎕⊃⍨` prompt (for activities), then pick the *n*th.

Example run:

```
      ⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕
⎕:
      15 60 15
⎕:
      85 102 119
⎕:
      'fencing' 'billiards' 'basketball'
basketball

```

# Answer
> 3 votes
# Python 2, ~~55~~ 54 bytes

```
lambda x:sorted(x,lambda(S,N,D),(s,n,d):N*d-n*D)[0][0]

```

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

Test it on Ideone.

# Answer
> 3 votes
## Retina, ~~64~~ 62 bytes

Byte count assumes ISO 8859-1 encoding.

```
\d+
$*
%`\G1
0
1
:$_:
Ts`0p¶`0_`:.+?:
+`(0+) \1
@$1
O`
!`\w+$

```

Input is one sport per line, with the format `value1 value2 name`. Output is one of the maximal results (if there's a tie it will give the one with the largest `value1` and if those are tied as well if will give the lexicographically larger `name`).

Note that this is *super* slow (for the exact same reasons as yesterday's Stack Exchange outage). To make it run in a reasonable amount of time, you can add a `\b` in front of the `(0+)` (which won't affect the way it processes the input at all but severely limits the backtracking of that regex). I've done that in the test link below.

Try it online!

# Answer
> 2 votes
## Haskell ~~72~~ 70 bytes

```
import Data.List
(n,(x,y))%(m,(a,b))=compare(x*b)$y*a
fst.minimumBy(%)

```

Usage :

```
main=putStr$(fst.minimumBy(%))[("fencing",(15,85)),("billiards",(60,102)),("basketball",(15,119))]

```

# Answer
> 1 votes
## Mathematica, 46 bytes

```
Last/@MaximalBy[#,g=LCM@@First/@#;g#2/#&@@#&]&

```

The order of the tuples should be `{value1,value2,name}`. Returns the full set of all maximal results.

I work around the use of fractions by multiplying the numerator by the LCM of all `value1`s before the division.

# Answer
> 1 votes
# Ruby, 72 bytes

```
e=0;while gets;n=$_.split;f=eval n[2]+"/"+n[1];m,e=n[0],f if f>e;end;p m

```

I really thought this would be shorter...

Input is taken from STDIN in the format of `name time calories`

Oh well, any help to shorten it is appreciated.

# Answer
> 1 votes
# R, ~~42~~ 40 bytes

```
function(v)v[which.max(v[,3]%/%v[,2]),1]

```

Takes input in the form of a data frame with column types of string (it also works with factors), numeric, numeric.

* `%/%` is integer division.

This is my first submission, let me know if it's within the rules.

**Edit:** Turns out you don't need the braces to define a one-line function.

# Answer
> 1 votes
# C++14, 89 bytes

Lambda function:

```
[](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];};

```

Ungolfed:

```
[](auto s,int*a,int*b,int l)
{
  int r = --l;
  while(l--)
    r = b[l] * a[r] > a[l] * b[r] ? l : r;
  return s[r];
};

```

Usage:

```
#include <iostream>

int main()
{
  const char* s[] = {"fencing", "billiards", "basketball"};
  int a[] = {15,60,15};
  int b[] = {85,102,119};
  std::cout << [](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];}(s,a,b,3);
}

```

# Answer
> 1 votes
# Haskell, 46 bytes

```
s(n,(x,y))=(divMod y x,n)
g =snd.maximum.map s

```

**EDIT:** This solution doesn't work as pointed out by Damien this doesn't solve the problem. I'm searching a nice fix.

# Answer
> 1 votes
# VBA Excel, 109 bytes

```
Function A(B)
R=1
For I=2 To B.Rows.Count
If B(R,2)*B(I,3)>B(I,2)*B(R,3) Then R=I
Next
A=B(R,1)
End Function

```

Invoke in spreadsheet cell referencing a table of activities and parameters:

# Answer
> 1 votes
# 05AB1E, ~~6~~ 7 bytes

```
P¹÷*ZQÏ

```

+1 byte to bugfix my divmod approach (see this comment on another answer) by porting *@LuisMendo*'s MATL answer, so make sure to upvote him!

Input is similar as his answer: three separated lists, being an integer-list of denominators; an integer-list of nominators; and a string-list of names.

Try it online or verify some more test cases.

**Explanation:**

```
P       # Take the product of the (implicit) input-list of denominators
        #  i.e. [85,102,119] → 1031730
 ¹÷     # (Integer)-divide it by each of the denominators of the first input-list
        #  i.e. 1031730 / [85,102,119] → [12138,10115,8670]
   *    # Multiply each (at the same positions) by the (implicit) input-list of nominators
        #  i.e. [12138,10115,8670] * [15,60,15] → [182070,606900,130050]
    Z   # Get the maximum of this list (without popping the list itself)
        #  i.e. [182070,606900,130050] → [182070,606900,130050] and 606900
     Q  # Check which values are equal to this maximum
        #  i.e. [182070,606900,130050] and 606900 → [0,1,0]
      Ï # Only leave the strings of the (implicit) input-list of names at the truthy indices
        #  i.e. ["fencing","billiards","basketball"] and [0,1,0] → ["billiards"]
        # (after which the result is output implicitly)

```

# Answer
> 1 votes
# PHP, 98 bytes

Used a simpler input format than the example, just like this:

**fencing,15,85,billiards,60,102,basketball,15,119**

```
$s=explode(",",$argn);for($x=0;$s[$x];$x+=3){if($y<$e=$s[$x+2]/$s[$x+1]){$y=$e;$z=$s[$x];}}echo$z;

```

Try it online!

# Answer
> 1 votes
# 8086 opcode, 24 bytes

```
31db 50ac f6e7 92ac f6e3 39d0 ad72 058b  1.P.......9..r..
5cfc 5ab2 58e2 ebc3                      \.Z.X...

org 100h
mov si, input
mov cx, 3
call f
mov dx, ax
mov ah, 9
int 0x21
ret
align 2
input:
db 15, 85
dw .fencing
db 60, 102
dw .billiards
db 15, 119
dw .basketball
.fencing db 'fencing$'
.billiards db 'billiards$'
.basketball db 'basketball$'
db 100h+2000-$ dup ? ; Easy to measure size
f:
; bx (record)
; dx (mul result 1)
; ax (result name, pushed)
; ax (mul result 2)
; cx (count)
; si (input array)
xor bx, bx
.L:
push ax
lodsb
mul bh ; nl*bh
xchg ax, dx
lodsb
mul bl ; nh*bl
cmp ax, dx
lodsw
jb .a
mov bx, [si-4]
pop dx
db 0xB2 ; Skip 1 byte
.a:
pop ax
loop .L
ret

```

# Answer
> 0 votes
# Java 8, 128 Bytes

```
String f(List<Object[]>l){return l.stream().max((x,y)->(int)x[2]*1000/(int)x[1]-(int)y[2]*1000/(int)y[1]).get()[0].toString();}

```

# Answer
> 0 votes
## Clojure, 63 bytes

```
#((last(sort(fn[[x a b][y c d]](-(* b c)(* a d)))%))0)

```

---
Tags: code-golf, arithmetic
---


title: Merging two strings

text:
# Question
Title: Merging two strings
### Introduction

Let's say that **S1** = `a...b` and **S2** = `..c..`. If we place them on top of each other, we get:

```
a...b
..c..

```

We merge both strings, with the `.` as the liquid character (which can overlapped). We get this:

```
a.c.b

```

If one of the string is longer than the other, we just apply the same algorithm:

```
a.....b
..c..

becomes:

a.c...b

```

and

```
a.....b
..c.......

becomes:

a.c...b...

```

If two characters collide, we just use the bottom character, e.g.

```
a..b
...c

becomes:

a..c

```

### The Task

Given two non-empty strings, output the **merged** string. **Note**, you can assume that the input only contains **periods** and **lowercase letters** (or uppercase letters if that is more convenient).

### Test cases

```
Input              Output
a....b ..c...      a.c..b
aaaaaa bbbbbb      bbbbbb
ab.ab. b.b.b.      bbbab.
a.......b c        c.......b

```

This is , so the submission with the least amount of bytes wins!

# Answer
## Jelly, 5 bytes

```
Œu»Œl

```

Input via command-line arguments.

Try it online!

### Explanation

This is a direct port of my CJam answer (see that for an explanation why this works):

```
Œu     # Convert first argument to upper case.
  »    # Element-wise maximum between both strings.
   Œl  # Convert result back to lower case.

```
> 11 votes

# Answer
## CJam, 9 bytes

```
leul.e>el

```

Test it here.

### Explanation

Makes use of the fact that `'.' < upper case letters < lower case letters`. This way, when taking the element-wise maximum between two strings, any letter overrides a `.`, but we can make a letter from the second input override a letter from the first if we upper case the first. Confusing? Here's one of the test cases as an example:

```
ab.ab.
b.b.b.

```

Convert first to upper case:

```
AB.AB.
b.b.b.

```

Take the element-wise maximum:

```
bBbAb.

```

Convert back to lower case:

```
bbbab.

```

And here is how the code does that:

```
l    e# Read first line.
eu   e# Convert to upper case.
l    e# Read second line.
.e>  e# Take element-wise maximum. If the lengths are different, the additional elements
     e# from the longer list are just appended.
el   e# Convert back to lower case.

```
> 15 votes

# Answer
# Javascript ES6, ~~52~~ 55 chars

```
(a,b)=>b.replace(/\./g,(m,i)=>a[i]||m)+a.slice(b.length)

```

Test

```
f=(a,b)=>b.replace(/\./g,(m,i)=>a[i]||m)+a.slice(b.length)
;`
a....b ..c...      a.c..b
aaaaaa bbbbbb      bbbbbb
ab.ab. b.b.b.      bbbab.
a.......b c        c.......b
c a....b           a....b
`.split('\n').filter(Boolean).map(s=>s.split(/\s+/)).every(a=>f(a[0],a[1])==a[2])

```
> 6 votes

# Answer
# Pyth, 11

```
smenD\.d.TQ

```

Try it online or run the Test Suite
> 5 votes

# Answer
## Seriously, 10 bytes

```
,û,Z`M`MΣù

```

Try it online!

Uses the same strategy as Martin's CJam answer

Explanation:

```
,û,Z`M`MΣù
,û          get first string, uppercase
  ,Z        get second string, zip with first string
    `M`M    map maximum
        Σù  join and uppercase

```
> 4 votes

# Answer
# Octave, 50 bytes

```
function c=m(a,b)c=b;c(a>0)=a;i=b>46;c(i)=b(i);end

```
> 4 votes

# Answer
## Haskell, ~~43~~ 42 bytes

```
(a:b)#(c:d)|c<'a'=a:b#d|1<2=c:b#d
a#b=a++b

```

Usage example: `"ab.ab." # "b.b.b."` -\> `"bbbab."`.

How it works:

* if both list are non-empty, pick the the head of the 1st list if the head of the 2nd list is `"."`, else pick the head of the second list. Append a recursive call with the tails of the lists.
* if at least one list is empty, append both lists.

Edit: @Lynn saved a byte. Thanks!
> 3 votes

# Answer
# Python 2, 47 bytes

```
lambda s,t:`map(max,s.upper(),t)`[2::5].lower()

```
> 3 votes

# Answer
# Julia, 101 bytes

```
f(s,t,r=i->rpad(i,max((n=endof)(s),n(t)),"."))=join([min(a,b)<90?max(a,b):b for(a,b)=zip(r(s),r(t))])

```

This is a function that accepts two strings and returns a string.

We compute `m` as the maximum length of the two inputs, then define a function `r` that right pads its input with `.`s to length `m` and store that as a function argument. We then `zip` the right padded inputs and check the minimum (as defined by the ASCII code) of each pair. If it's a `.`, we use whichever character has the bigger code, otherwise we use whichever came from the second input. The resulting array is `join`ed into a string and returned.
> 2 votes

# Answer
# C, ~~106~~ 89 bytes

```
i,j,k;f(s,z)char*s,*z;{for(i=0,j=k=1;j|k;i++)putchar((k=k?z[i]:0)>46|!(j=j?s[i]:0)?k:j);}

```

Test live on **ideone**.
> 2 votes

# Answer
# Retina, 55

```
$

+`(.?(\S* )(\w)|(\S)(\S* ).?)(\S* .*)
$2$5$6$3$4

```

Line 5 is a single space. Line 6 is an empty line (with no trailing newline).

Try it online.

I started this one in GNU sed, (with the -r option). Straightforward port to Retina once I got the regexes figured out. The sed version is:

```
s/$/ /
:
s/(.?(\S* )(\w)|(\S)(\S* ).?)(\S* .*)/\2\5\6\3\4/
t
s/ *//

```
> 1 votes

# Answer
# Python 2, 70 bytes

```
lambda x,y:"".join([k if k!="."and k else j for j,k in map(None,x,y)])

```

Try it here!

First we create zip both strings into one list. If the second string is longer than the first, it is padded with `None` (`map(None,x,y)` does that).
Then we iterate over this list with `j` being the character from the first string and `k` the one from the second string. We choose `k` if it's not a dot and otherwise `j`.

This could be 61 bytes if I could output the result as list of characters instead of a string.
> 1 votes

# Answer
# Perl, 48 + 3 = 51 bytes

```
s/\./substr($^I,$.=pos,1)||$&/ge;$_.=substr$^I,$.

```

Bah cannot find a shorter solution. (Same approach as @Qwertiy's JavaScript's answer).
Requires `-pl` and takes input from `stdin` and `-i`

```
$ perl -i'a...ce' -ple's/\./substr($^I,$.=pos,1)||$&/ge;$_.=substr$^I,$.' <<< '..b.d..f'
a.b.de..f

```
> 1 votes

# Answer
# q/kdb+, ~~43~~ 40 bytes

**Solution:**

```
lower{l:max(#:)each(x;y);upper[l$x]|l$y}

```

**Example:**

```
q)lower{l:max(#:)each(x;y);upper[l$x]|l$y}["a..b..";"...c"]
"a..c.."

```

**Explanation:**

```
(#:)                // k equivalent of count
max (#:) each(x;y)  // takes each string, count the length, return maximum
l$x                 // whites-space pad string x to length l
|                   // take the maximum (per Martin's strategy)
upper[...]          // convert padded string 1 to uppercase
lower{...}          // convert result of function to lowercase

```

**Notes:** I'm taking taking advantage of *"Given two non-empty **strings**"* and assuming that inputs are strings. In kdb `"c"` is an atom, `(),"c"` is a string, otherwise need to add 6 bytes to the score, as we cannot use `$` to pad an atom...
> 0 votes

# Answer
# PHP\>=7.1, 58 Bytes

```
for([,$x,$y]=$argv;~$c=$y[$i++];)$c<_?:$x[$i-1]=$c;echo$x;

```

Online Version
> 0 votes

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

```
f=([a,...b],[c,...d])=>a+c?(c>'.'?c:a||c)+f(b,d):d

```

Try it online!
> 0 votes

# Answer
# C (GCC), ~~86~~ 76 bytes

*-10 bytes thanks to @ceilingcat*

```
f(x,y)char*x,*y;{for(;*x|*y;putchar(0[y=*y?y:x]-46?*y:*x),x++,y++)x=*x?x:y;}

```

Attempt This Online!
> 0 votes

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


title: Sum pyramid of primes

text:
# Question
Title: Sum pyramid of primes
Given a number N, the challenge is to get the sum of the pyramid of N primes. To clarify things, here is an example:

```
Input: 4

```

We will list the first `4` primes, and then compute the sum of them. After that, we will compute the sums of the sums, and so on:

```
  2
    > 5
  3     > 13
    > 8      > 33
  5     > 20
    > 12
  7

```

You can see that the final result is **33**. Here is another example, with N = 8:

```
   2
     >   5
   3       >  13
     >   8       >  33
   5       >  20       >  83
     >  12       >  50       > 205
   7       >  30       > 122       > 495
     >  18       >  72       > 290       > 1169
  11       >  42       > 168       > 674
     >  24       >  96       > 384
  13       >  54       > 216
     >  30       > 120
  17       >  66
     >  36
  19

```

You can see that the final result is **1169**.

Here is another example with an odd N, N = 3:

```
 2
   > 5
 3     > 13
   > 8
 5

```

This gives us **13** as the result

Your task is to write a program or a function, that takes an integer greater than 0, and output the final result.

Here are some test results:

```
1:  2
2:  5
3:  13
4:  33
5:  83
6:  205
7:  495
8:  1169
9:  2707
10: 6169
11: 13889
12: 30993
13: 68701
14: 151469
15: 332349
16: 725837
17: 1577751
18: 3413221
19: 7349029
20: 15751187
21: 33616925
22: 71475193
23: 151466705
24: 320072415
25: 674721797
26: 1419327223
27: 2979993519
28: 6245693407
29: 13068049163
30: 27297614797
31: 56929779663
32: 118543624847
33: 246475746269
34: 511766428817
35: 1061264813321
36: 2198298700845
37: 4548996804811
38: 9405003164065
39: 19429190057417
40: 40107799133677
41: 82736199371081
42: 170553108953473
43: 351333736092089
44: 723224546040181
45: 1487710742395387
46: 3058157261678325
47: 6282142186547177
48: 12896743408107403
49: 26460652594917673
50: 54262186256186881
51: 111224391050741687
52: 227896496141836195
53: 466805185374509003
54: 955904519939662217
55: 1956988697590280537
56: 4005572366722212927
57: 8196803221276230093
58: 16769645303734608963
59: 34300013739423719561
60: 70136585692535099353
61: 143371352962891226373
62: 292978031452308375001
63: 598482012866917021541
64: 1222083126601616763473
65: 2494459637841415902073
66: 5089478703050176444803
67: 10379794709536133386939
68: 21160351440305258275579
69: 43119914481530819445497
70: 87833066190052490228187
71: 178841897161848754603319
72: 364014682565128163812791
73: 740654046243174781813209
74: 1506496270380756958474835
75: 3063280375436290387756263
76: 6227039507615221644290617
77: 12655020557561801933128885
78: 25712267089927372837530869
79: 52230425385198423845305957
80: 106076955379202815098486497
81: 215397386589448754140867649
82: 437308717912632286770415395
83: 887706233370396897803709611
84: 1801721089699452657985592689
85: 3656329898231436156162865559
86: 7418972676822310377574227797
87: 15051599987013574096449515927
88: 30532404546282900804722616529
89: 61926565462373271494414919017
90: 125582269494835615524470915169
91: 254631689768733901573206365479
92: 516210444730946464864091626473
93: 1046330617753410129672316234861
94: 2120493010460433691014704829565
95: 4296639990460140795780826898943
96: 8704509990931940668688755806845
97: 17631229933967301681217551193565
98: 35706243541395815998303171050377
99: 72298621492552303967009812018997

```

This is , so the shortest amount of bytes wins!

# Answer
# J, 15 bytes

```
p:@i.+/ .*i.!<:

```

Explanation:

Basically the same as my Mathematica answer.

```
p:@i.+/ .*i.!<:
          i.!<:    binomial coefficients
p:@i.              first n primes
     +/ .*         dot product

```
> 12 votes

# Answer
# Mathematica, ~~38~~ ~~36~~ 35 bytes

```
Prime[r=Range@#].Binomial[#-1,r-1]&

```
> 10 votes

# Answer
## Minkolang 0.14, 17 bytes

```
n[i3M$i1-i6M*+]N.

```

Try it here and check all test cases here.

### Explanation

```
n                    Take number from input (N)
 [                   Open for loop that repeats N times
  i                  Loop counter (n)
   3M                Pop n and push nth prime (where 2 is the 0th prime)
     $i1-            Max iterations - 1 (which is N-1)
         i           Loop counter (n)
          6M         Pop n,k and push kCn (binomial)
            *+       Multiply and add
              ]      Close for loop
               N.    Output as number and stop.

```

I use basically the same algorithm as several of the earlier answers that use binomial coefficients. Whenever you see such a pyramid of numbers being added, Pascal's triangle should be the first thing to come to mind. I don't see that any of the other answers have *explained* why this works, so I'll do that.

## MORE explanation

```
2
  > [2,3]
3         > [2,3,3,5]
  > [3,5]             > [2,3,3,3,5,5,5,7]
5         > [3,5,5,7]
  > [5,7]
7

```

As you can see, the primes `2,3,5,7` appear `1,3,3,1` times in the final result. Lemme change the layout a bit.

```
_ _ _ 7
_ _ 5
_ 3
2

```

The number of times that the `3` will contribute to the final result is the same as the number of paths from the `3` to the upper-left corner, **moving only up and left**. Here, there are three such paths for the `3`:

```
_    _    _ _
_    _ _    _
_ 3    3    3

```

Note that I can reverse the direction without loss of generality. So I want to know how many paths there are from the upper-left corner to each position along the jagged edge. I can count them like so...

```
1 1 1 1 1 . . .
1 2 3 4
1 3 6
1 4   .
1       .
.         .
.
.

```

For every number in this triangle, if it is X units from the left and Y units from the top, then the number at that position is

The way I use it, though, `X+Y = N` is constant and `X` ranges from 0 to `N`, which goes along one diagonal. I multiply each coefficient with the corresponding prime number and then add it all up.

See the Wikipedia article on Pascal's triangle for more on this.
> 10 votes

# Answer
# JavaScript ES7 107

Abusing the fixed limit at 27 - how boring is actually finding the primes.

```
n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")

```

Test snippet (using array comprehension it will work only in Firefox)

```
F=n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")

// Less golfed

Q=n=>{
  t=2;
  // Note: the golfed version will return the last computed value, that is p if the loop is entered, else t=2
  p=[for(v of '012242424626424662642646842') t-=-v] // build the array of first 27 primes in p
  while(--n) p = p.slice(0,n).map((v,i)=>v+p[i+1])
  return p
}

//TEST
console.log=x=>O.innerHTML+=x+'\n'

for(i=1;i<28;i++)console.log(i+' : '+F(i))
```

```
<pre id=O></pre>
```
> 7 votes

# Answer
# Pyth, 16 bytes

```
s*V.cLtQQ.f}ZPZQ

```

Very simple actually:

```
s*V          ; Dot product of
  .cLtQQ     ; the binomial coefficients for n
  .f}ZPZQ    ; and the first n prime numbers.

```
> 6 votes

# Answer
# Pyth - ~~16~~ 15 bytes

Uses reduce and `first_n` filter.

```
u+VGtGtQ.f}ZPZQ

```

Test Suite.
> 6 votes

# Answer
# Pyth, 18 bytes

```
husM.:G2tQ.f}ZPZQ0

```

Try it online: Demonstration

### Explanation:

```
husM.:G2tQ.f}ZPZQ0   implicit: Q = input number
          .f    Q0   find the first Q numbers Z >= 0, which satisfy
            }ZPZ        Z appears in the prime factorization of Z
                     this gives the first Q prime numbers
 u      tQ           assign this list to G and repeat the following Q-1 times:
    .:G2               create all subarrays of length 2
  sM                   sum them up and update G
h                    take the first element (=result) and print

```
> 5 votes

# Answer
# Shell + GNU and BSD utilities, 92

```
echo `primes 1|sed $1q`|sed -r ':
s/(\w+) (\w+)/$((\1+\2)) \2/
t
s/ \w+$//
s/^/echo /e
/ /b'

```
> 4 votes

# Answer
## Haskell, 74 bytes

```
import Data.Numbers.Primes
f n=([]:iterate(zipWith(+)=<<tail)primes)!!n!!0

```

Usage example:

```
*Main> map f [1..12]
[2,5,13,33,83,205,495,1169,2707,6169,13889,30993]

```

How it works: repeatedly calculate the neighbor sums of all primes. Take the head of the `n`th iteration.

```
[2,3,5,7,11,13,17,19,23,29,...]             -- plain primes (and 1st iteration)
[5,8,12,18,24,30,36,42,52,60,...]           -- 2nd iteration of neighbor sums
[13,20,30,42,54,66,78,94,112,128,...]       -- 3rd iteration
[33,50,72,96,120,144,172,206,240,274,...]
...

```

As the index operator `!!` is zero based, I'm prepending an empty list to avoid having to use `!!(n-1)`.
> 4 votes

# Answer
# Matlab, 76 bytes

Thanks to David for saving a lot of bytes!

```
n=input('');x=primes(103);
for s=2:n,x=conv(x,[1 1]);end
disp(num2str(x(n)))

```

**Old version, 98 bytes**

```
n=input('');m=1;x=[];while nnz(x)<n
m=m+1;x=primes(m);end
for s=2:n,x=conv(x,[1 1]);end
disp(x(n))

```
> 4 votes

# Answer
# JavaScript (ES6), 121 bytes

```
n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)

```

## Explanation

Most of the size comes from finding the prime numbers.

```
n=>
  eval(`                   // eval used to enable for loops without {} or return

    // Get primes up to n
    for(                   // loop from range 2 to n
      p=[],                // p = primes
      c=0,                 // c = count of primes
      x=1;                 // x = current number to check for primality
      c<n;
      s?p[c++]=x:0         // add the number to the primes if it has no divisors
    )
      for(                 // loop from range 2 to x to check for divisors
        s=                 // s = true if x is a prime
          i=++x;
        --i>1;
      )
        x%i?0:s=0;         // check if x has a divisor

    // Sum primes
    for(;--c;p=s)          // while the new pyramid has pairs to sum
      for(i=c,s=[];i;)     // loop through each pair of the pyramid
        s[c-i]=p[i]+p[--i] // push the sum of the pair to the new pyramid s
  `)                       // implicit: return the final sum

```

## Test

```
<input type="number" id="input" value="0" oninput="result.textContent=(

n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)

)(+this.value)" />
<pre id="result"></pre>
```
> 3 votes

# Answer
## Seriously, 23 bytes

```
,r`P`M;lD`;pX@dXZ'Σ£M`n

```

Outputs the result as a list of length 1: `8 -> [1169]`

Try it online

Explanation:

```
,r`P`M    push the first n primes as a list
;lD       push 1 minus the length of the list (we'll call this k) ([2,3,5,7],3)
`...`n    call the following function k times:
    ;pX      duplicate the list, pop and discard the first element
    @dX      swap, pop and discard the last element
    Z        zip the two lists
    'Σ£      push the string "Σ" and convert to function
    M        map the function over the list

```
> 2 votes

# Answer
# Fig, \\$18\log\_{256}(96)\approx\\$ 14.816 bytes

```
tF@pmC
?!{Lx[xoX+p

```

*-6.585 bytes thanks to @Seggan*

Try it online!

Explanation:

```
tF@pmC  #
t       # Take the first n from
    mC  # all positive integers
 F      # filtered by
  @p    # is prime.

?!{Lx[xoX+p  #
?            # If
 !           # not
   L         # length of
    x        # the list
  {          # decremented,
     [       # return the first item
      x      # from the list
       o     # otherwise call
        X    # the current function
         +   # the list plus
          p  # the list with the first removed

```
> 2 votes

# Answer
# Ruby `-rprime`, ~~66~~ 62 bytes

-4 bytes thanks to south

```
->n{a=Prime.take n
(eval"a=a.each_cons(2).map &:sum;"*~-n)[0]}

```

Attempt This Online!
> 2 votes

# Answer
# Mathematica 73 bytes

```
NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&

```

---

**How it works**

`Prime@n~Table~{n,#}&` gives a list of the first `#` primes.

`Partition[#,2,1]&` rearranges a list of numbers, `{a, b, c, d ...}` as `{{a,b}, {b,c}, {c,d}...}}`.

`Plus@@@` then returns `{a+b, b+c, c+d...}`.

`NestWhile` begins with the list of `#` primes and repeatedly applies `Plus@@@Partition...` as long as there is more than one number in the list.

---

```
NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&[4]

```

> 33

---

```
NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #}, Length@# > 1 &][[1]] &[5]

```

> 83

---

It takes about 1/5 sec to solve for the first 1000 primes.

```
NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #},
 Length@# > 1 &][[1]] &[10^3] // AbsoluteTiming

```

> {0.185611, 1917231113909474354152581359443368948301825453723617274940459548079399 7849439430405641625002631859205971635284844253657654843025188471660669 0868945436580032828177831204066809442374364181056590286849530757875874 9185665854180901580438781223737728559484382552514103542932932981340942 3918431043908415228663677}
> 1 votes

# Answer
# Python 2, 159 bytes

```
m=int(input())
q=[]
x=2
while len(q)<m:
 if not any([x%g<1 for g in q]):q+=[x]
 x+=1
for i in range(m-1):
 for p in q:q+=[q[1]+q[0]];q.pop(0)
 print(q.pop())
print q

```
> 1 votes

# Answer
## Ceylon, 169 bytes

```
alias I=>Integer;I s(I*l)=>l.size<2then(l[0]else 0)else s(*l.paired.map((I[2]i)=>i[0]+i[1]));I p(I n)=>s(*loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n));

```

This defines two functions – `s` calculates the pyramid sum of a sequence of integers, while `p` calls this on the sequence of the first `n` primes.

Looks like about half the size is finding the first `n` primes, other half is calculating the pyramid sum.

Here is a formatted/commented version:

```
// Sum pyramid of primes
//
// Question:  http://codegolf.stackexchange.com/q/65822/2338
// My answer: http://codegolf.stackexchange.com/a/65879/2338

alias I => Integer;

// Calculate the pyramid sum of some sequence.
I s(I* l) =>
        // If less than two elements ...
        l.size < 2
        // then use the first (only element), or 0 if no such.
        then (l[0] else 0)
        // otherwise,
        else s(*
               // take the iterable of pairs of consecutive elements,
               l.paired
               // and add each of them together.
                .map((I[2] i) => i[0] + i[1])
               // then apply s (recursively) on the result.
               );

// Calculate the pyramid sum of the first n primes.
I p(I n) => s(*
              // the infinite sequence of integers, starting with 2.
              loop(2)(1.plus)
              // filter by primality (using trial division)
              .filter((c) => !(2 : c-2)
                              .any((d) => c%d < 1))
              // then take the first n elements
              .take(n)
              // then apply s on the result.
             );

```
> 1 votes

# Answer
# Milky Way 1.4.8, ~~26~~ 25 bytes

This answer is not competing. Some of the operations were created after this question was posted (but not necessarily for this challenge).

```
'E&{~F§{G}:y1ba?{_^_}};!

```

I was able to remove a byte after reading through the comments. Output is a single-element list.

---

### Explanation

```
'                        #  read input from the command line
 E                       #  push a list of the first N primes
  &{~                }   #  while loop
     F                   #  push the sum of TOS elements i.e. [A, B, C] => [[A,B], [B,C]]
      §{ }               #  mapping
        G                #  sum i.e. [1, 2, 3] => 6
          :              #  duplicate the TOS
           y             #  push the length of the TOS to the stack
            1            #  push 1 to the stack
             b           #  evaluate equality of the TOS and STOS
              a          #  logical not
               ?{_ _}    #  if-else statement
                  ^      #  pop the TOS
                     ;   #  swap the TOS and STOS
                         #  dump the TOS to the stack
                      !  #  output the TOS

```

---

### Usage

```
python3 milkyway.py <path-to-code> -i <input-integer>

```
> 1 votes

# Answer
# Jelly, 7 bytes

```
ÆN€+ƝƬṀ

```

Try it online!

Originally I wrote a Brachylog answer, `1<|~lṗᵐ≠≜{s₂ᶠ+ᵐ}ⁱ~g`, but when it came out to 19 bytes I decided that I should probably try a different language.

```
      Ṁ    The largest value from
     Ƭ     every stage of repeatedly
   +       adding
    Ɲ      adjacent values, starting with
ÆN         nth prime
  €        mapped over the input.

```

Apparently, mapping over a number treats it as a range from 1 to itself inclusive, and integers sort as greater than lists or whatever `''` is.
> 1 votes

# Answer
# APL(NARS), 41 chars, 82 bytes

```
{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}

```

In input if one want to use big number has to enter the type number\_x as 47x. There could be something not ok: i here write that n primes are in the set 1..n^2 Test:

```
  h←{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}
  h 1
2
  h 2
5
  h 9
2707
  h 24
320072415
  h 47x
6282142186547177
  h 99x
72298621492552303967009812018997
  h 200x
433205808657246411262213593770934980590715995899633306941417373

```
> 1 votes

# Answer
# Perl 6, 52 bytes

```
{grep(&is-prime,1..*)[^$_],{[|$_]Z+.skip}...1& &say}

```

Try it online!

Anonymous code block that takes an argument and prints out a one element list containing the result.
> 1 votes

# Answer
# Husk, 7 bytes

```
ΩεẊ+↑İp

```

Try it online!

Pretty straighforward.
> 1 votes

# Answer
# Japt `-h`, 11 bytes

```
_j}jU
Å£=ä+

```

Try it
> 1 votes

# Answer
# Vyxal `G`, 7 bytes

```
ʁǎ≬2lṠ↔

```

*-1 byte thanks to Steffan*

Try it online, see a flagless version, or verify more test cases.

Explanation:

```
ʁ        # Range from 0 to n
 ǎ       # Nth prime (vectorising)
  ≬      # Three element lambda that:
   2l    #   Gets overlapping groups of 2
     Ṡ   #   And sums each of them
      ↔  # Apply that function until no change and collect intermediate results
         # Get the maximum item of of those results with the G flag

```
> 1 votes

# Answer
# Pyt, 10 bytes

```
Đ`ŕʁ+ĐŁ⁻łŕ

```

Try it online!

```
Đ              Implicit input; duplicate list
 `      ł      Do... while top of stack is not 0
  ŕ            Remove top of stack
   ʁ+          Reduce by addition
     ĐŁ⁻       Get the length of the resultant array and subtract 1
         ŕ     Remove the pesky 0; implicit print

```
> 1 votes

# Answer
# Stax, 13 bytes

```
ä/($◘é∟o¶Vƒm^

```

Run and debug it
> 0 votes

# Answer
# 05AB1E, 6 bytes

```
ÅpIGü+

```

Outputs the result wrapped in a list.

Try it online or verify all test cases.

**Explanation:**

```
Åp      # Push a list of the first (implicit) input amount of primes
  IG    # Loop the input-1 amount of times:
    ü   #  For each overlapping pair of integers in the list:
     +  #   Add them together
        # (after which the result is output implicitly)

```
> 0 votes

---
Tags: code-golf, math, primes
---


# Question
Title: Build an aesthetically pleasing divisor tree
An aesthetically pleasing divisor tree is a tree of divisors of input `n` that, for any composite number `m`, has two children nodes that are the **pair of divisors** that are closest to the **square root** of `m`. The left node should be the smaller divisor of `m` and the right node should be the larger divisor of `m`. A prime number in the tree should have no children nodes. Your tree may be in the form of text art or an image. The rules for text art output are as follows.

**Spacing rules**

To space out the nodes on the tree, we have the following rules:

* The nodes at a given depth from the root should all be on the same line of text in the output.

```
  /  \    NOT    /  \
 /    \         /    3
2      3       2

```
* For left nodes, the incoming branch should be on the upper right if the node is a single-digit number, else, just above the last digit. Example:

```
 /    AND    /
3          720

```
* For right nodes, the incoming branch should be on the upper left if the node is a single-digit number, else, just above the first digit. Example:

```
\    AND    \
 7          243

```
* For outgoing left branches, the branch should begin one space to the left of the number. Example:

```
  275
 /
11

```
* For outgoing right branches, the branch should begin one space to the right of the number. Example:

```
275
   \
   25

```
* Any two nodes on the same level of the tree should have a minimum of two spaces between them. At the same time, any two **subtrees** on the same level of the tree should have as few spaces between them as possible.

```

This tree doesn't work because the **subtrees** are too close.

        504
       /   \
      /     \
     /       \
    /         \
   21   .     24
  /  \  .    /  \
 /    \ .   /    \
3      7.  4      6
        . / \    / \
        .2   2  2   3

While this tree does have enough space between its branches.

         504
        /   \
       /     \
      /       \
     /         \
    /           \
   21   ...     24
  /  \  ...    /  \
 /    \ ...   /    \
3      7...  4      6
        ... / \    / \
        ...2   2  2   3

```
* If any two subtrees are too close together on a tree, they can be separated by adding another row of branches `/\` to the tree above the parents.

```
   441
  /   \    Last row is not filled in yet and we have already run out of space.
 21   21
/  \ /  \

Add another row of branches

     441
    /   \     Almost, but the 7 and the 3 are too close together.
   /     \    One more row should do it.
  21     21
 /  \   /  \
3    7 3    7

Add another row of branches

      441
     /   \      And we're done.
    /     \
   /       \
  21       21
 /  \     /  \
3    7   3    7

```

**Examples**

As a full example, the divisor tree of 24 will look like this:

```
     24
    /  \
   /    \
  4      6
 / \    / \
2   2  2   3

```

4 and 6 are the pair of divisors closest to the square root of 24. 4 is on the left, because it's smaller. On the next line, the number 2 to the left of 3, because it's smaller.

The divisor tree for 63 should look like:

```
  63        and NOT like this        63
 /  \                               /  \
7    9                             3   21
    / \                               /  \
   3   3                             7    3

```

In the incorrect tree, 3 and 21 are not the pair of divisors closest to the square root of 63, and 3 and 7 are not sorted properly. The branch placement on the 21 is correct, though.

For 42, you should have:

```
    42      and NOT        42
   /  \                   /  \
  6    7                 21   2
 / \                    /  \
2   3                  3    7

```

Let's have a look at 720. Note that we need five levels of branches from `720` so that the `24` and `30` subtrees are correctly spaced. Also, note that `24` and `30` have two levels of branches because `4` and `6` have children nodes that need correct spacing and the children nodes of `30` need to be on the same level as the children nodes of `24`.

```
           720
          /   \
         /     \
        /       \
       /         \
      /           \
     24           30
    /  \         /  \
   /    \       /    \
  4      6     5      6
 / \    / \          / \
2   2  2   3        2   3

```

**The challenge**

* Your task is to build a correctly-spaced aesthetically pleasing divisor tree for input `n`, where `n` is a positive integer greater than 1.
* Your output may contain leading and trailing spaces and leading and trailing newlines, but must otherwise conform to the spacing rules given above.
* Your output is allowed to be: text art, an image (other formats to be added, if needed).
* For images, make sure your tree's nodes are well-spaced, and that nodes at the same height in the tree are at the same height in the image.
* This is code golf. Least number of bytes (or equivalent) wins.

Credit to Stewie Griffin for thinking of this idea, and many thanks to Peter Taylor, Martin Ender, Mego, and Eᴀsᴛᴇʀʟʏ Iʀᴋ for their help in rewriting the specification. As usual, any suggestions or corrections are much appreciated. Good luck and good golfing!

**More test cases:**

```
2

  4
 / \
2   2

    20
   /  \
  4    5
 / \
2   2

  323
 /   \
17   19

                        362880
                       /      \
                      /        \
                     /          \
                    /            \
                   /              \
                  /                \
                 /                  \
                /                    \
               /                      \
              /                        \
            576                        630
           /   \                      /   \
          /     \                    /     \
         /       \                  /       \
        /         \                /         \
       /           \              /           \
      /             \            /             \
     24             24          21             30
    /  \           /  \        /  \           /  \
   /    \         /    \      /    \         /    \
  4      6       4      6    3      7       5      6
 / \    / \     / \    / \                        / \
2   2  2   3   2   2  2   3                      2   3

              1286250
             /       \
            /         \
           /           \
          /             \
         /               \
      1050               1225
     /    \             /    \
    /      \           /      \
   /        \         /        \
  30        35       35        35
 /  \      /  \     /  \      /  \
5    6    5    7   5    7    5    7
    / \
   2   3

```

# Answer
> 28 votes
# Python 2, ~~711~~ ~~651~~ ~~575~~ ~~559~~ ~~554~~ ~~547~~ ~~539~~ ~~540~~ ~~530~~ 522 bytes

After four months of trying to write this answer, running into a wall, leaving it for a weeks, rinse, repeat, I have **finally** finished a proper ASCII art answer for this challenge. All that's left is the golfing, and so, golfing suggestions are very welcome. Try it online!

**Golfs:** -60 bytes from renaming some often used functions and changing how the result is returned. -73 bytes from changing how the subtrees' heights are checked, how the spacing variables are calculated, and how the result is returned. -3 bytes from FlipTack's `isdigit()` replacement. -16 bytes golfing that `isdigit()` replacement even further and replacing " " with `E`. -5 bytes from minor improvements and changing from Python 3 to Python 2. -7 bytes from modifying how the result is returned. -8 bytes from a small change to how `A` is defined, ~~changing how `T` is defined, and adding `W`, using the hypothesis that any subtree with at least one longer branch than its counterpart, is necessarily longer overall than its counterpart~~, removing `Q` altogether, and editing how the result is returned. -10 bytes from using `A<10` instead of `L(S(A))<2` for `A` and `B`. -8 bytes from changing the default `H` to `[0]` since the code avoids the problem of mutable default arguments by never mutating `H`, changing how `q` is defined by using `(B>9)` instead of `1-(B<10)`, removing `p` altogether, and creating `F` as a replacement for `p+q-M`.

**Bug fixes:** Hypothesis was wrong, counterexample in `11**9 = 2357947691`. +1 byte

```
G=range;L=len;E=" "
def t(n,H=[0]):
 A=max(z*(n%z<1)for z in G(1,int(n**.5)+1));B=n/A;Z=str(n);M=L(Z)
 if A<2:return[Z]
 T=max([i for i in G(L(w))if"/"not in w[i]]for w in(t(A),t(B)));V=H[1:]or[T[k+1]-T[k]-1for k in G(L(T)-1)];x=t(A,V);y=t(B,V);P=x[0].rindex(str(A)[-1])+(A<10);q=y[0].index(str(B)[0])+(B>9);F=L(x[0])-P+q-M;h=H[0]or(F+M%2+2)/2or 1;return[E*(P+J)+(J<h and"/"+E*(2*h+M-2*J-2)+"\\"or Z)+E*(L(y[0])-q+J)for J in G(h,-1,-1)]+[(E*(2*h-F)).join(I<L(w)and w[I]or E*L(w[0])for w in(x,y))for I in G(max(L(x),L(y)))]

```

**Explanation**

The whole function can be boiled down to about four steps:

1. Determine the largest divisor pair of `n`, `A` and `B`.
2. Make the subtrees of `A` and `B`, redrawing as needed.
3. Determine the number of spaces that should go between the subtrees.
4. Draw and return the new divisor tree.

I will go through each step in order.

**Step 1.** This is the easiest step, quite frankly. Check every number `z` between 1 and the square root for divisibility into `n` and grab the largest `z` and `n//z` that matches. Return just `str(n)` if `n` is prime (either `A==1` or `B==n`)

**Step 2.** Draw the subtrees of `A` and `B` and get the number of `/\` branches between nodes in the subtrees. To do this, we get the indices of every step that has digits in them, get the first differences of the indices, and subtract 1 again. Once we have the heights, we compare them to get the largest, and redraw the subtrees with the new heights.

~~I have a sneaking suspicion that the subtree that is taller overall always has branches as long as or equal to the branches on the shorter subtree, and I can use that to golf the code, but I have no proof of this yet.~~ Counterexample in `11**9 = 2357947691`.

**Step 3.** This step is what took months to write. Step 2 took a few days to write and debug, but finding the right formulas for the spacing took ages. I'll see if I can condense what I figured out into a few paragraphs. Note that some of the code in this explanation has since been golfed out of the real code.

First, `p`, `q`, `h`, `P`, `Q`, `s` and `M`.`p` is the number of characters from the end of the left branch `/` to the right end of the left subtree. `q` is the number of characters from the left end of the right subtree to the end of the right branch `/`. `h` is the number of branches between the root and the subtrees. `P` and `Q` are just the inverses of `p` and `q` and are useful for placing the spaces around `/\` branches up to the root `n`. `s` is the number of spaces that add between the two subtrees. `M` is simplest; it's the length of `n`. Put graphically:

```
            M
           ---
           720
 |        /   \
 |       /     \
h|      /       \
 |     /         \
 |    /           \
   P    p    s   q   Q
------______---____------
     24           30
    /  \         /  \
   /    \       /    \
  4      6     5      6
 / \    / \          / \
2   2  2   3        2   3

```

The formula for determining `p` is this: `p = len(x[0]) - x[0].rindex(str(A)[-1]) - (A<10)`, the length, minus the zero-index of the last character in A, minus a correction for single-digit `A`s.

The formula for determining `q` is this: `q = y[0].index(str(B)[0]) + (B>9)`, the index of the first character in B, plus a correction for zero-indexing, minus a correction for single-digit `B`s (combined into one correction for multiple-digit `B`s).

The formula for determining `h` is this: `h = H[0] or (p+q+M%2+2-M)//2 or 1`. Either we grab from a predefined `H` which means we're redrawing the tree, we use `(from_the_left + from_the_right + parity_space + 2 - len(root)) // 2)`, or we use the minimum number of branch levels, 1.

The formula for determining `s` is this: `s = 2*h+M-p-q`. We subtract `p` and `q` from the number of spaces between the root's branches at their widest `2*h + M`.

**Step 4.** And finally we put it all together. First we make the root, `[" "*(P+h)+Z+" "*(Q+h)]`, then we put in the branches down to the subtrees, `[" "*(P+J)+"/"+" "*(2*h+M-2*J-2)+"\\"+" "*(Q+J)for J in G(h)][::-1]`, and finally we put in our properly spaced subtrees, `[(" "*(2*h+M-p-q)).join([(I<L(w)and w[I]or" "*L(w[0]))for w in(x,y)])for I in G(max(L(x),L(y)))]`.

Et voilà! We have ourselves an aesthetically pleasing divisor tree!

**Ungolfing:**

```
def tree(n, H=[0]):
    A = max(z for z in range(1, int(n**.5)+1) if n%z<1)
    B = n/A
    Z = str(n)
    M = len(Z)
    if A < 2:
        return [Z]

    # redraw the tree so that all of the numbers are on the same rows
    x = tree(A)
    y = tree(B)
    for W in [x, y]:
        T = [i for i in range(len(W)) if "/" not in W[i]]
    V = H[1:] or [T[k+1]-T[k]-1 for k in range(len(T)-1)]
    x = tree(A, V)
    y = tree(B, V)

    # get the height of the root from the two trees
    P = x[0].rindex(str(A)[-1]) + (A < 10)
    p = len(x[0]) - P
    q = y[0].index(str(B)[0]) + (B > 9)
    Q = len(y[0]) - q
    h = hs[0] or (p+q+M%2+2-M)/2 or 1

    # and now to put the root down
    R = []
    s = 2*h+M-p-q
    for I in range(max(len(x),len(y))):
        c = I<len(x) and x[I] or " "*len(x[0])
        d = I<len(y) and y[I] or " "*len(y[0])
        R += c + " "*s + d,
    for J in range(h, -1, -1):
        if J<h:
            C = "/" + " "*(2*h+M-2*J-2) + "\\"
        else:
            C = Z
        R += [" "*(P+J) + C + " "*(Q+J)]
    return R

```

# Answer
> 15 votes
# Mathematica, ~~96~~ ~~86~~ ~~81~~ ~~79~~ 78 bytes

Thanks @MartinEnder for 2 bytes.

```
TreeForm[If[PrimeQ@#,#,#0/@(#2[#,#2/#]&[Max@Nearest[Divisors@#,#^.5],#])]&@#]&

```

The output looks like this:

# Explanation

```
Max@Nearest[Divisors@#,#^.5]

```

Generate the list of divisors of the input. Find the element nearest to the square root of the input. (`Max` is for flattening the output)

```
#2[#,#2/#]&

```

Find the other divisor by dividing the input by the divisor found above, apply the input as the head of the result.

```
#0/@

```

Repeat the process.

```
If[PrimeQ@#,#, ... ]

```

If the input is prime, don't do anything.

```
TreeForm

```

Format the output.

# Edit: A more aesthetically pleasing version (258 bytes)

```
TreeForm[#/.{a_,_,_}:>a,VertexRenderingFunction->(#2~Text~#&),VertexCoordinateRules->Cases[#,{_,_},Infinity,Heads->True]]&@(If[PrimeQ@#,{##},{##}@@#0@@@({{#,#3-#4{1,√3}/2,#4/2},{#2/#,#3-#4{-1,√3}/2,#4/2}}&[Max@Nearest[Divisors@#,√#],##])]&[#,{0,0},1])&

```

The output looks like this:

# Answer
> 5 votes
# Charcoal, 302 bytes

```
≔⟦⟦Ｎ⁰θ⁰¦⁰⟧⟧θＦθ«≔§ι⁰ζ≔⌈Ｅ…·²Ｘζ·⁵∧¬﹪ζκκη¿η«Ｆ⟦η÷ζη⟧«≔⟦κ⊕§ι¹Ｉκ⁰¦⁰⟧κ⊞ικ⊞θκ»⊞υι»»≔…⁰⌈Ｅθ§ι¹ηＦ⮌η«§≔ηι⊕⌈⟦⁰⌈Ｅυ∧⁼§κ¹ι÷Σ⟦¹§§κ⁵¦⁴‹⁹§§κ⁵¦⁰§§κ⁶¦³‹⁹§§κ⁶¦⁰±Ｌ§κ²⟧²⟧ＦυＦ²§≔κ⁺³λ⁺⁺§ηι∨⊖Ｌ§§κ⁺⁵λ²¦¹§§κ⁺⁵λ⁺³λ»Ｆυ«§≔§ι⁵¦³⁻⁻§ι³§η§ι¹∨⊖Ｌ§§ι⁵¦²¦¹§≔§ι⁶¦³⁻⁺⁺§ι³Ｌ§ι²§η§ι¹‹⁹§§ι⁶¦⁰»Ｆ⊕Ｌη«Ｆθ«Ｆ⁼§κ¹ι«←⸿Ｍ§κ³→Ｆ‹⁵Ｌκ«↙Ｐ↙§ηι↗»§κ²↓Ｆ‹⁵ＬκＰ↘§ηι»»Ｍ⊕§ηι↓

```

Try it online! Link is to verbose version of code. As the verbose version is very verbose, he's a JavaScript transliteration of the main algorithm:

```
u = []; // predefined variable, used as list of branches
q = [[+s, 0, s, 0, 0]]; // list of nodes starts with the root.
for (i of q) { // iterate nodes, includes new nodes
    z = i[0]; // get node value
    h = Math.max(...[...Array(Math.floor(z ** 0.5) + 1).keys()].slice(2).filter(
        k => z % k < 1)); // find largest factor not above square root
    if (h) {
        for (k of [h, z / h]) {
            k = [k, i[1] + 1, `${k}`, 0, 0]; // create child node
            i.push(k); // add each child to parent (indices 5 and 6)
            q.push(k); // and to master nodelist
        }
        u.push(i);
    }
}
h = new Array(Math.max(...q.map(i => i[1]))); // list of branch heights
for (i = h.length; i --> 0; ) {
    // find branch height needed to space immediate children apart at this depth
    h[i] = 1 + Math.max(...u.map(k => k[1] == j && // filter on depth
        1 + k[5][3] + (k[5][0] > 9) + k[6][2] + (k[6][0] > 9) - k[2].length
        >> 1)); // current overlap, halved, rounded up
    // calculate the new margins on all the nodes
    for (k of u) {
        k[3] = h[i] + (k[5][2].length - 1 || 1) + k[5][3]; // left
        k[4] = h[i] + (k[6][2].length - 1 || 1) + k[6][4]; // right
    }
}
// calculate the absolute left margin of all the nodes under the root
for (i of u) {
    i[5][3] = i[3] - h[i[1]] - (i[5][2].length - 1 || 1);
    i[6][3] = i[3] + i[2].length + h[i[1]] - (i[6][0] > 9);
}
// print the nodes (sorry, no transliteration available)

```

# Answer
> 1 votes
# C (GCC) \+ Graphviz, 213 bytes

```
g(n,c,x,k,l){printf("a%d[label=\"%d\"]",k=c,n);for(x=(int)sqrt(n);x>1;x-=1)n%x||(printf("a%d->a%d a%d->a%d ",k,l,k,c=g(x,l=c+1)+1),c=g(n/x,c),x=0);return c;}main(n){scanf("%d",&n);puts("digraph{");g(n);puts("}");}

```

Assuming the compiled executable is `a.out`, run with `./a.out | dot -Tpng`.

Takes the input `n` from `stdin` and outpus a PNG image to `stdout`.

---
Tags: code-golf, ascii-art, graphical-output, binary-tree
---


title: Meta Length Logarithms

text:
# Question
Title: Meta Length Logarithms
Good Evening Golfers,

Your challenge, this evening, is logarithmic, and (as Abed would put it) "Meta"

Your goal is to write a program that takes an input from stdin or the command line, and returns the logarithm of that number, in the base of the length of your program in bytes.

So, if your program is 10 bytes, it must return the Log10 of the input number.

Rules:

* Program must be longer then 1 character
* Program must be able to accept floating point input in a form of your choice, or scientific format in a form of your choice with a minimum accuracy of 6 digits
* Program must output to a minimum of 6 digits of accuracy in decimal or scientific format
* Program must be entirely self contained, and must not access any files or network resources.

Your score in the natural logarithm of the amount of bytes in your source code.

Good luck.

# Answer
## APL 1.0986122886681098

```
3⍟⎕

```

⎕ Requests numerical screen input. Examples of use:

```
      3⍟⎕
      10
2.0959032742893844

      3⍟⎕
      1E1
2.0959032742893844

      3⍟⎕
      ○1
1.041978045992186

```

In the last example ○1 represents pi.
> 17 votes

# Answer
## Mathematica: 2.079.. (length in bytes = 8)

```
8~Log~#&

```

Usage

```
8~Log~# &@8
(*
 1
*)

```
> 7 votes

# Answer
# bc (with -l) - log(15) = 2.70805

```
l(read())/l(15)

```
> 6 votes

# Answer
# Q (log(16) = 2.772589)

```
16 xlog"F"$(0:)0

```

Example

```
q)16 xlog"F"$(0:)0
16
1f

q)16 xlog"F"$(0:)0
1.6e1
1f

q)16 xlog"F"$(0:)0
13.912231123
0.9495705

```
> 5 votes

# Answer
# Ruby: 2.995732273553991 (`Math.log 20`)

```
p Math.log$_.to_f,20

```

Sample run:

```
bash-4.2$ ruby -ne 'p Math.log$_.to_f,20' <<< 3.14
0.3819509540359265

```
> 4 votes

# Answer
## J, 2.4849066497880003102297094798389 (12 chars)

```
12^.".1!:1[1

```

Usage:

```
   12^.".1!:1[1
12
1

```
> 4 votes

# Answer
# Perl: 2.77258872223978 (`log 16`)

```
say log()/log 16

```

Sample run:

```
bash-4.2$ perl -nE 'say log()/log 16' <<< 3.14
0.412691139779226

```
> 3 votes

# Answer
## Tcl, 3.4011973816621555 (log 30)

```
puts [expr log($argv)/log(30)]

```
> 3 votes

# Answer
# MATL, ln(2) = 0.6931471805

```
Zl

```

Try it online!
> 3 votes

# Answer
# 05AB1E, score: 0.693147... (2 bytes)

05AB1E has a 2-byte \\$\log\_2{n}\\$ builtin. ¯\\\_(ツ)\_/¯

Try it online or verify the inputs in the range \[0,3\] in increments of 0.1.

Otherwise it would have been 3 bytes instead:

```
3.n

```

Try it online or verify the inputs in the range \[0,3\] in increments of 0.1.

**Explanation:**

```
.²  # Get the logarithm in base 2 of the (implicit) input
    # (after which the result is output implicitly)

3   # Push 3
 .n # Pop and get the logarithm in base 3 of the (implicit) input
    # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Python (`log 38`) score: `3.6375861597263857` \<- how embarrassing

```
>>> import math;print math.log(input(),38)
38**8
8.0

```
> 2 votes

# Answer
# Lua 3.5835189384561 (36 38 42 chars)

```
L=math.log;print(L(io.read())/L(36))

```

Sample run:

```
C:...>echo 42 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1.0430165662508
C:...>echo 38 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1.0150877453695
C:...>echo 36 | lua -e "L=math.log;print(L(io.read'*n')/L(36))"
1
C:...>

```
> 2 votes

# Answer
**Smalltalk** (Pharo 2.0) **(41 ln) 3.713572066704308**

```
Pharo -headless Pharo-2.0.image eval "FileStream stdin nextLine asNumber log:41"

```

No syntactic sugar is Smalltalk's pride, just regular sentence ;)
> 2 votes

# Answer
# Scala - ln(46) = 3.82864...

`print(math.log(args(0).toDouble)/math.log(46))`

`scala log.scala 12.34` -\> 0.6563283834264416
> 2 votes

# Answer
# CJam - ln(5) = 1.60943791243

```
rd5mL

```
> 1 votes

# Answer
**JavaScript 69 bytes, score=4.23410650459726**

```
function f(n){return Math.log(n)/Math.log(69);}

```

I counted bytes following this discussion: https://stackoverflow.com/questions/2219526/how-many-bytes-in-a-javascript-string

```
function byteCount(s) {
        return encodeURI(s).split(/%..|./).length - 1;
    }

```

The number of characters is only 37. Any advice on counting bytes in code golf?
> 1 votes

# Answer
# Pyth, 1.38629436112

```
.lQ4

```

Try it online!
> 0 votes

# Answer
# Pyt, score \\$\ln(2)=0.693147...\\$

```
ļƥ

```

Try it online!

```
ļ       implicit input; log base 2
 ƥ      prints the top of the stack

```
> 0 votes

---
Tags: code-golf, math
---


title: n-digit primes given the first m digits

text:
# Question
Title: n-digit primes given the first m digits
I just discovered this site and this is my first question, I hope I'm doing it correctly.

The challenge is the following, you must write a code that prints all the prime numbers of \\$n\\$ digits. Since this problem is computationally complicated, I think that one way to simplify it is to give a number \\$m\\$ that will be the first digits of the primes to be printed and let's take \\$n\in\[1,2,...,10\]\\$ (there are 45086079 10-digit primes OEIS A006879). To reduce problems that the primes of large digits (10,9,8) can generate, we can say that if \\$n=10,9,8,7\\$ then \\$\\#m\geq 3\\$, where \\$\\#m\\$ denotes the number of digits in \\$m\\$.

**EXAMPLE**

```
input:
n=4
m=22

output:
2203 2207 2213 2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297

```

**RULES**

* You can use built-in functions to generate prime numbers.
* The user must provide \\$m\\$ and \\$n\\$.
* Lowest number of bytes in each language wins.

# Answer
> 10 votes
# Bash \+ bsdgames package, 39

```
primes 1 $[10**$2]|grep ^$1|egrep .{$2}

```

Try it online!

# Answer
> 7 votes
# , 65 bytes

```
\(n,m,k=10^(n-nchar(m)))for(i in 0:k+m*k)sum(!i%%2:i)<2&&print(i)

```

Attempt This Online!

# Answer
> 6 votes
# Vyxal, ~~12~~ 11 bytes

```
↵:₀/ṡ~æ'⁰øp

```

Try it Online!

Takes `n` then `m`. Prints the primes in order from largest to smallest.

## Explained

```
↵:₀/ṡ~æ'⁰øp
↵:₀/         # 10 ** n, 10 ** (n - 1)
    ṡ        # range(^, ^)
     ~æ      # filtered to only include primes
       '⁰øp  # and filtered to only keep numbers which start with m

```

# Answer
> 4 votes
# Vyxal, 10 bytes

```
Lε↵~*~+ṡ~æ

```

Try it Online!

```

  ↵        # 10 **
 ε         # Digit count minus
L          # Length of starting digits
   ~*      # Multiply by starting digits (without popping)
     ~+    # Add to starting digits (without popping)
       ṡ   # Range from ^^ to ^
        ~æ # Filter by isprime

```

# Answer
> 4 votes
# Charcoal, 28 bytes

```
≔Ｘχ⁻ＮＬηθＩΦ⁺…⁰θ×Ｎθ∧›ι¹⬤…²ι﹪ιλ

```

Try it online! Link is to verbose version of code. Takes `n` as the first input and `m` as the second. Explanation:

```
≔Ｘχ⁻ＮＬηθ

```

Subtract the number of digits in `m` from `n` and then take `10` to that power.

```
ＩΦ⁺…⁰θ×Ｎθ∧›ι¹⬤…²ι﹪ιλ

```

Take the range from `0` to that number, add on `m` multiplied by that number, then output only the prime numbers in that range.

# Answer
> 4 votes
# Brachylog (v2), 10 bytes

```
⟨{~l}a₀⟩ṗ≜

```

Try it online!

A generator solution that generates all possible outputs (the TIO header converts the generator to a list for printing, but consensus is that the generator on its own is sufficient to output a list). Input is a list `[*n*,*m*]`.

This should be 8 bytes, but I had to add grouping characters `{}` to work around a bug in Brachylog's parser.

## Explanation

```
⟨{~l}a₀⟩ṗ≜
  ~          Checking values whose
   l           length
⟨              is the first input, and
     a₀        which have a prefix that is
       ⟩       the second input,
        ṗ    using only the values that are prime numbers,
         ≜   generate all specific values that meet these criteria.

```

The `{` and `}` don't do anything but are required to prevent the parser crashing.

One interesting quirk of Brachylog: the `l` doesn't imply anything about us looking for *numbers* here, and will also try 4-element lists, but a few of the later restrictions restrict the program to looking for numbers specifically and thus it'll discount 4-element lists as a possibility.

Brachylog's primality testing algorithm is slow but general – it'll work in theory for any number of digits and any size of prefix, but may take a long time on larger numbers.

# Answer
> 4 votes
# Python, 83 80 75 bytes

```
lambda n,m:primerange(x:=m*(y:=10**(n-len(str(m)))),x+y)
from sympy import*

```

Attempt This Online!

-3 bytes by changing list(x) to \[\*x\]

-5 bytes thanks to @emanresu A

# Answer
> 3 votes
# JavaScript (V8), 78 bytes

Expects `(n)(m)`, with `m` passed as a string.

```
n=>m=>{for(q=1;!m[n-1];q*=10)m+=0;for(;q--;m++)for(x=m;x-2||print(m),m%--x;);}

```

Try it online!

### Commented

```
n =>              // outer function taking n
m => {            // inner function taking m
  for(            // initialization loop:
    q = 1;        //   q = size of range, initialized to 1
    !m[n - 1];    //   stop when m is large enough
    q *= 10       //   at each iteration, multiply q by 10
  ) m += 0;       //   and append a trailing 0 to m
  for(            // main outer loop:
    ;             //
    q--;          //   stop when q = 0 / decrement it afterwards
    m++           //   increment m after each iteration
  )               //
    for(          //   main inner loop:
      x = m;      //     stat with x = m
      x - 2 ||    //     if we've reached x = 2 without breaking:
        print(m), //       m is prime --> print it
      m % --x;    //     decrement x and stop if it's a divisor of m
    );            //
}                 //

```

# Answer
> 3 votes
# Retina 0.8.2, 117 bytes

```
.+$
$*#
((.)+)¶(?<-2>#)+
$1
+%1`#
0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9
.+
$*
A`^1?$|^(11+)\1+$
%`1

```

Try it online! Takes `m` as the first input and `n` as the second. Explanation:

```
.+$
$*#

```

Convert `n` to unary.

```
((.)+)¶(?<-2>#)+
$1

```

Decrement `n` for each digit of `m`.

```
+%1`#
0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9

```

Extend `m` to be `n` digits long, a digit at a time.

```
.+
$*

```

Convert all the values to unary.

```
A`^1?$|^(11+)\1+$

```

Discard `0`, `1` and all composite numbers. (If `n` was always at least `2`, the `^1?$|` would not be needed for a saving of 5 bytes.)

```
%`1

```

Convert the remaining primes back to decimal.

# Answer
> 3 votes
# C (gcc) with `-lgmp`, ~~159~~ 147 bytes

* -2 thanks to ceilingcat
* -10 by removing the `#import`

Takes a number length and prefix (as a string).

Luckily GMP has a "next prime number" function, so I just had to turn the prime numbers into strings and compare the prefix to the stringified values.

```
*t,p[9];f(m,w,u,v)int*w;{u=strlen(w);__gmpz_init(p);for(v=0;v<=m;(v=__gmp_asprintf(&t,"%Zd",p))==m&!strncmp(w,t,u)&&puts(t))__gmpz_nextprime(p,p);}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 12 bytes

```
°DT÷Ÿʒp}ʒ²Å?

```

Try it online!

Port of lyxal's Vyxal answer. It can probably be a bit shorter, but I can't get it to work with just 1 filter.

**Explanation:**

```
°DT÷Ÿʒp}ʒ²Å?  # Implicit input, with n first then m
°             # 10 ** n
 DT÷          # 10 ** (n - 1)
    Ÿ         # Range between them
     ʒp}      # Primes only
        ʒ     # Keep only those
          Å?  # which start with
         ²    # the second input, m
              # Implicit output

```

# Answer
> 3 votes
# Thunno, \\$ 17 \log\_{256}(96) \approx \\$ 13.99 bytes

```
10@D10,s:gNkgz1ZV

```

(No ATO link since that's on an older version)

Port of lyxal's Vyxal answer.

#### Explanation

```
10@D10,s:gNkgz1ZV  # Implicit input, with n first then m
10@                # 10 ** n
   D10,            # 10 ** (n - 1)
       s:          # Range between them
         gNk       # Primes only
            g      # Keep only those
               ZV  # which start with
             z1    # the second input, m
                   # Implicit output

```

#### Screenshot

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
°ÅP¹ùʒIÅ?

```

Try it online.

**Explanation:**

```
°          # Push 10 to the power of the first (implicit) input-integer `n`
 ÅP        # Pop and push a list of all primes lower than (or equal to) that 10**n
   ¹ù      # Only keep the primes with a length equal to the first input `n`
     ʒ     # Filter it further by keeping those:
      IÅ?  #  That start with the second input-integer `m`
           # (after which the filtered list of primes is output implicitly as result)

```

---

If we could assume that \\$n\>L\_m\\$, where \\$L\_m\\$ is the length of \\$m\\$, it could be 7 bytes instead:

```
°Ý«¹ùʒp

```

Try it online.

Without that assumption, it would still be 9 bytes with this approach:

```
°Ý«Iš¹ùʒp

```

Try it online.

**Explanation:**

```
°          # Push 10 to the power of the first (implicit) input-integer `n`
 Ý         # Pop and push a list in the range [0,10**n]
  «        # Append each to the second (implicit) input-integer `m`
   ¹ù      # Only keep the integers with a length equal to the first input `n`
     ʒ     # Filter it further by keeping those:
      p    #  That are primes
           # (after which the filtered list is output implicitly as result)

   Iš      # (prepend the second input-integer `m` to the list; if the length of `m` is
           # equal to `n`, the final result will be `[m]` iff `m` is a prime, or an
           # empty list otherwise)

```

# Answer
> 2 votes
# Python, 105 bytes

```
lambda n,m:[p for p in primerange(10**n+1)if n==len(d:=str(p))and(s:=str(m))<=d<s+'~']
from sympy import*

```

Attempt This Online!

---
Tags: code-golf, primes
---


# Question
Title: Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window **of the default browser** to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

This is , so the shortest answer in bytes wins.

---

> Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

# Answer
## GNU Emacs, ~~29~~ ~~27~~ ~~14~~ 33 bytes

```
(eww"codegolf.stackexchange.com")

```

The previous answer with a URL shortener was:

```
(eww"ppcg.ga") ;; 14 bytes

```

However:

> Much like ppcg.lol, ppcg.ga has been unregistered, invalidating this answer. But unlike last time, there is no replacement short url. (@lyxal)

EWW is a browser inside Emacs. The `browse-web` function is an alias for `eww`, and so that makes `eww` the *default browser* in Emacs:

> Your job is to open a browser window of *the default browser* to http://codegolf.stackexchange.com.

Thanks to @CoolestVeto, @Jonathan Leech-Pepin and @zyabin101.
> 38 votes

# Answer
# Oration, 41 bytes

Not winning, but sure was fun. As of right now, I'm only 1 bytee behind python!

```
I need webbrowser
Now open "http:ppcg.ga"

```

Explanation:

`I need` compiles to `import $1` with `webbrowser` being the module.

`Now` runs the following command from the module as `module.command` with the arguments of anything following.

So this compiles to:

```
#!/usr/bin/env python3
import webbrowser
webbrowser.open("http:ppcg.ga")

```

I do end up needing the `http:` part though, and it can't be shortened.
> 47 votes

# Answer
# Batch, 17 bytes

Saved 3 bytes thanks to Mego.

```
start www.ppcg.ga

```

This will open in your default browser if you run it from the windows command line.

I think it'll work in Powershell too, but I'm not sure.
> 42 votes

# Answer
# PowerShell, ~~17~~ 16 Bytes

```
saps www.ppcg.lol

```

Using an even shorter domain provided by Milo.

```
saps www.ppcg.ga

```

---

While `start` is a known alias for `Start-Process` there is another one for `saps`. You can see this from `Get-Alias`. It follows the convention for similar `Start-` and `Stop-` cmdlets.

---

As those URLs no longer exist the only way to make this work is to use the horribly inefficient 36 characters for

`saps http:codegolf.stackexchange.com`

At least we can drop the slashes no problem
> 26 votes

# Answer
# Terminal (OSX), ~~20~~ ~~18~~ 17 bytes

```
open http:ppcg.ga

```

*Saved 2 thanks to CoolestVeto*
> 22 votes

# Answer
# MATLAB, ~~28~~ 25 bytes

```
web www.ppcg.lol -browser

```
* `www` is shorter than `http://` and ensures that the address is processed as a URL
* This is shorter using the implicit function call (which casts inputs as strings) rather than the explicit version `web('www.ppcg.lol', '-browser')`.
* If you are on a OS X, this can be simplified to `web ppcg.lol -browser` as MATLAB will automatically append an `http://` (**21 bytes**)

**Alternatives**:

* On windows this can be shortened to (**19 bytes**)

```
!start www.ppcg.lol

```
* On OS X (**21 bytes**)

```
!open http://ppcg.lol

```
* The following would work in a deployed MATLAB application (**16 bytes**)

```
web www.ppcg.lol

```
* If the built-in browser could be used this could be reduced even further as `http` is implied (**12 bytes**)

```
web ppcg.lol

```
> 14 votes

# Answer
# Python, ~~52~~ ~~48~~ ~~47~~ ~~45~~ 44 bytes

Shamelessly borrowing that shortened link.

```
from webbrowser import*;open("http:ppcg.ga")

```

Thanks to CrazyPython for -4 bytes, and Sp3000 for a further one.

Edit: shaved 2 more off thanks to CoolestVeto

Edit: thanks to MD XF for registering ppcg.ga and saving another byte
> 13 votes

# Answer
# AutoHotKey, 16 bytes

```
Run www.ppcg.lol

```
> 13 votes

# Answer
# Java 7, 151 bytes

```
class P{public static void main(String[]a)throws Exception{java.awt.Desktop.getDesktop().browse(new java.net.URI("http:codegolf.stackexchange.com"));}}

```

Java is not the best language for golfing... Here's the same program in a more readable format:

```
class P {
    public static void main (String[] a) throws Exception {
        java.awt.Desktop.getDesktop().browse(new java.net.URI("http:codegolf.stackexchange.com"));
    }
}

```

Saved 2 bytes by removing `//` in the URI/L~~, and another byte by switching to `.ga` from `.lol` (indirectly thanks to @Milo)~~
> 10 votes

# Answer
# Bash, ~~24~~ 22 bytes

```
xdg-open http:ppcg.lol

```

Not as short as some others. `firefox ppcg.lol` is shorter, but it doesn't meet question spec.
> 9 votes

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

```
interface P{static void main(String[]a)throws Exception{java.awt.Desktop.getDesktop().browse(new java.net.URI("http:ppcg.ga"));}}

```

Java is not the best language for golfing... Here's the same program in a more readable format:

```
interface P {
    static void main (String[] a) throws Exception {
        java.awt.Desktop.getDesktop().browse(new java.net.URI("http:ppcg.ga"));
    }
}

```

Saved 2 bytes by removing `//` (thanks @CoolestVeto), and another byte by switching to `.ga` from `.lol` (indirect thanks to @Milo)
> 8 votes

# Answer
# Pylongolf, 11 bytes

```
"ppcg.lol"p

```

Pushes ppcg.lol into the stack then `p` opens it.
> 8 votes

# Answer
# JavaScript, 34 bytes

```
require('open')('http://ppcg.lol')

```

Uses Node.js
> 7 votes

# Answer
# Mathematica, 28 bytes

```
SystemOpen@"http://ppcg.lol"

```
> 5 votes

# Answer
# Applescript, 28 bytes

* 3 bytes saved thanks to @CoolestVeto.

```
open location"http:ppcg.lol"

```
> 5 votes

# Answer
# R, 26 bytes

`shell.exec("www.ppcg.lol")`

I don't know of any shorter way to do this in R.
> 4 votes

# Answer
# Actionscript 3, 117 bytes

```
package{import flash.display.Sprite;public class A extends Sprite{function A(){navigateToUrl("ppcg.lol","_blank")}}}

```

Like Java, this is not a great golfing language. Here's the code with formatting:

```
package
{
    import flash.display.Sprite;

    public class A extends Sprite
    {
        function A()
        {
            navigateToUrl("ppcg.lol", "_blank")
        }
    }
}

```
> 4 votes

# Answer
# Perl 5, ~~66~~ ~~57~~ 76 bytes

Should work everywhere, but needs that import :(

8 bytes saved with @msh210 comment.

```
use Browser::Open open_browser;open_browser"http:codegolf.stackexchange.com"

```

Also, for funsies :

### Perl 5 (Windows), ~~34~~ 48 bytes

```
system "start http://codegolf.stackexchange.com"

```

### Perl 5 (Unix), ~~31~~ 49 bytes

```
system "xdg-open http:codegolf.stackexchange.com"

```
> 4 votes

# Answer
# Rebol 2, 16 15 bytes

```
browse"ppcg.ga"

```

if you accept an error before opening the page on Linux, no error on Windows

**20 bytes** without an error

```
browse http:ppcg.lol

```
> 4 votes

# Answer
# Factor, ~~38~~ ~~36~~ ~~26~~ 29 bytes

```
[ "http:t.ly/-E-J" open-url ]

```

I didn't know one could golf-off the `//` in the protocol.
> 3 votes

# Answer
# Red, 40 bytes

```
browse http://codegolf.stackexchange.com

```

(Don't) Try it online!

`ppcg.ga` no longer works, so needed to include the full domain name. But its funny that Red has its own URL data type!
> 3 votes

# Answer
# VBScript, 57 bytes

I used to have lots of fun creating tiny programs in VBScript, back in 2010.

I've remembered this language and used the code on: https://stackoverflow.com/a/13401872/2729937

It still works on Windows 7, at least.

```
set S=CreateObject("WScript.Shell")
S.run("www.ppcg.ga")

```

This is a bit different from the usual `start www.ppcg.lol`, in the sense that it executes the `www.ppcg.ga` directly, with an implicit `start`.

An alternative way would be `"cmd.exe /C start www.ppcg.ga"`.
> 2 votes

# Answer
# RFO-BASIC, 22 bytes

```
BROWSE "http:ppcg.lol"

```

Read about RFO-BASIC at laughton.com.
> 2 votes

# Answer
# Common Lisp, 31 bytes

```
(ext:shell "open http:ppcg.ga")

```

Note: This worked at the time of writing. The domain `ppcg.ga` has since expired, making this answer no longer valid.
> 2 votes

# Answer
# VBA, 84 bytes

```
Sub Main()
ThisWorkbook.FollowHyperlink("http://codegolf.stackexchange.com")
End Sub

```
> 2 votes

# Answer
# Zsh on MacOS, 19 bytes

```
open http:t.ly/-E-J

```

Try it online! (`t.ly` is a URL shortener).
> 2 votes

# Answer
# 05AB1E, 16 bytes

The features used here postdate the challenge, but that's fine. Code:

```
’…Ò ™³.ÐÏg.´¢’.E

```

You can try the **string** online here. This basically evaluates to this batch answer.

Uses the **CP1252** encoding.
> 1 votes

# Answer
# Ruby, ~~22~~ ~~20~~ 19 bytes (on OS X)

```
`open http:ppcg.ga`

```

Simple.

Thanks to Daniel for 2 bytes off.
> 1 votes

# Answer
# C#, 33 bytes

```
Process.Start("http://ppcg.lol");

```

Opens the default browser to the web address
> 1 votes

# Answer
# PHP (OSX), 33 bytes

```
<?php exec("open http:ppcg.lol");

```

# PHP (Windows), 34 bytes

```
<?php exec("start http:ppcg.lol");

```
> 1 votes

# Answer
# VB.NET, ~~32~~ 30 bytes

```
Process.Start("http:ppcg.lol")

```
> 1 votes

# Answer
# Game Maker Studio, 26 bytes

```
url_open('http://ppcg.ga')

```
> 1 votes

# Answer
# Windows Batch, 17 bytes

```
start www.gfa1.tk

```
> 1 votes

# Answer
# Python, 44 bytes

```
from webbrowser import*;open('http:ppcg.ga')

```

~~URL from this comment~~
**Edit**: ppcg.ga seems to become more popular now (but it WAS available when I posted this answer).

Ungolfed:

```
from webbrowser import * # Loads everything in the webbrowser module
open("http://ppcg.ga/") # Opens default browser to http://ppcg.ga/

```

---

# Python, 44 bytes

```
from webbrowser import*;open('http:gfa1.tk')

```

URL from this answer

Ungolfed:

```
from webbrowser import * # Loads everything in the webbrowser module
open("http://gfa1.tk/") # Opens default browser to http://gfa1.tk/

```

---

# Python, 45 bytes

```
from webbrowser import*;open('http:ppcg.lol')

```

Ungolfed:

```
from webbrowser import * # Loads everything in the webbrowser module
open('http://ppcg.lol/') # Opens default browser to http://ppcg.lol/

```

---

Take that, ppcg.lol! (1 byte shorter)

**Note**: I added a separate answer leading to ppcg.lol, 'cause I've noticed the other sites doesn't work for me in Internet explorer 11, and I saw other users having this problem too.

*Both are non-non-competing* ***(read that right?)***
> 1 votes

# Answer
# Perl 6, 45 bytes

Requires the `Browser::Open` module.

```
use Browser::Open;open_browser 'http:ppcg.ga'

```
> 1 votes

# Answer
# C++, 61 Bytes

```
#include <cstdlib>
main(){system("xdg-open http:ppcg.lol");}

```

Just a rip off of the bash solution using system, and it only works on systems using the freedesktop tools. Also shortened by using the short link some kindly provided, otherwise it would be much longer.
> 1 votes

# Answer
## Lua, 30 Bytes

```
os.execute'start http:ppcg.ga'

```
> 1 votes

# Answer
# Cheddar, 65 bytes

```
cheddar.internal(cheddar.uid).require("open").c("http://ppcg.ga")

```

Accesses cheddar internals and then calls upon `open` package and calls it with string to PPCG. Make sure you have `open` npm package installed
> 1 votes

# Answer
# Vyxal 7 bytes

```
`∨¤ β`E

```

Try it Online!

The short dictionary is a neat hidden feature, compressing the codegolf link to `β`
> 1 votes

# Answer
# NodeJS, 53 bytes

```
require('child_process').exec('open http://ppcg.lol')

```

Works on mac.
> 0 votes

# Answer
# Python, ~~43~~ ~~41~~ 40 bytes

```
import os
os.system("open http:ppcg.ga")

```
* -2 bytes thanks to @Quill.
* -1 byte thanks to @MDXF.
> 0 votes

# Answer
# Dyalog APL, ~~20~~ 19 bytes

-1 byte thanks to MD XF

```
]Open http://ppcg.ga

```

Uses the User Command \]Open, which is installed with Dyalog.
> 0 votes

# Answer
# C# (Full Class) 89 bytes

```
class P{static void Main(string[]a){System.Diagnostics.Process.Start("http://ppcg.ga");}}

```

Not sure that it's possible to write a full class (with the System.Diagnostics reference) any shorter.

Inside main method only without references, 32 bytes:

```
Process.Start("http://ppcg.ga");

```
> 0 votes

# Answer
# Nim, 47 bytes

```
import browsers
openDefaultBrowser"www.ppcg.ga"

```
> 0 votes

# Answer
# Python, 40 bytes

```
__import__('webbrowser').open('ppcg.ga')

```

Shorter version of everything else.
> 0 votes

# Answer
# VBScript, 47 bytes

```
CreateObject("WScript.Shell").Run"http:ppcg.gq"

```
> 0 votes

# Answer
**URL, 58 bytes**

```
[InternetShortcut]
URL=https://codegolf.stackexchange.com

```

In Windows create a file "url.URL", with a code editor put the code.
> 0 votes

# Answer
# R, 28 bytes

```
browseURL("http://ppcg.lol")

```

(in `utils` package)
> -1 votes

# Answer
# SX, 38 bytes

```
的 webbrowser im**;o&('http:ppcg.ga')

```

Save this shell script as `SXexec.sh` to your SX directory:

```
#!/bin/sh
N=$1.py;python Main.py $1;wine SXCompiler.exe $N;rm $N;python $N.py;rm $N.py

```

The script features tidying up after execution. To execute the above script, you need to have Wine and Python. Usage is like this:

```
SXexec.sh file

```
> -1 votes

# Answer
## C (gcc), ~~49~~ ~~38~~ 37 bytes

```
main(){system("start http:ppcg.ga");}

```

It's for Windows.
> -1 votes

---
Tags: code-golf, internet, browser
---


# Question
Title: Shortest class to implement Perl hash-of-hashes
At some point, I bumped into an SO question asking how to implement Perl's trivial hash-of-hashes data structure in Java.

For those who don't know Perl, the hash value can be a scalar or another hash, or technically speaking hash reference. Arbitrary depth. Additional feature offered by Perl is autovivification - assigning an element 4 layers deep will automatically create correct hashes with proper keys 4 levels deep, without Java's need to assign hash object on level 1, then hash object on level 2 (being added to the first hash as a value) etc...

So, Perl code to assign a value to N-level hash at a known depth is

```
my $myHash; # initialization isn't required due to autovivification
$myHash->{$key1}->{$key2}->{$key3}->{$key4} = $value;

```

And to retrieve it

```
my $value = $myHash->{$key1}->{$key2}->{$key3}->{$key4};

```

The more generic code to assign a hash by arbitrary set of keys can be implemented by 5-10 line subroutine done properly; or 2-3 lines golf hack with eval.

Not being anywhere near a Java expert, my SO answer was ~30 lines of code that implemented a fixed-depth 3 level hash of hash of hashes.

Your mission, should you choose to accept it, **is to produce the smallest code in a strongly typed language which implements Perl equivalent data structure which is a hashmap of hashmaps of ...; of arbitrary and non-uniform depth** (basically, a tree); with hasmap keys being of String type; and leaf-level values String or Integer. The code should support 100% of what the Perl hash-of-hashes code does, including:

* Retrieving a value based on a list of keys
* Assigning a value based on a list of keys

+ As part of this, you should be able to replace a scalar leaf level node with an internal hashmap node, if your list of keys leads to that.

    E.g. `set("val1","k1","k2");set("val2","k1","k2","k3")` basically erases `"val1"` from existence after second call as it's replaced by a 3rd level hashmap.

The code should be resilient, e.g. no null exceptions etc... even for the bad input (simply return NULL)

You can use any strongly typed language other than Java, though I would personally prefer Java answers due to how/why this question originated.

Caveat: using some 3rd party library that implements equivalent of Perl hashes is NOT acceptable. 100% of the code must be using only the native core capabilities of the language.

# Answer
> 1 votes
# C#, 215 bytes

```
class A:System.Collections.Generic.Dictionary<string,object>{public void B(string a,object b){if(ContainsKey(a))this[a]=b;else Add(a,b);}public dynamic C(string a){if(!ContainsKey(a))Add(a,new A());return this[a];}}

```

The class is named `A`. Use `hash.B("key", "val");` to set a value, and `hash.C("key");` to get a value. Nested keys can be achieved through, e.g., `hash.C("k1").C("k2").C("k3").B("k4", "value");`.

# Answer
> 1 votes
# Scala, ~~231~~ ~~214~~ ~~199~~ 193 bytes

Immutability always wins! (turns out the long package name of `collection.mutable.Map` wasn't worth the hassle...)

```
class A{var a=Map[String,Any]()
def g(s:String*):Any={val y=s(0);if(s.size>1)g(y).asInstanceOf[A].g(s.drop(1):_*)else if(a.contains(y))a(y)else{a+=y->new A;a(y)}}
def s(s:String,v:Any)=a+=s->v}

```

Only thing that's problematic is the need to cast back to A... but having another method entirely that'd return `a.type` is actually longer (and `with` cannot be used).

Example:

```
val a = new A()
a.g("hey").asInstanceOf[A].s("foo", "bar")
a.g("hey").asInstanceOf[A].s("int", 3)
println(a.g("hey").asInstanceOf[A].g("foo"))
println(a.g("hey", "foo"))
println(a.g("hey", "int"))
a.s("hey", 42)
println(a.g("hey"))

```

Output:

```
bar
bar
3
42

```

# Answer
> 1 votes
# Go, 136 bytes

```
type S=string
type A struct{m map[S]any}
func(a*A)g(k S)any{if _,o:=a.m[k];!o{a.m[k]=N()};return a.m[k]}
func(a*A)s(k S,v any){a.m[k]=v}

```

Attempt This Online!

Challenge specification does not specify constructors; this implementation does not include them. An implementation with a constructor is below:

### Go, with constructor, 174 bytes

```
type S=string
type A struct{m map[S]any}
func N()*A{return&A{make(map[S]any)}}
func(a*A)g(k S)any{if _,o:=a.m[k];!o{a.m[k]=N()};return a.m[k]}
func(a*A)s(k S,v any){a.m[k]=v}

```

Attempt This Online!

---
Tags: code-golf, data-structures, perl
---