title: We'll be counting stars

text:
# Question
Title: We'll be counting stars
Your objective is to take multiline ASCII like

```
|  v  |
* * * *
 * * *

```

and have an array that includes everything that isn't a star changed to a star (except for \[any-width\] spaces) and the number of stars it included and the number of stars it now includes. So the output of my example would be:

```
['*  *  *
* * * *
 * * *',7,10]

```

or

```
["*  *  *\n* * * *\n * * *", 7, 10]

```

depending on what your code language does.

This is a challenge, so the shortest bytes wins!

# Answer
### GolfScript, 30 characters

```
.{.'
 '?)\42if}%.{@'*'/,(}2*]`

```

Takes the input from stdin. *Example (test online):*

```
> |  v  |
> * * * *
>  * * *

["*  *  *\n* * * *\n * * *\n" 7 10]

```
> 3 votes

# Answer
# Python - 58 66 characters

Sooo... my first Code Golf attempt...

**Code:**

```
import re;p=re.sub(r'\S','*',i);print[p,i.count('*'),p.count('*')]

```

**Output:**

```
['*  *  *\n* * * *\n * * *', 7, 10]

```

**Variables:**

* `i` \- input string
* `p` \- pattern
* `o` \- output - *removed*

**Dependencies:**

Python `re` module

**Full code:**

```
import re
i = '|  v  |\n* * * *\n * * *'
p = re.sub(r'\S','*', i)
print [p, i.count('*'), p.count('*')]

```

**Edits:**

* Added `import re` to solution
* Replaced `o=` with print
* `r'[/\S/g]'` was changed to `r'\S'` *(thanks @14mRh4X0r)*
> 3 votes

# Answer
## Ruby 2.0, 53 characters

```
p [r=gets($n).gsub(/\S/,?*),$_.count(?*),r.count(?*)]

```

Not sure on the exact input/output formats required. This takes input on STDIN and formats the output like so:

Input:

```
|  v  |
* * * *
 * * *

```

Output:

```
["*  *  *\n* * * *\n * * *", 7, 10]

```
> 2 votes

# Answer
# JavaScript (ECMASCript 6) - 51 Characters

```
i=j=0,[A.replace(/\S/g,x=>(j++,i+=x=='*','*')),i,j]

```

Assumes the variable `A` contains the multiline ASCII input. To take it from the user then replace the `A` with `prompt()` (+7 characters) or as a function (again +7 characters):

```
f=A=>(i=j=0,[A.replace(/\S/g,y=>(j++,i+=y=='*','*')),i,j])

```

Output is to the console.

**Test:**

```
A='|  v  |\n* * * *\n * * *'
i=j=0,[A.replace(/\S/g,x=>(j++,i+=x=='*','*')),i,j]

```

Outputs:

```
["*  *  *
* * * *
 * * *", 7, 10]

```
> 2 votes

# Answer
## PHP ≥ 5.5, ~~84~~ ~~69~~ 63 bytes

```
$a=[preg_replace('/\S/','*',$s,-1,$n),substr_count($s,'*'),$n];

```

Not a lot to say about this. As there is no specification for how to handle input/output, I'm assuming variable storage. Expects the input in variable `$s` and stores the array in variable `$a`. Too bad those function names are s o long.
> 1 votes

# Answer
# Rebol, 84

```
c: s: 0 parse t[any["*"(++ s)|" "|"^/"| m: skip(change m"*" ++ c)]]reduce[t s s + c]

```

Set `t` to the text like so....

```
t: {|  v  |
* * * *
 * * *}

```

and this would return...

```
["*  *  *^/* * * *^/ * * *" 7 10]

```

Ungolfed version with some notes:

```
c: s: 0    ;; "s" is star count before change, "c" is count of chars changed to stars

; so using single-char ANY rule to parse each character in "t"

parse t [
    any [                              ;; so "t" is made up of ANY...
        "*"     (++ s) |               ;; "*" (if so then increment s)
        " "            |               ;; or a space
        "^/"           |               ;; or a newline
        m: skip (change m "*"  ++ c)   ;; or anything else (skip)
                                       ;;   (and so change to "*" & increment c)
    ]
]

reduce [t s s + c]      ;; return array with amended text (t) and counts

```
> 1 votes

# Answer
## Groovy : 96 92 chars

```
s=System.in.text
t=s.replaceAll(/[^\*\s]/,/\*/)
println "['$t',${s.count"*"},${t.count"*"}]"

```

Uses Groovy 2.2.1

Reads from STDIN. IMHO, not especially clever, but fairly easy to read (given its brevity)
> 1 votes

# Answer
# Stax, 12 bytes

```
ç≈°▼╔╔²AGΓM4

```

Run and debug it

## Explanation

```
.\S'*YRQx2Dy#P
.\S              push regex \S
   '*            push '*'
     Y           store star in Y
      R          perform regex replacement on the input
       Q         peek and print with newline
        x        push input again
         2D      execute the following twice:
           y     push '*'
            #    number of stars
             P   pop and print with newline

```
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
…
     м©S'*:I'*¢®g)

```

Assumes the mentioned "\[any-width\] spaces" only include spaces, tabs, and newlines (with codepoints 32, 9, and 10 respectively).

Try it online.

**Explanation:**

```
…\n\t м       # Remove all newlines, tabs, and spaces of the (implicit) input-string
       ©      # Store this string in variable `®` (without popping)
        S     # Convert it to a list of characters
         '*: '# Replace each non-whitespace character in the (implicit) input with a "*"
I             # Push the input again
 '*¢         '# Pop and count the amount of "*" in this string
®             # Push the non-whitespace string from variable `®`
 g            # Pop and push its length
            ) # Wrap everything on the stack into a list
              # (after which it is output implicitly as result)

```
> 1 votes

# Answer
# In JavaScript/CoffeeScript - 66 Characters

Like the PHP Example, the length is due to the length of the function names

```
[x.replace(/\S/g,"*"),x.split("*").length-1,x.match(/\S/g).length]

```

Example Usage (CoffeeScript):

```
((x="|  v  |\n* * * *\n * * *")->[x.replace(/\S/g,'*'),x.split('*').length-1,x.match(/\S/g).length])()

```
> 0 votes

# Answer
## C# - 116

Shortest way i can think of that returns an array..

```
object[]R(string a){var o=Regex.Replace(a,"\\S", "*");return new object[]{o,a.Count(x=>x=='*'),o.Count(x=>x=='*')};}

```
> 0 votes

# Answer
# Perl, 52 bytes

```
$_=join'',<>;printf'["%s",%s,%s]',$_,tr/*//,s/\S/*/g

```

Takes input from standard input, prints to standard output.

Assuming the output format like you described in your question, could be made quite a bit shorter if a different output format would be allowed.
> 0 votes

# Answer
# Javascript - 50 characters

```
i.replace(/\S/g,'*').replace(/\n/g,':').split(':')

```

## Test

### Input

```
var i = 'Lately I been, I been losing sleep\nDreaming about the things that we could be\nBut baby, I been, I been prayin\' hard';
i.replace(/\S/g,'*').replace(/\n/g,':').split(':')

```

### Output

```
["****** * ***** * **** ****** *****", "******** ***** *** ****** **** ** ***** **", "*** ***** * ***** * **** ******* ****"]

```
> 0 votes

# Answer
## AWK, (too long)

```
awk '{y+=gsub(/[^* ]/, "*"); x+=NF}NR>1{z=z "\n" $0} NR==1{z=z $0} END{print "[\x27"z (x-y) "," x "\x27]"}'

```

I'm no `awk` master so I'm sure it can be improved. The takeaway is I had fun writing it! The struggle came with how to preserve the `newlines` from the input but not put the `, 7,10]` on a new line. That bit of logic (`NR>1{z=z "\n" $0} NR==1{z=z $0}`) cost me a lot of characters. I'd be interested to see any other `awk` approaches on that front.

I didn't provide the file at the end of the script, but obviously the usage would be `awk '{<code>}' ascii.txt`, where `ascii.txt` contains the mult-line "input".

## Output

```
 ['* * *
 * * * *
 * * *',7,10]

```
> 0 votes

# Answer
## Java, 199 bytes

Golfed:

```
class C{public static void main(String[]a){String i=a[0],o=i.replaceAll("\\S","*");System.out.println("["+o+","+g(i)+","+g(o)+"]");}static int g(String x){return x.replaceAll("[^\\*]","").length();}}

```

Un-golfed:

```
public class CountingStars {

    public static void main(String[] args) {
        String input = args[0];
        //replace all non-white-space char with *
        String output = input.replaceAll("\\S", "*");
        System.out.println("[" + output + "," + getStars(input) + "," + getStars(output) +"]");
    }

    static int getStars(String x) {
        //replace all non-* characters with empty-string and return length
        return x.replaceAll("[^\\*]", "").length();
    }
}

```

Run online.
> 0 votes

# Answer
# Zsh `-F`, 44 bytes

```
T(){tr -dc *|wc -c}
T<f
tr<f -c '
 ' *>g
T<g

```

Try it online!

Input from a file `f`, output to stdout and a file `g`

Ungolfed and commented:

```
T () {        # define a function T
  tr -dc *  \ # keep only the asterisks in the input
    | wc -c   # count characters
}
T < f         # apply T to the file f
tr        \   # replace
  -c      \   # everything except
  '\n '   \   # spaces or newlines
  *       \   # with asterisks
  < f     \   # input from the file f
  > g         # output to the file g
T < g         # apply T to the file g

```

`-F` prevents the `*` from being interpreted specially
> 0 votes

---
Tags: code-golf
---


title: Expand Comparison Chains

text:
# Question
Title: Expand Comparison Chains
Unlike most languages, Python evaluates `a<b<c` as it would be done in mathematics, actually comparing the three numbers, as opposed to comparing the boolean `a<b` to `c`. The correct way to write this in C (and many others) would be `a<b && b<c`.

In this challenge, your task is to expand such comparison chains of arbitrary lengths from the Python/intuitive representation, to how it would be written in other languages.

# Specifications

* Your program will have to handle the operators: `==, !=, <, >, <=, >=`.
* The input will have comparison chains using only integers.
* Don't worry about the trueness of any of the comparisons along the way, this is purely a parsing/syntactical challenge.
* The input won't have any whitespace to prevent answers that trivialize parsing by splitting on spaces.
* However, your output may have a single space surrounding either just the `&&`'s, or both the comparison operators and the `&&`'s, or neither, but be consistent.

# Test Cases

```
Input                  Output
---------------------------------------------------------------

3<4<5                  3<4 && 4<5
3<4<5<6<7<8<9          3<4 && 4<5 && 5<6 && 6<7 && 7<8 && 8<9
3<5==6<19              3<5 && 5==6 && 6<19
10>=5<7!=20            10>=5 && 5<7 && 7!=20
15==15==15==15==15     15==15 && 15==15 && 15==15 && 15==15

```

This is , so shortest code in **bytes** wins!

# Answer
> 6 votes
# Retina, ~~33~~ ~~22~~ 17 bytes

*-5 bytes thanks to @MartinEnder*

```
-2`\D(\d+)
$&&&$1

```

Try it online!

# Answer
> 5 votes
# Husk, ~~16~~ 14 bytes

Prints a space around each operator.

```
wJ"&&"m←C2X3ġ±

```

Try it online!

### Explanation:

```
                  Implicit input, e.g            "3<4<5<6"
            ġ±    Group digits                   ["3","<","4","<","5","<","6"]
          X3      Sublists of length 3           [["3","<","4"],["<","4","<"],["4","<","5"],["<","5","<"],["5","<","6"]]
        C2        Cut into lists of length 2     [[["3","<","4"],["<","4","<"]],[["4","<","5"],["<","5","<"]],[["5","<","6"]]]
      m←          Take the first element of each [["3","<","4"],["4","<","5"],["5","<","6"]]
 J"&&"            Join with "&&"                 ["3","<","4","&&","4","<","5","&&","5","<","6"]
w                 Print, separates by spaces

```

# Answer
> 3 votes
# Retina, ~~42~~ ~~47~~ 22 bytes

Massively golfed thanks to Kevin Cruijssen

```
(\D(\d+))(?=\D)
$1&&$2

```

Try it online!

# Answer
> 2 votes
# , 37 bytes

```
òÍ¨ä«„0-9& ]«©¨ä«©¨„0-9& ]«©/±² ¦¦ ²³

```

Try it online!

Hexdump:

```
00000000: f2cd a8e4 ab84 302d 3926 205d aba9 a8e4  ......0-9& ]....
00000010: aba9 a884 302d 3926 205d aba9 2fb1 b220  ....0-9& ]../..
00000020: a6a6 20b2 b3                             .. ..

```

# Answer
> 2 votes
## Clojure, 88 bytes

Update: `subs` instead of `clojure.string/join`.

```
#(subs(apply str(for[p(partition 3 2(re-seq #"(?:\d+|[^\d]+)" %))](apply str" && "p)))4)

```

# Answer
> 2 votes
# , ~~59~~ 46 bytes

```
4(}.;)_2{.\3' && '&;\]</.~0+/\@,2~:/\e.&'!<=>'

```

Try it online!

### How it used to work

```
                        (0 , }. ~:&(e.&'!<=>') }:)

```

We’re looking for operator boundaries. “Beheaded” and “curtailed” strings are turned into zeroes and ones where 0s are digits, then xored together. Prepend zero to match the length.

```
                   +/\                      </. ]     Split on boundaries.
              ┌──┬──┬─┬─┬─┬──┬──┐
              │10│>=│5│<│7│!=│20│
              └──┴──┴─┴─┴─┴──┴──┘
         3' && '&;\          Add && to infixes of 3.
              ┌────┬──┬──┬──┐
              │ && │10│>=│5 │
              ├────┼──┼──┼──┤
              │ && │>=│5 │< │
              ├────┼──┼──┼──┤
              │ && │5 │< │7 │
              ├────┼──┼──┼──┤
              │ && │< │7 │!=│
              ├────┼──┼──┼──┤
              │ && │7 │!=│20│
              └────┴──┴──┴──┘
    _2{.\                    Take even numbered rows.
;}.,                         Concatenate after dropping the first box.

```

# Answer
> 1 votes
# Charcoal, 29 bytes

```
≔ ηＦθ«¿›ι9«Ｆ›η!⁺&&η≔ωη»≔⁺ηιηι
≔ ηＦθ«Ｆ∧›ι9›η!⁺&&η≔⎇›ι9ω⁺ηιηι

```

Two slightly different formulations of the same basic algorithm. The input string is iterated by character. As digits are found they are collected in a variable. When a boundary between a number and operator is found, an extra "&&" plus the variable is printed and the variable is cleared. The variable is initially initialised to a space so that the first boundary doesn't trigger the extra "&&".

# Answer
> 1 votes
# Jelly, 16 bytes

```
e€ØDŒg⁸ṁṡ3m2j⁾&&

```

Try it online!

Explanation:

```
e€ØDŒg⁸ṁṡ3m2j⁾&& Uses Jelly stringification, thus full program only
e€ØD             For each each char, 1 if it's in '0123456789', otherwise 0
    Œg           Split into longest runs of equal elements
      ⁸ṁ         Reshape original input like the list we just made
                 Reshaping will separate numbers from operators
        ṡ3       Get contiguous sublists of length 3
          m2     Keep every second item, starting from the first
                 This will keep every (number operator number) and
                 remove every (operator number operator) substring
            j⁾&& Join with '&&'

```

# Answer
> 1 votes
# Java 8, 46 bytes

```
s->s.replaceAll("(\\D(\\d+))(?=\\D)","$1&&$2")

```

**Explanation:**

Try it here.

```
s->                       // Method with String as both parameter and return-type
   s.replaceAll("(\\D(\\d+))(?=\\D)",
                "$1&&$2") //  Replace the match of the regex
                          //  with the second String
                          // End of method (implicit / single-line return-statement)

```

Regex explanation:

```
(\D(\d+))(?=\D)   # 1) For all matches of this regex
   (\d+)          #  Capture group 2: a number (one or more digits)
(\D \d+ )         #  Capture group 1: anything but a number + the number
                  #   (`\D` will match the `=`, `!`, `<`, or `>`)
         (?=\D)   #  Look-ahead so everything after the match remains as is

 $1&&$2           # 2) Replace it with
 $1               #  Result of capture group 1 (trailing part of the equation + the number)
   &&             #  Literal "&&"
     $2           #  Result of capture group 2 (the number)

```

Step by step example of the replacements:

```
Initial:                             10>=5<7!=20
 Match of first replacement:            =5
 Replace with:                          =5&&5
After first replacement:             10>=5&&5<7!=20
 Match of second replacement:                <7
 Replace with:                               <7&&7
After second replacement (result):   10>=5&&5<7&&7!=20

```

# Answer
> 0 votes
# Perl 5, 47 + 1 (-p) = 48 bytes

```
$\.=$1." && "x(!!$')while s/(\d+\D+(\d+))/$2/}{

```

Try it online!

# Answer
> 0 votes
# Python 2, ~~60~~ ~~59~~ ~~58~~ 57 bytes

```
lambda s:re.sub(r'(\D(\d+))(?=\D)',r'\1&&\2',s)
import re

```

Try it online!

# Answer
> 0 votes
# Ruby, 37 bytes

```
->s{s.gsub(/\D(\d+)(?=\D)/,'\&&&\1')}

```

Try it online!

# Answer
> 0 votes
# JavaScript (SpiderMonkey), 43 bytes

```
f=s=>s.replace(/(\W+(\d+))(?!$)/g,"$1&&$2")

```

Try it online!

# Answer
> 0 votes
# Jelly, 15 bytes

```
e€ØDnƝkṡ3m2j⁾&&

```

Try it online!

Outputs with no spaces around the `&&`, but the Footer in the TIO link adds the spaces to make the output easier to read

## How it works

```
e€ØDnƝkṡ3m2j⁾&& - Main link. Takes a string S on the left
e€ØD            - Replace digits with 1, otherwise 0
     Ɲ          - To overlapping pairs [a,b]:
    n           -   a ≠ b
      k         - Split S on truthy elements, grouping digits together
       ṡ3       - Split into overlapping lists of length 3
         m2     - Take every other element
           j⁾&& - Join by "&&"

```

---
Tags: code-golf, parsing, conversion, syntax
---


# Question
Title: Abstract Syntax Tree Golfing: FizzBuzz, Python
## Summary

Implement FizzBuzz in Python, with the fewest possible tokens.

## Challenge

Write a program that prints the decimal numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Programs must be written in some version of Python.

For more details, see 1, 2, Fizz, 4, Buzz

## Scoring

Your score will be equal to the number of nodes in the abstract syntax tree of your code, as reported by this program for Python 3, or this program for Python 2. To run the programs, provide the filename of your code as command line argument to the program. For instance:

```
python simple_counter.py fizzbuzz.py

```

These programs are based off of Python's ast module. If you have any difficulty, let me know.

To prevent trivial solutions, such as executing a long string with the actual program, or hardcoding the output, there are some additional restrictions:

* No token in your code may be longer than 15 characters. The above programs will check this requirement for you. Note that for ease of implementation, the above programs count comments as tokens.
* Code execution/evaluation is banned.

If you have questions as to whether something is allowed, ask me.

## Scoring Heuristics

The following rules are typically enough to calculate the score of your program:

* Block statements are 1 points: `if`, `for ... in ...`, `while`, `else`, etc.
* Standalone statements are 1 point: `print` in Python 2, `break`, `pass`, etc.
* Variables are 2 points
* Single-token literals are 1 point: `2131`, `"Hello, world!"`, `True`
* Functions are 3 points (2 for using a variable, 1 extra): `print` in Python 3, `range`, etc.
* Operators are 2 points: `+`, `*`, `%`, `and`, `not`, etc.
* `=` is 1 point
* Augmented assignment is 2 points: `+=`, `|=`, etc.
* Parentheses, indentation, etc. are 0 points.
* A line containing an expression, as opposed to an assignment or an expression, is + 1 point.
* Having code at all is 1 point.

## Challenge:

The lowest score wins. Good luck!

# Answer
> 10 votes
# 33

**Python 2**

```
for i in range(1,101):print[i,'Fizz','Buzz','FizzBuzz'][int(`300102100120100`[i%15])]

```

# Answer
> 4 votes
# 46

```
for x in range(100):print('Fizz'*(x%3>1)+'Buzz'*(x%5>3)or str(x+1))

```

# Answer
> 4 votes
# ~~39~~ 34

```
for i in range(1,101):print [i,'Fizz','Buzz','FizzBuzz'][19142723>>2*(i%15)&3]

```

# Answer
> 4 votes
# Python 3, 35

```
for x in range(1,101): print(('' if x%3 else 'Fizz') + ('' if x%5 else 'Buzz') or x)

```

# Answer
> 2 votes
# Python 2, 36

```
for i in range(1, 101):
    print (not i % 3) * "Fizz" + (not i % 5) * "Buzz" or i

```

I think this is the shortest of the approaches that don't use large numbers / strings.

---
Tags: python, fizzbuzz, atomic-code-golf
---


# Question
Title: Finding The nth Prime such that the prime - 1 is divisible by n
## Problem

The goal is as the title says to find the \\$n\\$th prime such that \\$\text{the prime}-1\\$ is divisible by \\$n\\$.

## Explanation

Here is an example so you understand the question, *this is not necessarily the way it ought to be solved. It merely as a way to explain the question*

given \\$3\\$ as an input we would first look at all the primes

```
 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 ...

```

Then we select the primes such that \\$\text{the prime}-1\\$ is divisible by \\$n\\$ (3 in this case)

```
 7 13 19 31 37 43 61 67 73 79 97 103 107 109 127 ...

```

We then select the \\$n\\$th term in this sequence

We would output \\$19\\$ for an input of \\$3\\$

## Note

We can also think of this as the \\$n\\$th prime in the sequence \\$\\{1, n + 1, 2n + 1, 3n + 1 ...kn + 1\\}\\$ where \\$k\\$ is any natural number

## Test Cases

```
  1 --> 2
  2 --> 5
  3 --> 19
  4 --> 29
100 --> 39301
123 --> 102337

```

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

05AB1E uses CP-1252 encoding.

Saved a byte thanks to *Osable*

```
µN¹*>Dp½

```

Try it online!

**Explanation**

```
µ          # for N in [1 ...] loop until counter == input
 N¹*>      # N*input+1 (generate multiples of input and increment)
     D     # duplicate
      p½   # if prime, increase counter
           # implicitly output last prime

```
> 9 votes

# Answer
# Python 2, 58 bytes

```
n=N=input();m=k=1
while N:m*=k*k;k+=1;N-=m%k>~-k%n
print k

```
> 7 votes

# Answer
## Haskell, ~~59~~ 47 bytes

```
f n=[p|p<-[1,n+1..],all((<2).gcd p)[2..p-1]]!!n

```

Usage example: `f 4` -\> `29`.

How it works:

```
[p|p<-[1,n+1..]                     ]    -- make a list of all multiples of n+1
                                         -- (including 1, as indexing is 0-based)
           ,all((<2).gcd p)[2..p-1]      -- and keep the primes
                              !!n       -- take the nth element

```

Edit: Thanks @Damien for 12 bytes by removing the divisibility test and only looking at multiples in the first place.
> 5 votes

# Answer
# Mathematica, 48 bytes

```
Select[Array[Prime,(n=#)^3],Mod[#-1,n]==0&][[n]]&

```

Unnamed function taking a single argument, which it names `n`. Generates a list of the first `n^3` primes, selects the ones that are congruent to 1 modulo `n`, then takes the `n`th element of the result. It runs in several seconds on the input 123.

It's not currently known if there's always even a single prime, among the first `n^3` primes, that is congruent to 1 modulo `n`, much less `n` of them. However, the algorithm can be proved correct (at least for large `n`) under the assumption of the generalized Riemann hypothesis!
> 5 votes

# Answer
# Jelly, 9 bytes

```
‘ÆP>%ð#Ṫ‘

```

Try it online!

### How it works

```
‘ÆP>%ð#Ṫ‘  Main link. Argument: n

     ð#    Call the dyadic chain to the left with right argument n and left
           argument k = n, n+1, n+2, ... until n of them return 1.
‘          Increment; yield k+1.
 ÆP        Test k+1 for primality, yielding 1 or 0.
    %      Compute k%n.
   >       Compare the results to both sides, yielding 1 if and only if k+1 is
           prime and k is divisible by n.
       Ṫ   Tail; extract the last k.
        ‘  Increment; yield k+1.

```
> 3 votes

# Answer
# Java 7, 106 bytes

```
int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}}

```

**Ungolfed:**

```
int c(int n){
  for(int z = 1, i = 2, j, x; ; i++){
    x = i;
    for(j = 2; j < x; x = x % j++ < 1
                           ? 0
                           : x);
    if(x > 1 & (i-1) % n < 1 && z++ == n){
      return i;
    }
  }
}

```

**Test code:**

Try it here (last test case results in a *Time limit exceeded* on ideone)

```
class M{
  static int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}}

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(2));
    System.out.println(c(3));
    System.out.println(c(4));
    System.out.println(c(100));
    System.out.println(c(123));
  }
}

```

**Output:**

```
2
5
19
29
39301
102337

```
> 3 votes

# Answer
**Nasm 679 bytes (Instruction Intel 386 cpu 120 bytes)**

```
isPrime1:
push ebp
mov ebp,dword[esp+ 8]
mov ecx,2
mov eax,ebp
cmp ebp,1
ja .1
.n: xor eax,eax
jmp short .z
.1: xor edx,edx
cmp ecx,eax
jae .3
div ecx
or edx,edx
jz .n
mov ecx,3
mov eax,ebp
.2: xor edx,edx
cmp ecx,eax
jae .3
mov eax,ebp
div ecx
or edx,edx
jz .n
inc ecx
inc ecx
jmp short .2
.3: xor eax,eax
inc eax
.z: pop   ebp
ret 4
Np:
push esi
push edi
mov esi,dword[esp+ 12]
xor edi,edi
or esi,esi
ja .0
.e: xor eax,eax
jmp short .z
.0: inc esi
jz .e
push esi
call isPrime1
add edi,eax
dec esi
cmp edi,dword[esp+ 12]
jae .1
add esi,dword[esp+ 12]
jc .e
jmp short .0
.1: mov eax,esi
inc eax
.z: pop edi
pop esi
ret 4

```

this is ungolfed one and the results

```
;0k,4ra,8Pp
isPrime1:
          push    ebp
          mov     ebp,  dword[esp+  8]
          mov     ecx,  2
          mov     eax,  ebp
          cmp     ebp,  1
          ja      .1
.n:       xor     eax,  eax
          jmp     short  .z
.1:       xor     edx,  edx
          cmp     ecx,  eax
          jae     .3
          div     ecx
          or      edx,  edx
          jz      .n
          mov     ecx,  3
          mov     eax,  ebp
.2:       xor     edx,  edx
          cmp     ecx,  eax
          jae     .3
          mov     eax,  ebp
          div     ecx
          or      edx,  edx
          jz      .n
          inc     ecx
          inc     ecx
          jmp     short  .2
.3:       xor     eax,  eax
          inc     eax
.z:
          pop     ebp
          ret     4

; {1, n+1, 2n+1, 3n+1 }
; argomento w, return il w-esimo primo nella successione di sopra
;0j,4i,8ra,12P
Np:
          push    esi
          push    edi
          mov     esi,  dword[esp+  12]
          xor     edi,  edi
          or      esi,  esi
          ja      .0
.e:       xor     eax,  eax
          jmp     short  .z
.0:       inc     esi
          jz      .e
          push    esi
          call    isPrime1
          add     edi,  eax
          dec     esi
          cmp     edi,  dword[esp+  12]
          jae     .1
          add     esi,  dword[esp+  12]
          jc      .e
          jmp     short  .0
.1:       mov     eax,  esi
          inc     eax
.z:
          pop     edi
          pop     esi
          ret     4

00000975  55                push ebp
00000976  8B6C2408          mov ebp,[esp+0x8]
0000097A  B902000000        mov ecx,0x2
0000097F  89E8              mov eax,ebp
00000981  81FD01000000      cmp ebp,0x1
00000987  7704              ja 0x98d
00000989  31C0              xor eax,eax
0000098B  EB28              jmp short 0x9b5
0000098D  31D2              xor edx,edx
0000098F  39C1              cmp ecx,eax
00000991  731F              jnc 0x9b2
00000993  F7F1              div ecx
00000995  09D2              or edx,edx
00000997  74F0              jz 0x989
00000999  B903000000        mov ecx,0x3
0000099E  89E8              mov eax,ebp
000009A0  31D2              xor edx,edx
000009A2  39C1              cmp ecx,eax
000009A4  730C              jnc 0x9b2
000009A6  89E8              mov eax,ebp
000009A8  F7F1              div ecx
000009AA  09D2              or edx,edx
000009AC  74DB              jz 0x989
000009AE  41                inc ecx
000009AF  41                inc ecx
000009B0  EBEE              jmp short 0x9a0
000009B2  31C0              xor eax,eax
000009B4  40                inc eax
000009B5  5D                pop ebp
000009B6  C20400            ret 0x4
68

000009B9  56                push esi
000009BA  57                push edi
000009BB  8B74240C          mov esi,[esp+0xc]
000009BF  31FF              xor edi,edi
000009C1  09F6              or esi,esi
000009C3  7704              ja 0x9c9
000009C5  31C0              xor eax,eax
000009C7  EB1D              jmp short 0x9e6
000009C9  46                inc esi
000009CA  74F9              jz 0x9c5
000009CC  56                push esi
000009CD  E8A3FFFFFF        call 0x975
000009D2  01C7              add edi,eax
000009D4  4E                dec esi
000009D5  3B7C240C          cmp edi,[esp+0xc]
000009D9  7308              jnc 0x9e3
000009DB  0374240C          add esi,[esp+0xc]
000009DF  72E4              jc 0x9c5
000009E1  EBE6              jmp short 0x9c9
000009E3  89F0              mov eax,esi
000009E5  40                inc eax
000009E6  5F                pop edi
000009E7  5E                pop esi
000009E8  C20400            ret 0x4
000009EB  90                nop
120

[0, 0] [1, 2] [2, 5] [3, 19] [4, 29] [5, 71] [6, 43] [7, 211] [8, 193] [9, 271] [1
0, 191] [11, 661] [12, 277] [13, 937] [14, 463] [15, 691] [16, 769] [17, 1531] [18
, 613] [19, 2357] [20, 1021] [21, 1723] [22, 1409] [23, 3313] [24, 1609] [25, 3701
] [26, 2029] [27, 3187] [28, 2437] [29, 6961] [30, 1741] [31, 7193] [32, 3617] [33
, 4951] [34, 3877] [35, 7001] [36, 3169] [37, 10657] [38, 6271] [39, 7879] [40, 55
21] [41, 13613] [42, 3823] [43, 15137] [44, 7349] [45, 9091] [46, 7499] [47, 18049
] [48, 6529] [49, 18229] [50, 7151] [51, 13159] [52, 10141] [53, 26501] [54, 7669]
 [55, 19801] [56, 11593] [57, 18127] [58, 13109] [59, 32569] [60, 8221] [61, 34649
] [62, 17981] [63, 21799] [64, 16001] [65, 28081] [66, 10429] [67, 39799] [68, 193
81] [69, 29947] [70, 14771] [71, 47713] [72, 16417] [73, 51539] [74, 25013] [75, 2
9101] [76, 26449] [77, 50051] [78, 16927] [79, 54037] [80, 23761] [81, 41149] [82,
 31489] [83, 68891] [84, 19237] [85, 51341] [86, 33713] [87, 45589] [88, 34057] [8
9, 84551] [90, 19531] [91, 64793] [92, 42689] [93, 54499] [94, 41737] [95, 76001]
[96, 27457] [97, 97583] [98, 40867] [99, 66529] [100, 39301] [101, 110899] [102, 2
9989] [103, 116803] [104, 49297] [105, 51871] [106, 56711] [107, 126047] [108, 385
57] [109, 133853] [110, 42901] [111, 76369] [112, 53089] [113, 142607] [114, 40129
] [115, 109481] [116, 63337] [117, 83071] [118, 67733] [119, 112337] [120, 41281]
[121, 152219] [122, 70639] [123, 102337]

```
> 3 votes

# Answer
# Actually, 13 bytes

Golfing suggestions welcome! Try it online!

```
;╗`PD╜@%Y`╓NP

```

**Ungolfing**

```
         Implicit input n.
;╗       Save a copy of n to register 0.
`...`╓   Push first n values where f(x) is truthy, starting with f(0).
  PD       Get the x-th prime - 1.
  ╜@%      Push (x_p - 1) % n.
  Y        If x_p-1 is divisible by n, return 1. Else, return 0.
NP       Get the n-th prime where n_p-1 is divisible by n.
         Implicit return.

```
> 2 votes

# Answer
# Common Lisp, 162 bytes

```
(defun s(n)(do((b 2(loop for a from(1+ b)when(loop for f from 2 to(1- a)never(=(mod a f)0))return a))(a 0)(d))((= a n)d)(when(=(mod(1- b)n)0)(incf a)(setf d b))))

```

Usage:

```
* (s 100)

39301

```

Ungolfed:

```
(defun prime-search (n)
  (do ((prime 2 (loop for next from (1+ prime) when
                 (loop for factor from 2 to (1- next) never
                      (= (mod next factor) 0)) return next))
       (count 0) (works))
      ((= count n) works)
    (when (= (mod (1- prime) n) 0)
      (incf count)
      (setf works prime))))

```

Some of those `loop` constructs can probably be shortened into `do` loops, but this is what I've got for now.
> 2 votes

# Answer
# MATL, 12 bytes

```
1i:"`_YqtqG\

```

Try it online!

(For input `123` it times out in the online compiler, but it works offline.)

### Explanation

```
1          % Push 1
i:         % Input n and push [1 2 ... n]
"          % For each (that is, do the following n times)
  `        %   Do...while
    _Yq    %     Next prime
    tq     %     Duplicate, subtract 1
    G      %     Push n again
    \      %     Modulo
           %   End (implicit). Exit loop if top of stack is 0; else next iteration
           % End (implicit)
           % Display (implicit)

```
> 2 votes

# Answer
# Perl, ~~77~~ 76 + 1 = 77 bytes

```
for($p=2;@a<$_;$p++){push@a,$p if(1 x$p)!~/^(11+?)\1+$/&&($p%$_<2)}say$a[-1]

```

Uses the prime-testing regex to determine if `$p` is prime, and makes sure that it's congruent to 1 mod the input (the only nonnegative integers below 2 are 0 and 1, but it can't be 0 if it's prime, so it has to be 1. saves 1 byte over `==1`).
> 1 votes

# Answer
**Mathematica 44 Bytes**

```
   Pick[x=Table[i #+1,{i,# #}],PrimeQ/@x][[#]]&

```

Very fast. Uses the idea from the "Note"

```
% /@ {1, 2, 3, 4, 100, 123} // Timing

```

Output

```
{0.0156001, {2, 5, 19, 29, 39301, 102337}}

```
> 1 votes

# Answer
# Perl 6,  ~~46 39~~  37 bytes

```
->\n{(2..*).grep({.is-prime&&($_-1)%%n})[n-1]}

```

```
->\n{(1,n+1...*).grep(*.is-prime)[n-1]}

```

```
{(1,$_+1...*).grep(*.is-prime)[$_-1]}

```
> 1 votes

# Answer
# Java 8, 84 bytes

### Golfed

```
(n)->{for(int s=n,i=1;;i+=n)for(int j=2;i%j>0&j<i;)if(++j==i&&--s<1)return n>1?i:2;}

```

### Ungolfed

```
(n) -> {
for (int s = n,      // Counting down to find our nth prime.
    i = 1;           // Counting up for each multiple of n, plus 1.
    ;                // No end condition specified for outer for loop.
    i += n)          // Add n to i every iteration.
for (int j = 2;      // Inner for loop for naive primality check.
     i % j > 0)      // Keep looping while i is not divisible by j
                     // (and implicitly while j is less than i).
     if(++j==i       // Increment j. If j has reached i, we've found a prime
     &&              // Short-circutting logical AND, so that we only decrement s if a prime is found
     --s < 1)        // If we've found our nth prime...
     return n>1?i:2; // Return it. Or 2 if n=1, because otherwise it returns 3.
}

```

## Explanation

Solution inspired by several other answers. Function is a lambda that expects a single int.

The `n>1?i:2` is a cheap hack because I couldn't figure out a better way to consider the case of n=1.

Also, this solution times out on Ideone, but has been tested for all test cases. It times out because in order to shave a couple bytes off, I took out the explicit `j<i` check in the inner loop. It's mostly implied by `i%j>0`... except in the case of `i=1` and `j=2` (the very first iteration), in which case the loop runs until j overflows (I'm assuming). Then it works fine for all iterations afterwards.

For a version that doesn't time out that's a couple bytes longer, see here!
> 0 votes

# Answer
## Racket 109 bytes

```
(let p((j 2)(k 0))(cond[(= 0(modulo(- j 1)n))(if(= k(- n 1))j(p(next-prime j)(+ 1 k)))][(p(next-prime j)k)]))

```

Ungolfed:

```
(define (f n)
  (let loop ((j 2)
             (k 0))
    (cond
      [(= 0 (modulo (sub1 j) n))
       (if (= k (sub1 n))
           j
           (loop (next-prime j) (add1 k)))]
      [else (loop (next-prime j) k)]  )))

```

Testing:

```
(f 1)
(f 2)
(f 3)
(f 4)
(f 100)
(f 123)

```

Output:

```
2
5
19
29
39301
102337

```
> 0 votes

# Answer
## Ruby 64 bytes

```
require'prime';f=->(n){t=n;Prime.find{|x|(x-1)%n==0&&(t-=1)==0}}

```

Called like this:

```
f.call(100)
# 39301

```

Also, this command-line app works:

```
n=t=ARGV[0].to_i;p Prime.find{|x|(x-1)%n==0&&(t-=1)==0}

```

called like this

```
ruby -rprime find_golf_prime.rb 100

```

but I am not so sure how to count the characters. I think I can ignore the language name, but have to include the `-rprime` and space before the script name, so that is slightly shorter, at 63 . . .
> 0 votes

# Answer
## R, 72 bytes

```
n=scan();q=j=0;while(q<n){j=j+1;q=q+1*(numbers::isPrime(j)&!(j-1)%%n)};j

```

Terribly inefficient and slow but it works. It reads input from stdin and then uses the `isPrime` function from the `numbers` package to find the primes. The rest is just checking whether `prime - 1` is divisible by `n`.
> 0 votes

# Answer
## JavaScript (ES6), 65 bytes

```
f=(n,i=n,j=1)=>i?f(n,i-!/^(..+?)\1+$/.test('.'.repeat(j+=n)),j):j

```

Uses the regexp primality tester, since it's a) 8 bytes shorter and b) less recursive than my pure recursive approach.
> 0 votes

# Answer
**Axiom 64 bytes**

```
f(n)==(n<0 or n>150=>0;[i*n+1 for i in 0..2000|prime?(i*n+1)].n)

```

does someone know how to write above using Axiom streams?... some example

```
-> f(i)  for i in 1..150
   Compiling function f with type PositiveInteger -> NonNegativeInteger

   [2, 5, 19, 29, 71, 43, 211, 193, 271, 191, 661, 277, 937, 463, 691, 769,
    1531, 613, 2357, 1021, 1723, 1409, 3313, 1609, 3701, 2029, 3187, 2437,
    6961, 1741, 7193, 3617, 4951, 3877, 7001, 3169, 10657, 6271, 7879, 5521,
    13613, 3823, 15137, 7349, 9091, 7499, 18049, 6529, 18229, 7151, 13159,
    10141, 26501, 7669, 19801, 11593, 18127, 13109, 32569, 8221, 34649, 17981,
    21799, 16001, 28081, 10429, 39799, 19381, 29947, 14771, 47713, 16417,
    51539, 25013, 29101, 26449, 50051, 16927, 54037, 23761, 41149, 31489,
    68891, 19237, 51341, 33713, 45589, 34057, 84551, 19531, 64793, 42689,
    54499, 41737, 76001, 27457, 97583, 40867, 66529, 39301, 110899, 29989,
    116803, 49297, 51871, 56711, 126047, 38557, 133853, 42901, 76369, 53089,
    142607, 40129, 109481, 63337, 83071, 67733, 112337, 41281, 152219, 70639,
    102337, 75641, 126001, 42589, 176531, 85121, 107071, 62791, 187069, 55837,
    152419, 94873, 104761, 92753, 203857, 62929, 226571, 72661, 144103, 99401,
    193051, 69697, 168781, 112859, 133183, 111149, 250619, 60601]

```

## Type: Tuple NonNegativeInteger
> 0 votes

# Answer
# Husk, ~~9~~ 8 bytes

```
!⁰fṗ¡+⁰1

```

Try it online!

```
!⁰         # get the input-th element of
  fṗ       # the elements that are primes among
    ¡      # the list formed by repeatedly
     +⁰    # adding the input to the last result
       1   # starting with 1.

```
> 0 votes

---
Tags: code-golf, number, number-theory, primes
---


# Question
Title: Return each number from a group of numbers
## The challenge

The program must return all numbers included into a group (comma and hyphen separated sequence) of numbers.

## Rules

* `s` is the sequence string;
* all numbers included in `s` are **positive**;
* numbers will always **increase**;
* numbers will **never repeat**
* when you answer, show the output for `s="1,3-5,9,16,18-23"`

## Examples

```
input(s)    outputs
-----------------
1           1
1,2         1,2
1-4         1,2,3,4
1-4,6       1,2,3,4,6
1-4,8-11    1,2,3,4,8,9,10,11

```

Good luck. =)

# Answer
## GolfScript (24 chars)

```
','/{~.,!{~)),>~}*}%','*

```

E.g.

```
$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

```

I actually have four 24-char solutions, but I chose this one because it doesn't have any alphanumeric characters.

### How it works

```
# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
    # This is executed for each of those strings in a map
    # So stack holds e.g. "1" or "3-5"

    # Evaluate the string.
    # If it's a single number, this puts the number on the stack.
    # Otherwise it's parsed as a positive number followed by a negative number.
    ~
    # Stack holds e.g. 1 or 3 -5
    # Duplicate the last element on the stack and make a list of that length.
    # If it's negative or zero, the list will be empty
    .,
    # Negate. An empty list => 1; a non-empty list => 0
    !
    # If the string was a single number "n", the stack now holds n 0
    # If the string was a range "m-n", the stack now holds m -n 1
    # The following block will be executed 0 times for "n" and once for "m-n"
    {
        # Here we rely on twos-complement numbers satisfying ~n = -n -1
        # Stack: m -n
        ~))
        # Stack: m -(-n)-1+2  =  m n+1
        ,
        # Stack: m [0 1 2 ... n]
        >
        # Stack: [m m+1 ... n]
        ~
        # Stack: m m+1 ... n
    }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output

```
> 6 votes

# Answer
## Perl 25 26 25

`$_` is the sequence string

```
s/-/../g;$_=join",",eval

```

Sample session:

```
[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

```

Added 1 character to the character count for the `-n``-p` option (thanks Gareth, ..kinda).
> 7 votes

# Answer
## golfscript, 46 45

My first ever golf script program, took hours to complete.

```
{','/{'-'/{~}%.,1-{))+{,}/\-~}{~}if}%","*}:r;

# call:
"1,3-5,9,16,18-23"r

# return:
1,3,4,5,9,16,18,19,20,21,22,23

```

You can try it at http://golfscript.apphb.com/

My best throw at explaining this atrocity:

```
{...}:r;     # makes a function block ... and names it r

','/         # slices the top element of stack from each ','
             # so we get ["1" "3-5" "9" "16" "18-23"]

{...}%       # makes a function block ... and calls it for
             # each element in the list

'-'/{~}%     # slices the list by '-' and evals each element
             # from string to int. ["1"] becomes [1],
             # ["3-5"] becomes [3 5]

.,1-         # adds the length of the list -1 on top of the stack
             # so for [1] the stack becomes [1] 0, for [3 5]
             # it becomes [3 5] 1

# next we add two function blocks, they, like the 0/1 just before
# are used by an if clause a tiny bit later. First block is for
# lists that have a 1 on top of them, the latter for ones with 0.

# First block, we have something like [3 5]

))+          # pops the top element of the array, increments
             # it and puts back. [3 6]

## It seems {...}%~ is same as {...}/
## this is why these two are not in the code any more

{,}%         # , makes a list from 0 to n-1, where n is the parameter
             # so we get [[0 1 2] [0 1 2 3 4 5]]

~            # Dumps the outer array, [0 1 2] [0 1 2 3 4 5]

\            # swaps the two arrays

-            # set complement [3 4 5]

~            # dumps the array, so the elements are left in the stack

# Second block, we have something like [16]

~            # just dumps the array, 16

# Blocks end

if           # takes the top three elements of the stack, evaluates the
             # first (0 or 1), runs second if true (anything but
             # [], "", 0 or {} ), otherwise the third.

","*         # joins an array with ","

```

**edit 1:** changed the last {}%~ to {}/, also my description was likely wrong.
> 4 votes

# Answer
# , 44 bytes

```
`-`=seq;eval(parse(t=c("c(",scan(,""),")")))

```

Try it online!

Redefine `-` to mean `seq` (i.e. `:`), surround the input with `c()` and evaluate the corresponding expression.
> 4 votes

# Answer
# K, 47

```
","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0

```

Test case

```
k)","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0
1,3-5,9,16,18-23
"1,3,4,5,9,16,18,19,20,21,22,23"

```
> 3 votes

# Answer
# Jelly, 9 bytes

```
⁾-ryṣ”,VF

```

Try it online!

```
   y         Replace
⁾-r          hyphens with the letter r,
    ṣ”,      split on commas,
       V     evaluate every element,
        F    and flatten.

```

The range dyad `r` takes two arguments on either side of it and produces an inclusive range between them.
> 3 votes

# Answer
## J, 53 43 41 39 38 characters

```
;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1

```

Takes input from the keyboard:

```
   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1-4,8-11
1 2 3 4 8 9 10 11

```

Output for the requested test case:

```
   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1,3-5,9,16,18-23
1 3 4 5 9 16 18 19 20 21 22 23

```
> 2 votes

# Answer
# Hassium, 173 Bytes

This was pretty long and might not be competing since there is a trailing , at the end.

```
 func main(){p="1,2,3,5-8".split(",")for(c=0;c<p.length;c++){e=p[c]if(e.contains("-")){p=e.split("-")for(x=p[0].toInt();x<=p[1].toInt()print(x++ +",")){}}else print(e+",")}}

```

Run online and see expanded here
> 2 votes

# Answer
## Perl (37)

```
$_=<>;s/^/say join',',/;s/-/../g;eval

```
> 1 votes

# Answer
## PowerShell, ~~79~~ 71 bytes

```
('('+($args[0]-replace'-','..'-replace',','),(')+')'|iex|%{$_})-join','

```

Try it online!

The inner part changes "1,5-9,12" into a "(1),(5..9),(12)" format that PowerShell understands, then executes that with iex, which creates an array of arrays. Then iterate through each inner array, then finally join all outer array elements together

Borrows code from my "Help Me Manage My Time" answer

### Usage

```
PS C:\Tools\Scripts\golfing> .\return-each-number-from-a-group-of-numbers.ps1 '1,3-5,9,16,18-23'
1,3,4,5,9,16,18,19,20,21,22,23

```

*-8 bytes thanks to Veskah*
> 1 votes

# Answer
## Python 2.7, 147 138 Bytes

```
z,f=input().split(','),[]
for i in z:
 x=i.split('-')
 if len(x)>1:f+=range(int(x[0]),int(x[1])+1)
 else:f+=[int(x[0])]
print str(f)[1:-1]

```

Usage:

```
>>>python nums.py
"1,3-5,9,16,18-23"
1, 3, 4, 5, 9, 16, 18, 19, 20, 21, 22, 23

```

Not the best program...
> 1 votes

# Answer
## MATLAB, 47 bytes

```
disp(eval(['[',strrep(input(''),'-',':'),']']))

```

This snippet reads a string input from the command window, replaces '-' by ':', adds square brackets to the string and then evaluates it, so that the input will be expanded to a full array of numbers.

Example input:

```
'1,3-5,9,16,18-23'

```

Example output:

```
1     3     4     5     9    16    18    19    20    21    22    23

```

I believe this output is allowed, as the challenge only say that all numbers in a group should be displayed.
> 1 votes

# Answer
## Perl 6, 36 bytes

```
$_=get;say join ',',EVAL S:g/\-/../

```

```
1,3,4,5,9,16,18,19,20,21,22,23

```
> 1 votes

# Answer
# K (oK), ~~40~~ 31 bytes

**Solution**

```
,/{{x+!1+y-x}. 2#.:'"-"\x}'","\

```

Try it online!

**Explanation:**

Managed more golfing whilst adding the explanation...

```
,/{{x+!1+y-x}. 2#.:'"-"\x}'","\ / the solution
                           ","\ / split input on ","
  {                      }'     / apply lambda to each
                    "-"\x       / split x on "-"
                 .:'            / value (.:) each (')
               2#               / 2 take (dupe if only 1 element)
   {        }.                  / diadic lambda, 2 args x and y
         y-x                    / y subtract x
       1+                       / add 1
      !                         / range 0..n
    x+                          / add x
,/                              / flatten

```
> 1 votes

# Answer
# Husk, 11 bytes

```
ṁȯ…mix'-x',

```

Try it online!
> 1 votes

# Answer
## Clojure, 110 bytes

```
#(clojure.string/join","(for[s(.split %",")[a b][(map read-string(.split s"-"))]r(if b(range a(inc b))[a])]r))

```

Dealing with strings isn't much fun :(
> 0 votes

# Answer
# Python 2, 112 bytes

Pretty simple and straightforward answer.

```
L=[]
for s in input().split(','):
 if'-'in s:a,b=map(int,s.split('-'));L+=range(a,b+1)
 else:L+=[int(s)]
print L

```

Try it online!
> 0 votes

# Answer
# Ruby `-p`, 33 bytes

```
gsub(/(\d+)-(\d+)/){[*$1..$2]*?,}

```

Try it online!
> 0 votes

# Answer
# Japt, 12 bytes

```
q, c@OvXr-'ò

```

Try it
> 0 votes

# Answer
# Python 2, 90 bytes

```
lambda s:sum((range(u[0],u[-1]+1)for u in[map(int,t.split('-'))for t in s.split(',')]),[])

```

Try it online!
> 0 votes

# Answer
## Lua (126 bytes)

Just for fun:

```
(("1,3-5,9,16,18-23"):gsub("(%d+)-(%d+)",function(a,b)t={}for i=a,b do t[#t+1]=math.ceil(i)end return table.concat(t,",")end))

```
> 0 votes

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


title: Pythagorean Triple Sequence

text:
# Question
Title: Pythagorean Triple Sequence
> A Pythagorean triple consists of three positive integers a, b, and c, such that a2 \+ b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5). If (a, b, c) is a Pythagorean triple, then so is (ka, kb, kc) for any positive integer k. A primitive Pythagorean triple is one in which a, b and c are coprime.

Using this knowledge, we can create a sequence by chaining together the least lengths of triples, where the next element in the sequence is the hypotenuse (largest number) of the smallest primitive Pythagorean triple containing the previous element as the smallest one of its lengths.

Start with the smallest primitive Pythagorean triple (3, 4, 5). The sequence begins with `3`, and the hypotenuse (next element in the sequence) is `5`. Then find the smallest primitive Pythagorean triple with `5` as a leg, and you get (5, 12, 13). So the sequence continues with `13`.

Either output the sequence forever, or take an integer input `n` and output the first `n` elements of the sequence, either zero or one indexed.

You need to support output at least through and including `28455997`, but if the limit of the data type you are using was suddenly raised, it would need to work for that new limit. So you cannot hard code a list of numbers.

```
3
5
13
85
157
12325
90733
2449525
28455997
295742792965
171480834409967437
656310093705697045
1616599508725767821225590944157
4461691012090851100342993272805
115366949386695884000892071602798585632943213
12002377162350258332845595301471273220420939451301220405

```

**OEIS A239381**

Similar sequences (don't output these!):

# Answer
> 13 votes
# Jelly, 19 bytes

```
o3ṄÆF*/€ŒPP€²+Ṛ$HṂß

```

Saved a byte thanks to @Dennis by refactoring to an infinite sequence.

Takes no input and arguments, then outputs the sequence infinitely by printing each term as it computes them. This method slows down as the numbers get larger since it depends on prime factorization.

Try it online!

This calculates the next term by computing the prime power factorization of the current term. For 12325, this is {52, 17, 29}. There is a variant of Euclid's formula for calculating Pythagorean triples {*a*, *b*, *c*},

where *m* \> *n* and the triple is primitive iff *m* and *n* are coprime.

To calculate the next primitive root from 12325, find *m* and *n* such that *mn* = 12325 and choose *m*,*n* so that gcd(*m*, *n*) = 1. Then generate all pairs of *m*,*n* by creating all subsets of {52, 17, 29} and finding the product of each of those subsets which are {1, 25, 17, 29, 425, 725, 493, 12325}. Then divide 12325 by each value and pair so that each pair is *m*,*n*. Compute the formula for *c* using each pair and take the minimum which is 90733.

* The previous method failed for determining the next term after 228034970321525477033478437478475683098735674620405573717049066152557390539189785244849203205. The previous method chose the last value as a factor when the correct choice was the 3rd and last primes. The new method is slower but will always work since it tests all pairs of coprimes to find the minimal hypotenuse.

## Explanation

```
o3ṄÆF*/€ŒPP€²+Ṛ$HṂß  Main link. Input: 0 if none, else an integer P
o3                   Logical OR with 3, returns P if non-zero else 3
  Ṅ                  Println and pass the value
   ÆF                Factor into [prime, exponent] pairs
     */€             Reduce each pair using exponentation to get the prime powers
        ŒP           Powerset of those
          P€         Product of each
            ²        Square each
               $     Monadic chain
             +         Add vectorized with
              Ṛ        the reverse
                H    Halve
                 Ṃ   Minimum
                  ß  Call recursively on this value

```

# Answer
> 5 votes
# Brachylog, 36 bytes

```
3{@wB:?>:^a+~^=C:B:?:{$pd}ac#d,C:1&}

```

Try it online!

You have to wait for the program to time out (1 minute) before TIO flushes the output. In SWI-Prolog's REPL this prints as soon as it finds the value.

This will print the sequence forever.

After a few minutes on the offline SWI-Prolog's interpreter, I obtained `90733` after `12325`. I stopped it after this point.

This isn't complete bruteforce as it uses constraints to find pythagorean triples, though it is obviously not optimised for speed.

### Explanation

```
3{                                 }    Call this predicate with 3 as Input
  @w                                    Write the Input followed by a line break
    B:?>                                B > Input
           +                            The sum...
        :^a                             ...of Input^2 with B^2...
            ~^                          ...must equal a number which is itself a square
              =C                        Assign a fitting value to that number and call it C
               C:B:?:{$pd}a             Get the lists of prime factors of C, B and Input
                                          without duplicates
                           c#d,         Concatenate into a single list; all values must be
                                          different
                               C:1&     Call recursively with C as Input

```

# Answer
> 4 votes
# Perl, 73 bytes

```
for($_=3;$_<1e9;$_=$a**2+$b**2){$a++until($b=($_+$a**2)**.5)==($b|0);say}

```

All Pythagorean Triples `a²+b²=c²` satisfy `a=r(m²-n²), b=2rmn, c=r(m²+n²)` for some integers `r,m,n`. When `r=1` and `m,n` are coprime with exactly one being divisible by 2, then `a,b,c` is a primitive triple, where `a,b,c` are all pairwise coprime.

With this in mind, given some `a`, I use a brute-force algorithm to calculate the smallest `n` such that `a²-n²` is a square, namely . Then, `c` is equal to `n²+m²`.

# Answer
> 2 votes
# Python 3, 178 bytes

```
from math import*
p,n=[3,5],int(input())
while len(p)<n:
 for i in range(p[-1],p[-1]**2):
  v=sqrt(i**2+p[-1]**2)
  if v==int(v)and gcd(i,p[-1])==1:
   p+=[int(v)];break
print(p)

```

This is basically just a brute force algorithm, and thus is very slow. It takes the amount of terms to output as the input.

I'm not 100% sure about the correctness of this algorithm, the program checks for the other leg up to the first leg squared, which I believe is enough, but I haven't done the math.

**Try it on repl.it! (Outdated)** (Please don't try it for numbers greater than 10, it will be very slow)

# Answer
> 2 votes
# MATL, 27 bytes

```
Ii:"`I@Yyt1\~?3MZdZdq]}6MXI

```

This produces the first terms of the sequence. Input is 0-based.

The code is very inefficient. The online compiler times out for inputs greater than `5`. Input `6` took a minute and a half offline (and produced the correct `90733` as 6-th term).

Try it online!

```
I            % Push 3 (predefined value of clipboard I)
i            % Input n
:"           % For each (i.e. execute n times)
  `          %   Do...while
    I        %     Push clipboard I. This is the latest term of the sequence
    @        %     Push iteration index, starting at 1
    Yy       %     Hypotenuse of those two values
    t1\      %     Duplicate. Decimal part
    ~?       %     If it is zero: we may have found the next term. But we still
             %     need to test for co-primality
      3M     %       Push the two inputs of the latest call to the hypotenuse
             %       function. The stack now contains the hypotenuse and the
             %       two legs
      ZdZd   %       Call GCD twice, to obtain the GCD of those three numbers
      q      %       Subtract 1. If the three numbers were co-prime this gives
             %       0, so the do...while loop will be exited (but the "finally"
             %       part will be executed first). If they were not co-prime
             %       this gives non-zero, so the do...while loop proceeds
             %       with the next iteration
    ]        %     End if
             %     If the decimal part was non-zero: the duplicate of the
             %     hypotenuse that is now on the top of the stack will be used
             %     as the (do...while) loop condition. Since it is non-zero,
             %     the loop will proceed with the next iteration
  }          %   Finally (i.e. execute before exiting the do...while loop)
    6M       %     Push the second input to the hypotenuse function, which is
             %     the new term of the sequence
    XI       %     Copy this new term into clipboard I
             %   Implicitly end do...while
             % Implicitly end for each
             % Implicitly display the stack, containing the sequence terms

```

# Answer
> 2 votes
## Racket 106 bytes

```
(let p((h 3))(println h)(let p2((i 1))(define g(sqrt(+(* h h)(* i i))))(if(integer? g)(p g)(p2(add1 i)))))

```

Ungolfed:

```
(define (f)
  (let loop ((h 3))
    (let loop2 ((i 1))
      (define g (sqrt (+(* h h) (* i i))))
      (if (not(integer? g))
          (loop2 (add1 i))
          (begin (printf "~a ~a ~a~n" h i g)
                 (loop g))))))

```

Testing:

```
(f)

```

Output of golfed version:

```
3
5
13
85
157
12325
12461
106285
276341
339709
10363909
17238541

```

Output of ungolfed version:

```
3 4 5
5 12 13
13 84 85
85 132 157
157 12324 12325
12325 1836 12461
12461 105552 106285
106285 255084 276341
276341 197580 339709
339709 10358340 10363909
10363909 13775220 17238541

```

(Error after this on my machine)

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

```
Nest[c/.#&@@Solve[{#^2+b^2==c^2,#<b<c&&GCD[b,c]==1},{b,c},Integers]&,3,#]&

```

Try it online!

---

# Wolfram Language (Mathematica), 74 bytes

```
Nest[#&@@Cases[Divisors@#,d_/;GCD[d,#/d]<2&&d^2>#:>(d^2+(#/d)^2)/2]&,3,#]&

```

Try it online!

# Answer
> 1 votes
# PHP, 139 bytes

```
for($k=3;$i=$k,print("$k\n");)for($j=$i+1;($k=sqrt($m=$i*$i+$j*$j))>(int)$k||gmp_intval(gmp_gcd(gmp_gcd((int)$i,(int)$j),(int)$k))>1;$j++);

```

The above code breaks after 28455997 on 32-bit systems. If higher numbers are needed, it becomes 156 bytes:

```
for($k=3;$i=$k,print("$k\n");)for($j=$i+1;!gmp_perfect_square($m=bcadd(bcpow($i,2),bcpow($j,2)))||gmp_intval(gmp_gcd(gmp_gcd($i,$j),$k=bcsqrt($m)))>1;$j++);

```

# Answer
> 1 votes
# Java 8, 133 Bytes

-25 bytes thanks to miles ***Using n\*n instead of Math.pow(n, 2)***

-24 bytes thanks to miles ***Using for loops instead of while, changing datatype, eliminating () due to order of operations***

```
()->{long b=3,c,n;for(;;){for(n=1;;n++){c=b+2*n*n;double d=Math.sqrt(c*c-b*b);if(d==(int)d&b<d){System.out.println(b);break;}}b=c;}};

```

Uses the fact that

for any pair of integers m \> n \> 0. Therefore, C is equal to A plus 2(N)2. The function above finds the least value of N that satisfies this relation, while making the second element of the Pythagorean triple an integer and greater than the first element. Then it sets the value of the first element to the third element and repeats with the updated first element.

Ungolfed:

```
void printPythagoreanTriples() {
    long firstElement = 3, thirdElement, n;
    while (true) {
        for (n = 1; ; n++) {
            thirdElement = firstElement + (2 * n * n);
            double secondElement = Math.sqrt(thirdElement * thirdElement - firstElement * firstElement);
            if (secondElement == (int) secondElement && firstElement < secondElement) {
                System.out.println("Found Pythagorean Triple [" +
                        firstElement + ", " +
                        secondElement + ", " +
                        thirdElement + "]");
                break;
            }
        }
        firstElement = thirdElement;
    }
}

```

Ideone it!

\*The ideone does not print the last required element due to time limits, however as you can see through the logic of the program and the ungolfed version (which prints the 28455997 as the third element of the previous Pythagorean triple rather than the first element of the next), the values are, with a higher time limit, printed.

# Answer
> 1 votes
# Python 3.5, 97 bytes

*Wrong output after `28455997`, because of the limits of the floating point data type. The `sqrt` function isn't good enough, but if the precision was magically increased, it'd work.*

Pretty simple to understand. Incrementing `c` by two instead of one cuts the runtime in half, and only odd numbers need to be checked anyway, because the elements are always odd.

```
import math
c=a=3
while 1:
	c+=2;b=(c*c-a*a)**.5;i=int(b)
	if math.gcd(a,i)<2<a<b==i:print(a);a=c

```

**Try it online**

The program cannot be run on Ideone, because Ideone uses Python 3.4

---

For output to stay accurate longer, I'd have to use `decimal`:

```
import math
from decimal import*
c=a=3
while 1:
	c+=2;b=Decimal(c*c-a*a).sqrt();i=int(b)
	if i==b>a>2>math.gcd(a,i):print(a);a=c

```

**Try it online**

To stay accurate indefinitely, I could do something horrid like this (increasing the precision required *every single iteration*:

```
import math
from decimal import*
c=a=3
while 1:
	c+=2;b=Decimal(c*c-a*a).sqrt();i=int(b);getcontext().prec+=1
	if i==b>a>2>math.gcd(a,i):print(a);a=c

```

# Answer
> 1 votes
# , ~~54~~ 47 bytes

```
-:@+/@:*:@((*/:~)/)@,.&1@x:@(^/)@(2&p:)^:(<12)3

```

TIO

greedy split of prime factors into coprime factors

~~old 54 bytes TIO~~

# Answer
> 1 votes
# Pari/GP, 71 bytes

```
n->a=3;for(i=1,n,a=[d^2+e^2|d<-divisors(a),gcd(d,e=a/d)<2&&d>e][1]/2);a

```

Try it online!

# Answer
> 1 votes
# APL(NARS), 169 chars, 338 bytes

```
h←{{(m n)←⍵⋄(mm nn)←⍵*2⋄(2÷⍨nn+mm),(2÷⍨nn-mm),m×n}a⊃⍨b⍳⌊/b←{⍵[2]}¨a←a/⍨{(≤/⍵)∧1=∨/⍵}¨a←(w÷a),¨a←∪×/¨{k←≢b←1,π⍵⋄∪{b[⍵]}¨↑∪/101 1‼k k}w←⍵}⋄p←{⍺=1:⍵⋄⍵,(⍺-1)∇↑h ⍵}⋄q←{⍵p 3x}

```

test ok until 14 as argument of q:

```
  q 1
3
  q 2
3 5
  q 10
3 5 13 85 157 12325 90733 2449525 28455997 295742792965
  q 12
3 5 13 85 157 12325 90733 2449525 28455997 295742792965 171480834409967437 656310093705697045
  q 13
3 5 13 85 157 12325 90733 2449525 28455997 295742792965 171480834409967437 656310093705697045
  1616599508725767821225590944157
  q 14
NONCE ERROR
  q 14
  ∧

```

this below would find all divisors of its argument...

```
∪×/¨{k←≢b←1,π⍵⋄∪{b[⍵]}¨↑∪/101 1‼k k}

```

# Answer
> 1 votes
# Husk, 14 bytes

```
m√¡ȯ`ḟİ□o£İ□-9

```

Try it online!

This times out after the fifth element, but it’s an infinite list.

```
m√¡ȯ`ḟİ□o£İ□-9
             9  Starting with 9
  ¡             Make an infinite list of legs^2 by applying this function repeatedly:
   ȯ`ḟİ□o£İ□-   This function finds the next leg, squared
    `ḟ          Find a number in
      İ□        The infinite list of perfect squares, such that
            -   It minus the previous leg^2 is
         £      An element of
          İ□    The infinite list of perfect squares
m               Then map each to
 √              Its square root

```

# Answer
> 0 votes
# JavaScript (Node.js), 101 bytes

```
_=>{for(var a=3,b,c;;){for(c=1;;c++)if(b=a+2*c*c,d=Math.sqrt(b*b-a*a),d==+d&a<d){alert(a);break}a=b}}

```

Try it online!

Suggestions on golfing are welcome

---
Tags: code-golf, sequence
---


title: It's almost Christmas!

text:
# Question
Title: It's almost Christmas!
Because of this, families from all over the world are building Christmas trees.

But this normal tree can get boring after a while, so let's make an ASCII tree!

Leafs are represented by `#` and must be arranged as shown in the example output. We have 5 balls (`O`) and 5 candy canes (`J`), which we place randomly around the tree. We also have a candle on top.

**Input:** none

**Output:**

```
         ^
         |
        ###
       ##O##
      #######
       #####
      ####J##
     #########
    ####O######
   #############
      ###J###
     #########
    ####O###J##
   #######O#####
  ###J########O##
 ###########J#####
        ###
        ###

```

### Rules (if it's not in the rules, assume you can)

* Balls and candy canes must be randomly placed on the tree and must have at least one leaf between them, not counting diagonals.
* Each leaf must have a non-zero chance of getting a ball or a candy cane.
* There may be leading or trailing spaces on each line, as long as the tree has the proper shape.
* This is , so shortest code in characters wins.

# Answer
> 5 votes
## JavaScript (ES6), 148 bytes

Hopefully, this should comply with the 'random enough' condition.

```
_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)

```

### Demo

```
let f =

_=>[...'887656543254321077'].map(n=>' '.repeat(n)+'#'.repeat(17-2*n)).join`
`.replace(/#/g,_=>'OJ^|#'[++i<4?i:i>133|++j%13?4:j/13&1],i=1,j=new Date)

console.log(f())
```

# Answer
> 8 votes
# CS-Script - 306 bytes

```
var c=new string(' ',342).ToCharArray();var r=new Random();int e=18,i,j,w;for(;i<e;i++){c[i*e+e]='\n';w=i<5?i:i<10?i-2:i<16?i-6:2;for(j=1;j++<w*2;)c[i*e+8-w+j]='#';}for(i=0;i<10;){j=37+r.Next(288);if(c[j]=='#'&c[j+1]<42&c[j-1]<42&c[j+e]<42&c[j-e]<42)c[j]=i++<5?'J':'O';}c[8]='^';c[27]='|';Console.Write(c);

```

Once more with formatting and comments:

```
// create 'char bitmap' filled with spaces
var c=new string(' ',342).ToCharArray();
// Random for placing ornaments
var r=new Random();
int e=18,i,j,w;
// once for each row
for(;i<e;i++)
{
    // add new lines
    c[i*e+e]='\n';
    // determine width of tree for this row
    w=i<5?i:i<10?i-2:i<16?i-6:2;
    for(j=1;j++<w*2;)
        // add leaves
        c[i*e+8-w+j]='#';
}
for(i=0;i<10;)
{
    // select random location
    j=37+r.Next(288);
    if( // check we have a leaf
        c[j]=='#' &
        // check surrounding to be leaf/space/new-line
        c[j+1]<42 & c[j-1]<42 & c[j+e]<42 & c[j-e]<42)
        // add ornament if location is valid
        c[j]=i++<5?'J':'O';
}
// light candle
c[8]='^';
c[27]='|';
// print
Console.Write(c);

```

It's basically C#, but using CS-Script allows me to skip all the boiler-plate.

Try it here!

**Notes:**

This currently outputs another line of white spaces below the tree to make sure the that 'checking for existing ornaments below' does not throw an IndexOutOfBoundsException. Other solutions would be:

* Checking if it is the last line before checking below (adds a few more character)
* Not adding ornaments to the 'stem' of the tree (Same byte count, but seems to me to be against rules)

I'll leave it to the OP if this should be changed.

Lastly, this is my first golf, so any feedback is appreciated. ;)

# Answer
> 4 votes
# TSQL, ~~556~~ ~~532~~ ~~494~~ 476 bytes

This script needs to be executed on the master database

**Golfed:**

```
DECLARE @ varchar(max)='',@h INT=0,@w INT=0WHILE @h<18SELECT
@+=space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)+space(9-@w)+CHAR(10),@h+=1,@w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)WHILE
@h>7WITH C as(SELECT*,substring(@,number,1)v,number/20r,number%20c
FROM spt_values WHERE type='P'and number<358)SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1FROM
c d WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)ORDER BY newid()PRINT @

```

**Ungolfed:**

```
DECLARE @ varchar(max)='',@h INT=0,@w INT=0

WHILE @h<18
  SELECT @+=
    space(9-@w)+REPLICATE(char(IIF(@h<2,94+30*@h,35)),@w*2+1)
      +space(9-@w)+CHAR(10),
    @h+=1,
    @w+=CHOOSE(@h,0,1,1,1,-1,1,1,1,1,-2,1,1,1,1,1,-8,0)

WHILE @h>7
  WITH C as
  (
    SELECT*,substring(@,number,1)v,number/20r,number%20c
    FROM spt_values
    WHERE type='P'and number<358
  )
  SELECT @=stuff(@,number,1,CHAR(74+@h%2*5)),@h-=1
  FROM c d
  WHERE v='#'and not exists(SELECT*FROM c WHERE abs(d.c-c)+abs(d.r-r)<2and'A'<v)
  ORDER BY newid()

PRINT @

```

**Try it out**

# Answer
> 1 votes
# JavaScript, 204 bytes

```
f=(s='^|1232345634567811'.replace(/./g,x=>(y=x|0,' '.repeat(8-y)+(y?'#'.repeat(y*2+1):x)+`
`)),o=5,j=5,r=(Math.random()*56|0)*4,k)=>j?f(s.replace(/###/g,(_,i)=>i-r?_:k=o?'#O#':'#J#'),k?o-!!o:o,k?j-!o:j):s

console.log(f());
```

```
.as-console-wrapper{max-height:100%!important;top:0}
```

# Answer
> 1 votes
# Python 3 - ~~450~~ 427 bytes

I know `450` is too much for python. But, but.....

```
from random import randint as r
t=lambda o,g:(o*g).center(19,' ')+';';s,z='','#';s+=t(z,3)*2
for h,w in zip([6,5,3],[17,13,7]):
 for i in range(h):s+=t(z,w);w-=2
s+=t('|',1)+t('^',1);s=[list(i)for i in s.split(';')]
for o in'O'*5+'J'*5:
 while 1:
  h,w=r(2,15),r(1,16)
  m=s[h]
  C,m[w]=m[w],o
  P=s[h-1][w]+s[h+1][w]+m[w-1]+m[w+1]
  if not('O'in P or'J'in P)and C!=' ':break
  m[w]=C
print (*[''.join(i)+'\n'for i in s][::-1])

```

If the `for i in'O'*...` is turned into a *better recursive function* then lots of bytes can be cut down.

Try it here

**Edit**:

Saved 2 bytes by using `;` as delimiter and several bytes by taking newline byte count as 1 byte.

# Answer
> 1 votes
# PHP, 200 bytes

might be shorter with a more sophisticated approach; but I´m in a hurry.

```
for(;$c="^|2343456745678922"[$i++];)$s.=str_pad(+$c?str_pad("",2*$c-1,"#"):$c,17," ",2)."
";for(;$n++<10;)$s[$p=rand(0,288)]!="#"|($s[$p-18]|$s[$p+18]|$s[$p-1]|$s[$p+1])>A?$n--:$s[$p]=OJ[$n&1];echo$s;

```

requires PHP 5.6 or 7.0. Run with `-nr` or try it online.

# Answer
> 0 votes
# Scala, 329 bytes

```
var r=scala.util.Random;var z=r.nextInt(2);def t{print(new StringBuilder({"^|234345645678922".map(x=>{val t=if(x>57)8 else(57-x);" "*t+{if(x>57)""+x else "#"}*(17-(t*2))+" "*t+" \n"})}.mkString)match{case e=>{var w=0;while(w<10){{val b=(r.nextInt(e.size/2)*2)+z;if(e.charAt(b)=='#'){e.setCharAt(b,if(w<5)'O'else'J');w+=1}}};e}})}

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 101 bytes

```
↑¯9↑¨'^|'
f←{⍵×(≢⍵)⍴2?2}
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵}↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'

```

Try it online!

A full program which returns the tree.

Tree creation algorithm borrowed from Arnauld's answer.

## Explanation

**Displaying the top**

```
↑¯9↑¨'^|'
     '^|' string
 ¯9↑¨     pad each with 8 spaces
↑         convert to matrix

```

---

**Distancing the ornaments**

```
f←{⍵×(≢⍵)⍴2?2} store the following lambda as f:
          2?2  generate 0 1 or 1 0 (random)
     (≢⍵)⍴     reshape to the length of the input
   ⍵×          multiply the input with it(vectorizes)

```

---

**Display the tree**

```
↑{' #'/⍨⍵,17-2×⍵}¨⍎¨'7656543254321077'
                  ⍎¨'7656543254321077' create an array of digits from the string
 {              }¨                     for each digit x:
        ⍵,17-2×⍵                       array [x,17-2*x]
  ' #'/⍨                               replicate spaces and hashes as per that
↑                                      convert to matrix

```

---

**Add the ornaments:**

```
{(5/'OJ')@(x[10?≢x←⍸↑f¨f¯2↓↓'#'=⍵])⊢⍵} apply the following to the tree:
                            '#'=⍵      boolean matrix for the tree
                           ↓           convert to 2d array
                        ¯2↓            remove trunk rows
                     f¨f               convert to swiss cheese with function f
                   ⍸↑                  get the indices of all 1s
                 x←                    and store in x
             10?≢                      pick 10 random indices in length(x) range
           x[                    ]     and take those from x
         @(                       )⊢⍵  replace those coordinates with:
 (5/'OJ')                              5 instances of 'O' and 5 instances of 'J'

```

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


# Question
Title: Find the Intersection of 2 Sets in Unioned Interval Notation
## Find the Intersection of 2 Sets in Unioned Interval Notation

Given two sets of real numbers described as the union of intervals, output a description of the intersection of these two sets as a union of the same type of interval.

The input sets will always consist of unions of intervals such that each interval begins and ends at a different integer (i.e. no interval has measure zero). However, different intervals in the same set may begin or end at the same integer or overlap.

The output set must also be a union of intervals which begin and end at integers, but *no interval in the output may overlap any other* even at a single integer.

The input may take any form that is suitable for your language of choice, as long as it consists of two lists of pairs of integers.

For example, you may represent the set  as:

```
[-10,-4]u[1,5]u[19,20]

```

Or as:

```
[[-10,-4],[1,5],[19,20]]

```

Or as:

```
[-10,-4;1,5;19,20]

```

Your output representation must be identical to your input representation (except that it is only one list of intervals instead of two).

### Examples/Test cases:

Input:

```
[[[-90,-4],[4,90]],[[-50,50]]]

```

Output:

```
[[-50,-4],[4,50]]

```

In other words, we're intersecting the set that contains all real numbers between -90 and -4 and all real numbers between 4 and 90 with the set that contains all real numbers between -50 and 50. The intersection is the set containing all real numbers between -50 and -4 and all real numbers between 4 and 50. A more visual explanation:

```
-90~~~~~-4  4~~~~~90   intersected with
    -50~~~~~~~~50        yields:
    -50~-4  4~~50

```

---

Input:

```
"[-2,0]u[2,4]u[6,8]
[-1,1]u[3,5]u[5,9]"

```

Output:

```
"[-1,0]u[3,4]u[6,8]"

```

---

Input:

```
[-9,-8;-8,0;-7,-6;-5,-4]
[-7,-5;-1,0;-8,-1]

```

Output:

```
[-8,0]

```

Invalid Output (even though it represents the same set):

```
[-8,0;-7,-5;-5,0]

```

## Scoring:

This is so shortest source in bytes wins, as potentially modified by the following bonus.

### Bonus:

-15% if you also support positive and negative infinity as bounds of intervals. You may choose what token(s) represent these numbers. (And yes, infinity is a number in the hyperreals ;P)

# Answer
> 3 votes
# Mathematica, 41 bytes - 15% = 34.85

Mathematica has a built-in function for interval intersection.

```
List@@IntervalIntersection@@Interval@@@#&

```

Example:

```
In[1]:= List@@IntervalIntersection@@Interval@@@#&[{{{-90, -4}, {4, Infinity}}, {{-50,Infinity}}}]

Out[1]= {{-50, -4}, {4, Infinity}}

```

# Answer
> 3 votes
## Haskell, 145 bytes

```
import Data.List
q(a,b)=[a,a+0.5..b]
p@(a,b)%(h:t)|h==b+0.5=(a,h)%t|1<2=p:(h,h)%t
p%_=[p]
a#b|h:t<-nub$sort$intersect(q=<<a)$q=<<b=(h,h)%t|1<2=[]

```

Usage example: `[(-2.0,0.0),(2.0,4.0),(5.0,6.0),(6.0,8.0)] # [(-1.0,1.0),(3.0,5.0),(5.0,9.0)]` -\> `[(-1.0,0.0),(3.0,4.0),(5.0,8.0)]`.

How it works:

```
                 q=<<a            -- turn each pair in the 1st input list into
                                  -- lists with halves in between (e.g. (1,4) ->
                                  -- [1,1.5,2,2.5,3,3.5,4]) and concatenate them
                                  -- to a single list
                      q=<<b       -- same for the second input list
    nub$sort$intersect            -- sort the intersection of those lists
                                  -- and remove duplicates
h:t<-                             -- call the first element h and the rest t
                       (h,h)%t    -- start rebuilding the intervals
                          |1<2=[] -- if there's no first element h, one of the
                                  -- input lists is empty, so the output is also
                                  -- empty

p@(a,b)%(h:t)                     -- an interval p = (a,b), build from a list (h:t)
             =(a,h)%t             -- becomes (a,h)
      |h==b+1                     --   if h equals b+0.5
                    p:(h,h)%t     -- or is put in the output list, followed by
                                  --       a new interval starting with (h,h)
      |1<2                        --   otherwise
p%_=[p]                           -- base case of the interval rebuilding function

```

I'm putting the "half"-values `x.5` in the list, because I need to distinguish `(1,2),(3,4)` from `(1,4)`. Without `x.5`, both would become `[1,2,3,4]`, but with `x.5` the 1st becomes `[1,1.5,2,3,3.5,4]` (which lacks `2.5`) and the second `[1,1.5,2,2.5,3,3.5,4]`.

# Answer
> 2 votes
# APL (Dyalog Extended), 37 bytes

```
.5×(⊢/,⊃)¨{⍵⊂⍨1,1<2-/⍵}⊃∩/∨⍤∊¨…/¨¨2×⎕

```

Try it online!

A full program which takes a nested array in STDIN and returns a nested array.

Code fixed by bubbler.

---
Tags: code-golf, number, set-partitions
---