title: Evaluate the primorial of a number

text:
# Question
Title: Evaluate the primorial of a number
The primorial of a number is the product of all the primes until that number, itself included.

Take a number from `STDIN` as the input and evaluate its primorial, also known as the prime factorial.

Don't use libraries. Shortest code wins.

**Test cases:**

```
1 1
2 2
3 6
4 6
5 30
6 30
7 210
8 210
9 210
10 210
11 2310
12 2310
13 30030
14 30030
15 30030
16 30030
17 510510
18 510510
19 9699690

```

# Answer
## J, 13 characters

```
*/p:i._1 p:1+

```

Examples:

```
   */p:i._1 p:1+7
210

   */p:i._1 p:1+12
2310

```
> 6 votes

# Answer
## Python 2, 49 bytes

```
P=k=1
exec"P*=P**k%k<1or k;k+=1;"*input()
print P

```

Counts up `k` from 1 to the input, updating the primorial `P` by multiplying `P` by `k` whenever it's prime. Since `P` contains all lower prime factors, a sufficiently high power of `P` will contain `k` as a factor if and only if `k` is non-prime. The power `P**k` suffices, and we check whether `P**k%k<1`, multipling `P` by 1 if so (doing nothing) and by `k` otherwise.
> 5 votes

# Answer
# Mathematica 21

The large Pi represents the product function.

`PrimePi@n` returns the number of primes up to and including n.

`Prime@i` returns the ith prime.
> 4 votes

# Answer
# PARI/GP, 22 bytes

```
prodeuler(x=1,input,x)

```
> 4 votes

# Answer
### Python, 72 characters

Quickly golfed, I imagine there are better python solutions.

```
n=t=1;exec"t*=(1,n)[all(n%i for i in range(2,n))];n+=1;"*input();print t

```

I used wikipedia to verify up to 71

Usage:

```
$ python primorial.py
100
2305567963945518424753102147331756070

$ python primorial.py
101
232862364358497360900063316880507363070

```
> 3 votes

# Answer
## Mathematica, 27 chars

```
Times@@Prime@Range@PrimePi@

```

Usage

```
Times@@Prime@Range@PrimePi@100
(*
2305567963945518424753102147331756070
*)

```
> 3 votes

# Answer
# C, 125 bytes

```
p(n,x){return x==1?n:n%x?p(n,x-1):1;}
f(n){return n==1?1:p(n,n-1)*f(n-1);}
main(){int n;scanf("%d",&n);printf("%d\n",f(n));}

```
> 1 votes

# Answer
## Haskell, 90 chars

```
main=getLine>>= \v->print.product.takeWhile(<=read v)$[n|n<-[2..],all((>0).rem n)[2..n-1]]

```

or (also 90 chars):

```
main=getLine>>=print.product.flip takeWhile [n|n<-[2..],all((>0).rem n)[2..n-1]].(>=).read

```

### Compilation

```
ghc primorial.hs

```

### Usage

```
$ echo "12" | ./primorial
2310

```

or

```
$ ./primorial
12<ENTER>
2310

```
> 1 votes

# Answer
## R - 48

```
x=1:scan();prod(x[rowSums(outer(x,x,`%%`)<1)<3])

```
> 1 votes

# Answer
# MATLAB/Octave, 23 bytes

```
prod(primes(input('')))

```

Try it online!
> 1 votes

# Answer
# Casio-Basic, 41 bytes

```
prod(seq(piecewise(isPrime(x),x,1),x,1,n

```

Since the calculator doesn't have a "select" function of any kind, a piecewise/hybrid function is used to return the number if it's prime, otherwise return 1. `seq` does this over a range of integers from 1 to n, and `prod` multiplies the whole list together.

40 bytes for the function, +1 byte to enter `n` in the parameters box.
> 1 votes

# Answer
**Smalltalk**, Squeak 4.x flavour

Let's say we read n from stdin in 38 chars (this kind of requirement is just killing!)

```
n:=FileStream stdin nextLine asNumber.

```

If only product were defined in Collection in base image, this could be as simple as

```
^(0class primesUpTo:n+1)product

```

or:

```
^((2to:n)select:#isPrime)product

```

Unfortunately, we have to code #product by ourself in 48 chars (**86** total).

```
(0class primesUpTo:n+1)inject:1into:[:p :i|p*i]

```

Or if primesUpTo: is considered as a library, we can use isPrime in 62 chars (**100** total)

```
^(1to:n)inject:1into:[:p :i|i isPrime ifTrue:[p*i]ifFalse:[p]]

```

If even isPrime is forbidden we can find by ourselves in 67 chars (**105** total)

```
p:=1. 2to:n do:[:i|((2to:i-1)anySatisfy:[:d|i\\d=0])or:[p:=p*i]].^p

```

Or for the fun, we can use a sieve in 108 chars (**146** total)

```
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.(z+1bitAnd:s)=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1bitAnd:s]].^p

```

Explanation of the sieve at http://smallissimo.blogspot.fr/2011/07/revisiting-sieve-of-erathostenes.html

Nota: bitAnd: has a short-cut operator & in Pharo 2.0, which would reduce Sieve cost to 94 chars (**132** total)

```
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.z+1&s=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1&s]].^p

```
> 0 votes

# Answer
# Haskell, 76 bytes

```
main=interact$ \n->show$product[x|x<-[2..read n],and[x`mod`y>0|y<-[2..x-1]]]

```

Example:

```
$ echo 12 | ./primorial
2310

```
> 0 votes

# Answer
# Java 7, 213 bytes

```
class M{public static void main(String[]a){c(new Long(a[0]));}static void c(long n){long r=1,i=0;for(;++i<=n;r*=p(i)?i:1);System.out.print(r);}static boolean p(long n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}}

```

**Ungolfed:**

```
class M{
  static void c(long n){
    long r = 1,
         i = 0;
    for (; ++i <= n; r *= p(i) ? i : 1);
    System.out.print(r);
  }

  public static void main(String[] a){
    c(new Long(a[0]));
  }

  static boolean p(long n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1 ? 0 : n;
    }
    return n > 1;
  }
}

```

**Usage:** `java -jar M.jar 17`
**Output:** `510510`
> 0 votes

# Answer
# Jelly, 3 bytes

```
ÆRP

```

Try it online!
> 0 votes

# Answer
# RProgN 2, 6 bytes

```
S²P¬-*

```

## Explained

```
S²P¬-*
S       # Produce as stack from 1 to the input.
 ²  -   # Filter it by the function provided
  P¬    # Is it not a prime?
     *  # Get the product of the now list of primes.

```

Try it online!
> 0 votes

# Answer
# Japt, 6 bytes

```
õ fj ×

```

Try it here
> 0 votes

# Answer
# 05AB1E, 3 bytes

```
ÅPP

```

Try it online!
> 0 votes

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


# Question
Title: Exponentiation to multiplication to addition
Multiplication between 2 integers can be reduced into a series of addition like so

```
3 * 5 = 3 + 3 + 3 + 3 + 3 = 5 + 5 + 5

```

Exponentiation (raising **a** to the power **b**) can also be reduced into a series of multiplications:

```
5 ^ 3 = 5 * 5 * 5

```

Therefore, exponentiation can be reduced into a series of additions, by creating a multiplication expression, then into a series of additions. For example, `5 ^ 3` (5 cubed) can be rewritten as

```
5 ^ 3 = 5 * 5 * 5
      = (5 + 5 + 5 + 5 + 5) * 5
      = (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5) + (5 + 5 + 5 + 5 + 5)
      = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5

```

Your task is, given expressions added together consisting of exponentiation, multiplication and addition, reduce it to the shortest series of additions. The "shortest" expression is defined as the expression with the fewest number of `+` symbols, still using only one of the two numbers in the original expression. For example, the shortest expression of `10 * 2` is `10 + 10`.

The numbers involved in the input will all be positive integers, and the expression will consist of only `+` (addition), `*` (multiplication) and `^` (exponentiation), along with integers and brackets (`()`) to indicate precedence.

The output should consist of positive integers and `+` symbols only. You shouldn't output the individual steps of the reductions, just the final output. The output may not consist of any numbers that don't appear in the input. However, you may use any 3 distinct symbols instead of `+*^`, but please say what symbols they are

The spaces separating inputs and outputs may or may not be used in your programs, i.e. `3 * 5` can be outputted as either `5 + 5 + 5` or `5+5+5`.

Note that in most cases, addition is not actually performed. The only case where addition is to be performed is when you have something like `5 ^ (1 + 2)`, in which case, addition is necessary to continue `-> 5 ^ 3 -> 5 * 5 * 5 -> ...`. See test case #4.

Your code does not need to handle inputs that arrive at an ambiguous expression. For example, `(2 + 2) * (4 + 1)`. Because of the rules set forth so far, the goal is not to calculate the answer, the goal is to simplify to additions. So the result could be different depending on the order that expressions are resolved or commuted (which additions to simplify, which to leave?). Another invalid example: `((3 + 2) ^ 2) ^ 3 -> ((3 + 2) * (3 + 2)) ^ 3 -> ???`.

This is so shortest code wins

## Test cases

```
Input => output

5 ^ 3 + 4 * 1 ^ 5 => 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 4
2 ^ 1 * 2 + 3 + 9 => 2 + 2 + 3 + 9
2 ^ 1 * (2 + 3) + 9 => 2 + 3 + 2 + 3 + 9
2 ^ (1 * (2 + 3)) + 9 => 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 9
10 + 3 * 2 + 33 ^ 2 => 10 + 3 + 3 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33 + 33
100 * 3 => 100 + 100 + 100
2 ^ 1 + 2 ^ 1 + 2 ^ 2 + 8 ^ 1 => 2 + 2 + 2 + 2 + 8
(1 + 2 + 5 * 8 + 2 ^ 4) * 2 => 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 + 2 + 8 + 8 + 8 + 8 + 8 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2

```

# Answer
# Retina, 302 bytes

I'm sure this can be golfed, but at this point, I'm just glad it works. The exponentiation and multiplication sections are both very similar, but since order of operations is important, I don't know how to combine them.

`y` \- Exponentiation
`x` \- Multiplication
`p` \- Addition

```
\d+
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)
>$0<
(?<=>(\(\w+\)|1+)y1*)1
$1x
>(\(\w+\)|1+)y
(
x<
)
\((1+(x1+)*)\)(?!y)
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)
$2x$1
1`(\(\w+\)|1+)x1+
>$0<
(?<=>(\(\w+\)|1+)x1*)1
$1p
>(\(\w+\)|1+)x
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)
$1
y\((1+)p([1p]*\))
y($1$2
}`y\((1+)\)
y$1
1+
$.0

```

**Try it online** \- all test cases

Test case converter

### Explanation

```
\d+                             Convert to unary
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)    Begin loop: Delimit current exponentiation group
>$0<
(?<=>(\(\w+\)|1+)y1*)1          Replace exponentiation with multiplication
$1x
>(\(\w+\)|1+)y                  Replace garbage with parentheses
(
x<
)
\((1+(x1+)*)\)(?!y)             Remove unnecessary parentheses around multiplication
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)  Maybe swap order of multiplicands
$2x$1
1`(\(\w+\)|1+)x1+               Delimit current multiplication group
>$0<
(?<=>(\(\w+\)|1+)x1*)1          Replace multiplication with addition
$1p
>(\(\w+\)|1+)x                  Replace garbage with parentheses
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)   Remove unnecessary parentheses around addition
$1
y\((1+)p([1p]*\))               Handle the 4th test case by adding if necessary
y($1$2
}`y\((1+)\)                     End of loop
y$1
1+                              Convert unary back to decimal
$.0

```

You may also notice that the most commonly used group is `(\(\w+\)|1+)`. This matches an inner expression with parentheses, or an integer. I chose to use the symbols I did so that I could use `\w` rather than a character class. I'm not sure if it would be better to use non-word symbols and replace some lookarounds with word borders (`\b`).
> 6 votes

# Answer
# Mathematica, ~~250~~ ~~218~~ ~~183~~ 170 bytes

```
f~(s=SetAttributes)~HoldAll;{a,t}~s~Flat;f@n_:=Infix[Hold@n//.{a_~Power~b_:>t@@Hold@a~Table~b,Times->t,Plus->a,Hold->Dot}/.t->(a@@Table[#,1##2]&@@Reverse@Sort@{##}&),"+"]

```

It works! Finally!

Defines the function in `f`.

The input is a plain math expression. (i.e. `1 + 2` not `"1 + 2"`).

Try it Online!

Note that the TIO link has a slightly different code, as TIO (which, I presume, uses Mathematica kernel) doesn't like `Infix`. I used `Riffle` instead to get the same appearance as Mathematica REPL.

## Ungolfed

```
f~(s = SetAttributes)~HoldAll;  (* make f not evaluate its inputs *)

{a, t}~s~Flat;  (* make a and t flat, so that a[a[1,a[3]]] == a[1,3] *)

f@n_ :=  (* define f, input n *)

 Infix[

  Hold@n  (* hold the evaluation of n for replacement *)

    //. {  (* expand exponents *)

     (* change a^b to t[a,a,...,a] (with b a's) *)
     a_~Power~b_ :> t @@ Hold@a~Table~b,

     (* Replace Times and Plus with t and a, respectively *)
     Times -> t,
     Plus -> a,

     (* Replace the Hold function with the identity, since we don't need
         to hold anymore (Times and Plus are replaced) *)
     Hold -> Dot

     } /.  (* Replace; expand all t (= `Times`) to a (= `Plus`) *)

        (* Take an expression wrapped in t. *)
        (* First, sort the arguments in reverse. This puts the term
            wrapped in `a` (if none, the largest number) in the front *)
        (* Next, repeat the term found above by <product of rest
            of the arguments> times *)
        (* Finally, wrap the entire thing in `a` *)
        (* This will throw errors when there are multiple elements wrapped
           in `a` (i.e. multiplying two parenthesized elements) *)
        t -> (a @@ Table[#, 1 ##2] & @@
               Reverse@Sort@{##} &),

  "+"]  (* place "+" between each term *)

```
> 5 votes

# Answer
# Mathematica, ~~405~~ 406 bytes

```
f~SetAttributes~HoldAll;p=(v=Inactive)@Plus;t=v@Times;w=v@Power;f@x_:=First@MinimalBy[Inactivate@{x}//.{w[a___,b_List,c___]:>(w[a,#,c]&/@b),t[a___,b_List,c___]:>(t[a,#,c]&/@b),p[a___,b_List,c___]:>(p[a,#,c]&/@b),p[a_]:>a,w[a_,b_]:>t@@Table[a,{Activate@b}],t[a___,t[b__],c___]:>t[a,b,c],p[a___,p[b__],c___]:>p[a,b,c],{a___,{b__},c___}:>{a,b,c},t[a__]:>Table[p@@Table[i,{Activate[t@a/i]}],{i,{a}}]},Length];f

```

## Ungolfed and explained

```
SetAttributes[f, HoldAll]
p = Inactive[Plus]; t = Inactive[Times]; w = Inactive[Power];
f[x_] := First@MinimalBy[
   Inactivate[{x}] //. {
     w[a___, b_List, c___] :> (w[a, #, c] & /@ b),
     t[a___, b_List, c___] :> (t[a, #, c] & /@ b),
     p[a___, b_List, c___] :> (p[a, #, c] & /@ b),
     (* distribute lists of potential expansions over all operations *)
     p[a_] :> a,
     (* addition of a single term is just that term *)
     w[a_, b_] :> t @@ Table[a, {Activate@b}],
     (* a^b simplifies to a*a*...*a b times no matter what b is *)
     t[a___, t[b__], c___] :> t[a, b, c],
     p[a___, p[b__], c___] :> p[a, b, c],
     {a___, {b__}, c___} :> {a, b, c},
     (* operations are associative *)
     t[a__] :> Table[p @@ Table[i, {Activate[t@a/i]}], {i, {a}}]
     (* for a product, generate a list of potential expansions *)}
   , Length]
f

```

I went to a great deal of trouble to get the following effect: this function takes as input a standard Mathematica expression, with the usual `+`, `*`, and `^` operations (and parentheses) in it, and outputs what looks like a standard Mathematica expression (but with "deactivated" plus signs) as the answer.

The function above begins by deactivating all operations in the input. Then, it applies expansion rules repeatedly until nothing can be simplified anymore. Whenever it encounters a product such as `2 * 3 * 4`, which can be expanded in multiple ways, it makes a list of possible expansions, and keeps going. At the end, we get a list of possible final answers, and the shortest is picked.
> 3 votes

---
Tags: code-golf, math, arithmetic, parsing
---


title: Golfing Newton's Method

text:
# Question
Title: Golfing Newton's Method
I have the following code which I've written to emulate Newton's method for deriving the square root of a number:

```
r=(x,y)=>
  (z=((y=y||x)*y-x)/(2*y)>1e-15)?
r(x,y-(y*y-x)/(2*y)):y

```

Where `r(37)` would result in `6.08276253029822` which is great given the limitations of my browser.

I'd like to golf this code further seeing there's some repetition here, not to mention, I'd also like to reduce my error limit (the `1e-15`). This is the furthest I've gotten. Can anyone help? If possible I'd love to eliminate the need of the error limit without resulting in a "maximum stack call size exceeded" error...

This is for a blog post I'm working on JavaScript and alternatives to native methods. I'll give a special shout out on the blog post to the persons who can help me out.

Thanks in advance.

# Answer
# Golfed only, -23 bytes

ES6 supports default parameters.

> **Default function parameters** allow formal parameters to be initialized with default values if no value or `undefined` is passed.

So, we can replace `y=y||x` with just `r=>(x,y=x)`.

`(y*y-x)/(2*y)` can be rewritten as `y/2-x/2/y`. And since this expression appears twice in the code, we can assign it to a new variable ***z***.

We get:

```
r=(x,y=x)=>(z=y/2-x/2/y)>1e-15?r(x,y-z):y

```

As suggested by **ETHproductions** in the comments, we now can save 2 more bytes by multiplying ***z*** by 2:

```
r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y

```

```
r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y

console.log(r(37))
```

---

# Alternate version, -26 bytes

To save more bytes, another approach is to just iterate *enough times* rather than using a test on the result.

That could be done that way:

```
r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y

```

```
r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y

console.log(r(37))
```

We start with `k = x` and divide it by 2 at each iteration. No matter the initial value of ***x***, we will eventually reach 0 because of arithmetic underflow.

The good thing about this method is that the number of iterations doesn't heavily rely on the value of ***x***. For instance, we'll get 1142 iterations for ***x = 1020*** and 1009 iterations for ***x = 10 -20***. In both cases, we iterate far too many times than necessary, without exceeding the default maximum number of iterations of common browsers.

Some more notes:

* The error is negligible for ***x \> 10 -215*** and quickly grows below this bound.
* For the same byte count and less iterations, we can divide by 9 instead. In that case, a safe bound is ***x \> 10 -124***.
* Unlike `Math.sqrt()`, this method does not return `NaN` for negative numbers or `±Infinity` (and neither does the original code).
> 9 votes

# Answer
This is almost similar to "@Arnauld Alternate version" and has same bytes with that, but this can work in `x < 1e-215`

```
r=(x,y=k=9)=>k?r(x,(y+x/y)/2,k/=2):y

```
> 1 votes

---
Tags: code-golf, math, tips, javascript, algorithm
---


title: Make a list continuous!

text:
# Question
Title: Make a list continuous!
Take an input list **L** containing positive integers, and insert the least amount of integers into the sequence, so that you make it a continuous one.

### Example:

```
L = 4 2 6 1
Out: 4 3 2 3 4 5 6 5 4 3 2 1

```

The input and output formats are optional.

### Test cases:

```
L = 1
Out: 1

L = 10 4
Out: 10 9 8 7 6 5 4

L = 13 13
Out: 13 13

L = 3 6
Out: 3 4 5 6

L = 4 4 1 1 4 4
Out: 4 4 3 2 1 1 2 3 4 4

```

This is ... You know the rules.

# Answer
# Builtin

### Husk:

Try it online!

I bet this builtin exists in more than one language, so I made this a community wiki, just add in more languages where this is a builtin if you know them!
> 2 votes

# Answer
# Brachylog, 11 bytes

```
⊆.s₂ᵇ-ᵐ~ṡᵐ∧

```

Try it online!

It's long and slow but at least it's declarative…

### Explanation

```
⊆.        ∧       The Input is an ordered subset of the Output
  s₂ᵇ             Take all substring of 2 consecutive elements in the Output
     -ᵐ           Take the subtractions of all those substrings
       ~ṡᵐ        They must all be valid "ṡigns" (i.e 1, 0 or -1)

```
> 2 votes

# Answer
# Mathematica, 72 bytes

Another approach using `ReplaceAll`.

```
#//.{(p={a___,b_,c_,d___})/;b>c+1->(f={a,b,b-#,c,d}&)@1,p/;b<c-1->f@-1}&

```
> 1 votes

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


title: Build me some string stairs

text:
# Question
Title: Build me some string stairs
# String Stairs

**Disclaimer:** This is the first challenge I propose. Any and all feedback is welcome. If this is a duplicate, please point it out.

Here's a link to the sandbox post.

# Goal

The goal of this challenge is to, given a string and an integer, print the string into blocks of that integer's size. If a word has more characters than the size of a block, print it into a descending "stair" pattern.

# Rules

* The "stair pattern" mentioned above means that, for every block of a same word, that block must begin exactly where the block above it ends. Check the test cases (or ask) if you have any questions.
* If a word is broken in multiple blocks, the following word must be printed with an adequate number of spaces, that is, it must be separated from the preceding word's lowermost block by exactly one whitespace. Check the test cases (or ask) for clarification.
* You can assume the input string will consist only of printable ASCII characters. Also, it will not have multiple whitespaces in a row.
* You can also assume that the integer will always be in the range \[1, +∞).
* Trailing whitespace or newlines are allowed.
* You can use any reasonable method for I/O.
* Standard Loopholes apply.
* This is , so shortest code (in bytes, per language) wins. After a week (or so), I'll accept the overall shortest answer.

# Test Cases

```
(String, Integer) => (Output)

"This is a large string", 3 => Thi is a lar  str
                                 s        ge   ing

"This is an even larger string!", 2 => Th  is an ev  la   st
                                        is        en  rg   ri
                                                       er   ng
                                                             !
"Ooooh dear, what a big string you have!", 3
=> Ooo  dea  wha a big str   you hav
     oh   r,   t         ing       e!

"Staphylococcus saprophyticus", 4 => Stap        sapr
                                        hylo        ophy
                                           cocc        ticu
                                              us          s

"I hope you find this challenge interesting", 2
=> I ho  yo fi  th  ch    in
      pe  u  nd  is  al    te
                      le    re
                       ng    st
                        e     in
                               g

"Well, this test case looks kinda pointless now doesn't it?", 15
=> Well, this test case looks kinda pointless now doesn't it?

"This one looks a lot more interesting!", 1 => T o l a l m i
                                               h n o   o o n
                                               i e o   t r t
                                               s   k     e e
                                                   s       r
                                                           e
                                                           s
                                                           t
                                                           i
                                                           n
                                                           g
                                                           !
"Keep in mind, people: 'Punctuation! Does! Matter!'", 2
=> Ke  in mi  pe   'P      Do  Ma
    ep     nd  op   un      es  tt
            ,   le   ct      !   er
                 :    ua          !'
                       ti
                        on
                         !

```

# Answer
# Charcoal, 22 bytes

```
Ｆ⪪θ «↑⸿⸿ＦＬι«Ｍ¬﹪κＩη↙§ικ

```

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

```
  θ                      First input
 ⪪                      Split on spaces
Ｆ   «                   Loop over each word
     ↑⸿⸿                Move the cursor to the top row and two columns right*
          ι             Current word
         Ｌ              Length
        Ｆ  «            Loop over implicit range
               κ        Current index
                 η      Second input
                Ｉ       Cast to integer
              ﹪         Modulo
             ¬          Logical not
            Ｍ     ↙     Move that many characters down and left
                    ι   Current word
                     κ  Current index
                   §    Index into word and implicitly print

```

\*More precisely, "move to the start of the next line twice, but as if the canvas was rotated." Edit: In between this challenge being set and this answer being accepted, Charcoal actually acquired a means of splitting a string into pairs of characters, reducing the code 16 bytes:
`Ｆ⪪θ «↑⸿⸿Ｆ⪪ιＩη«κ↙` Try it online! Link is to verbose version of code. Explanation:

```
  θ                 First input
 ⪪                  Split on spaces
Ｆ   «               Loop over each word
     ↑⸿⸿            Move the cursor to the top row and two columns right
          ι         Current wordＩη
            η       Second input
           Ｉ        Cast to integer
         ⪪          Split into substrings of that length
        Ｆ    «      Loop over each substring
              κ     Print the substring
               ↙    Move the cursor down and left

```
> 7 votes

# Answer
# SOGL V0.12, ~~28~~ ~~27~~ 26 bytes

```
ā,θ{0Eā;{ēb÷eb‰⁴bH*+I;Iž}┼

```

Try it Here!

I did implement  while making this, but the documentation for it existed before.

Explanation:

```
ā                            push an empty array - the main canvas
 ,                           push the first input
  θ{                         for each word (pushing the word each time)
    0E                         set the variable E to 0
      ā;                       below the current word place an empty array - current word canvas
        {               }      for each character of the word
         ēb÷                     push (E++ // B) - note that E is incremented after being used
            eb‰                  push E positive modulo B - like regular modulo but in the 0 output case it gives B
               ⁴                 duplicate the item below ToS
                bH               push B-1
                  *              multiply [(E++ // B) and B-1]
                   +             add [that multiplication to E‰B] - current letters X position
                    I            increase the X position to have one leading space row
                     ;           swap top 2 items - current X position and (E++ // B)
                      I          increase to create current letters Y position
                       ž         in those positions insert the current letter in the current words canvas
                         ┼     append to main canvas current word canvas horizontally

```
> 3 votes

# Answer
# Javascript ES6 , 187 183 174 166 163 148 145 143 141 140 138 bytes

* for readability added some bytes in the code and removed them in the bytes count
* instead of s="",j=0 i did j=s=""
* instead of for(i in s) - regular for loop - removed 1 byte
* using already generated values in the indexers of the arrays - removed 8 bytes
* using already with value i= s.length (from the first loop) in the eval - instead of the real array length - causes trailing space which are allowed
* using map of S instead of eval - reduces by 3 bytes
* using fill instead on initializing empty array- so there is not need for the loop in the map result
* could replace || with | - reduced by 2 bytes
* thanks to @Justin Mariner - replace occurrences ==" " with \<"!" reduces 2 bytes
* moved the conditions from the a\[I\] to the other statement to reduces one " u\<"!" " - reduces 2 bytes
* instead of (I+=2,j=0) - j=!(I+=2) - reduced 1 byte
* "for of" instead of for
```
F=(s,n)=>{R=[I=j=i=0]
for(u of s)
a=R[z=u<"!"?j=!(I+=2):(j%n&&I++,j++/n|0)]=R[z]||[...s].fill` `,a[I]=u
return R.map(x=>x.join``).join`
`}
console.log(F("This is a large string", 3));
console.log(F("This is an even larger string!", 2));
console.log(F("Ooooh dear, what a big string you have!", 3));
console.log(F("Staphylococcus saprophyticus", 4));
console.log(F("I hope you find this challenge interesting", 2));
console.log(F("Well, this test case looks kinda pointless now doesn't it?", 15));
console.log(F("This one looks a lot more interesting!", 1))
console.log(F("Keep in mind, people: 'Punctuation! Does! Matter!'", 2));
```
> 3 votes

# Answer
## C#, 200 bytes

```
int x=-2,y=0;Regex.Split(i,@"\s+").ToList().ForEach(w =>{y=0;Regex.Matches(w,".{0,"+s+"}").Cast<Match>().ToList().ForEach(c=>{x+=(y==0?2:s-1);Console.SetCursorPosition(x,y);Console.Write(c);y++;});});

```

Where the string is specified by **i** and the size is specified by **s**.

E.g.

```
string i = "Staphylococcus saprophyticus";
int s = 2;
int x=-2,y=0;Regex.Split(i,@"\s+").ToList().ForEach(w =>{y=0;Regex.Matches(w,".{0,"+s+"}").Cast<Match>().ToList().ForEach(c=>{x+=(y==0?2:s-1);Console.SetCursorPosition(x,y);Console.Write(c);y++;});});

```

Basically, the first part **Regex.Split** uses white spaces to split the sentence into words, and the **Regex.Matches** splits each word into chunks specified by **s**. The chunk is written to Cursor position (x,y) where Y is set to 0 for every new word, and x is incremented by 2 for the first chunk of a word and subsequently (s-1) for each chunk.

x starts off it's life at -2 to ensure it's first use is set to 0.

I'm not knowledgable enough in C# trivia to be able to to make it smaller, but suspect it probably can be.
> 2 votes

# Answer
# Python 2, ~~203~~ 199 bytes

```
s,l=input()
S=s.split()
x=[]
for w in S:L=len(w);W=[i/l*~-l*' '+w[i:i+l]for i in range(0,L,l)];x+=[[c.ljust(L/l*~-l+L%l)for c in W+['']*len(s)]]
for l in zip(*x):
 L=' '.join(l)
 if L.strip():print L

```

Try it online!
> 1 votes

# Answer
## Perl 5, 59 bytes

**55 bytes code + 4 for `-ai`.**

```
$-=s/.{$^I}\K(?=.)/\x1b[1B\x1b[1D/g,print$_,"\x1b[1A"x$-,$"for@F

```

**Note: the `\x1b`s are literal `ESC` chars, but escaped here for easy copy and paste.**

This script utilises ANSI escape sequences and requires input via the `-i` flag which is non-standard. If either of these are not acceptable, please let me know and I'll updated.

### Example runs

```
perl -ai3 string-stairs.pl <<< 'This is a large string' 2>/dev/null
Thi is a lar  str
  s        ge   ing

perl -ai2 string-stairs.pl <<< 'This is an even larger string!' 2>/dev/null
Th  is an ev  la   st
 is        en  rg   ri
                er   ng
                      !

perl -ai3 string-stairs.pl <<< 'Ooooh dear, what a big string you have!' 2>/dev/null
Ooo  dea  wha a big str   you hav
  oh   r,   t         ing       e!

perl -ai4 string-stairs.pl <<< 'Staphylococcus saprophyticus' 2>/dev/null
Stap        sapr
   hylo        ophy
      cocc        ticu
         us          s

perl -ai2 string-stairs.pl <<< 'I hope you find this challenge interesting' 2>/dev/null
I ho  yo fi  th  ch    in
   pe  u  nd  is  al    te
                   le    re
                    ng    st
                     e     in
                            g

perl -ai15 string-stairs.pl <<< "Well, this test case looks kinda pointless now doesn't it?" 2>/dev/null
Well, this test case looks kinda pointless now doesn't it?

perl -ai1 string-stairs.pl <<< 'This one looks a lot more interesting!' 2>/dev/null
T o l a l m i
h n o   o o n
i e o   t r t
s   k     e e
    s       r
            e
            s
            t
            i
            n
            g
            !

perl -ai2 string-stairs.pl <<< "Keep in mind, people: 'Punctuation! Does! Matter!'" 2>/dev/null
Ke  in mi  pe   'P       Do   Ma
 ep     nd  op   un       es   tt
         ,   le   ct       !    er
              :    ua            !'
                    ti
                     on
                      !

```
> 1 votes

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


# Question
Title: Simulate a 'battle' in the playing card game 'Oorlog'
Let's build a simulation for an aspect in the card game, which I personally know by the Dutch name 'Oorlog' (translates to 'War').

## How does 'Oorlog' work?

Two decks of cards (each including two Jokers) are equally divided between the amount of players playing. Each player shuffles their own stock, put it upside down in front of them, and all players open up the first card of the stock at the same time.
The winner of that 'battle' is determined by the values of the cards following these rules: Joker/Ace defeats King; King defeats Queen; Queen defeats Jack; Jack defeats 10; 10 defeats 9; .... In addition, both 2 and 3 defeat Ace/Joker. The last rule may lead to a cycle where 2 or 3 beats Ace or Joker, Ace or Joker beats some other card, which in turn beats the 2 or 3. In this case, the 2 or 3 wins the battle.
(Suit is irrelevant in this card game.)

When two or more players have the equal highest cards, they have a 'war'. This means they put one card upside down, and then each opens up a new card from their stock, again looking who has the highest card. This continues until a single player wins the entire battle.
(All cards of that battle go to the discard pile of the player that won the battle. Then everyone opens up a new card. When a player's stock is out of cards, they turn their discard pile upside down and continue with this new stock. This continues until a player is out of all his/her cards and then the player with the highest amount of cards wins.)

***Example 'battles' with three players:***

1. 4, 8, Jack:
Jack wins.
2. 7, Ace, Queen:
Ace wins.
3. 10, 10, King:
King wins.
4. 3, Joker, 2:
3 wins.
5. Ace, Joker, 2:
2 wins.
6. 3, Queen, Ace:
3 wins.
7. Queen, Queen, 9:
Queen & Queen are having a 'war', so it continues with two new cards: 4, 8;
8 wins.
8. 4, 4, 4:
All are having a 'war', so it continues with three new cards: 8, Ace, 2;
2 wins.
9. Jack, 5, Jack:
Jack & Jack are having a 'war', so it continues with two new cards: 5, 5;
5 & 5 are also equal, so the 'war' continues again with two new cards: 10, King;
King wins.
10. Joker, Joker, Ace:
All are having a 'war', so it continue with three new cards: 9, 7, 9;
9 & 9 are also equal, so the 'war' continues with two new cards: Jack, 3;
Jack wins.

---

## So, onto the code challenge:

**Input:**

STDIN with an array, or a string simulating an array (your call - even if your language does support arrays). This array contains the cards of a battle in chronological order (see test cases for a clearer understanding of this).

**Output:**

STDOUT the index of the player that won the battle.
You can choose whether you want a zero-indexed (i.e. `0`, `1`, or `2`) or one-indexed output (i.e. `1`, `2`, `3`).

**Challenge rules:**

* The input will be a single array / string representing an array. So you can't have an array of arrays to simplify it. You also can't have surrogate items for cards not participating in the war.
* We use number notations for the face-cards instead of letter notation. So Ace/Joker = `1`; Jack = `11`; Queen = `12`; and King = `13`.
* In this challenge we can assume we are always playing with **3 players**.
* The first three indicate the start of the 'battle'. When two or more players have a 'war' the continuing cards in the array indicate their battle (see test cases for a clearer understanding of this).

**General rules:**

* This is tagged , so shortest answer in bytes wins.
This doesn't mean non code-golfing languages shouldn't enter. Try to come up with an as short as possible code-golf answer for 'every' programming language.
* Please mention which indexing (zero- or one-indexed) you've used for the output.

***Test cases:***

```
Test case 1:  [4, 8, 11]                 ->  2 (or 3)
Test case 2:  [7, 1, 12]                 ->  1 (or 2)
Test case 3:  [10, 10, 13]               ->  2 (or 3)
Test case 4:  [3, 1, 2]                  ->  0 (or 1)
Test case 5:  [1, 1, 2]                  ->  2 (or 3)
Test case 6:  [3, 12, 1]                 ->  0 (or 1)
Test case 7:  [12, 12, 9, 4, 8]          ->  1 (or 2)
Test case 8:  [4, 4, 4, 8, 1, 2]         ->  2 (or 3)
Test case 9:  [11, 5, 11, 5, 5, 10, 13]  ->  2 (or 3)
Test case 10: [1, 1, 1, 9, 7, 9, 11, 3]  ->  0 (or 1)
Test case 11: [13, 13, 4, 1, 3]          ->  1 (or 2)
Test case 12: [13, 4, 13, 2, 3]          ->  2 (or 3)

```

# Answer
> 4 votes
### q - 142 characters

```
{p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p}

```

Note: zero indexed.

There is no notion of reading stdin in q, so you should call it as a function: `{p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p}[1,2,3]`

Pretty long, actually, but there are plenty of corner cases. It keeps a roster of active players, and consumes the list of cards in a loop. The most problematic thing is to detect the correct winner in hands like `[13, 2, 3]`, since `3` beats `2`, as normal, but it had to be duplicated to be put into the corner case.

# Answer
> 3 votes
## JavaScript (ES6), 146 bytes

```
f=a=>(b=a.splice(0,3)).filter(m=>m-n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length>1?b.indexOf(n):f([...b.map(m=>m-n?0:a.shift()),...a])

```

Returns a zero-based index. 127 bytes if I'm allowed the initial deal as a separate array (this also works for an arbitrary number of hands of course):

```
f=(b,a)=>b.filter(m=>m==n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length<2?b.indexOf(n):f(b.map(m=>m-n?0:a.shift()),a)

```

# Answer
> 0 votes
# Java 8, ~~257~~ 247 bytes

```
int c(int[]a){int t=0,f=0,q,r=0,i=-1,l=a.length,x[];for(;++i<3;t=a[i]>t?a[r=i]:t)a[i]+=a[i]==1?f++*0+13:0;for(;i-->0;t=f<1|a[i]>3|t==3&2<a[i]?t:a[r=i]);for(f=i,x=new int[q=l<7?3:l>7?l-3:5];l>3&++i<q;)x[i]=t==a[i]|i>2?a[++f+3]:0;return l>3?c(x):r;}

```

-10 bytes thanks to *@ceilingcat*.

Ok, my challenge is harder than I thought it would be with everything in a single array like that. ;) But since it's been more than I year ago since I posted this challenge, I decided to give it a go myself. Took me quite a while with multiple work-arounds and quirks.. So it can definitely be golfed some more, but I'll look into that another time. This already took way longer than I expected..

**Explanation:**

Try it here.

```
int c(int[]a){      // Recursive method with integer-array parameter & integer return
  int t=0,f=0,q,    //  Temp integers
      r=0,          //  Result-integer
      i=-1,         //  Index-integer
      l=a.length,   //  Length of the input-array
      x[];          //  Temp array we use when there is a war
  for(;++i<3        //  Loop `i` in the range [0,3):
      ;t=           //    After every iteration, change `t` to:
         a[i]>t?    //     If the current item is larger than `t`:
          a[r=i]    //      Use the current item (and save its index in `r`)
         :          //     Else:
          t)        //      Leave `t` the same
    a[i]+=a[i]==1?  //   If the current item is a 1 (Ace/Joker):
         f++*0      //    Increase `f` by 1,
         +13        //    and change the 1 to 14 (by increasing with 13)
        :           //   Else:
         0;         //    Leave the current item the same (by increasing with 0)
  for(;i-->0;       //  Loop `i` in the range (3,0]:
    t=f<1           //   If no Joker/Ace was present
      |a[i]>3       //   Or the current item is NOT a 2 or 3
      |t==3         //   Or `t` is 3:
       &a[i]>2?     //   and the current item is NOT a 2:
        t           //    Leave `t` unchanged
      :             //   Else:
       a[r=o]);     //    Change `t` to the current item (and save its index in `r`)
  for(f=i,          //  Reset `f` to -1
      x=new int[    //  Create the temp array `x` with length:
         q=l<7?     //   If the current length is 6 or lower:
            3       //    New length after war is 3
           :l>7?    //   Else-if the current length is 8 or higher:
            l-3     //    New length after war is the current length - 3
           :        //   Else(-if current length is 7):
            5];     //    New length after war is 5
      l>3&          //  If there is a war:
          ++i<q;)   //   Loop `i` in the range [0,3):
    x[i]=t==a[i]    //    If the current item is at war,
         |i>2?      //    or the current item is after the first 3 items:
          a[++f+3]  //     Fill the new array with the correct next item
         :          //    Else:
          0;        //     Fill the item of the new array with 0
                    //     (since it won't participate in the next round)
  return l>3?       //  If there was a war:
          c(x)      //   Recursive-call with the new array
         :          //  Else:
          r;}       //   Return the index of the card that won

```

---
Tags: code-golf, game, card-games
---