title: Greeting The User

text:
# Question
Title: Greeting The User
Create a program which when run displays the text below:

```
)-*-*-*^_^*-*-*-(
| Welcome User! |
)-*-*-*^_^*-*-*-(

```

Use any functions or language to answer this, have fun. Shortest code wins

# Answer
> 8 votes
# Japt, ~~41~~ 39 bytes

*Saved 2 bytes thanks to @Shaggy*

```
[U="){"-*-*-*^_"ê}("`| WelÖ  U r! |`U]·

```

## Explanation:

```
[U="){"-*-*-*^_"ê}("`| WelÖ  U r! |`U]·
[                                    ]    // Create a new array
 U=                                       // Variable U =
   ")                                     //   ")
     {            }                       //   Evaluate everything in curley-brackets as code
      "-*-*-*^_"ê                         //   "-*-*-*^_" mirrored -> -*-*-*^_^*-*-*-
                  ("                      //   ("
                                          * Now we have [U=")-*-*-*^_^*-*-*-("]
                    `| WelÖ  U r! |`      // "| Welcome User! |" decompressed by `...`
                                     U    // ")-*-*-*^_^*-*-*-("
                                          * Now we have [")-*-*-*^_^*-*-*-(","| Welcome User! |",")-*-*-*^_^*-*-*-("]
                                      ·   // Split with new-lines

```

Try it online!

# Answer
> 33 votes
# Python 2, 54 bytes

```
print(")-*-*-*^_^*-*-*-(\n| Welcome User! |\n"*2)[:53]

```

Try it online!

# Answer
> 12 votes
# T-SQL, 60 bytes

```
PRINT')-*-*-*^_^*-*-*-(
| Welcome User! |
)-*-*-*^_^*-*-*-('

```

SQL allows splitting string literals over lines, so those returns are counted.

Working on a procedural solution, but doubt I'll find one under 60.

**New Edit**: Found a simple `REPLACE` that ties the trivial solution:

```
PRINT REPLACE('1
| Welcome User! |
1',1,')-*-*-*^_^*-*-*-(')

```

Turns out that `REPLACE` will do an implicit conversion of a numeral to a string, so this lets me save 2 characters by eliminating the quotes around my replacement character.

Trying to put it into a variable is too long, due to the overhead of the `DECLARE` (69 bytes):

```
DECLARE @ CHAR(17)=')-*-*-*^_^*-*-*-('PRINT @+'
| Welcome User! |
'+@

```

# Answer
> 8 votes
## Python 2.7, 55 bytes

```
a="\n)-*-*-*^_^*-*-*-(\n"
print a+'| Welcome User! |'+a

```

Pretty simple. Includes leading and trailing newlines.

# Answer
> 7 votes
# C (gcc), ~~78~~ 75 bytes

```
main(i){for(;printf(")-*-*-*^_^*-*-*-(")&i--;puts("\n| Welcome User! |"));}

```

Try it online!

# Answer
> 7 votes
# Bubblegum, 43 bytes

```
00000000: d3d4 d502 c1b8 f838 30ad abc1 55a3 109e  .......80...U...
00000010: 9a93 9c9f 9baa 105a 9c5a a4a8 50c3 a589  .......Z.Z..P...
00000020: ae06 00bd 4d85 9835 0000 00              ....M..5...

```

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~31~~ ~~29~~ 26 bytes

-3 Bytes thanks to Emigna

```
")-*-*-*^_".∞D”|‡Ý‚Ý! |”s»

```

Try it online!

### Explanation

```
")-*-*-*^_".∞D”|‡Ý‚Ý! |”s»
")-*-*-*^_"                # Push )-*-*-*^_
           .∞              # Intersected mirror (results in )-*-*-*^_^*-*-*-( )
             D             # Duplicate top of stack
              ”|‡Ý‚Ý! |”   # Pushes | Welcome User! |
                        s  # Swap top items on stack
                         » # Join on newlines

```

# Answer
> 5 votes
# Charcoal, ~~32~~ 30 bytes

```
_^×*-³(⸿emocleW |‖Ｂ¬Ｊ¹¦¹ User!

```

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

```
_^              Print("_^");
×*-³            Print(Times("*-", 3));
(⸿emocleW |     Print("(\remocleW |");

```

Prints the mirror image of the top left portion of the output.

```
‖Ｂ¬             ReflectButterfly(:¬);

```

Reflects down and to the left to create the top and bottom lines and the left of the middle line.

```
Ｊ¹¦¹            JumpTo(1, 1);
 User!          Print(" User!");

```

Fixes up the middle line.

# Answer
> 4 votes
# JavaScript, 56 bytes

```
alert(`${s=")-*-*-*^_^*-*-*-("}
| Welcome User! |
${s}`)

```

# JavaScript (ES6), ~~50~~ 48 bytes (function)

```
_=>(s=")-*-*-*^_^*-*-*-(")+`
| Welcome User! |
`+s

```

-2 bytes thanks to Rick Hitckcock

# Answer
> 4 votes
# Python 3, 62 bytes

```
print(")-*-*-*^_^*-*-*-(\n| Welcome User! |\n)-*-*-*^_^*-*-*-(")

```

# Answer
> 4 votes
# ///, 42 bytes

```
/#/)-*-*-*^_^*-*-*-(
/#| Welcome User! |
#

```

Try it online!

Shorter than the Bubblegum solution!

# Answer
> 4 votes
# Braingolf, 55 bytes

```
22#)[#-#*]"^_^"[#*#-]#(V"
| Welcome User! |
"R!&@v&@R&@

```

Try it online!

It's 2 bytes shorter than hardcoding the output.

## Explanation

```
22                         Push 2 2s to the stack
                             These are used for loop counting
  #)                       Push )
    [#-#*]                 Push -* 3 times, using one of the 2s
          "^_^"            Push ^_^
               [#*#-]      Push *- 3 times, using the remaining 2
                     #(    Push (
                       V   Create a new stack
                        "
| Welcome User! |
"                          Push \n| Welcome User! |\n to the new stack
 R!&@                      Return to main stack, print entire stack without popping
     v&@                   Switch to 2nd stack, pop and print stack
        R                  Return to main stack, pop and print stack

```

# Answer
> 4 votes
# \>\<\>, ~~56~~ 54 bytes

```
/a"| !resU emocleW |>"01pa
 l?!;o
/"(-*-*-*^_^*-*-*-)"

```

Try it online!

2 bytes saved by AGourd

# Answer
> 4 votes
# Perl 5, 49 bytes

```
print$\=")-*-*-*^_^*-*-*-(","
| Welcome User! |
"

```

Try it online!

Uses the fact that `$\` is implicitly printed after each `print`.

# Answer
> 3 votes
# C, 75 bytes

```
main(){char*S=")-*-*-*^_^*-*-*-(";printf("%s\n| Welcome User! |\n%s",S,S);}

```

# Answer
> 3 votes
# , 35 bytes

```
é)8a-*r(ãhR^_^Äo| Welcome User! |

```

Try it online!

Hexdump:

```
00000000: e929 3861 2d2a 1b72 28e3 6852 5e5f 5e1b  .)8a-*.r(.hR^_^.
00000010: c46f 7c20 5765 6c63 6f6d 6520 5573 6572  .o| Welcome User
00000020: 2120 7c                                  ! |

```

Explanation:

```
é)                          " Insert a '('
  8a                        " Append 8 copies of the following:
    -*<esc>                 "   '-*'
           r(               " Replace the last character on this line with '('
             ãh             " Move to the middle of this line
               R            " And write the following text over the existing text:
                ^_^<esc>    "   '^_^'
                        Ä   " Duplicate this line
o                           " On a new line:
 | Welcome User! |          "   Write the whole middle line

```

# Answer
> 3 votes
# **Pyth, 41 bytes**

It's boring, but I just cant find a way to creat `)-*-*-*^_^*-*-*-(` or `| Welcome User! |` in less bytes than just copying the strings.

```
J")-*-*-*^_^*-*-*-("J"| Welcome User! |"J

Explanation:
J")-*-*-*^_^*-*-*-("                      # J = ")-*-*-*^_^*-*-*-("
                    J                     # Print J with new line
                     "| Welcome User! |"  # Print "| Welcome User! |" with new line
                                        J # Print J with new line

```

try it Online

# Answer
> 3 votes
# C# (.NET Core), 60 bytes

```
_=>")-*-*-*^_^*-*-*-(\n| Welcome User! |\n)-*-*-*^_^*-*-*-("

```

Try it online!

# Answer
> 3 votes
# Golang, 82 bytes

```
func main(){var a string=")-*-*-*^_^*-*-*-(\n";Printf(a+"| Welcome User! |\n"+a)}

```

Try it online!

# Answer
> 3 votes
# Vim, 38 Bytes

```
i)^[8a-*^[r(9hR^_^^[Yo| Welcome User! |^[p

```

Shoutout to the homies in the comments

Original:

```
i)-\*^[vhyl2pa^_^\*-^[vhyl2pa(^[Vyo| Welcome User! |^[p

```

Where `^[` is the `ESC` key

# Answer
> 3 votes
# Sed, 51

Two for the price of one:

```
s/^/)-*-*-*^_^*-*-*-(/p
x
s/^/| Welcome User! |/p
x

```

Try it online.

```
s/^/)-*-*-*^_^*-*-*-(\n| Welcome User! |/p
s/\n.*//

```

Try it online.

# Answer
> 3 votes
# MATLAB / Octave, 53 bytes

```
a=')-*-*-*^_^*-*-*-(';disp([a;'| Welcome User! |';a])

```

# Answer
> 3 votes
# Carrot, 51 bytes

```
)-*-*-*\^_\^*-*-*-(
^*1//.+/gS"
| Welcome User! |
"

```

Try it online!

### Explanation

```
)-*-*-*\^_\^*-*-*-(
^                            Give the stack-string this value ")-*-*-*^_^*-*-*-(\n"
 *1                          Append 1 duplicate of the stack-string to itself
                             stack-string: ")-*-*-*^_^*-*-*-(\n)-*-*-*^_^*-*-*-("
//.+/g                       Get matches of /.+/g and set the stack-array to this result
                             stack-array: [")-*-*-*^_^*-*-*-(",")-*-*-*^_^*-*-*-("]
S"
| Welcome User! |
"                            Join the stack-array on "\n| Welcome User! |\n" and
                             set the stack-string to this result

```

# Answer
> 2 votes
# PHP, 50 bytes

```
<?=$a=")-*-*-*^_^*-*-*-(","
| Welcome User! |
$a";

```

Try it online!

# Answer
> 2 votes
# Mathematica, 52 bytes

```
Column@{t=")-*-*-*^_^*-*-*-(","| Welcome User! |",t}

```

# Answer
> 2 votes
# Ruby, 49 bytes

```
$><<[")-*-*-*^_^*-*-*-("]*2*"
| Welcome User! |
"

```

Try it online!

# Answer
> 2 votes
# Minecraft Functions, 77 bytes

```
tellraw @a {"text":")-*-*-*^_^*-*-*-(\n| Welcome User! |\n)-*-*-*^_^*-*-*-("}

```

# Answer
> 2 votes
# SOGL V0.12, 27 bytes

```
↑αMΟ±.○h+‘╬1"→ū↑, ¶‘θ⁾@∑32ž

```

Try it Here!
I have no idea why I still haven't added a capitalize 1st letter of each word function... Here it uses a 4-byte replacement

# Answer
> 2 votes
# Batch, 70 bytes

```
@SET b=@ECHO )-*-*-*^^^^_^^^^*-*-*-(
%b%
@ECHO ^| Welcome User! ^|
%b%

```

I mostly enjoy this one because all the escape characters make the emoticon `^_^` look like an adorable Lovecraft abomination `^^^^_^^^^`

# Answer
> 2 votes
# C, 65 66 bytes

```
main(){printf("%s| Welcome User! |\n%1$s",")-*-*-*^_^*-*-*-(\n");}

```

Yes, there are other C solutions, also coming in at about 66 bytes.

Ungolfed

```
main()
{
    printf("%s| Welcome User! |\n%1$s",
          ")-*-*-*^_^*-*-*-(\n"
          );
}

```

GCC produces a warning for the missing printf prototype.

The %1$s says use argument 1 (again) for the second string argument.

In real-life programs, it can also be used to pass in precision/width arguments into a printf. This avoids having to use a printf to create the format string for the real printf.

# Answer
> 2 votes
# Braingolf, 48 bytes

```
")-*-*-*^_^*-*-*-("!&@"
| Welcome User! |
"@19&@

```

Try it online!

## Explanation

```
")-*-*-*^_^*-*-*-("        push the string ")-*-*-*^_^*-*-*-(" as characters
                   !&@     print all the characters on the stack without popping
                      "
| Welcome User! |          push the string "\n| Welcome User! |\n"
"
 @19                       pop and print 19 characters on the stack
    &@                     print all the characters on the stack

```

# Answer
> 2 votes
# Java 8, 62 bytes

```
x->"".format("%s| Welcome User! |\n%<s",")-*-*-*^_^*-*-*-(\n")

```

Try it here.

Or as full program (**110 bytes**):

```
interface A{static void main(String[]a){System.out.printf("%s| Welcome User! |\n%<s",")-*-*-*^_^*-*-*-(\n");}}

```

Try it here.

Surprised there wasn't a Java answer yet.

# Answer
> 2 votes
# PowerShell, 47 bytes

```
($z=')-*-*-*^_^*-*-*-(')
"| Welcome User! |
$z"

```

Try it online!

Ran into the problem everyone else is running into: there's not enough meat to justify trying to encode the top line's pattern. A fancier join method also turned out to cost one more byte

# Answer
> 2 votes
# Vyxal `J`, 174 bitsv1, 21.75 bytes

```
`)-*-*-*^_`øM:`| ÷… ƛ⁼! |`$

```

Try it Online!

Most likely golfable.

```
`)-*-*-*^_`                 # literal string
           øM               # flip brackets (`[]()`=>`][)(`) and palindromise
              `| ÷… ƛ⁼! |`  # the compressed string `| Welcome User! |`
             :            $ # put the first string on the top of the stack to wrap it around ^
                            # J flag joins by newlines

```

# Answer
> 1 votes
# Retina, 42 bytes

```

A¶| Welcome User! |¶A
A
)-*-*-*^_^*-*-*-(

```

Try it online!

# Answer
> 1 votes
# PHP, 56 52 bytes

```
<?=$s=")-*-*-*^_^*-*-*-(\n","| Welcome User! |\n$s";

```

# Answer
> 1 votes
# bash, 52 bytes

```
f=")-*-*-*^_^*-*-*-("
echo "$f
| Welcome User! |
$f"

```

# Answer
> 1 votes
# TCL, 73 bytes 54 bytes

~~`set a )-*-*-*^_^*-*-*-(
 set b "| Welcome User! |"
 puts " $a\n $b\n $a"`~~

---

```
puts "[set a )-*-*-*^_^*-*-*-(]
| Welcome User! |
$a"

```

Thanks @sergiol for the suggestion!

# Answer
> 1 votes
# Kotlin, 88 bytes

```
fun main(a:Array<String>){val s=")-*-*-*^_^*-*-*-(";print("$s\n| Welcome User! |\n$s")}"

```

# Answer
> 1 votes
# Stax, 25 bytes

```
æu√hy╘£.ÅJnc¡┐ßD.P☻Θ╖>╘rÇ

```

Run and debug it

# Answer
> 1 votes
# Wren, 64 bytes

```
Fn.new{"1| Welcome User! |
1".replace("1",")-*-*-*^_^*-*-*-(
")}

```

Try it online!

## Explanation

```
Fn.new{                           // New anonymous function
       "1| Welcome User! |
1"                                // Create the string "| Welcome User! |"
  .replace("1",")-*-*-*^_^*-*-*-(
")}                               // Prepend & append the string ")-*-*-*^_^*-*-*-(\n"

```

# Answer
> 1 votes
# C (gcc), 63 bytes

```
f(){printf("%s| Welcome User! |\n%1$s",")-*-*-*^_^*-*-*-(\n");}

```

Try it online!

Three bytes shorter than all the previous solutions because new rules allow functions.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 57 bytes

```
Write("{0}\n| Welcome User! |\n{0}",")-*-*-*^_^*-*-*-(");

```

Try it online!

# Answer
> 1 votes
# C++ (gcc), ~~127~~ 107 bytes

```
#include <iostream>
int main(){std::string a="\n)-*-*-*^_^*-*-*-(\n";std::cout<<a;std::cout<<"| Welcome User! |";std::cout<<a;}

```

Try it online!

Lowered to 107 by noodle man

```
#include <iostream>
int main(){std::string a="\n)-*-*-*^_^*-*-*-(\n";std::cout<<a<<"| Welcome User! |"<<a;}

```

# Answer
> 0 votes
## \>\<\>, ~~76~~ 61 bytes

```
!v"(-*-*-*^_"~! |
 >~")"a"| !resU emocleW |v"61pa10.
l?!;o >

```

# Answer
> 0 votes
# PHP, 55 bytes

```
$a=')-*-*-*^_^*-*-*-(';
echo <<<S
$a
| Welcome User! |
$a
S;

```

# Answer
> 0 votes
# VBA, 48 Bytes

Anonymous VBE immediate window function that takes no input and outputs a greeting to the user via the immediate window

```
a=")-*-*-*^_^*-*-*-(":?a:?"| Welcome User! |":?a

```

# Answer
> 0 votes
# Golang, 67 Bytes

```
func n(){a:=")-*-*-*^_^*-*-*-(\n";Print(a+"| Welcome User! |\n"+a)}

```

Prints with a trailing newline.

Try it online!

# Answer
> 0 votes
# Canvas, 29 bytes

```
-*３×^_＋)×│| Welcome User! |┌）

```

Try it here!

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

```
(u=')-*-*-*^_^*-*-*-(')=>[u,'| Welcome User! |',u].join`
`

```

Try it online!

I am sure I can golf if down , but later

# Answer
> 0 votes
# Runic Enchantments, 46 bytes

```
>")-*-*-*^_^*-*-*-(":$ak"| Welcome User! |"ak@

```

Try it online!

It will appear to process until it times out, due to the two `^` commands which spawn IPs that do nothing (necessitating the explicit entry `>`). I am disapointed that this is 2 bytes shorter than the multiple IP method. Constructing the first and last lines using multiplication/duplication turns out to be even more expensive as well (50 bytes). :(

# Answer
> 0 votes
# PowerShell, 48 bytes

```
$a=')-*-*-*^_^*-*-*-(';$a;"| Welcome User! |";$a

```

Try it online!

# PowerShell, 54 bytes

```
$a=')-*-*-*^_^*-*-*-(';write $a;"| Welcome User! |";$a

```

Try it online!

### Old - 68 bytes

```
Write-Host ")-*-*-*^_^*-*-*-(`n| Welcome User! |`n)-*-*-*^_^*-*-*-("

```

# Answer
> 0 votes
# , 61 bytes

```
r=")-*-*-*^_^*-*-*-(\n";cat(r,"| Welcome User! |\n",r,sep="")

```

Try it online!

Has a trailing newline. I couldn't see if that was approved or not, so I just rolled with it.

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


title: Concatenating n with n + 1

text:
# Question
Title: Concatenating n with n + 1
## Introduction

OEIS sequence A127421 is the sequence of numbers whose decimal expansion is a concatenation of 2 consecutive increasing non-negative numbers. Put simply, every number in the sequence is formed by putting together *n* with *n+1* for some non-negative, integer value of *n*. The first several terms are:

> 1, 12, 23, 34, 45, 56, 67, 78, 89, 910, 1011, 1112, 1213, 1314, 1415, 1516, 1617, 1718, 1819, 1920, 2021, 2122, 2223, 2324, 2425, 2526, 2627, 2728, 2829, 2930, 3031, 3132, 3233, 3334, 3435, 3536, 3637, 3738, 3839, 3940, 4041, 4142, 4243, 4344, 4445, 4546, …

## Challenge

Given a single positive integer *n*, print the first *n* entries of OEIS sequence A127421 in increasing order.

* Input and output can be in any acceptable format. Strings or numbers are fine for output.
* Leading zeroes are **not** permitted.
* Either a full program or function is permitted.
* For the purposes of this challenge, *n* will be positive and under 100.
* Standard loopholes are disallowed by default.
* This question is code golf, so lowest byte-count wins.
* Here is some sample input and output:

```
1 => 1
2 => 1, 12
3 => 1, 12, 23
10 => 1, 12, 23, 34, 45, 56, 67, 78, 89, 910

```

If you have any questions, don't hesitate to ask. Good luck.

*P.S this is my first challenge, so hopefully this all makes sense.*

*EDIT: Removed output restriction to allow numbers or strings.*

# Answer
# Jelly, 3 bytes

```
ŻVƝ

```

A monadic link accepting an integer which yields a list of integers

**Try it online!**

### How?

```
ŻVƝ - Link: integer       e.g. 59
Ż   - zero-range               [0,1,2,3,4,5,6, ... ,58,59]
  Ɲ - apply to each pair: i.e: [0,1] or [5,6]  or  [58,59]
 V  -   evaluate* jelly code   1     or 56     or  5859
    -                       -> [1,12,23,45,56, ... 5859]

* When given a list V actually joins the Python string values and evaluates that
  ...so e.g.: [58,59] -> ['58','59'] -> '5859' -> 5859

```
> 13 votes

# Answer
# , 32 bytes

```
strtoi(paste0((x=1:scan())-1,x))

```

Try it online!

Outgolfed by MickyT, so go upvote that answer!
> 10 votes

# Answer
# Python 3, 39 bytes

```
f=lambda n:1//n or f'{f(n-1)} {n-1}{n}'

```

Try it online!
> 10 votes

# Answer
## Haskell, ~~38~~ 37 bytes

```
f n=("":)>>=zipWith(++)$show<$>[1..n]

```

Try it online!

Thanks to Cat Wizard for a byte!
> 8 votes

# Answer
# Perl 6, ~~19~~ 18 bytes

```
{(^$_ Z~1..$_)X+0}

```

Try it online!

Anonymous code block that zips the range 0 to n-1 with 1 to n using the concatenation operator, then adds 0 to every element to force it to a number and remove leading 0s.
> 7 votes

# Answer
# Cubix, 19 bytes

```
I.1.W)>OSo;u.uO;@!-

```

Try it online!

This wraps onto the cube as follows

```
    I .
    1 .
W ) > O S o ; u
. u O ; @ ! - .
    . .
    . .

```

Watch It Run

Got a little room to play with yet, but at the moment

* `W` redirect to the top face heading down
* `I1>` set up the stack with the input and 1 then redirect into the main loop
* `OSo;u` output the top of stack, add space to stack, output, remove and uturn
* `-!@;Ou)` subtract TOS from input, if 0 halt else pop result, output TOS, uturn and increment TOS. Back into the main loop.
> 7 votes

# Answer
# , ~~30~~ 29 bytes

An extra byte thanks to @Giuseppe

```
10^nchar(n<-1:scan())*(n-1)+n

```

Try it online!

A mostly mathematical solution, except for using `nchar()` rather than `floor(log10())`. I was really surprised that it came in shorter than the string version.
> 7 votes

# Answer
# APL (Dyalog), ~~13~~ 12 bytes

*1 byte saved thanks to @FrownyFrog*

```
(⍎⍕,∘⍕1∘+)¨⍳

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~42~~ 41 bytes

```
f=lambda n:n-1and f(n-1)+[`n-1`+`n`]or[1]

```

Try it online!

Recursive function that returns a mixed list of strings and integers
> 4 votes

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

```
f=n=>--n?f(n)+','+n+-~n:1

```

Try it online!
> 4 votes

# Answer
# Brachylog, 6 bytes

```
⟦s₂ᶠcᵐ

```

Try it online!

### Explanation

```
⟦         Range: [0, …, Input]
 s₂ᶠ      Find all substrings of length 2
    cᵐ    Map concatenate

```
> 4 votes

# Answer
# Haskell, 34 bytes

```
f n="1":[show=<<[i-1,i]|i<-[2..n]]

```

Try it online!
> 4 votes

# Answer
# Blossom, 88 bytes

```
rule e<int x>[1(x)]=>[1(x-1),2(str(x)+str(x+1))];rule c[1(0)]=>[];e!c

```

Blossom is a graph programming language I'm working on. It can only take graphs as inputs, so this programme expects a graph comprising a single node with its label an integer. It returns a graph of connected edges to form the closest to an array I can get, and the resultant graph is printed to output.

An unminified version of the code is this:

```
rule expand <int x>
    [ 1 (x) ]
 => [ 1 (x-1), 2(str(x)+str(x+1)) ]
where x > 0;

rule clean
    [ 1 (0) ]
 => [];

expand! clean

```

It defines two rules: one called `expand`, which (while there is a node with an integer-valued label in the current graph) creates another node with its increment concatenated, and lowers the value. This rule also has the condition that x is greater than 0.

The `!` executes this rule for as long as it can be applied on the graph, so in this case it will execute until x is 0. And then the `clean` rule removes this 0 node.

Blossom was not made for golfing, but it doesn't do too badly, I don't think., considering what it is. There currently isn't really an easy way for people to test blossom code (and the interpreter I'm working on at the moment is not quite finished and a little buggy), but this isn't exactly a competing entry!
> 4 votes

# Answer
# Python 3, ~~55 48 47~~ 43 bytes

```
f=lambda n:n-1and f(n-1)+[f"{n-1}{n}"]or[1]

```

Try it online!

Recursive function that takes an integer and returns a mixed list of strings and numbers.
> 3 votes

# Answer
# C (gcc), 44 43 bytes

```
f(i){i--&&printf(" %2$d%d"+5*!f(i),i+1,i);}

```

Try it online!
> 3 votes

# Answer
## Shakespeare, 703 bytes

```
Q.Ajax,.Ford,.Act I:.Scene I:.[enter Ajax and Ford]Ford:Open mind!Scene V:.Ajax:You is the sum of thyself the sum of myself the sum of a big bad fat old red pig a big bad fat old lie!Ford:Open mind!Is you nicer zero?Ajax:If so, you is twice the sum of the sum of twice thyself twice thyself thyself!If so,Let us Scene V!Ford:You a cat!Open heart!Scene X:.Ajax:You is the sum of thyself a pig!Is you worse than a cat?If so,let us Scene C.Remember thyself.You is the sum of the sum of a big old red cute rich cat a big old red cute joy a big old pig!Speak mind!You is a big old red cute rich cat!Speak mind!Recall!Ford:Open heart!You is the sum of thyself a joy!Open heart!Let us Scene X.Scene C:.[exeunt]

```

try it here

## ungolfed version

```
127421th Night.
Ajax, likes to read the stars.
Ford, someone Ajax can always count on.
Act I:.
Scene I: Ajax reads a star.
[enter Ajax and Ford]
Ford: Open your mind!
Scene V: Ford counts what ajax has learned.
Ajax: you are the sum of thyself and the sum of myself and the sum of a big bad fat old red pig and a big bad fat old lie!
Ford: Open Your mind! Are you nicer than zero?
Ajax: If so, you are twice the sum of the sum of twice thyself and twice thyself and thyself!
If so, Let us Scene V!
Ford: You are a cat! Open your heart!

Scene X: Ajax and Ford recall the nights.
Ajax: You are the sum of thyself and a pig! Are you worse than a cat? If so, Let us Scene C.
Remember thyself.
You are the sum of the sum of a big old red cute rich cat and a big old red cute joy and a big old pig!
Speak you mind!
You are a big old red cute rich cat! Speak your mind! Recall your finest hour!
Ford: Open your heart! You are the sum of thyself and a joy! Open your heart! Let us Scene X.
Scene C: Fin.
[exeunt]

```
> 3 votes

# Answer
# Groovy, 35 bytes

```
{(0..<it)*.with{""+it+++it as int}}

```

Try it online!

I came up last minute with the idea of using \*.with instead of .collect. I have no idea what `it+++it` parses to but whether it's `it++ + it` or `it + ++it` they both do the same thing. I tried to think of a way of getting rid of the \< in ..\< by turning it into 1..it and decrementing but I don't think it would get any shorter.
> 3 votes

# Answer
# Pyth, ~~9~~ ~~8~~ 6 bytes

```
ms+`dh

```

Try it online!

Explanation:

```
       - implicit output
m      - map function with argument d:
  +    -  concatenate
    d  -  argument d
   `   -  to string
     h -  into implicit d + 1
       - into Q (implicit input)

```
> 3 votes

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

```
Mrx'_Jx}

```

Try it online!

```
Mrx'_Jx}
Mrx'     # For every number in the range [0, input)
       } # Input + 1
     Jx  # Prepend the input to that
    _    # Parse as number to remove leading 0s

```
> 3 votes

# Answer
# Jelly, 4 bytes

```
ḶżRV

```

Try it online!

### How it works

```
ḶżRV  Main link. Argument: n

Ḷ     Unlength; yield [0, ..., n-1].
  R   Range; yield [1, ... n].
 ż    Zipwith; yield [[0, 1], ..., [n-1, n]].
   V  Eval; cast each array to string and evaluate, yielding integers.

```
> 2 votes

# Answer
# Python 2, 44 bytes

```
for i in range(input()):print`i`*(i>0)+`i+1`

```

Try it online!
> 2 votes

# Answer
# Japt `-m`, ~~6~~ 5 bytes

```
ó2 ¬n

```

Try it online!

As always, *know the flags*.

### Unpacked & How it works

```
-m       Convert to range and map...

Uó2 q n
Uó2      Construct [U, U+1]
    q    Join
      n  Convert to number

         Implicit output (Array is printed as comma-delimited values)

```
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
>GNJ,N

```

Try it online!

**Explanation**

```
>G       # for N in [1 ... input]
  N      # push N
   J     # join stack
    ,    # print
     N   # push N (for next iteration)

```

`LεD<ìï` would work for same byte count but with list output
> 2 votes

# Answer
# APL (Dyalog Classic), 9 bytes

```
1,2,/⍕¨∘⍳

```

Try it online!
> 2 votes

# Answer
# Powershell, ~~27~~ 26 bytes

```
1.."$args"|%{"$p$_";$p=$_}

```

-1 byte: thanks AdmBorkBork

Test script:

```
$f = {
1.."$args"|%{"$p$_";$p=$_}
}

&$f 1
""
&$f 2
""
&$f 3
""
&$f 10
""
&$f 46

```
> 2 votes

# Answer
# Husk, ~~11~~ 9 bytes

<sup>-2 thanks to @BMO!</sup>

```
mSöd+d←dḣ

```

Try it online!

## Explanation

```
m          map(                                              )
 S                                               <*>
  ö            (           .).    .         .
   d            fromDecimal
    +                         (++)
     d                             toDecimal
      ←                                      (+1)
       d                                            toDecimal
                                                              .
        ḣ                                                      (\n->[1..n])

mSöd+d←dḣ  map((fromDecimal.).(++).toDecimal.(+1)<*>toDecimal).(\n->[1..n])

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~103~~ ~~71~~ ~~64~~ 56 bytes

---

**Golfed** Try it online!

```
i=>{for(int x=0;x<i;)Write($"{(x>0?$",{x}":"")}{++x}");}

```

---

**Ungolfed**

```
i => {
    for( int x = 0; x < i; )
        Write( $"{( x > 0 ? $",{x}" : "")}{ ++x }" );
}

```

---

**Full code**

```
Action<Int32> a = i => {
    for( int x = 0; x < i; )
        Write( $"{( x > 0 ? $",{x}" : "")}{ ++x }" );
    };

Int32[]
    testCases = new Int32[] {
        1,
        2,
        3,
        10,
    };

foreach( Int32[] testCase in testCases ) {
    WriteLine( $" Input: {testCase}\nOutput:" );
    a(testCase);
    WriteLine("\n");
}

```

---

**Older versions:**

* ***v1.2, 64 bytes***

```
i=>{for(int x=0;x<i;)Write($"{(x>0?$",{x}":"")}{++x}");}

```
* ***v1.1, 71 bytes***

```
i=>{for(int x=0;x<i;)System.Console.Write($"{(x>0?$",{x}":"")}{++x}");}

```
* ***v1.0, 103 bytes***

```
i=>{for(int x=0;x<i;)System.Console.Write($"{(x>0?",":"")}{x++*System.Math.Pow(10,$"{x}".Length)+x}");}

```

---

**Releases**

* **v1.3** \- `- 8 bytes` \- Removed `Console` thanks again to raznagul
* **v1.2** \- `- 7 bytes` \- Removed `System` thanks to raznagul
* **v1.1** \- `-32 bytes`
* **v1.0** \- `103 bytes` \- Initial solution.

---

**Notes**

* None
> 2 votes

# Answer
# Haskell, 37 bytes

```
f x=[[y-1|y>1]++[y]>>=show|y<-[1..x]]

```

Try it online!
> 2 votes

# Answer
# J, 14 bytes

```
(,&.":>:)"0@i.

```

Try it online!
> 2 votes

# Answer
## ABAP, 101 bytes

Not really a golfing language, but I'm having a lot of fun with it

```
WHILE x<w.
CLEAR z.
IF x=1.
WRITE x.
ELSE.
CONCATENATE y x INTO z.
WRITE z.
ENDIF.
y=x.
x=x+1.
ENDDO.

```

W is the input term, X is the counter from 1, Y is X-1 from the second pass onward, Z is concatenated string.
> 2 votes

# Answer
# PHP, ~~33~~ 32 bytes

```
while($argv[1]--)echo" $i".++$i;

```

Try it Online

Old version

```
for(;$i<$argv[1];)echo" $i".++$i;     // 33 bytes

```
> 2 votes

# Answer
# Python 2, 41 bytes

```
lambda l:[`n`[:n]+`n+1`for n in range(l)]

```

Try it online!
> 2 votes

# Answer
# Javascript, 43 ~~44,46,49,53~~ bytes

```
n=>[...Array(n)].map((_,a)=>~~(a+(a+1+"")))

```

Previous versions :

```
n=>[...Array(n)].map((_,a)=>~~(a+(""+ ++a)))
n=>[...Array(n)].map((_,a)=>0- -(a+(""+ ++a)))
n=>[...Array(n).keys()].map(a=>0- -(a+(""+ ++a)))
n=>[...Array(n).keys()].map(a=>parseInt(a+(""+ ++a)))

```

Saved 3 bytes thanks to @Shaggy's solution (which is better than mine) to remove `.keys()`
> 2 votes

# Answer
# yup, 48 bytes

```
0eee0ee-0ee-*:0e#[:@]0e-{]:[:]-:#0e0~--#]:@]0e-}

```

Try it online!

## Explanation

yup only knows of a few commands. To modify data, I'll be using `0` (nilad pushing that number), `e` (natural exponentiation), and `-` (subtraction).

For example, the snippet `0e` is equal to `1`, since \\$e^0=1\\$.

This program is divided into two parts: initialization and iteration.

### Initialization

```
0eee0ee-0ee-*:0e#[:@]0e-

```

`0eee` pushes \\$e^e\approx15.1543\\$ and `0ee` pushes \\$e\approx2.7183\\$. Thus, the expression `0eee0ee-0ee-` pushes:

$$e^e-e-e\approx9.7177$$

This encodes `0x10` (the linefeed), since numbers are rounded to the nearest integer before being outputted. This is our numeric separator.

The next part is to initialize the stack with data. `*:` pushes the input twice, and `0e#` outputs a `1`. `[:@]` outputs a linefeed without popping it from the stack, and `0e-` decrements the input. This handles the edge case of outputting `1` instead of `01`. Rather than handle this with a conditional, hardcoding the first entry is shorter.

## Iteration

```
{]:[:]-:#0e0~--#]:@]0e-}

```

`{...}` loops while the TOS is defined and positive. In this case, it will stop when it hits zero. Each iteration starts off with a stack like this:

```
[9.7177, input, iterator]

```

`iterator` starts at `input - 1`. `]:[:]-` calculates `input - iterator` and gives us our true iterator value. Then, `:#0e0~--#` first outputs the true iterator then the same number plus 1, where `0e0~--` encodes \\$-(-n-e^0)=-(-n-1)=n+1\\$. Then, `]:@]` restores the stack to its initial shape and `0e-` subtracts `1` from the iterator, continuing our loop. This repeats until `iterator` reaches `0`, at which point the loop stops and the program terminates.
> 2 votes

# Answer
# Python 3, 44 bytes

```
lambda n:[f"{j or''}{j+1}"for j in range(n)]

```

Try it online!
> 2 votes

# Answer
# Vyxal, 4 bytes

```
ƛ‹p⌊

```

Try it Online!
> 2 votes

# Answer
# Scratch, 107 bytes

```
define(y
delete all of[x v
set[i v]to(0
repeat(y
add((join(i)((i)+(1)))-())to[x v
change[i v]by(1
end
say(x

```

I would've used `for each`, but scratchblocks doesn't support it.
> 2 votes

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

```
{.,/$x+!2}'!:

```

Try it online!

`!` generate the list 0 1 ... n-1

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

`'` applied to each

`!2` is `0 1`

`x+!2` is `x, x+1`

`$` format as strings

`,/` concatenate

`.` evaluate (convert to number)
> 1 votes

# Answer
# Jelly, ~~8~~ 6 bytes

```
ṭ’DFḌ)

```

Try it online!

```
ṭ’DFḌ)    Monadic link with argument n
     )    For each int in the range 1..n
 ’        n-1
ṭ         [n-1, n]
  D       Digits of n-1 and n
   F      Flatten into one list
    Ḍ     Convert back to an integer.

```
> 1 votes

# Answer
# Canvas, 6 bytes

```
ŗ²；＋┤］

```

Try it here!

Explanation:

```
{     ]  map over 1..input
 ŗ         convert to string (required as `＋` needs 1 arg to be a string to not add)
  ²;       place a 0-indexed version of the index below TOS
    +      join the two
     ┤     cast to number

```

`ŗ²×┤］` (or even `²×┤］`) would work if I didn't try to push the absolute most out of characters and didn't make `×` \- reverse add - do not that when not receiving 2 strings.
> 1 votes

# Answer
# cQuents, 11 bytes

```
=1::($-1)~$

```

Try it online!

Way too long for a language that this is supposed to be easy in, guess I should have implemented unary subtract-one and add-one operators.

# Explanation

```
=1            First term in sequence is 1
  ::          Mode: for input n, output first n terms in sequence
              For each term in the sequence:
    ($-1)      Subtract 1 from the current index
         ~$    Concatenate that to the current index

```
> 1 votes

# Answer
# APL (Dyalog Classic), 13 bytes

```
2{⍎∊⍕¨⍺⍵}/0,⍳

```

Try it online!
> 1 votes

# Answer
# Perl 5, ~~24~~ 21 bytes

*@DomHastings came up with a way to save 3 bytes*

```
say$i++.$i|0for 1..<>

```

Try it online!
> 1 votes

# Answer
# Momema, 36 bytes

```
z0w+1=*0-8*0w00+1*0-8*0-9 10z=+_M-*0

```

Try it online! Requires the `-i` interpreter flag.

## Explanation

```
                                                     #  i = 0
d   0            #  d0:  nop                         #  do {
i   (+ 1 =*0)    #  i0:  jump to i(![0])             #    if i {
-8  *0           #       print [0]                   #      print i
i   0            #  i1:  nop                         #    }
0   (+ 1 *0)     #       [0] = [0] + 1               #    i += 1
-8  *0           #       print [0]                   #    print i
-9  10           #       print chr(10)               #    print \n
d   =(+ _M -*0)  #  d1:  jump to d(!!(input - [0]))  #  } while (input - i != 0)

```

The Momema reference interpreter provides an "interactive mode", enabled by `-i`, which is intended to be used on the command line.

One of the features it allows is the ability to add *holes*, denoted by `_`, which effectively allow one to substitute an integer read from STDIN into an expression. This is already shorter than `*-8` (read from memory-mapped I/O location `-8`), which does the same thing without interactive mode and without displaying a prompt to STDERR.

Crucially, holes can also be *named* with a sequence of capital letters after the `_`. Evaluation of named holes is memoized. Input will be read the first time a named hole is evaluated but subsequent evaluations of a hole with the same name will reuse the input number. This means that we can use `_M` to stand in for "the input", but input will only be read on the first iteration of the loop.
> 1 votes

# Answer
# Red, 56 bytes

```
func[n][prin"1 "repeat i n - 1[prin rejoin[i i + 1" "]]]

```

Try it online!
> 1 votes

# Answer
# Rust, 56 bytes

```
|n|(0..n).map(|n|format!("{}{}",n,n+1).parse().unwrap())

```

Try it online!
> 1 votes

# Answer
# Java, 48 bytes

```
String f(int n){return--n>0?f(n)+","+n+-~n:"1";}

```

Port of tsh's JavaScript answer. Try it online here.

Ungolfed:

```
String f(int n) { // recursive function taking an integer as argument and returning a String
    return --n > 0 ? f(n) // decrement n and recurse if n is still positive after
                   + "," + n // return the result of the recursive call concatenated with n and ...
                   + (- ~n) // ... n+1; writing it as -~n gives it precedence over the concatenation
                   : "1"; // if n is now 0 on the other hand, return "1"
}

```
> 1 votes

# Answer
# MATL, 9 bytes

```
:"@qV@VhU

```

Try it online!

```
              % implicit input n
:             % range, push 1..n
"             % for loop:
 @            % push for loop index
 q            % decrement
 V            % convert to string (num2str)
 @            % push for loop index
 V            % convert to string (num2str)
 h            % horizontally concatenate
 U            % convert to number (str2num)
              % implicit end of for loop
              % implicit end of program, display stack contents

```
> 1 votes

# Answer
# Panacea, 6 bytes

```
re
D>j

```

Explanation:

```
r        Range [0.. input]
 e       Map each element with the following line
D        Duplicate
 >       Increment
  j      Join digits; multiply by ten and add
         Since this works with integers, it removes the preceding 0.

```
> 1 votes

# Answer
# Japt, 5 bytes

```
õÈsiY

```

Try it

---

## Explanation

```
          :Implicit input of integer U
õ         :Range [1,U]
 È        :Map each integer at index Y
  s       :  Convert to string
   iY     :  Prepend index
          :  Implicitly convert back to integer
          :Implicit output of resulting array

```

---

## Alternative

```
Ç°s+Z

```

Try it

```
          :Implicit input of integer U
Ç         :Map each integer Z in the range [0,U)
 °        :  Postfix increment
  s       :  Convert to string
   +Z     :  Append (the now incremented) Z
          :  Implicitly convert back to integer
          :Implicit output of resulting array

```
> 1 votes

# Answer
# , 20 bytes

```
".(,&":)/@(,>:)"0@i.

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 33 bytes

```
: f dup 1 ?do i . i 1 .r loop . ;

```

Try it online!

### Explanation

Loops through all numbers in range and outputs the number twice, the first with a space appended, and the second without.

This results in the first output being appended to the previous output. To fix the last case, the input is outputted so that it can be appended to the last number in the loop.

### Code Explanation

```
: f                   \ start a new word definition
  dup 1               \ duplicate the input and put a 1 on the stack
  ?do                 \ begin counted loop from 1 to n (does nothing if 1 == n)
    i .               \ output loop index with a space appended
    i 1 .r            \ output loop index right-aligned with minimum 1 character length
  loop                \ end the loop
  .                   \ output the input we duplicated earlier
;                     \ end the word definition

```
> 1 votes

# Answer
# Yabasic, 37 bytes

An anonymous function that takes input from STDIN and outputs to STDOUT.

```
Input""n
?1
For i=2TO n?i-1,"",i
Next

```

Try it online!

-14 bytes thanks to @ErikF
> 1 votes

# Answer
# Excel VBA, 29 bytes

An anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the console.

```
?1:For i=2To[A1]:?i-1 &i:Next

```
> 1 votes

# Answer
# dc, 29 bytes

```
[d1-d0<F]dsFx+p[npz1<G]sGz1<G

```

Try it online!

This is a good showing for dc because its printing capabilities are so limited, but line up perfectly with the challenge spec. Input is from the stack (and must be the only thing on the stack), output is to stdout. There's some duplication near the end I can't figure out how to get rid of without breaking the case n=1

# Explanation

```
F will be the macro [d1-d0<F]
d        copy the top of the stack
 1-      decrement
   d0<F  repeat (tail recursion) until a 0 is on top

G will be the macro [npz1<G]
n        print the top (pop, but no newline)
 p       print the new top (newline, but no pop)
  z1<G   repeat (tail recursion) until only one number is on the stack

Full program (example input: 4)
[d1-d0<F]dsFx      Store F and run it: new stack is 0 1 2 3 4
+                  Drop the zero (can't just recurse to 1, or n=1 breaks)
p                  Print (no pop) the '1': stack is 1 2 3 4
[npz1<G]sG        Store G
z1<G               Run G if there's more than one number on the stack

```
> 1 votes

# Answer
# dc, 34 bytes

```
sj1psi[lid1+dsiZAr^*li+pzlj>M]dsMx

```

Try it online!

Completely different (and less golfy, unfortunately) approach than Sophia's `dc` answer. I juggle a lot of register activity here that I wish I could cut down, seems the likeliest way to golf a couple of bytes. Expects input as the sole stack entry.

`sj1psi` stores the input into register `j`, prints the initial 1, and stores 1 in register `i`. Macro `M` duplicates `i`, increments it, and then multiplies it by 10 to the power of however many digits the incremented value has (`ZAr^*`). Fetches the newly incremented version, and adds the two together. Compares register `j` to the number of entries on the stack, and runs until they match.
> 1 votes

# Answer
## MATLAB 45 63 bytes

```
@(j)eval('for a=0:j-1;disp([num2str(a)*a/a,num2str(a+1)]);end')

```

Somewhat ugly `*a/a` in order to avoid printing leading zero for the first element

Fixed by wrapping into `disp` and anonymous function
> 1 votes

# Answer
# , 93 bytes

```
import std.math;_[]f(_)(_ n){_[]k;foreach(i;0..n)k~=++i+10^^(cast(_)i--.log10+1)*i;return k;}

```

Try it online!

I couldn't find a nice (short) solution that evades an `import`, and this was the shortest of the bunch.
> 1 votes

# Answer
# QBasic, ~~60~~ 53 bytes

```
INPUT n
?1
FOR i=2TO n
?STR$(i-1)MID$(STR$(i),2)
NEXT

```

~~A math-based solution, because converting numbers to strings in QBasic is a lot more complicated than it ought to be.~~ Nope, strings are still shorter, you just have to special-case the first item. The problem with `STR$(i)` is that it adds a space to the start of positive numbers, so we take all but the first character by using `MID$`. Other than that, it's pretty straightforward.
> 1 votes

# Answer
# DC, 33 bytes

```
si[lidZAr^spd1-dsilp*+li0<d]dsdxf

```

Explanation

```
si[lidZAr^spd1-dsilp*+li0<d]dsdxf  Whole program.
si                                 Save the value on the stack to the i register.
  [                        ]dsdx   Create a macro, duplicate it, store it in the d register, and execute it.
   li                              Put the value from the i register on the stack.
     dZ                            Duplicate the top value, and change it to the number of digits it has.
       Ar                          Push 10 on the stack, and reverse the top two values.
         ^sp                       Do 10^x, and store it in the p register.
            d1-                    Duplicate the top value, and subtract 1 from it.
               dsi                 Duplicate the top value, and store it in the i register.
                  lp*+             Put the value from the p register on the stack, and multiply it by the the value we just put in the i register. Then, add the top two values together.
                      li0<d        Put the value from the i register and then 0 on the stack. If 0 < li, then we run the d macro again.
                                f  Print the stack.

```

Input is the number of numbers to be generated, on the stack.

Output is printed.
> 1 votes

# Answer
# Kotlin, 48 bytes

```
{"1, "+(2..it).map{"$it${it+1}"}.joinToString()}

```

Yes I know, I could save 1 more byte by removing the blank behind the first comma, but it looks nicer with it :-)

Try it online!
> 1 votes

# Answer
# Shakespeare Programming Language, 310 bytes

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy.Ajax:You cat.Open heart.[Exit Ajax][Enter Page]Scene V:.Ford:Am I worse Ajax?If notlet usScene X.You be twice the sum ofa cat a big big cat.Speak thy.Page:Open heart.You be the sum ofyou a cat.Open heart.Let usScene V.Scene X:.[Exeunt]

```

Try it online!
> 1 votes

# Answer
# MathGolf, ~~8 6 5~~ 4 bytes

```
{└§p

```

Try it online!

Outputs a newline separated series.

### Explanation:

```
{└§p
{       Start a loop over the range(0, input)
 └      Push the top of stack (implicitly the index of the loop) + 1
  §     Concatenate the two (this removes leading 0s)
   p    And print the value

```
> 1 votes

# Answer
# Runic Enchantments, 33 bytes

```
/01iR1-:0)?;{1+:
\$1<\}$q}:+1{$ '

```

Try it online!

Uncompressing the entry sequence and moving the reflectors to the other side:

```
>1$01iR1-:0)?;{1+:\
      \}$q}:+1{$ '/

```

Entry sequence (`>1$01i`) is fairly straight forward. Push and print `1`, push `0`, push `1`, read input and push it to the top of the stack.

At `R` we enter the program's main loop (unrolled with directional control characters removed):

```
1-:0)?;{1+:' ${1+:}q$}

```

At this point the stack is `[0,1,i]` where `i` is the input value.

The loop subtracts 1 from the input value (`1-`), compares it to greater than 0 (if true, skip terminator, else terminate; `:0)?;`).

Then a series of stack manipulations (`{1+:{1+:}`) and increments to result in `[2,(i-1),1,1,2]` as well as printing a space (`' $`). `q` then concats the top two items on the stack, which is then printed (giving `12` in the output stream).

Finally the stack is rotated once more, leaving `[1,2,(i-1)]` as the input to the next loop iteration.

## Bonus challenge: using two IPs? 40 bytes

```
>1$0iR1-:0)?;1{+:' \
> F1iU }$~?=am$?=9m/

```

Try it online!

As there's no way to clone the input to a second instruction pointer (I have thought about stack cloning, so this may be possible in the future, but the spec for it would be difficult to implement), we have to read it from the input stream twice.

Flow results in the second pointer being a step behind the first (avoiding merging) and the `F`izzle lets us distinguish the two IPs, letting one print a space and the other discards it. I can't figure out a shorter way of performing this check.

However if it allowable to print *two* spaces as a separator it can be reduced to *this* (30 bytes):

```
>1$0iR1-:0)?;1\
> F1iU}$:+{$ '/

input: 4 4
output: 1  12  23  34

```

But this is an admittedly dubious answer due to how it has to take input, but 3 bytes shorter than the single IP answer, which is interesting.

Try it online!

### Update: Stack transfer

Getting the two pointers to enter the `T` command in the right execution order is a *huge* pain. The remaining two spaces in this program can't be removed, as it messes with the timing, but it avoids having to supply the input value twice. Prints 2 spaces between each entry in the sequence (35 bytes).

```
>1$0y TR1-:0)?;1\
 >1i:1/U}$:+{$ '/

```

Try it online!
> 1 votes

# Answer
# MBASIC, ~~102~~ 94 bytes

```
1 INPUT N:FOR I=0 TO N-1:IF I>0 THEN PRINT MID$(STR$(I),2);
2 PRINT MID$(STR$(I+1),2);" ";:NEXT

```

Output:

```
? 3
1 12 23

? 10
1 12 23 34 45 56 67 78 89 910

? 16
1 12 23 34 45 56 67 78 89 910 1011 1112 1213 1314 1415 1516

```

Could have been much cleaner, but the STR$(n) number-to-string conversion function returns with a leading space that had to be dealt with.

Turns out the variable for NEXT and the trailing PRINT are not needed, saving 8 bytes.
> 1 votes

# Answer
# jq, ~~30~~ 27 characters

```
1,(range(1;.)|"\(.)\(.+1)")

```

Sample run:

```
bash-5.1$ jq -r '1,(range(1;.)|"\(.)\(.+1)")' <<< 5
1
12
23
34
45

```

Try it online!
> 1 votes

# Answer
# \>\<\>, ~~15~~ 13 bytes

```
ln1-:?!;aoln:

```

Try it online!

We take in the input as a command line argument.

Thanks to @jo king for 2 byte loss (noticing the input loop value could be used as stack length.

Explanation (simple):

```
ln1-:?!;aoln:
ln              : Add the length of the stack to the stack and print.
   1-:?!;       : Take 1 off the input loop and check if zero, if 0, end.
         ao     : Print new line
           ln:  : Add the length of the stack to the stack, print and duplicate the input loop.

```
> 1 votes

# Answer
# J-uby, ~~26~~ 25 bytes

-1 byte thanks to Razetime

```
:*|:*&(-[I,:+&1]|:join|Z)

```

Attempt This Online!

## Explanation

```
:* |              # Range 0..n-1, then
:* & (            # map with ...
  -[I, :+ & 1] |  #   [m, m+1] (I is identity), then
  :join |         #   join, then
  Z               #   convert to int (for special case "01")
)

```
> 1 votes

# Answer
# Nim, 70 bytes

```
import sugar,sequtils,math
s(x=>toSeq(1..x).map y=>(y-1)*10^len($y)+y)

```

Attempt This Online!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
ʀ¨pJ⌊

```

Try it Online!

### Explained

```
ʀ¨pJ⌊
ʀ     # Inclusive zero range
 ¨p   # each overlapping pair
   J  # merge
    ⌊ # floor

```
> 1 votes

# Answer
# Nim, 46 bytes

```
proc(x:any)=
 echo 1;for i in(2..x):echo i-1,i

```

Try it online!
> 1 votes

# Answer
# Rockstar, 76 bytes

```
listen to N
X's 0
while N-X
let S be X
let X be+1
let S be+""+X
cast S
say S

```

Try it here (Code will need to be pasted in)

```
listen to N       :Read input string into variable N
X's 0             :Initialise X as 0
while N-X         :While X is less than N
let S be X        :  Assign X to S
let X be+1        :  Increment X
let S be+""+X     :  Append X to S
cast S            :  Cast S to an integer
say S             :  Output S

```
> 1 votes

# Answer
# Julia, 28 bytes

```
!n=["1";2:n.|>i->"$(i-1)$i"]

```

Try it online!

based on the answer by Sundar R
> 1 votes

# Answer
# Tcl, 59 bytes

```
proc C n {puts [incr i]
time {puts $i[incr i]} [expr $n-1]}

```

Try it online!

PS: I will golf it more later!
> 0 votes

# Answer
# Haskell, 57 55 bytes

```
f n=read<$>zipWith((.show).(++).show)[0..][1..n]::[Int]

```

A function which takes a number and returns a list.

*EDIT: -2 Bytes thanks to Cat Wizard*

Try it online!
> 0 votes

# Answer
# RAD, ~~28~~ 27 bytes

```
(⊢(⊢+⊣×10*1+∘⌊10⍟⊢)1+⊢)¨0,⍳

```

Repository

Must be called like: `((⊢(⊢+⊣×10*1+∘⌊10⍟⊢)1+⊢)¨0,⍳) <value>`, as I broke assignment of functions when I implemented shy results.

**Note:** this should also work in Dyalog APL, and due to that: -1 byte thanks to @Adám!

The  can either be the APL symbol or the greek one if run in RAD, but must be the APL version ifran in Dyalog APL
> 0 votes

# Answer
# CJam, 11 bytes

```
{{_)s+si}%}

```

Try it online!
> 0 votes

# Answer
# Python 2, 43 bytes

```
lambda i:[1]+[`x`+`x+1`for x in range(1,i)]

```

Try it online!

First element is an integer, the rest are strings.
> 0 votes

# Answer
## Perl 5, 29 bytes

```
say"@{[1,map$_-1 .$_,2..<>]}"

```
> 0 votes

# Answer
# C# (Visual C# Compiler), 54 bytes

Uses space as seperator character.

```
n=>{var r="";for(;n-->1;)r=" "+n+(n+1)+r;return"1"+r;}

```

Try it online!

**Ungolfed full code:**

```
class P
{
    static void Main()
    {
        System.Func<int, string> f =
            n =>
            {
                var r = "";        //Declare variable for the result
                for (; n--> 1;)    //Loop until n is 1

                    r =            //Set the result to:
                        " " +      //Seperator +
                        n +        //Value of n as string
                        (n + 1) +  //Value of n + 1 as string
                        r;         //Previous content of the result

                return "1" + r;    //Return 1 (first item) + the result.
            }
            ;

        System.Console.WriteLine(f(1));
        System.Console.WriteLine(f(2));
        System.Console.WriteLine(f(3));
        System.Console.WriteLine(f(10));
        System.Console.WriteLine(f(100));
    }
}

```
> 0 votes

# Answer
# C# (Visual C# Compiler), 46 bytes

If you are allowed to have some `using static` directives in the top whose bytes do not count:

```
n=>1+Concat(Range(1,n-1).Select(x=>","+x+++x))

```

Try it online!

Will explode if input `n` is `0`.

It is interesting that, while the C# rules say `","+x+++x` means `( "," + (x++) ) + x`, if it had meant `( "," + x ) + (++x)` instead, the program would still work!
> 0 votes

# Answer
# Clojure, 54 bytes

```
#(reduce(fn[a n](conj a(str n(inc n))))[1](range 1 %))

```

Try it online!

Just a reduction over a range between 1 (inclusive) and n (exclusive).

```
(defn concat-n-n+1 [n]
  (reduce (fn [acc m]
            (conj acc (str m (inc m))))
          [1]
          (range 1 n)))

```

The first element of the list is a number, the rest are strings. This seems to be allowed by the spec.
> 0 votes

# Answer
# K (oK), 12 bytes

**Solution:**

```
,/'$1,2':1+!

```

Try it online!

**Examples:**

```
,/'$1,2':1+!1
,,"1"
,/'$1,2':1+!2
(,"1"
 "12")
,/'$1,2':1+!3
(,"1"
 "12"
 "23")
,/'$1,2':1+!10
(,"1"
 "12"
 "23"
 "34"
 "45"
 "56"
 "67"
 "78"
 "89"
 "910")

```

**Explanation:**

```
,/'$1,2':1+! / the solution
           ! / range 0..n
         1+  / add 1
      2':    / sliding window of 2
    1,       / prepend 1
   $         / convert to strings
,/'          / flatten each

```
> 0 votes

# Answer
## C Sharp 51 bytes

```
n=>new int[n].Select((_,o)=>int.Parse($"{o}{o+1}"))

```
> 0 votes

# Answer
# Attache, 15 bytes

```
{N!_'-~_}=>Iota

```

Try it online!

## Explanation

```
{N!_'-~_}=>Iota
{       }=>        map the inside function:
           Iota    (over each number k from 0 to n-1)
    '              array concatenate:
   _               k
     -~_           k+1
 N!                convert [k, k + 1] to an integer (concatenates and returns a number)

```
> 0 votes

# Answer
# Rutger, 108 bytes

```
x=$Input;
f=For[$x];
f=f[@i];
f=f[{p=Subtract[$i];r=Concat[Str[p[1]]];Print[Integer[r[Str[$i]]]];}];
Do[$f];

```

Try it online!

## Ungolfed

```
input = $Input;
for = For[$input];
for = for[@index];

for = for[{
    dec = Subtract[$index];
    ret = Concat[Str[dec[1]]];
    Print[Integer[ret[Str[$index]]]];
}];

Do[$for];

```

The basic concept of Rutger is the lack of multi-adic commands: every command takes a single argument, and if the command needs multiple argument, each new call returns a curried function.

First, we take evaluated input and store it in \\$x\\$. We then create a `For` object, a tri-adic command. The first two calls create a variable \\$f\\$, that will loop \\$x\\$ times, using the iteration variable \\$i\\$, starting at \\$i := 1\\$. The third call indicates the code to be run:

```
{p=Subtract[$i];r=Concat[Str[p[1]]];Print[Integer[r[Str[$i]]]];}

```

This creates a block of code containing 3 statements. Our first two are variable assignments. First, we create a curried function `Subtract[$i]`, which prepares to subtract a value from \\$i\\$. This curried function is saved in the \\$p\\$ variable. Next, we create a second curried variable, \\$r\\$, which starts by calling `p[1]`, subtracting \\$1\\$ from \\$i\\$. We then convert \\$i-1\\$ to a string and pass it as the first argument to the `Concat` function. Finally, we convert \\$i\\$ to a string, concatenate it to \\$str(i - 1)\\$ and convert it to an integer to reomve the leading \\$0\\$ when \\$i = 1\\$. This is then printed.

The last line, `Do[$f];`, runs the for loop.
> 0 votes

# Answer
**C, 39 bytes**

```
x(n){n&&x(n-1);printf("%d%d, ",n,n+1);}

```

eliminated the ternary conditional and shaved off 3 bytes.
> 0 votes

# Answer
# ARBLE, ~~23~~ 20 bytes

Saved a handful of bytes by using better named variables.

```
range(0,n)//(x..y|0)

```

Try it online!
> 0 votes

# Answer
# RAD, 72 bytes

```
0,(⊢+10×⊣)⍁¨∊¨(⌽∘⌊(⊢|⍨10*(⍳(1+∘⌊10⍟⊢)))÷10*1-⍨(⍳(1+∘⌊10⍟⊢)))¨¨(⊢,1+⊢)¨⍳⎕

```

Link to repository

I wanted to try to see if I could do it in a "non-mathematical" way by splitting a number up into its digits.
> 0 votes

# Answer
# Ruby, ~~34~~ 33 bytes

```
->n{$><<i||=p(1);p(i+=1)<n&&redo}

```

Try it online!

Pseudocode:

```
loop
  if i is undefined
    set i to 1
    print 1
    print newline
  end if
  print i
  increment i by 1
  print i
  print newline
  if i >= n
    break and return
  end if
end loop

```
> 0 votes

# Answer
# Python 2.7, 52 bytes

I tried my best. Not yet familiar with this golfing thing.

```
def a(n):
    for e in range(n):
        print int(`e`+`e+1`)

```

The `int()` removes the leading zero in the first output, as specified in the rules.
> 0 votes

# Answer
# Twig, 72 bytes

Twig is very verbose, causing some issues when trying to reduce the length.

```
{%macro f(a)%}{%for i in 1..a%}{{o~i}}
{%set o=i%}{%endfor%}{%endmacro%}

```

This requires that "strict variables" is disabled (default).

---

## How to use?

Simply import the macro and call it:

```
{% import "fn.twig" as fn %}
{{ fn.f(<number>) }}

```

You can test it on https://twigfiddle.com/lah1a5
> 0 votes

# Answer
# Haskell, 35 bytes

```
f n="1":map(show.(-1+)<>show)[2..n]

```

Try it online! <sup>1</sup>

## Explanation / Ungolfed

The operator `(<>)` is the addition of Semigroups, in case of the Semigroup `a -> b` (where `b` needs to be a Semigroup) it is defined as:

```
(f <> g) = \x-> f x <> g x

```

And in case of the Semigroup `String` it is the same as concatenation, so the code becomes:

```
f n = "1" : map (\x-> show (x-1) ++ show x) [2..n]

```

---

<sub>1 (imports `(<>)` since it's not part of the Prelude in GHC 8.2.2)</sub>
> 0 votes

# Answer
## TI-Basic, 22 bytes

```
:seq(A,A,1,Ans
:Ans+(Ans-1)10^(1+int(log(Ans

```
> 0 votes

# Answer
# Bash, 56 bytes

```
echo 1;for i in $(seq $(($1-1)));do echo $i$((i+1));done

```

A pretty naive approach.
> 0 votes

# Answer
# Lua, 62 bytes

```
loadstring't={1}for i=2,(...)do t[#t+1]=(i-1)..i end return t'

```

Try it online!

---

### Explanation

This is an anonymous function.

```
t={1} -- initializes the return table, with the number 1 already in it
for i = 2, (...) do -- loop from 2 to the number of the input
                  -- (this is actual code, ... gets the arguments of the program/function
  t[#t+1] = (i-1)..i -- append to the table i-1 concatenated with i
end
return t -- returns the table

```
> 0 votes

# Answer
# Swift 4, 43 bytes

```
print(1);(1..<n).map{print("\($0)\($0+1)")}

```

Try it online!

`n` is the input of the program
> 0 votes

# Answer
# Noether, 15 bytes

```
I(iWi1+W+WP?!i)

```

Try it online!

## Explanation

```
I(             ) - Loop until the top of the stack equals the input
  iW             - Push i and convert it to a string
    i1+W         - Add one to i and convert to string
        +        - Concatenate two strings
         WP      - Convert string to a number and print it
           ?     - Print a newline
            !i   - Increment i

```
> 0 votes

# Answer
**VBA (Excel), 31 bytes**

using immediate window and Cell `[A1]` as input

`for x=1to[a1]:?int(x-1 &x):next`
> 0 votes

# Answer
# Pepe, 68 bytes

```
RrEEEEEREeErREEREEEEEREErEEEEEeEErEEEereEEreeErEEEEEeeEReerREEREeRee

```

Try it online!

Previous code has errors when giving input 0, so this is fixed!

Explanation:

```
# Preparation

  RrEEEEE # Stack r: [0, 1]

  REeE # Stack R: [input]

# Loop

  rREE # create label input (r flag: skip until REe)

    REEEEE # increment input (loop preparation)
    REE # create label input

      rEEEEEeEE # join all
      rEEEe # move r pointer to last
      reEE # output as int
      reeE # output newline "\n"
      rEEEEEeeE # increment all

    Ree # repeat if input != last content of stack
    rREE # create label input + 1 (r flag: skip until REe)
    REe # stop skipping commands

  Ree # if not 0, go to loop

```
> 0 votes

# Answer
# Python 2, 42 bytes

I know there are plenty of shorter answers already.

```
a=0
exec"print`a`[:a]+`a+1`;a+=1;"*input()

```

Try it online!
> 0 votes

# Answer
# Kotlin,  ~~43~~  41 bytes

```
{(1..it).mapIndexed{i,v->"$i$v".toInt()}}

```

Try it online!
> 0 votes

# Answer
# Microscript II, 16 bytes

```
1vsN-s{lPps1+v}*

```

Output is newline-separated.
> 0 votes

# Answer
# Gol\>\<\>, 11 bytes

```
IFLL?nLPN|;

```

Try it online!

Explanation:

```
IFLL?nLPN|;

I           //Take a number as input
 F          //Loop as many times as the input specified
  LL        //  Push the loop counter twice to the stack (same as L:)
    ?n      //  Check wether the count is zero, if not print the counter as the first digit
      LP    //  Push the loop counter and add 1
        N   //  Output the next digits of the number with nl
         |; //Exit code

```
> 0 votes

# Answer
# Dart, ~~46~~ 45 bytes

```
f(n)=>List.generate(n,(e)=>e<1?1:'$e${e+1}');

```
- -1 byte by replacing `e==0` by `e<1`

Try it online!
> 0 votes

# Answer
# Knight, 29 bytes

```
;=n+0P;=i 0W>n iO+0++""i=i+1i

```

Try it online!
> 0 votes

# Answer
# Gema, 42 characters

```
*=@repeat{*;${n;}@set{n;@add{${n;};1}}$n }

```

Sample run:

```
bash-5.1$ gema '*=@repeat{*;${n;}@set{n;@add{${n;};1}}$n }' <<< 5
1 12 23 34 45

```

Try it online!
> 0 votes

# Answer
# Ly, 12 bytes

```
Rrp[:u`u' o]

```

Try it online!

This is pretty brute force, but short enough to warrant a post I think...

```
R            - generate an inclusive rangefrom "0" to the STDIN number
 rp          - reverse the stack, delete the "0"
   [       ] - for each number on the stack...
    :u       - duplicate number, print it
      `u     - increment the number, print it
        ' o  - print a space

```

# AWK, 26 bytes

```
a=$1{for(;a;a--)$a=a a+1}1

```

Try it online!

Turns out that a version in AWK is pretty short too, so here's that one...

```
a=$1                       - stash the number we want
    {                   }  - code always runs if STDIN>0
     for(;a;a--)           - loop for N, N-1, N-2, ... 1
                $a=a a+1   - set positional var to N appended w/ N+1
                         1 - print all the positional vars we just set

```

This really just abuses the fact that AWK will reset the positional variable count if you set them to a value. And it uses a "truthy" condition with no associated code block to print them all.
> 0 votes

# Answer
# Go, 122 bytes, using string operations

```
import(."strconv";."fmt")
func f(n int)(o[]int){for i:=0;i<n;i++{k,_:=Atoi(Sprintf("%d%d",i,i+1))
o=append(o,k)}
return o}

```

Attempt This Online!

# Go, 125 bytes, using formula

```
import."math"
func f(n int)(o[]int){for i:=0;i<n;i++{o=append(o,i*int(Pow10(1+int(Floor(Log10(float64(i)+1)))))+i+1)}
return}

```

Attempt This Online!

Uses the formula \\$a(n) = n\cdot10^{1 + \lfloor\log\_{10}(n+1))\rfloor} + n + 1\\$ for \\$n \ge 0\\$.
> 0 votes

# Answer
# Vyxal, 29 bits<sup>v2</sup>, 3.625 bytes

```
ʀzṅ⌊

```

Try it Online!

## Explained

```
ɾzṅ
ɾ   # range [1, input]
 z  # overlapping pairs (equivalent to 2l)
  ṅ # concatenate each pair into a single string

```
> 0 votes

# Answer
# SAS

Input is passed by:

```
%let n=123;

```

# 4GL - 38

```
data;
do i=1to &n;x=cats(i-1,i)+0;put x;end;
run;

```

The `data;` and `run;` are obligatory for every 4GL data step, so the code effectively doing the job is in line 2.

# Macrolanguage - 44

```
%macro
m(n,x);%do i=1%to&n;%put&x&i;%let x=&i;%end;
%mend;

```

The `%macro` and `%mend;` are obligatory for every Macroprogram, so the code effectively doing the job is in line 2.

To run macro execute:

```
%m(&n)

```
> 0 votes

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


title: Approximate arcsinc

text:
# Question
Title: Approximate arcsinc
The goal is simple: Output a nonzero real solution `x` to the equation `sin(x) = -mx`, given input `m`, in the fewest number of bytes.

Specifications:

* Your answer must be correct to 3 significant figures.
* You may output any real solution other than the trivial solution `x=0`. You can assume `m` is such that at least one solution exists. You may also assume `m!=0`.

An obviously suboptimal python solution using *gradient descent*:

```
from math import *
from random import *
a=x=0.001
m = 5.
def dE(x):return 2*(sin(x)+m*x+1)*(cos(x)+m)
for i in xrange(1000): x-=dE(x)*a
print x

```

Test cases

```
-0.25 -> ±2.4746
-0.1  -> ±2.8523 or ±7.0682 or ±8.4232
 0.2  -> ±4.1046 or ±4.9063

```

# Answer
# ised: ~~32~~ 28 bytes

Using Newton's iteration starting from π:

```
{:x-{sinx+$1*x}/{cosx+$1}:}:::pi

```

The argument is passed in `$1`, which can be taken from a file, like this:

```
ised --l inputfile.txt 'code'

```

A bit less stable, but shorter version:

```
{:{x-tanx}/{1+$1/cosx}:}:::pi

```

Sometimes it throws iteration limit warnings but the accuracy seems fine considering the conditions.

Unicode version (same bytecount):

```
{λ{x-tanx}/{1+$1/cosx}}∙π

```

Starting from 4 cuts another byte and seems to converge to the same values

```
{λ{x-tanx}/{1+$1/cosx}}∙4

```
> 1 votes

# Answer
## Haskell, 34 bytes

```
f m=until(\x->sin x< -m*x)(+1e-3)0

```

Counts `x` up from 0 by 0.001 until `sin(x)< -m*x`.

Ouput examples

```
f -0.2 ->   2.595999999999825
f -0.1 ->   2.852999999999797
f  0.0 ->   3.141999999999765
f  0.1 ->   3.4999999999997256
f  0.2 ->   4.1049999999997056

```
> 8 votes

# Answer
# Mathematica, 28 bytes

```
x/.FindRoot[Sinc@x+#,{x,1}]&

```

Searches for a numerical root from the initial guess `x=1`. Test cases:

```
% /@ {-0.25, -0.1, 0.2}
(* {2.47458, 2.85234, 4.10462} *)

```
> 2 votes

# Answer
# C, 99 bytes

```
#include<math.h>
float f(float m){float x=1,y;do{x=(y=sin(x)+m*x)+x;}while(fabs(y)>1e-4);return x;}

```

ungolfed:

```
#include<math.h>
float f(float m){
 float x=1,y;
 do{x=(y=sin(x)+m*x)+x;}while(fabs(y)>1e-4);
 return x;
}

```
> 1 votes

# Answer
# C++ 11, ~~92~~ 91 bytes

-1 byte for using `#import`

```
#import<cmath>
using F=float;F f(F m,F x=1){F y=sin(x)+m*x;return fabs(y)>1e-4?f(m,x+y):x;}

```
> 1 votes

# Answer
# MATL, 17 bytes

```
`@2e3/tY,wG_*>}4M

```

This uses linear search on the positive real axis, so it is slow. All test cases end within 1 minute in the online compiler.

Try it online!

### Explanation

```
`         % Do...while
  @       %   Push iteration index, starting at 1
  2e3/    %   Divide by 2000
  t       %   Duplicate
  Y,      %   Sine
  w       %   Swap
  G_*     %   Multiply by minus the input
  >       %   Does the sine exceed that? If so, next iteration
}         % Finally (execute after last iteration, before exiting loop)
   4M     %   Push input of sine function again
          % Implicit end
          % Implicit display

```
> 1 votes

# Answer
# Python 2, ~~81~~ 78 bytes

### Fixpoint iteration

As recursive lambda

```
from math import*
f=lambda m,x=1:abs(sin(x)+m*x)>1e-4and f(m,sin(x)+m*x+x)or x

```

As loop (81 bytes):

```
from math import*
m=input()
x=1
while abs(sin(x)+m*x)>1e-4:x=sin(x)+m*x+x
print x

```
> 0 votes

# Answer
# Mathematica, 52 bytes

```
NSolve[Sin@x==-x#,x,Reals][[;;,1,2]]~DeleteCases~0.&

```

Anonymous function. Takes a number as input, and returns a list of numbers as output. Just uses `NSolve` to solve the approximate equation.
> 0 votes

# Answer
# Axiom, 364 bytes

```
bisezione(f,a,b)==(fa:=f(a);fb:=f(b);a>b or fa*fb>0=>"fail";e:=1/(10**(digits()-3));x1:=a;v:=x2:=b;i:=1;y:=f(v);if(abs(y)>e)then repeat(t:=(x2-x1)/2.0;v:=x1+t;y:=f(v);i:=i+1;if i>999 or t<=e or abs(y)<e then break;if fb*y<0 then(x1:=v;fa:=y)else if fa*y<0 then(x2:=v;fb:=y)else break);i>999 or abs(y)>e=>"fail";v)
macro g(m) == bisezione(x+->(sin(x)+m*x), 0.1, 4.3)

```

ungolf

```
bisezione(f,a,b)==
    fa:=f(a);fb:=f(b)
    a>b or fa*fb>0=>"fail"
    e:=1/(10**(digits()-3))
    x1:=a;v:=x2:=b;i:=1;y:=f(v)
    if(abs(y)>e) then
      repeat
        t:=(x2-x1)/2.0;v:=x1+t;y:=f(v);i:=i+1
        if i>999 or t<=e or abs(y)<e then break
        if      fb*y<0 then(x1:=v;fa:=y)
        else if fa*y<0 then(x2:=v;fb:=y)
        else break
    i>999 or abs(y)>e=>"fail"
    v

macro g(m) == bisezione(x+->(sin(x)+m*x), 0.1, 4.3)

```

results

```
(3) -> g(0.2)
   AXIOM will attempt to step through and interpret the code.
   (3)  4.1046198505 579058527
                                                              Type: Float
(4) -> g(-0.1)
   (4)  2.8523418944 500916556
                                                              Type: Float
(5) -> g(-0.25)
   (5)  2.4745767873 698290098
                                                              Type: Float

```
> 0 votes

# Answer
## Haskell, 50 bytes

I just learned about newton's method in my calc class, so here goes in `haskell` using newton's method.

`f m=foldl(\x _->x-(sin x+m*x)/(cos x+m))0[1..10]`
> 0 votes

# Answer
# Scala, 68 bytes

Modified from @xnor's Haskell answer.

---

Golfed version. Try it online!

```
m=>Stream.iterate(0.0)(_+1e-3).dropWhile(x=>math.sin(x)>= -x*m).head

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(f(-0.2))
    println(f(-0.1))
    println(f(0.0))
    println(f(0.1))
    println(f(0.2))
  }

  def f(m: Double): Double = {
    def until(condition: Double => Boolean, action: Double => Double, x: Double): Double = {
      if (condition(x)) x
      else until(condition, action, action(x))
    }

    until(x => Math.sin(x) < -m * x, _ + 1e-3, 0)
  }
}

```
> 0 votes

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


title: Draw the Sawtooth Alphabet

text:
# Question
Title: Draw the Sawtooth Alphabet
A simple one today. Write the shortest program that draws a "sawtooth alphabet" given a positive integer for the height. You must write the name of your programming language when you come to the letter it starts with.

For example, if your language is Python and the input is `1` the output should be:

```
ABCDEFGHIJKLMNOPythonQRSTUVWXYZ

```

If the input is `2` the output should be:

```
 B D F H J L N Python R T V X Z
A C E G I K M O      Q S U W Y

```

If the input is `4` the output should be:

```
   D     J     Python     V
  C E   I K   O      Q   U W
 B   F H   L N        R T   X Z
A     G     M          S     Y

```

**Notes**

* `A` always starts at the bottom left.
* Input can be via stdin or function call or similar. Output to stdout.
* Input above `26` doesn't need to work.
* No trailing spaces.

# Answer
if **n** holds the height:

# C + escape codes: 81

```
x;main(y){for(y=n--;x<26;x++)printf("\033[%d;%dH%c",n?x/n&1?y++:y--:y,x+1,x+65);}

```

# C: 110

```
x;char a[702]={[0 ...701]=32};main(y){for(y=--n;x<26;a[x*27-1]=10)a[27*(n?x/n&1?y++:y--:y)+x]=x+++65;puts(a);}

```
> 15 votes

# Answer
## C, 134

```
n,m,c,p;
main(r){
for(scanf("%d",&n),m=--n?n*2:1;n+r--;puts(""))
for(c=-1,p=1;c++<25;)
p+=(c-n-r)%m*((c-n+r)%m)?1:1-printf("%*c",p,c+65);
}

```

Compiles on gcc with a few warnings. Newlines aren't included in the character count.

**122 characters** if the input is already stored in `n`.

Thanks to user2992539, tolos and edc65 for improvements.
> 19 votes

# Answer
# TI-BASIC - 148 bytes (raw text), 186 bytes (graphic)

In response to the OP, the wonderful TI-83 (and newer) comes with a size of 16 x 8 (just using the standard large text) or with a size of 94 x 62 pixels (which with small text is worth about 10 lines).

Now, this has a little problem (to which I would like clarification). The size impositions can't be "ignored" by the interpreter; in other words, if we were to try to set the sawtooth height at 20, it would give an error preventing the full execution of the code. I *could* write code that would, in an infinite environment, produce the correct output, except it wouldn't run on the machine.

With this being said, I present you the (running) versions of the programs. They all depend on the variable `N` being set to the desired height in lines before running:

* Raw text approach

```
:ClrHome
:"ABCDEFGHIJKLMNOPQRSTI-BASICUVWXYZ"→Str1
:8→R
:For(C,1,16
:If N=1
:Then
:0→F
:Else
:If R<2 or 10-R>N
:1→F
:If R>7
:-1→F
:End
:If C≠20
:Then
:Output(R,C,sub(Str1,C,1
:Else
:Output(R,C,sub(Str1,C,8
:C+7→C
:End
:R+F→R
:End

```

In order to make this work regardless of the terminal, change `For(C,1,16` to `For(C,1,33` and remove the upper bound checking (`R<2 or`). Here is the output with `5→N`:
* Graphic approach (this may also need `AxisOff` for clarity)

```
:ClrDraw
:N*6→N
:"ABCDEFGHIJKLMNOPQRSTI-BASICUVWXYZ"→Str1
:57→R
:For(C,1,56
:If N=6
:Then
:0→F
:Else
:If R<7 or 64-R>N
:6→F
:If R>51
:-6→F
:End
:If C≠20
:Then
:If C>50
:Then
:Text(R,C,sub(Str1,C-23,1
:Else
:Text(R,C,sub(Str1,C,1
:End
:Else
:Text(R,C,sub(Str1,C,8
:C+30→C
:End
:R+F→R
:End

```

This one works OK, with two minor quirks. The height is still a problem, although the width isn't. However, I didn't space the letters, so in some cases (when the letter starts to rise or decline from the sawtooth), the letters may be chopped off by their successors. To make it work regardless of the terminal, remove the upper bound check (`R<7 or`). Then follows the graph:
> 13 votes

# Answer
# Pure Bash (no coreutils), 181 bytes

```
m=$1
for l in A Bash {C..Z};{
((m))||s=++
((m>$1-2))&&s=--
for((m=$1==1?1:m,m$s,i=0;i<$1;i++));{
((i-m))&&a[i]+=${l//?/ }||a[i]+=$l
}
}
shopt -s extglob
printf %s\\n "${a[@]%%+( )}"

```

### Output:

Piped to `cat -E` just to prove there are no trailing newlines.

```
$ ./sawtooth.sh 1 | cat -E
ABashCDEFGHIJKLMNOPQRSTUVWXYZ$
$ ./sawtooth.sh 5 | cat -E
       E       M       U$
      D F     L N     T V$
     C   G   K   O   S   W$
 Bash     H J     P R     X Z$
A          I       Q       Y$
$

```
> 11 votes

# Answer
# JavaScript (ES6) 231 ~~244~~

**Edit** Bug fix, some reordering and a different way of managing height==1
Moreover, changed to a function as this is allowed by OP, so no prompt() for input

No changes to the general algorithm that probably is NOT the best for this challenge

```
F=h=>{for(p=s=[i=z=b=t=''];++p<h;)i=1,z=b=' ',s[p]=t;for(p=--h,k=64;++k<91;)s[p]+=t+String.fromCharCode(k),k-74||(s=s.map((x,q)=>x+(p-q?'         ':'avascript'))),p-=i,p<0|p>h?(i=-i,p-=i+i,t=z,b=t+t):t+=b;console.log(s.join('\n'))}

```

**Explained**

```
F=h=>{
  // row in s for output must be initialized to ''. In the same step I make other initializations
  for(p=s=[i=z=b=t='']; ++p < h;) // initialize for height 1, all increment and spacing can be null
    i=1,z=b=' ',s[p]=t; // the for body is entered only if height > 1, initializing spacing and increment to the right values
  for(p=--h,k=64;++k<91;)
    s[p]+=t+String.fromCharCode(k),
    k-74||(s=s.map((x,q)=>x+(p-q?'         ':'avascript'))), // if 'J' modify each line of output adding the name or spacing
    p-=i,p<0|p>h?(i=-i,p-=i+i,t=z,b=t+t):t+=b; // index bouncing
  console.log(s.join('\n'))
}

```

**Examples**

1

```
ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ

```

3 going up

```
  C   G            K   O   S   W
 B D F H Javascript L N P R T V X Z
A   E   I            M   Q   U   Y

```

4 on top

```
   D     Javascript     P     V
  C E   I          K   O Q   U W
 B   F H            L N   R T   X Z
A     G              M     S     Y

```

7 going down

```
      G                    S
     F H                  R T
    E   I                Q   U
   D     Javascript     P     V
  C                K   O       W
 B                  L N         X Z
A                    M           Y

```
> 10 votes

# Answer
## Ruby, 112 bytes

```
o="#{' '*29}
"*h
26.times{|i|o[(h-i%(h<2?1:2*h-2)-1).abs*30+i+(i>17?3:0)]=(i+65).chr}
puts o.gsub('R   ','Ruby')

```

Expects the input to be stored in `h`.

Let me know if this needs clarification.
> 9 votes

# Answer
**JAVA** **(393)**

As always a great language for golfing:

```
public class P{public static void main(String[]a){int h=Integer.valueOf(a[0]);String x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";String[]l=new String[h];Arrays.fill(l,"");int i=h-1;int d=-1;for(char c:x.toCharArray()){for(int n=0;n<l.length;n++){String k=(n==i)?(c=='J')?"Java":c+"":(c=='J')?"    ":" ";l[n]+=k;}if(i==0&&d==-1)d=1;if(i==h-1&&d==1)d=-1;if(h>1)i+=d;}for(String s:l){System.out.println(s);}}}

```
> 9 votes

# Answer
# J : 75 bytes

```
NB. without IO |:26([:u:65+i.@[)`(($(,|.@}.@}:)@i.)<"1@,.i.@[)`(' '$~,~)}5
2(1!:2)~|.26([:u:65+i.@[)`(($(,|.@}.@}:)@i.)<"1@,.i.@[)`(' '$~,~)}".1!:1[1

```

Using the wonderful Amend conjunction. As usual the IO is ugly and clunky, not going into details there. The core solution takes 3 gerunds (a sort of noun-ified verb (aka. function)):

* a) generating the alphabet
* b) generating the indices
* c) generating the matrix to make amends to

x (a`b`c}) y

a) is a pretty trivial lookup in the ascii table

c) is even more trivial

b) is the interesting one. The morale is that the horizontal indices are supposed to be starting from 0 going to y-1 and back down, repeating this 26 times. Eg. for y == 4:

```
0 1 2 3 2 1 0 1 2 3 2 1 ...

```

Implementing this gives for b):

```
($(,|.@}.@}:)@i.) <"1@,. i.@[)       NB. is equivalent too
(tine0 tine1 tine2)                  NB. a fork with tines defined as
tine0 =:
  hook0 =: hook0_0 hook0_1           NB. a dyadic hook: x (g h) y -: x g h y
     hook0_0 =: $                    NB. reshape
     hook0_1 =: (hook1_0 hook1_1)@i. NB. do hook1 after making 0-y
       hook1_0=: ,                   NB. append to self
       hook1_1=: |.@}.@}:            NB. rotated version of y after beheading and curtailing
tine2 =: i.@[                  NB. generate 0-x
tine1 =: <"1@,.                NB. glue together coordinates.

```

And oh yea, handy fact: J's name is ... "J".
> 7 votes

# Answer
## R (204)

```
f=function(x) {
  m=matrix(" ",x,26)
  i=x
  d=ifelse(x==1,0,-1)
  for (j in 1:26) {
    m[i,j]=LETTERS[j]
    if (!((i+d) %in% 1:x)) d=-d
    i=i+d
  }
  for (i in 1:x) cat(m[i,],"\n",sep="")
}

```

Result

```
> f(1)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
> f(2)
 B D F H J L N P R T V X Z
A C E G I K M O Q S U W Y
> f(3)
  C   G   K   O   S   W
 B D F H J L N P R T V X Z
A   E   I   M   Q   U   Y
> f(7)
      G           S
     F H         R T
    E   I       Q   U
   D     J     P     V
  C       K   O       W
 B         L N         X Z
A           M           Y

```
> 5 votes

# Answer
## J, ~~67 57~~ 61 characters

```
echo@dtb"1@|.@|:@(26&,$(u:65+i.26)#~1 j.26$(0#~1=]),<:#-&0 2)

```

Use as a function:

```
   echo@dtb"1@|.@|:@(26&,$(u:65+i.26)#~1 j.26$(0#~1=]),<:#-&0 2)
   D     J     P     V
  C E   I K   O Q   U W
 B   F H   L N   R T   X Z
A     G     M     S     Y

```

---

**Explanation:** this solution uses a different approach than the other J solution. Instead of generating a sawtooth wave *0 1 2 3 2 1 0 1 ...*, I looked at the spacing between consecutive letters. For instance, for *n=4* if you go from the A upwards, wrap over to the second column and reach B, then you find four spaces between A and B. This pattern of spacing between letters is very regular: for *n=4* the pattern is *4 4 4 2 2 2 4 4 4 ...*.

So the idea is to first build the flattened (and transposed) array, and then re-shape it and flip it so it look right. The output routine is straightforward (for being J, at least): *dtb* is "delete trailing blanks" and `"1` says "operate on each line". *dtb* and *echo* are both provided by the standard library.

Thanks to Zsbán Ambrus for some golfing help.
> 4 votes

# Answer
## Javascript - ~~248~~ ~~224~~ 235

```
z=~~prompt(),y="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");y[9]="Javascript";for(w=[],v=0;v<z;v++)w[v]="\n";v--;for(i=0;i<26;i++){for(j=0;j<z;j++)w[j]+=j-v?i-9?" ":"          ":y[i];~~(i/(z-1))%2?v++:v--;}if(z==1)w=y;console.log(w.join(""))

```

Here is a link to the jsfiddle, where you can test it.
edit: Made a console log for a monospaced font and removed the commas if input==1.
> 3 votes

# Answer
# MetaPost (207)

```
numeric h,d,y;h=5;d=-1;y=1;u=5mm;pair p;string s;for x=1upto26:p:=(x,y)*u;s:=char(x+64);if x=13:s:="MetaPost";elseif x>13:p:=(x+2,y)*u;fi;label.rt(s,p);if(y=h)or(y=1):d:=d*-1;fi;if h=1:d:=0;fi;y:=y+d;endfor;

```

You can try it here.
> 3 votes

# Answer
# Perl 119

```
$s.=/26/?++$r&&$/:$m-1&&$r-abs$_%(2*$m-2)+1-$m?$"x(1+3*/15/):/15/?Perl:(A..Z)[$_]for(0..26)x($m=<>);print$s=~s/\s+$//rg

```

This program takes input from `STDIN` and prints the result to `STDOUT`.

And bonus - a version that is against the rules as it prints trailing spaces, but adds some interaction:

```
#!/usr/bin/perl -p
$r=0;$_=join'',map{/26/?++$r&&$/:$m-1&&$r-abs$_%(2*$m-2)+1-$m?$"x(1+3*/15/):/15/?Perl:(A..Z)[$_]}(0..26)x($m=$_)

```

...and some tests below:

```
1
ABCDEFGHIJKLMNOPerlQRSTUVWXYZ
2
 B D F H J L N Perl R T V X Z
A C E G I K M O    Q S U W Y
4
   D     J     Perl     V
  C E   I K   O    Q   U W
 B   F H   L N      R T   X Z
A     G     M        S     Y
6
     F         Perl         Z
    E G       O    Q       Y
   D   H     N      R     X
  C     I   M        S   W
 B       J L          T V
A         K            U

```
> 3 votes

# Answer
# Bash (213) (223)

```
read i
p=0
d=1
printf '\n%.0s' `seq $i`
for l in {A..Z}
do (($p==$i-1))&&((p=$p*-1))
(($i==1))&&p=0
(($p!=0))&&echo -en "\033[s\033[${p#-}A"
[[ "$l" == "B" ]]&&l="Bash"
echo -en $l"\033[s\033[${p#-}B"
((p++))
done

```

Minor tweaks and we're down to 213.

The original one had a minor bug. Tested and confirmed to work on bash version 4.2.37.

Thanks to @manatwork for pointing out the bug and some tips.
> 2 votes

# Answer
**Javascript (~~204 185 150~~ 145)**

```
h=m=4;d=h>1?-1:0;o=[];for(a=0;a<35;a++){for(r=h;r;r--)o[r]=(o[r]||"")+(r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ");if(a<9||a>17){m+=d;if(m<2||m==h)d=-d}}console.log(o.join("\n"))

```

## EDIT

Saved 13 bytes by not building an array and .join("\n"). Required flipping the for loops. Then, with help from C coding son, made code entirely too clever to save another 12 bytes.

Here is the readable version showing the logic change.

```
for (row = height; row; row--) {
    rowOfNextActiveLetter = 1;
    direction = height > 1 ? -1 : 0;
    output = "";
    for (a = 0; a < 35; a++) {
        output += (row == rowOfNextActiveLetter ? "ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a] : "");
        if (a < 9 || a > 17) {
            rowOfNextActiveLetter -= direction;
            if (rowOfNextActiveLetter < 2 || rowOfNextActiveLetter == height)direction = -direction
        }
    }
    console.log(output)
}

```

Golfed (161):

```
for(r=h;r;r--){m=1;d=h>1?-1:0;o="";for(a=0;a<35;a++){o+=(r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ");if(a<9||a>17){m-=d;if(m<2||m==h)d=-d}}console.log(o)}

```

Golfed and obfuscated (149):

```
for(r=h;r;r--,console.log(o))for(m=1,d=h>1?1:0,o="",a=0;a<35;)if(o+=r==m?"ABCDEFGHIJavascriptKLMNOPQRSTUVWXYZ"[a]:" ",a<9|a++>17)d=(m+=d)<2|m==h?-d:d

```

Reversed Alphabet and loop (145):

```
for(r=h;r;r--,console.log(o))for(m=d=1,o="",a=35;a;)if(o+=" ZYXWVUTSRQPONMLKtpircsavaJIHGFEDCBA"[r==m?a:0],a<18|a-->26)d=h<2?0:(m+=d)<2|m==h?-d:d

```
> 2 votes

# Answer
# C#/LINQ:

```
using System;
using System.Linq;

namespace SawtoothAlphabet
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = Int32.Parse(args[0]);   // eg 4
            Console.WriteLine(
                String.Join(Environment.NewLine, Enumerable.Range(0, N).Select(line =>
                    String.Concat(Enumerable.Range(0, 26).Select(i =>
                        line == Math.Abs(i % (2 * (N - 1)) - (N - 1))
                            ? (i == 2) ? "C#" : Char.ConvertFromUtf32(i + 'A')
                            : (i == 2) ? "  " : " ")
            ).TrimEnd())));
        }
    }
}

```

Brief explanation: `Enumerable.Range(0, N).Select(...)` causes a string to be generated for each line which is eventually concatenated into a single string with `String.Join(Environment.NewLine, ...)`. For each line we cycle through all 26 characters with `Enumerable.Range(0, 26).Select(...)`, the test at the start of the lambda expression determines whether to generate a character or space while the `i==2` checks for "C" and converts it to either "C#" or two spaces depending on the line. The `String.Concat(...)` converts the resulting `IEnumerable<char>` for each line into a string before passing it to `TrimEnd(...)` to cleanly strip away any trailing whitespace.
> 2 votes

# Answer
# Haskell – 432 Bytes (unfortunately...)

This turned out to be much harder than I expected to accomplish purely, hence the hefty byte count. I am sure I (or someone) could do better, but I've spent too much time on this as it is. The golfed version is as follows:

```
import Data.Matrix
import Data.Vector(toList)
r=repeat
s h=y h$l(take 26(case h of 1->r 1;_->concat$r$[h,h-1..1]++[2..h-1]))['A'..'Z']$matrix h 32(const ' ')<|>matrix h 1(const '\n')
l _[]m=m
l(x:i)(r:e)m=l i e$u m(let z=26-length i in if z<9 then z else z+6)x r
l _ _ m=m
u m c r h=case h of 'H'->t c r"Haskell"m;_->setElem h(r,c)m
t _ _[]m=m
t c r(x:i)m=t(c+1)r i$setElem x(r,c)m
y h m=concat[toList$getRow x m|x<-[1..h]]

```

To run, load the code into `ghci` and execute `putStr $ s Int` where `Int` is your desired height. You could also add

```
import System.Environment
main :: IO ()
main = fmap (s . read . head) getArgs >>= putStr

```

under the `import`s in a text file, compile it with `ghc`, and pass the height as a command line argument. Ungolfed version:

```
import System.Environment
import Data.Matrix
import Data.Vector (toList)

main :: IO ()
main = fmap (sawtooth . read . head) getArgs >>= putStr

type M = Matrix Char

sawtooth :: Int -> String
sawtooth height = let mat     = matrix height 32 (const ' ') <|> matrix height 1 (const '\n')
                      numbers = take 26 (case height of 1 -> repeat 1
                                                        _ -> concat $ repeat $ [height,height-1..1]++[2..height-1])
                      chars   = ['A'..'Z']
                  in toString height $ makeMatrix numbers chars mat

makeMatrix :: [Int] -> String -> M -> M
makeMatrix []     []     mat = mat
makeMatrix (x:xs) (s:ss) mat = makeMatrix xs ss $ updateMatrix
                                                    mat (let z = 26 - length xs in if z < 9 then z else z + 6) x s
makeMatrix _      _      mat = mat

updateMatrix :: M -> Int -> Int -> Char -> M
updateMatrix mat col row char = case char of 'H' -> insertHaskell col row "Haskell" mat
                                             _   -> setElem char (row, col) mat

insertHaskell :: Int -> Int -> String -> M -> M
insertHaskell _   _   []     mat = mat
insertHaskell col row (x:xs) mat = insertHaskell (col+1) row xs $ setElem x (row, col) mat

toString ::Int -> M -> String
toString height mat = concat [ toList $ getRow x mat | x <- [1..height] ]

```
> 2 votes

# Answer
# K, 60 bytes

```
`0:'{+{x!y}.'+(26#{(!x),|1_!x-1}x;(((x-1)#" "),)'`c$65+!26)}

```

Pretty straightforward, and it looks like I just edged out the J solution. :)

First, generate an alphabet:

```
  `c$65+!26
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

```

And a sawtooth wave of an appropriate length:

```
  26#{(!x),|1_!x-1}5
0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0 1

```

Pad each letter of the alphabet with leading spaces:

```
  (((5-1)#" "),)'"ABC"
("    A"
 "    B"
 "    C")

```

Zip the alphabet and the square wave together, and rotate each row:

```
  +(0 1 2;("  A";"  B";"  C"))
((0
  "  A")
 (1
  "  B")
 (2
  "  C"))

  {x!y}.'+(0 1 2;("  A";"  B";"  C"))
("  A"
 " B "
 "C  ")

```

And the transposition of that is our answer:

```
  +{x!y}.'+(0 1 2;("  A";"  B";"  C"))
("  C"
 " B "
 "A  ")

```

Try it here in oK.
> 2 votes

# Answer
## C, 214 169 bytes, no trailing spaces

Thank to @edc65 and @tolos for their helpful suggestions.

```
#define C ((c-i+n-65)%z&&(c+i+n-67)%z)
n,i,m,c,z;main(){scanf("%d",&n);z=n<2?1:2*n-2;for(;i++<n;){for(m=c=64;c++<90;)m=C?m:c;for(c=64;c++<m;)putchar(C?32:c);puts("");}}

```
> 1 votes

# Answer
# PHP (216) (205)

New version:

```
$b=array_fill(65,26,' ');$b[80]='   ';$b=array_fill(0,$i,$b);for($j=--$i,$x=64;++$x<91;$i||$j=0){$b[$j][$x]=chr($x);$x==80&&$b[$j][$x]='PHP';$j+=($d=$j<($d?$i:1))*2-1;}echo join("\n",array_map('join',$b));

```

Old version:

```
$b=array_fill(0,$i,array_fill(0,28,' '));for($j=--$i,$x=-1;++$x<28;$i||$j=0){$q=&$b[$j];$q[$x]=chr($x-($x&16)/8+65);$x==15&&($q[++$x]='H')*$q[++$x]='P';$j+=($d=$j<($d?$i:1))*2-1;}echo join("\n",array_map('join',$b));

```

expects the variable $i to be the height.
> 1 votes

# Answer
# Perl 5 \+ `-p`, 79 bytes

Not the shortest, and I think there's a chance this isn't valid (as it uses ANSI escape sequences to position the letters...) - happy to remove if this is deemed invalid.

```
//;$_=$/x$_;$|-=++$-<$'?0:($-=1),$\.=$_.($|?".":".[A")x($'>1)for A..O,Perl,Q..Z
```

Try it online!

## Explanation

The initial `//` is purely to store the current value of `$_` in `$'` so `$_` can be used in the body of the loop, saving a variable assignment. Then `$_` is set to `$/` (newline) `$_` times, to move the cursor down the screen.

The main body of the program is the `for` loop that iterates over the alphabet, replacing `P` with `Perl` as a bareword. `$|` can be used as a binary toggle when decremented so if the post-incremented `$-` is less than `$'`, subtract nothing, keeping the value the same, otherwise, set `$-` to `1` and decrement that. Next, append to `$\` (which is automatically output after `$_` at the end of the program thanks to `-p`) the current letter (`$_` \- implicitly set by the `for` loop) with if `$|` is truthy, form feed (to move the cursor down a line) otherwise `\x1b[A` to move the cursor up one line, `$'>`` times. This last condition is to satisfy the requirement of input` 1\` being a straight line and feels the most out of place in the answer...
> 1 votes

# Answer
## Python - 137

Input to be stored in i. e.g. `i=8`

```
l=[""]*h;k=j=0;y=h-1;exec'l[y]+=" "*(j-len(l[y]))+chr(k+65)+"ython"*(k==15);j=len(l[y]);y-=1^k/(h-(h>2))%2*-2;k+=1;'*26;print"\n".join(l)

```
> 0 votes

# Answer
# ~~C: ~~142~~ 139 characters~~

~~Dreadfully long, I expect to be able to shorten it a bit:~~

```
char a[26][27],i,j,p,d;main(n){for(scanf("%d",&n);i<26;d^=!p^p+2>n,p+=d-(d^n>1),i++)for(j=n;j--;a[j][i]=p^j?32:i+65);while(n)puts(a[--n]);}

```

Slightly more readable:

```
char a[26][27], i, j, p, d;
main(n) {
    for (
        scanf("%d", &n);
        i < 26;
        d ^= !p ^ p + 2 > n,
        p += d - (d ^ n > 1),
        i++
    )
        for (
            j = n;
            j--;
            a[j][i] = p ^ j
                ? 32
                : i + 65
        );

    while (n)
        puts(a[--n]);
}

```

Edit: I missed the "no trailing spaces"-rule, but I will be back.
> 0 votes

# Answer
# Scala, 246 bytes

```
def f(h:Int)={val a=Seq.fill(h)(Array.fill(32)(' '));var(r,x,d)=(h-1,0,if(h==1)0 else-1);def p(c:Char){a(r)(x)=c;x+=1};for(c<-'A'to'Z'){p(c);if(c==83)"cala"foreach p;r+=d;if(r==0|r==h-1)d*= -1};for(z<-a)println(new String(z)replaceAll(" +$",""))}

```

reformatted and commented:

```
def f(h: Int) = {
  val a = Seq.fill(h)(Array.fill(32)(' '));
  // r - row; x - x coordinate, column; d - direction
  var (r, x, d) = (h - 1, 0, if(h==1) 0 else -1);
  def p(c: Char) { // p for "put the character"
    a(r)(x) = c;
    x += 1
  };
  for(c <- 'A' to 'Z') {
    p(c);
    if(c == 83)      // 83 == 'S'
      "cala" foreach p;
    r += d;
    if(r == 0 | r == h - 1)     // | is shorter than ||
      d *= -1
  };
  for(z <- a)
    println(new String(z) replaceAll (" +$", ""))  // trimming trailing whitespace
}

```

Results:

```
scala> f(4)
   D     J     P         V
  C E   I K   O Q       U W
 B   F H   L N   R     T   X Z
A     G     M     Scala     Y

scala> f(5)
    E       M           U
   D F     L N         T V
  C   G   K   O   Scala   W
 B     H J     P R         X Z
A       I       Q           Y

scala> f(1)
ABCDEFGHIJKLMNOPQRScalaTUVWXYZ

```
> 0 votes

# Answer
# Racket

Here's a clean functional version: suggestions to shorten it welcome.

```
(define (sawtooth n)
  (define (ST i d m lns)
    (if (null? m)
        lns
        (let* ([v (first m)]
               [spc (make-string (string-length v) #\space)]
               [I (+ i d)])
          (ST I
              (if (or (zero? I) (= (sub1 n) I)) (* d -1) d)
              (rest m)
              (for/list ([ln lns] [j n])
                       (~a ln (if (= i j) v spc)))))))
  (displayln
   (string-join
    (ST (sub1 n)
        (if (= n 1) 0 -1)
        (string-split "A B C D E F G H I J K L M N O P Q Racket S T U V W X Y Z")
        (make-list n "\n")))))

```

## Output

```
> (sawtooth 1)
ABCDEFGHIJKLMNOPQRacketSTUVWXYZ

> (sawtooth 2)
 B D F H J L N P Racket T V X Z
A C E G I K M O Q      S U W Y

> (sawtooth 8)
       H                  V
      G I                U W
     F   J              T   X
    E     K            S     Y
   D       L     Racket       Z
  C         M   Q
 B           N P
A             O

```
> 0 votes

# Answer
# JavaScript, 168 bytes

```
f=(n,o=0,a=[...Array(n)])=>o<26?f(n,o+1,a.map((s='',i)=>s+(o-9?String.fromCharCode(65+o):'JavaScript').replace(i*i-(o%(2*n-2)-n+1)**2&&/./g,' '))):a.map(s=>s.trimEnd())

```

Try it online!

Returns an array of lines.

Ungolfed and explained:

```
f = (
  n,                 // input
  o = 0,             // offset for recursion (current step)
  a = [...Array(n)]  // array containing output lines
) =>
  o < 26 ?    // if not at end yet
    f(        // call function again
      n,      // with same input
      o + 1,  // increment offset
      a.map((s = '', i) =>  // add next letter to each line of a
        s +                 // current line
        (
          o - 9 ?                          // if letter is not J
            String.fromCharCode(65 + o) :  // current letter
            'JavaScript'                   // else 'JavaScript'
        ).replace(
          // replace with spaces if not at a triangular wave point
          i != Math.abs(o % (2 * n - 2) - n + 1) &&
          /./g, ' '
        )
      )
    ) :
    a.map(s => s.trimEnd())  // return array with trailing spaces removed

```
> 0 votes

# Answer
# Scala, 332 bytes

Golfed version. Try it online!

```
object P extends App{val h=args(0).toInt;val x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";val l=Array.fill[String](h)("");var i=h-1;var d= -1;for(c<-x.toCharArray){for(n<-l.indices){val k=if(n==i){if(c=='S')"Scala"else c.toString}else{if(c=='S')"    "else" "};l(n)+=k};if(i==0&&d== -1)d=1;if(i==h-1&&d==1)d= -1;if(h>1)i+=d};for(s<-l){println(s)}}

```

Ungolfed version. Try it online!

```
object P extends App {
  val h = args(0).toInt
  val x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  val l = Array.fill[String](h)("")
  var i = h - 1
  var d = -1
  for (c <- x.toCharArray) {
    for (n <- l.indices) {
      val k = if (n == i) {
        if (c == 'S') "Scala" else c.toString
      } else {
        if (c == 'S') "    " else " "
      }
      l(n) += k
    }
    if (i == 0 && d == -1) d = 1
    if (i == h - 1 && d == 1) d = -1
    if (h > 1) i += d
  }
  for (s <- l) {
    println(s)
  }
}

```
> 0 votes

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