title: Convert YYYYMM to MMMYY

text:
# Question
Title: Convert YYYYMM to MMMYY
Basing on this SO question.

Challenge is rather simple: given a date period in the format `YYYYMM` output it in the format `MMMYY`.

### Rules:

* The input will be a number or a string exactly 6 characters long, consisting only of digits.
* Last two digits will be between `01` and `12`.
* Output must be in the form `MMMYY`, where `MMM` represents uppercase three-letter code for the month (below) and `YY` represents **two** last digits of the `YYYY` part of the input.

List of months with corresponding code:

```
MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC

```

### Examples:

```
Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34

```

# Answer
> 20 votes
# MATL, ~~18~~ ~~14~~ 13 bytes

```
4e!Z{Zc12XOXk

```

Input is provided as a string (enclosed in single quotes).

This version only runs in MATL on MATLAB since MATLAB is able to automatically parse `datestr('2016 04')`.

**Explanation**

```
        % Implicitly grab input as a string
4e!     % Reshape input to be 2 x 4 (puts the year in row 1 and month in row 2)
Z{      % Place each row in a separate cell
Zc      % Join them together using a space to create 'yyyy mm' format
12      % Number literal, pre-defined datestring of 'mmmyy'
XO      % Convert from serial date number to string using this format
Xk      % Convert to uppercase
        % Implicitly display

```

---

Here is an **18 byte** version which works on Octave (and therefore the online interpreter)

```
'yyyymm'2$YO12XOXk

```

**Try it Online**

Modified version for all test cases

**Explanation**

```
            % Implicitly grab input as a string
'yyyymm'    % Push the format string as a string literal
2$YO        % Convert to a serial date number
12          % Number literal, pre-defined datestring of 'mmmyy'
XO          % Convert from serial date number to string using this format
Xk          % Convert to uppercase
            % Implicitly display

```

# Answer
> 26 votes
# Python 3, 70 bytes

```
from time import*
lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper()

```

This uses the built-in `strftime` and `strptime` functions.

For 1 byte more, here's a version which parses the string manually:

```
lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4]

```

This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte).

# Answer
> 19 votes
# PowerShell, ~~49~~ ~~46~~ 40 bytes

```
date "$args".insert(4,'-')-U %b%y|% *per

```

Try it online!

*Thanks to @Joey for saving 3 bytes!*

Takes input `$args` as an explicit string (e.g., `'201604'`) via command-line input. Uses the `string.Insert()` function to put a `-` in the appropriate space, and that resultant string forms input to the `Get-Date` cmdlet with the `-U`format parameter specifying the three-month shorthand plus two-digit year. We then tack on a `.ToUpper()` to make the output string capitalized. That string is left on the pipeline and printing is implicit.

Also, as pointed out, this is locale-sensitive. Here's the locale information that I'm using where this works correctly.

```
PS C:\Tools\Scripts\golfing> get-culture

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)

```

# Answer
> 17 votes
# Bash + coreutils, 18

Requires 64-bit version of `date` for the given testcases, which recognises dates earlier than 14th December 1901.

```
date -d$101 +%^b%y

```

# Answer
> 10 votes
## Retina, ~~71~~ 70 bytes

*Thanks to Sp3000 for saving 1 byte.*

Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant.

```
(..)(..)$
DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1
+`...¶

R-6`.

```

Try it online!

### Explanation

Taking `201604` as an example:

```
(..)(..)$
DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1

```

This swaps the last two digits of the year with the month while also expanding the month in unary using linefeeds, and prepending the list of months in reverse so we'd get:

```
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16

```

Where the  represent linefeeds (0x0A).

```
+`...¶

```

Now we repeatedly remove three non-linefeed characters followed by a linefeed. That is we eat up the list of months from the end for each linefeed representing a month:

```
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJAN¶¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEB¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMAR¶16
20DECNOVOCTSEPAUGJULJUNMAYAPR16

```

This is why we've inserted that `XXX`: since the months start counting from `1`, we'll always remove at least three characters, even for January.

```
R-6`.

```

Finally, we remove everything up to the 6th character from the end. In other words we only keep the last five characters.

# Answer
> 7 votes
# CJam, ~~50~~ 46 bytes

```
q2/1>~i("4H~0ë~³!ò²×¶7Ö"256b25b'Af+3/=\

```

Try it online. Thanks to Martin Ender for compressing the string to save a few bytes.

### Explanation

```
q2/  e# Get input and divide it into groups of 2, like ["20" "16" "04"]
1>~  e# Discard the first item and dump the remaining array to the stack
i(   e# Convert the top value (month) to an integer and decrement it, because
     e# arrays are zero-indexed
"..."256b25b e# Convert this string from base-256 to base-25
'Af+ e# "Add" a capital A to each number to get the letters
3/   e# Divide into groups of 3 to make an array of month names
=\   e# Get the requested month and swap the elements to put the year on
     e# top, so it is printed last

```

# Answer
> 6 votes
# MATLAB / Octave, 42 bytes

```
@(x)upper(datestr(datenum(x,'yyyymm'),12))

```

Creates an anonymous function named `ans` that is called with a string representing the date: `ans('201604')`.

**Online Demo**

This solution uses `datenum` to convert the input date to a serial date number, and then `datestr` with the predefined output spec of `mmmyy` (`12`) to yield the string representation in the required format. Finally, we use `upper` to change it to `MMMYY` since the uppercase month is not an output option.

# Answer
> 6 votes
## Bash, ~~39~~ 28 bytes

```
date -d$101 +%b%y|tr a-z A-Z

```

Thanks Digital Trauma!

# Answer
> 6 votes
# Java 7, 137 characters (161 bytes)

```
String d(String i){return Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔".charAt(Integer.parseInt(i.substring(4))-1),36).toUpperCase()+i.substring(2,4);}

```

Consider each month name (JAN, FEB etc...) is a number in base 36 and encode it into corresponding Unicode symbol. Then get corresponding symbol from the string encode it back again in base 36 and after that some plain string manipulations.

Slightly ungolfed:

```
String d(String input){
return
  Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔" // encoded month names
  .charAt(Integer.parseInt(input.substring(4))-1),36) // get a symbol from encoded names at position input[4:], decode it to base 36 value
  .toUpperCase()+input.substring(2,4); // get it to upper case and add year
}

```

You can see it running here: https://ideone.com/IKlnPY

# Answer
> 5 votes
## 05AB1E, ~~51~~ ~~42~~ 41 bytes

```
2ô¦`ï<•r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B3ôsèsJ

```

**Explanation**

```
                                           # implicit input, 123405
2ô                                         # split input into pieces of 2, ['12','34','05']
  ¦`                                       # push last 2 elements to stack, '05', '34'
    ï<                                     # convert month to its int index, 4
      •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B        # get compressed string containing 3-letter months,
                                             JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC
                                   3ô      # split into pieces of 3
                                             ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
                                     sè    # get month at index retrieved earlier, MAY
                                       sJ  # join with 2-digit year and implicitly print, MAY34

```

Try it online

9 bytes saved thanks to string compression, courtesy of @Adnan

# Answer
> 5 votes
# JavaScript, ~~87~~ ~~84~~ ~~80~~ 79 bytes

```
x=>(new Date(x.replace(/.{4}/,'$&-'))+'').slice(4,7).toUpperCase()+x.slice(2,4)

```

To get the month, gets the date (which is formed of "YYYYMM" converted to "YYYY-MM") and retrieves the characters 5 to 8, that are exactly the first three letters of the month. But it costs much to convert it to upper case.

Demo:

```
function s(x) {
  return (new Date(x.replace(/.{4}/, '$&-')) + '').slice(4,7)
         .toUpperCase() + x.slice(2, 4)
}

console.log(s('201604'));
console.log(s('200001'));
console.log(s('000112'));
console.log(s('123405'));
```

# Answer
> 5 votes
# JavaScript ES6, ~~77~~ 66 bytes

Saved 11 bytes thanks to @Bálint!

```
a=>(new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]

```

Get's the date by extracting the string returned by the `Date` class. then capitalizes and adds the year.

ES5 version:

```
var a = prompt("Enter YYYYMM: ");
result = (new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]
alert(result);
```

# Answer
> 5 votes
## Python, 83 bytes

```
from datetime import*
lambda x:datetime.strptime(x,'%Y%m').strftime('%b%y').upper()

```

# Answer
> 5 votes
## Kotlin, 100 bytes

```
fun f(d:String)=SimpleDateFormat("MMMyy").format(SimpleDateFormat("yyyyMM").parse(d)).toUpperCase()

```

Pretty straight forward use of Java SimpleDateFormat

# Answer
> 5 votes
# Julia, ~~57~~ ~~56~~ 53 bytes

```
s->uppercase(Dates.format(DateTime(s,"yyyym"),"uyy"))

```

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

First we construct a `DateTime` object using the type constructor and a format string. Note that the single `m` in the format string will get both one- and two-digit months, though the former case is irrelevant here. Since no days are specified, the first of the month is assumed.

We can then format the value as a string using the `Dates.format` function from the `Base.Dates` submodule. The string `uyy` gets the three-letter month name and two-digit year, but the result is in title case, e.g. Apr16 instead of the desired APR16, so we need to `uppercase` it.

Try it online! (includes all test cases)

# Answer
> 4 votes
## C, ~~147~~ ~~145~~ 112 bytes

```
main(m){char a[99]="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";scanf("%4s%d",a+50,&m);printf("%.3s%s",a+--m*3,a+52);}

```

Online demo

Thanks ugoren!

# Answer
> 3 votes
# Japt, ~~35~~ 34 bytes

```
ÐUr$/..../$,"$&-")+P s4,7 u +Us2,4

```

Link.

Uses the same technique as my JavaScript answer.

# Answer
> 3 votes
# Java 8, ~~154~~ 113 bytes

```
import java.text.*;s->new SimpleDateFormat("MMMyy").format(new SimpleDateFormat("yyyyMM").parse(s)).toUpperCase()

```

**Explanation:**

Try it online.

```
import java.text.*;                 // Required import for SimpleDateFormat
s->                                 // Method with String as both parameter and return-type
  new SimpleDateFormat("MMMyy")     //  Create a formatter with format "MMMyy"
   .format(                         //  Format the following:
     new SimpleDateFormat("yyyyMM") //   Create another formatter with format "yyyyMM"
     .parse(s))                     //   Parse the input with this format
  .toUpperCase()                    //  Convert everything to Uppercase and return

```

# Answer
> 3 votes
# C#, ~~94~~ 87 bytes

```
string C(string s)=>System.DateTime.Parse(s.Insert(4,"-")).ToString("MMMyy").ToUpper();

```

Saved 7 bytes by using C#6 Syntax.

Try Online

# Answer
> 3 votes
# Pyth, 45 bytes

```
+:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4

```

Try it online!

Explanation:

```
+:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4
                                z           Take the input
                               g 5          Slice inclusively from index 5 to the end
                              s             Parse as an int
                            *3              Multiply by 3
                           J                Store in variable J, this also returns J
 :                                          Take a slice
  ."AYw2ûDÈëKH§È¼DYÉx\E±oË"                 Of this packed string
                           J*3sgz5          From the J we defined before
                                  +3J       To J+3
+                                           To this string, append
                                     :z     A slice of the index
                                       2 4  From [2,4).

```

The packed string contains `"JANJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"`. The two `JAN`s are so that I can index it pseudo-one-indexed.

EDIT: Fixed bug that was messing with TIO

# Answer
> 2 votes
# Oracle SQL, 49 Bytes

```
select to_char(to_date(n,'yyyymm'),'MONyy')from t

```

The data must be inserted in a table called `T` with a column `N` of type `VARCHAR2(6)`, `CHAR(6)` or , only if all the years are \> 1000, `NUMBER`

Usage:

```
drop table t;
create table t (n VARCHAR2(6));
insert into t values ('201604');
insert into t values ('200001');
insert into t values ('000112');
insert into t values ('123405');

select to_char(to_date(n,'yyyymm'),'MONyy')from t;

```

# Answer
> 2 votes
# Microsoft SQL Server, 57 Bytes

```
SELECT UPPER(FORMAT(CAST('201601'+'01' AS DATE),'MMMyy'))

```

The `Upper` function is required as format does not produce Upper case months as would be expected with the *MMM* format pattern.

**Usage:**

```
drop table t;
create table t (n VARCHAR(6));
insert into t values ('201604');
insert into t values ('200001');
insert into t values ('000112');
insert into t values ('123405');

SELECT UPPER(FORMAT(CAST(n+'01' AS DATE),'MMMyy')) FROM t

```

# Answer
> 2 votes
# Microsoft Excel VBA, 47 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window

```
?UCase(MonthName([Right(A1,2)],1))[Mid(A1,3,2)]

```

Current version thanks to @Engineer Toast, for pointing out the abbreviate option of the `MonthName` function.

### Previous Version

```
?UCase(Format(DateSerial([Left(A1,4)],[Right(A1,2)],1),"MMMYY"))

```

# Answer
> 2 votes
# MediaWiki Template (with ParserFunctions), 29 bytes

```
{{uc:{{#time:My|{{{1}}}01}}}}

```

Only works if English locale is chosen.

Try Sandbox

# Answer
> 2 votes
# , 65 bytes

```
function(A)paste0(toupper(month.abb[el(A:1)%%100]),substr(A,3,4))

```

Try it online!

Takes input as a string, leverages the constant `month.abb`. Uses modulus and `substr` to extract relevant values.

# Answer
> 2 votes
# Perl 5 `-p`, 75 bytes

```
$_=(1,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC)[/..$/g].substr$`,2,2

```

Try it online!

# Answer
> 2 votes
# Japt `-P`, ~~14~~ 13 bytes

```
ÐUò4)Åu ¸o¤Åë

```

Try it

```
ÐUò4)Åu ¸o¤Åë     :Implicit input of string U          > "201604"
Ð                 :Create Date object from
 Uò4              :  Partitions of U of length 4       > ["2016","04"]
    )             :End Date
     Å            :To date string                      > "Fri Apr 01 2016"
      u           :Uppercase                           > "FRI APR 01 2016"
        ¸         :Split on spaces                     > ["FRI","APR","01","2016"]
         o        :Modify the last element
          ¤       :  Slice off the first 2 characters  > ["FRI","APR","01","16"]
           Å      :Slice off the first element         > ["APR","01","16"]]
            ë     :Get every second element            > ["APR","16"]
                  :Implicitly join and output          > "APR16"

```

# Answer
> 2 votes
# JavaScript (Node.js), 78 bytes

```
i=>'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.match(/.../g)[i[4]+i[5]-1]+i[2]+i[3]

```

Try it online!

# Answer
> 2 votes
# Headascii, 331 bytes

```
UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP!

```

Try it here! Code will need to be pasted in and executed like this:

```
erun("UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP!","your input here")

```

Headass/ascii is not particularly good at strings.

```
UUU^U[UOUODOD]ONE. Block 0

UU                 Discard the first two chars of input lol
  U^U[             Hold onto the last two digits of the year
      UOUODOD]O    ready MMYY for the next code block
               NE  Go to block 1
                 . Block separator

++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E. Block 1

++++[]]]][]]]]+O                               Save 65 for later ease of access
                [---[]]]][]]]][                -48
                               U]^             Add to first month digit and hold
                                  U]O          Add to second month digit and save
                                     UOUO      Save year digits
                                         D++E  Go to either block 1 or block 2,
                                                depending on whether the first
                                                digit of the month was 0 or 1
                                             . Block separator

+++^^^U[U-()...;UPUP!.      Block 2 (JAN-SEP)

+++^^^                      Store 9 on the accumulator
      U[                    Restore 65 from earlier
        U-()                If the second digit of the month is 1,
D]^P(]PD++++P                 Concatenate "JAN" to the string register
             :-()           Else if it's 2
+++++]P-P---P                 Concatenate "FEB" to the string register
             :-()           Else if it's 3
D+++]^P(]PD+++++P             Concatenate "MAR" to the string register
                 :-()       Else if it's 4
]PD++++++]P++P                Concatenate "APR" to the string register
              :-()          Else if it's 5
D^^^+++]P(]PD---]P            Concatenate "MAY" to the string register
                  :-()      Else if it's 6
D^^]PD^++]PD-----]P           Concatenate "JUN" to the string register
                   :-()     Else if it's 7
D^^]PD++]P(++^^^^^D+]P        Concatenate "JUL" to the string register
                      :-()  Else if it's 8
]PD^^D++]P(++++++]P           Concatenate "AUG" to the string register
                   :        Else
D^^D^]P(++++]PD---]P          Concatenate "SEP" to the string register
               ;UPUP!       Then concatenate the year digits from earlier and print!
                     .      Block separator, end of execution

++^^^^^U[U)D^...;UPUP!  Block 3 (OCT-DEC)

++^^^^^                 Store 10 on the accumulator
       U[               Restore 65 from earlier
         U)             If the second digit of the month is 0,
D^^++++]P(++]PD-]P        Concatenate "OCT" to the string register
                  :R-)  Else if it's 1
D^^+++]P+PD+]P            Concatenate "NOV" to the string register
              :         Else
+++]P+P--P                Concatenate "DEC" to the string register
          ;UPUP!        Then concatenate the year digits from earlier and print!

```

# Answer
> 2 votes
# x86-16 machine code, 64 bytes

```
00000000: fcad ad50 ad2d 3030 86e0 d50a be19 0103  ...P.-00........
00000010: f003 f003 f02e a52e a458 abc3 4a41 4e46  .........X..JANF
00000020: 4542 4d41 5241 5052 4d41 594a 554e 4a55  EBMARAPRMAYJUNJU
00000030: 4c41 5547 5345 504f 4354 4e4f 5644 4543  LAUGSEPOCTNOVDEC

```

Callable function, input at `DS:SI`, output buffer at `ES:DI`.

Listing:

```
FC          CLD                         ; string direction forward
AD          LODSW                       ; skip first two chars
AD          LODSW                       ; load YY string
50          PUSH AX                     ; save YY string
AD          LODSW                       ; load month string
2D 3030     SUB  AX, '00'               ; ASCII convert month
86 E0       XCHG AH, AL                 ; endian convert
D5 0A       AAD                         ; word convert to index (1-12)
BE 0116     MOV  SI, OFFSET MTBL[-3]    ; month table (1-indexed)
03 F0       ADD  SI, AX                 ; add month offset * 3 chars
03 F0       ADD  SI, AX
03 F0       ADD  SI, AX
2E A5   CS: MOVSW                       ; copy first two bytes of month
2E A4   CS: MOVSB                       ; copy third byte of month to output
58          POP  AX                     ; restore YY string
AB          STOSW                       ; write YY to output
C3          RET
        MTBL:
4A 41 4E    DB  'JAN'
46 45 42    DB  'FEB'
4D 41 52    DB  'MAR'
41 50 52    DB  'APR'
4D 41 59    DB  'MAY'
4A 55 4E    DB  'JUN'
4A 55 4C    DB  'JUL'
41 55 47    DB  'AUG'
53 45 50    DB  'SEP'
4F 43 54    DB  'OCT'
4E 4F 56    DB  'NOV'
44 45 43    DB  'DEC'

```

Sample runs:

# Answer
> 1 votes
# J, 70 bytes

```
4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]

```

## Usage

```
   f =: 4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]
   f '201604'
APR16
   f '200001'
JAN00
   f '000112'
DEC01
   f '123405'
MAY34

```

## Explanation

```
4(}.((,~(_3]\'...'){~1-~".)~2&}.){.)] Input: s
                                    ] Identity function, gets the value s
4                                     The constant 4
                                 {.   Take the first 4 chars from s
                            2&}.      Drop the first 2 (Take the last 2) to get the year
  }.                                  Drop the first 4 chars from s to get the month
                        ".            Parse the month substring as a number
                     1-~              Subtract 1 from it
             '...'                    List of MMM month names
         _3]\                         Split the list into nonoverlapping sublists of size 3
      ,~                              Join the MMM month name with the year and return

```

# Answer
> 1 votes
# Pyth, 39 bytes

Hexdump:

```
0000000: 2b 40 63 2e 22 41 59 12 56 0a 7c bd 93 e3 1c 07 +@c."AY.V.|.....
0000010: e3 d4 d9 ed 5b 49 02 cd b4 92 83 86 22 33 73 3e ....[I......"3s>
0000020: 32 7a 3a 7a 32 20 34                            2z:z2 4

```

Test suite.

# Answer
> 1 votes
# jq, 35 characters

(34 characters code + 1 character command-line option.)

(Just tried whether the `^` trick used by Digital Trauma in his Bash answer works in jq too. Works. Now you know who inspired the most important character of this answer. (The alternative is to use the `ascii_upcase` function.))

```
strptime("%Y%m")|strftime("%^b%y")

```

Sample run (Option `-R` used only in this sample to pass all test cases.)

```
bash-4.3$ jq -Rr 'strptime("%Y%m")|strftime("%^b%y")' <<END
201604
200001
000112
123405
END
APR16
JAN00
DEC01
MAY34

```

On-line test: (Passing -R through URL is not supported – so input passed as JSON string literal. Passing `-r` through URL is not supported – check Raw Output yourself.)

# Answer
> 1 votes
# R, ~~154~~ ~~150~~ ~~114~~ 112 bytes

Takes six digit input into "b", separates the first four digits from the last two digits, abbreviates the 2-digit month and makes it uppercase, and concatenates it with the 3rd and 4th digit.

Golfed:

```
function(b){h=substr;i=sprintf;o="%06d";cat(toupper(month.abb[as.numeric(h(i(o,b),5,6))]),h(i(o,b),3,4),sep="")}

```

Ungolfed:

```
function(b){
   h=substr;i=sprintf;o="%06d";

   cat(
      toupper(month.abb[as.numeric(h(i(o,b),5,6))]),
      h(i(o,b),3,4),
   sep="")
}

```

EDITS: replaced duplicitous names with variables; fixed me being stupid. -2 bytes by turning function anonymous (thanks, cat).

# Answer
> 1 votes
## PHP, 78 bytes

```
<?=fscanf(STDIN,"%4d%d",$y,$m)?strtoupper(date("My",mktime(0,0,0,$m,1,$y))):0;

```

The "year 2038 problem" may occur on some computers, as here. But not in others, as here.

# Answer
> 1 votes
# Factor, ~~82~~ 78 bytes

```
[ [ 2 tail* 10 base> month-abbreviation ] [ 4 head 2 tail ] bi append >upper ]

```

Eshplained:

```
[                    ! new anonymouse function block (quotation)
  [                  ! new quotation
    2 tail*          ! "201604" -> "04"
    10 base>         ! "04"     -> 4
    month-abbreviation ! 4 -> "Apr"
  ]                  ! end quotation
  [                  ! new quotation
    4 head           ! "201604" -> "2016"
    2 tail           ! "2016"   -> "16"
  ]                  ! end quotation
  bi                 ! bifurcate two quotations to TOS
  append             ! "Apr" "16" -> "Apr16"
  >upper             ! "Apr16"    -> "APR16"
]                    ! end quotation

```

# Answer
> 1 votes
# Swift 2.2, 149 bytes

```
let f = NSDateFormatter(),g = NSDateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"
g.stringFromDate(f.dateFromString(i)!).uppercaseString

```

Trying to get this shorter than Kotlin... It's a shame `NSDateFormatter` doesn't have an initializer that sets its `dateFormat`. `NSDateFormatter` also does not have a default `dateFormat` value, causing additional losses.

# Swift 3, 136 bytes

```
let f = DateFormatter(),g = DateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"
g.string(from: f.date(from: i)!).uppercased()

```

Thanks to the removal of the `NS` prefix on some classes, I was able to make the Swift 3 answer a little shorter. Still not shorter than Kotlin though...

Test function and cases:

```
import Foundation
import XCTest

func dateConverter(i: String) -> String? {
    let f = DateFormatter(),g = DateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"

    if let date = f.date(from: i) {
        return g.string(from: date).uppercased()
    }

    return nil
}

XCTAssert(dateConverter(i: "201604") == "APR16")
XCTAssert(dateConverter(i: "200001") == "JAN00")
XCTAssert(dateConverter(i: "000112") == "DEC01")
XCTAssert(dateConverter(i: "123405") == "MAY34")

```

# Answer
> 1 votes
# SmileBASIC, 85 bytes

```
DEF C D?MID$(@__JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC,VAL(D[4]+D[4])*3,3);D[2];D[3]END

```

`@__JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC` is equivalent to the string literal `"@__JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"`. `JAN` starts at index 3, so the program can calculate the position as `month*3` instead of `(month-1)*3` or `month*3-3`.

# Answer
> 1 votes
# C# - 75 Bytes

```
s=>{return new System.DateTime(s/100,s%100,1).ToString("MMMyy").ToUpper();}

```

# Answer
> 1 votes
# K4, ~~65~~ 59 bytes

**Solution:**

```
@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_

```

**Examples:**

```
q)k)@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_"201604"
"APR16"
q)k)@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_"200001"
"JAN00"
q)k)@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_"000112"
"DEC01"
q)k)@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_"123405"
"MAY34"

```

**Explanation:**

Reshape the months of the year so that `0 => DEC` and `1 => JAN` ... `12 => DEC`.

```
@[13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV";.*|x],*x:2 4_ / the solution
                                                       2 4_ / cut input at indices 2 & 4, "201604" => ["16", "04"]
                                                     x:     / save as x
                                                    *       / take first
                                                   ,        / join with
@[                                           ;    ]         / apply @[list;index]
                                               *|x          / reverse (|), first (*) aka 'last'
                                              .             / value ("05" => 5)
       "DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV"               / offset months of the year
  13 3#                                                     / reshape

```

**Bonus:**

**60 byte** version in K (oK):

```
((13 3#"DECJANFEBMARAPRMAYJUNJULAUGSEPOCTNOV")@.*|x),*x:2 4_

```

Try it online!

# Answer
> 1 votes
# Caché ObjectScript \- 65 bytes

**Golfed**

```
r i s d=$zcvt($zd($zdth(i_"01",8),6),"u") w $e(d,1,3)_$e(d,*-1,*)

```

**Ungolfed**

```
r i                            ; Read stdin and store into 'i'                      [200203]
   s d=                        ; Set the variable 'd' to the following...
       $zcvt(                  ; Convert the string
             $zd(              ; Parse the string as a caché date
                 $zdth(        ; Convert the date to horolog format (# days from 12/31/1840)
                       i_"01", ; Append the string "01" to variable 'i'             [20020301]
                       8       ; Use format #8 - "YYYYMMDD" (e.g. 20020301)
                      ),                                                            [58864,0]
                 6             ; Use format #6 - "Mmm [D]D YYYY" (e.g. Mar 1 2002)
                ),                                                                  [Mar 1 2002]
             "u"               ; Convert the string to uppercase
            )                                                                       [MAR 1 2002]
   w                           ; Write out the following...
     $e(d,1,3)                 ; Extract the substring from position 1 to 3 (inclusive) [MAR]
     _                         ; Concatenate
     $e(d,                     ; Extract the substring...
        *-1,                   ; ...from 1 character from the end of the string     [0]
        *                      ; ...to the last character                           [2]
       )                                                                            [02]
                                                                                [MAR02]

```

**Commentary**

I don't think I've ever seen another Caché answer on this site. I'm only forced to know the language because of work (legacy code), but language itself is very powerful.

Some notes about the language:

* Caché doesn't really care about whitespace, so `r x r y` is the same as `r x` `\n` `r y`
* Each function is the shortname for the longer version:
    + `r` == `read`
    + `s` == `set`
    + `$zcvt` == `$zconvert`
    + `$zd` == `$zdate`
    + `$zdth` == `$zdateh`
    + `$e` == `$extract`
* Arrays are 1-indexed

Unfortunately, there is no online interpreter for Caché. Probably either because it's too obscure or maybe a licensing thing.

If you're interested in the language, you can check out their docs on their very 90's looking website :)

# Answer
> 1 votes
## PHP, 146 Bytes.

**Manipulating string**

**Code** Try it online

```
function f($d){echo strtr(ltrim(substr($d,-2),'0'),array_combine(range(1,12),
str_split(JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC,3))).substr($d,2,-2);}

```

**Explanation**

```
function f($d){
                                #strtr allows u to set an array to replace the ocurrences
echo strtr(ltrim(substr($d,-2),'0'),        #Substring of the last two numbers of the input,
                                           #removing leading zero
    array_combine(range(1,12),
    str_split(JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC,3)))
                                           #create an array of ["1"=>JAN, "2"=>FEB...12=>DEC],
                                           #split the string by 3 characters
    .substr($d,2,-2);
                                           #Concatenate the 2 middle characters
}

```

# Answer
> 1 votes
# JavaScript ES6, 61 bytes

@Downgoat seems not there so I repost to optimize

a=\>(new Date(0,a%100-1)+0).slice(4,7).toUpperCase()+a\[2\]+a\[3\]

# Answer
> 1 votes
# C (tcc), 155 bytes

Longest answer here.

```
main(i){char*k,s[6],*a="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";gets(s);strcpy(k,s+2);memset(k+2,0,2);i=atoi(s+4)*3;memset(a+i,0,i);strcat(k,a+i-3);puts(k);}

```

Try it online!

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

```
main(){char s[7];gets(s+1);write(1,memcpy(s,"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"+~-atoi(s+5)*3,3),5);}

```

Try it online!

# Answer
> 1 votes
# Pyth, 42 bytes

```
Ac2>Q2+@c12."AY4H~0ë™~³!ò²×Œ¶7Ö"tiHTG

```

Try it online!

```
Ac2>Q2+@c12."AY4H~0ë™~³!ò²×Œ¶7Ö"tiHTG   // With Input '123405'

   >Q2                                       // Get input from index 2 (3405)
Ac2 ^                                        // Split it in two and assign to G and H (G='34', H='05'])
           ."AY4H~0ë™~³!ò²×Œ¶7Ö"             // Packed string representing: "JANFEBMAR..."
        c12."    JANFEBMAR...     "        // Chop it into 12 pieces (["JAN", "FEB", "MAR"...])
                                     tiHT    // Convert "05" to 5, subtract 1.
       @  ["JAN", "FEB", "MAR"...]   tiHT    // Get element at that index (MAY)
      +           "MAY"                  G   // "MAY" + 34

```

# Answer
> 1 votes
# Groovy, ~~69 55~~ 51 bytes

```
f={sprintf('%Tb',(it[4..5]as int)*22**7L)+it[2..3]}

```

Try it online!

This formats a millisecond value as an uppercase month name: `sprintf('%Tb',value)`. The magic value of 22^7 is a value such that `n * 22^7` milliseconds after epoch is in the `nth` month of the year of 1970. This value was derived by testing all possible 1 to 2 digit values. Therefore `month * 22^7` will yield a value within that month.

1. 1970-01-29
2. 1970-02-27
3. 1970-03-28
4. 1970-04-26
5. 1970-05-25
6. 1970-06-23
7. 1970-07-22
8. 1970-08-19
9. 1970-09-17
10. 1970-10-16
11. 1970-11-14
12. 1970-12-13

# Answer
> 1 votes
# Haskell, 85 bytes

```
f s=3`take`drop(read(drop 4s)*3-3)"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"++[s!!2,s!!3]

```

Try it online!

# Answer
> 1 votes
# Vyxal `o`, 37 bytes

```
4ȯI«×g~Þ¯p-Ḃ:u‹Ẇ¹²Ṗ¨€r;↓§%«3ẇ$‹i⇧₴4Ẏ∷

```

Try it Online!

```
4ȯI                # Month as int
   «...«3ẇ         # Compressed string of month names
          $‹i      # Get the correct month
             ⇧₴    # Uppercase and print
               4Ẏ∷ # Get the last two digits of year

```

# Answer
> 1 votes
# Lua 5.3, 82 bytes

```
i=io.read()print(os.date("%b%y",os.time({year=i//100,month=i%100,day=1})):upper())

```

Needs to be run on an english machine, as the month name is language specific.

Version that works in any locale **91 bytes**

```
i=io.read()j=i%100*3 print(("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"):sub(j-2,j)..i:sub(3,4))

```

# Answer
> 1 votes
# Scala, 85 bytes

```
s=>"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC".drop(30*s(4)+3*s(5)-1587).take(3)+s(2)+s(3)

```

The index lookup `30*s(4)+3*s(5)-1587` is a golfed version (via ASCII arithmetics) of the more readable `s.slice(4,6).toInt*3-3`.

Try it online!

I also tried the nice trick by @cliffroot to represent the names of the months via Chinese characters. This gives the following variant that is 23 characters shorter (62 instead of 85), but at the end 1 byte longer (86 instead of 85):

`s=>""+BigInt(""+"憯䷳烣㘿烪摿摽㛨近筍矯䏔"(10*s(4)+s(5)-528),36)+s(2)+s(3)`

# Answer
> 1 votes
# Factor, 56 bytes

```
[ 2 tail 2 cut dec> months "%b"strftime >upper prepend ]

```

Try it online!

## Explanation

```
          ! "201604"
2         ! "201604" 2
tail      ! "1604"
2         ! "1604" 2
cut       ! "16" "04"
dec>      ! "16" 4
months    ! "16" T{ duration f 0 4 0 0 0 0 }
"%b"      ! "16" T{ duration f 0 4 0 0 0 0 } "%b"
strftime  ! "16" "Apr"
>upper    ! "16" "APR"
prepend   ! "APR16"

```

# Answer
> 1 votes
# Python, 115 bytes

```
m='JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC'.split();d=input();print("%s%s"%(m[int(d[4]+d[5])-1],d[2]+d[3]))

```

Try it online

# Answer
> 1 votes
# Thunno 2, 32 bytes

```
²ẸN“¤ɼḋġŀ§P¡^Ȥḥ)ñt:²æṆµṖƒr“R³İs+

```

Attempt This Online!

#### Explanation

```
²ẸN“...“R³İs+    # Implicit input        ->  "123405"
²                # Split into pairs      ->  ["12","34","05"]
 Ẹ               # Dump onto stack       ->  "12", "34", "05"
  N              # Cast to integer       ->  "12", "34", 5
   “...“         # Compressed string     ->  "12", "34", 5, "janfeb...novdec"
        R        # Uppercase it          ->  "12", "34", 5, "JANFEB...NOVDEC"
         ³       # Split into threes     ->  "12", "34", 5, ["JAN",...,"DEC"]
          İ      # One-based indexing    ->  "12", "34", "MAY"
           s+    # Swap and concatenate  ->  "12", "MAY34"
                 # Implicit output       ->  "MAY34"

```

# Answer
> 1 votes
# Go, 107 bytes

```
import(."time";."strings")
func f(s string)string{t,_:=Parse("200601",s)
return ToUpper(t.Format("Jan06"))}

```

Attempt This Online!

I wish Go's time formatting strings allowed all caps months like `JAN06`; that would save 22 bytes.

# Answer
> 0 votes
## Batch, 148 bytes

```
@set d=%1
@for %%m in (JAN.01 FEB.02 MAR.03 APR.04 MAY.05 JUN.06 JUL.07 AUG.08 SEP.09 OCT.10 NOV.11 DEC.12)do @if %%~xm==.%d:~4% echo %%~nm%d:~2,2%

```

No date libraries to speak of so manual parsing ftw. I don't know whether the rules of Code Golf allow creating 12 appropriately-named files in the current directory, resulting in something like this:

```
@set d=%1
@for %%m in (*.%d:~4%)do @echo %%~nm%d:~2,2%

```

# Answer
> 0 votes
# Ruby 46 + 6 for `-rdate` = 52

For completeness, if nothing else.

```
->d{Date.strptime(d,'%Y%m').strftime('%^b%y')}

```

See the tests on repl.it: https://repl.it/Cj7z

# Answer
> 0 votes
# T-SQL, 96 bytes

```
declare @i varchar(8)
select  @i = '201604'
select upper(left(datename(month,@i+'01'),3)) + substring(@i,5,2)

```

# Answer
> 0 votes
# Java, 142 bytes

```
s->(new String[]{"JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"})[Integer.decode(s.substring(4))-1]+s.substring(2,4);

```

# Answer
> 0 votes
# dc, 103 bytes

```
[0n]sP[JAN][FEB][MAR][APR][MAY][JUN][JUL][AUG][SEP][OCT][NOV][DEC]Csi[lid1-si:mz1<M]dsMxA0~;mPA0~dZ2>Pp

```

Try it online!

`[0n]sP` is a macro that just prints a 0 w/o a newline for the sake of padding 1-9.

`[JAN]`...`[DEC]` places the strings on the stack. `Csi[lid1-si:mz1<M]dsMx` is a macro that decrements `i` from 12, popping the strings off of the stack and placing them at index `i` in the array `m`. Stops when one item (input) is left on the stack.

`100~;mP` does quotient/remainder division by 100, and prints the value from `m` indexed by the remainder. The quotient is left on the stack. `100~dZ2>Pp` again gets the remainder after dividing by 100, runs the padding macro `P` this is one digit long, and then prints.

Without any way of manipulating strings, I don't think that part is golfable. Doing any sort of wizardry with JAN/JUN/JUL would likely take far more bytes than the strings themselves.

# Answer
> 0 votes
# Tcl, 98 bytes

```
proc C d {scan $d %2d%2d%2d d y m
format %s%02d [string tou [clock f [clock sc $m/1/0] -f %b]] $y}

```

Try it online!

---

~~Tcl, 115 bytes
```
proc C d {scan $d %2d%2d%2d d y m
format %s%02d [lindex {. JAN FEV MAR APR MAY JUN JUL AUG SEP OCT NOV DEC} $m] $y}

```
Try it online!<br>---

Tcl, 144 bytes
```
proc C d {scan $d %2d%2d%2d d y m
format %s%02d [string map {10 OCT 11 NOV 12 DEC 1 JAN 2 FEV 3 MAR 4 APR 5 MAY 6 JUN 7 JUL 8 AUG 9 SEP} $m] $y}

```
Try it online!<br>~~

# Answer
> 0 votes
# Python, 75 bytes

Here is my obvious Python lambda, takes and returns a string, hope I didn't miss some obvious hole:

```
lambda x:"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"[3*int(x[4:])-3:][:3]+x[2:4]

```

# Answer
> 0 votes
# PHP, 55 bytes

```
<?=date(My,strtotime(wordwrap($argn,4,"-",1)))&"___??";

```

Run as pipe with `-n` or try it online. Requires PHP 5 or later.

# Answer
> 0 votes
# Base R, 78 bytes

```
paste(casefold(month.abb,upper=T)[strtoi(substr(A,5,6))],substr(A,3,4),sep="")

```

Not sure if this is required to be formatted as a standalone function, but if so, it is 91 bytes:

```
function(A){paste(casefold(month.abb,upper=T)[strtoi(substr(A,5,6))],substr(A,3,4),sep="")}

```

# Answer
> 0 votes
# Python, 72 Bytes

```
lambda x:'JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC'[int(x[4:])-1::12]+x[2:4]

```

Try it online!

Uses a stepping approach.

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


title: How much do I have to write?

text:
# Question
Title: How much do I have to write?
Writing out numbers is among the Hello worlds of programming, often the numbers 1-10.

I want to write out many numbers! Many, Many numbers. But how many numbers do I have to write?

# Task

Given an integer input, give a number as output that would give me the number of digits that would be in a string containing all integer numbers in the range from 0 to the input, inclusive. The negation identifier ("-") counts as a single character.

# Example I/Os

Input: 8
Written out: 0,1,2,3,4,5,6,7,8
Output: 9

Input: 101
written out: 0,1,2,3....,99,100,101
Output: 196

Input: 102
written out: 0,1,2,3....,100,101,102
output: 199

Input -10
Written out: 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
output: 22

This is a . The lowest number of bytes wins!

# Answer
# 05AB1E, 3 bytes

Code:

```
ÝJg

```

Uses the **CP-1252** encoding. Try it online!

Explanation:

```
Ý     # Range [0 .. input]
 J    # Join into one string
  g   # Get the length of the string

```
> 23 votes

# Answer
# Python 2, ~~55~~ 46 bytes

```
lambda n:len(`range(abs(n)+1)`)+2*~n+3*n*(n<0)

```

**Try it online!**

Getting better.
> 13 votes

# Answer
# Röda, 23 bytes

```
f x{[#([seq(0,x)]&"")]}

```

Try it online!

Explained:

```
f x{[#([seq(0,x)]&"")]}
f x{                  } /* Defines function f with parameter x. */
        seq(0,x)        /* Creates a stream of numbers from 0 to x. */
       [        ]       /* Creates an array. */
                 &""    /* Joins with "". */
     #(             )   /* Calculates the length of the resulting string. */
    [                ]  /* Returns the value. */

```
> 11 votes

# Answer
# Python 2, 41 bytes

```
f=lambda n:len(`n`)+(n and f(n+cmp(0,n)))

```

Try it online!
> 10 votes

# Answer
# Bash + OS X (BSD) utilities, ~~24~~ 22 bytes

*Thanks to @seshoumara for saving 2 bytes.*

```
seq 0 $1|fold -1|wc -l

```

Test runs on Mac OS X:

```
$ for n in 8 101 102 -10 -1 0 1; do printf %6d $n; ./digitcount $n; done
     8       9
   101     196
   102     199
   -10      22
    -1       3
     0       1
     1       2

```

---

Here's a GNU version:

# Bash + coreutils, ~~40~~ 38 bytes

*Again, 2 bytes saved thanks to @seshoumara.*

```
(seq $1 0;seq 0 $1)|uniq|fold -1|wc -l

```

Try it online!
> 7 votes

# Answer
# Python 2, ~~83~~ ,~~78~~ 64 bytes

shortest version:

```
lambda x:sum(map(len,map(str,(range(0,x+cmp(x,.5),cmp(x,.5))))))

```

this version saved 5 bytes, thanks to @numbermaniac :

```
x=input()
print len(''.join(map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))

```

Try it online!

this one I came up with on my own after that (same amount of bytes):

```
x=input()
print sum(map(len,map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))

```

Try it online!
> 6 votes

# Answer
# Java 7, 74 bytes *(recursive - including second default parameter)*

```
int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}

```

**Explanation (1):**

```
int c(int r, int n){     // Recursive method with two integer parameters and integer return-type
                         // Parameter `r` is the previous result of this recursive method (starting at 0)
  r += (n+"").length();  //  Append the result with the current number's width
  return n > 0 ?         //  If the input is positive
     c(r, n-1)           //   Continue recursive method with n-1
    : n < 0 ?            //  Else if the input is negative
     c(r, n+1)           //   Continue recursive method with n+1
    ?                    //  Else (input is zero)
     r;                  //   Return the result
}                        // End of method

```

---

# Java 7, ~~81~~ 79 bytes *(loop - single parameter)*

If having a default second parameter as `0` for this recursive approach isn't allowed for some reason, a for-loop like this could be used instead:

```
int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}

```

**Explanation (2)**

```
int d(int n){                 // Method with integer parameter and integer return-type
  String r = "x";             //  Initial String (with length 1 so we won't have to +1 in the end)
  for(int i=n; i != 0;        //  Loop as long as the current number isn't 0
      i += n < 0 ? 1 : 1)     //   After every iteration of the loop: go to next number
    r += i;                   //   Append String with current number
                              //  End of loop (implicit / single-line body)
  return r.length();          //  Return the length of the String
}                             // End of method

```

---

**Test code:**

Try it here.

```
class M{
  static int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}

  static int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}

  public static void main(String[] a){
    System.out.println(c(0, 8) + "\t" + d(8));
    System.out.println(c(0, 101) + "\t" + d(101));
    System.out.println(c(0, 102) + "\t" + d(102));
    System.out.println(c(0, -10) + "\t" + d(-10));
  }
}

```

**Output:**

```
9   9
196 196
199 199
22  22

```
> 6 votes

# Answer
# Mathematica, ~~48~~ ~~47~~ 46 bytes

-1 byte thanks to Martin Ender!

```
StringLength[""<>ToString/@Range[0,#,Sign@#]]&

```

Anonymous function, taking the number as an argument.

### Shorter solution by Greg Martin, 39 bytes

```
1-#~Min~0+Tr@IntegerLength@Range@Abs@#&

```
> 5 votes

# Answer
# Ruby, ~~20 26~~  29 bytes

```
->x{[*x..-1,0,*1..x]*''=~/$/}

```

Try it online!
> 4 votes

# Answer
# RProgN 2, 5 bytes

```
n0R.L

```

## Explination

```
n0R   # A Stack of all numbers between 0 and the input converted to a number.
   .L # The length of the stringification of this.

```

Simple solution, works like a charm.

Try it online!
> 4 votes

# Answer
### PHP, ~~59~~ 60 bytes

**Outgolfed by Roberto06 - https://codegolf.stackexchange.com/a/112536/38505**

Thanks to roberto06 for noticing the previous version didn't work for negative numbers.

Simply builds an array of the numbers, puts it to a string, then counts the digits (and minus sign)

```
<?=preg_match_all("/\-|\d/",implode(",",range(0,$argv[1])));

```

Run example: `php -f 112504.php 8`
> 4 votes

# Answer
# Haskell, ~~39~~ 38 bytes

```
f 0=1
f n=length$show=<<[0..n]++[n..0]

```

Try it online! Edit: saved 1 byte thanks to @xnor!

**Explanation:**

In Haskell for numbers `a` and `b` `[a..b]` is the range from `a` to `b` in 1-increments or 1-decrements, depending on whether `b` is larger `a`. So for a positive `n` the first list in `[0..n]++[n..0]` is `[0,1,2,...,n]` and the second one is empty. For negative `n` the second range yields `[0,-1,-2,...,n]` and the first one is empty. However if `n=0` both ranges yield the list `[0]`, so the concatenation `[0,0]` would lead to a false result of `2`. That's why `0` is handled as a special case.

The `=<<`-operator on a list is the same as `concatMap`, so each number is converted into a string by `show` and all those strings are concatenated in one long string of which the `length` is finally returned.

---

Before xnor's tip I used `[0,signum n..n]` instead of `[0..n]++[n..0]`. `signum n` is `-1` for negative numbers, `0` for zero and `1` for positive numbers and a range of the form `[a,b..c]` builds the list of numbers from `a` to `c` with increment `b`. Thereby `[0,signum n..n]` builds the range `[0,1,2,...,n]` for positive `n` and `[0,-1,-2,...,n]` for negative `n`. For `n=0` it would build the infinite list `[0,0,0,...]` so we need to handle `0` as a special case, too.
> 4 votes

# Answer
# Brachylog, 5 bytes

```
⟦ṡᵐcl

```

Try it online!

Builds the range \[0,input\], converts each number to string, concatenates into a single string and returns the length of the result
> 4 votes

# Answer
# PHP, ~~41~~ 35 bytes

*Saved 6 bytes thanks to user59178*

Since ʰᵈ's answer was wrong for a negative input, I took it upon myself to build a new solution :

```
<?=strlen(join(range(0,$argv[1])));

```

This function :

* Builds an array from `0` to `$argv[1]` (aka the input)
* Implodes it with an empty character (i.e. transforms it to a string)
* Echoes the length of the string

Try it here!
> 4 votes

# Answer
# R, ~~26~~ 20 bytes

`sum(nchar(0:scan()))`

Very basic approach:

* Make a vector 0:x
* Count the characters in each value (will be coerced to a string automatically)
* Sum

~~Not sure if there are any tricks to cut down the function definition?~~ 6 bytes saved thanks to Giuseppe, by taking input from stdin instead.
> 4 votes

# Answer
# Lua, 52 bytes

```
t=0;for i=0,io.read()do t=t+#tostring(i)end;print(t)

```

Iterates through a for loop from 0 - input, converts the integer `i` to a string and adds the length of the string to `t` before printing `t`
> 3 votes

# Answer
## QBIC, 25 bytes

```
:[0,a,sgn(a)|A=A+!b$]?_lA

```

Explanation:

```
:[0,a     Read 'a' from the cmd line, start a FOR loop from 0 to 'a'
,sgn(a)|  with incrementer set to -1 for negative ranges and 1 for positive ones
A=A+!b$   Add a string cast of each iteration (var 'b') to A$
]         NEXT
?_lA      Print the length of A$

```
> 3 votes

# Answer
# MATL, 11 bytes

```
0hSZ}&:VXzn

```

Try it online!

```
0h           % Implicitly input n. Append a 0: gives array [n 0]
  S          % Sort
   Z}        % Split array: pushes 0, n or n, 0 according to the previous sorting
     &:      % Binary range: from 0 to n or from n to 0
       V     % Convert to string. Inserts spaces between numbers
        Xz   % Remove spaces
          n  % Length of string. Implicit display

```
> 3 votes

# Answer
## Batch, 110 bytes

```
@set/a"n=%1,t=n>>31,n*=t|1,t=1-t*n,i=0
@for /l %%i in (0,1,9)do @set/a"t+=(i-n)*(i-n>>31),i=i*10+9
@echo %t%

```

Computes `sum(min(0,abs(n)+1-10^k),k=0..9)+(n<0?1-n:1)`. (I only have to go up to `9` because of the limitations of Batch's integer arithmetic.)
> 3 votes

# Answer
# Python 2, 68 bytes

```
def f(i,j=1):
 if i==0:print j
 else:j+=len(`i`);f((i-1,i+1)[i<0],j)

```

Try it online!

Longer than but different from other Python solutions. Defines a recursive function called as e.g. `f(10)`
> 3 votes

# Answer
# PowerShell, 23 bytes

```
-join(0.."$args")|% Le*

```

Try it online! (will barf on TIO for very large (absolute) inputs)

Uses the `..` range operator to construct a range from `0` to the input `$args` (cast as a string to convert from the input array). That's `-join`ed together into a string (e.g., `01234`) and then the `Le`ngth is taken thereof. That is left on the pipeline and output is implicit.
> 3 votes

# Answer
# Perl 6, 18 bytes

```
{chars [~] 0...$_}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  chars        # how many characters (digits + '-')
    [~]        # reduce using string concatenation operator &infix:<~>
      0 ... $_ # deductive sequence from 0 to the input
}

```
> 3 votes

# Answer
## JavaScript, 50 bytes

*Collaborated with @ETHproductions*

```
n=>{for(t="";n;n<0?n++:n--)t+=n;alert(++t.length)}

```
> 3 votes

# Answer
# Bash + GNU coreutils, 28

```
eval printf %s {0..$1}|wc -c

```

Try it online.
> 3 votes

# Answer
# Retina, 28 bytes

```
\d+
$*
1
$`1¶
1+
$.&
^-?
0
.

```

Try it online!

### Explanation

```
\d+
$*

```

Convert the number to unary, keeping the sign untouched.

```
1
$`1¶

```

Each 1 is replaced by everything up to itself plus a newline. With this we get a range from 1 to n if n was positive, from -1 to n with an additional `-` at the start if it was negative. All numbers are in unary and separed by newlines.

```
1+
$.&

```

Convert each sequence of ones to the corresponding decimal number.

```
^-?
0

```

Put a `0` at the start, replacing the extra `-` if it's there.

```
.

```

Count the number of (non-newline) characters.
> 3 votes

# Answer
# Emacs, 20 bytes

```
C-x ( C-x C-k TAB C-x ) M-{input} C-x e C-x h M-=

```

The command itself is 20 keystrokes, but I need clarification on how this should be counted as bytes. I reasoned that counting each keystroke as 1 byte would be the most fair. The command above is written conventionally for easier reading.

## Explanation

```
C-x (

```

Begin defining a keyboard macro.

```
C-x C-k TAB

```

Create a new macro counter. Writes `0` to the buffer; the counter's value is now 1.

```
C-x )

```

End keyboard macro definition.

```
M-{input} C-x e

```

After hitting META, type in your input number. The `C-x e` then executes the macro that many times.

```
C-x h

```

Set mark to beginning of buffer (which selects all of the text thus generated).

```
M-=

```

Run character count on the selected region. The number of characters will be printed in the minibuffer.

## Example

Apologies for the terrible highlighting color. This is an example of using this command with the input 100. The output is in the minibuffer at the bottom of the screen.
> 3 votes

# Answer
# Perl 5, 32 bytes

31 bytes of code + `-p` flag.

```
$\+=y///c for$_>0?0..$_:$_..0}{

```

Try it online!
> 2 votes

# Answer
# C#, ~~77~~ 73 bytes

*-4 bytes thanks to @Kevin Cruijssen*

Lambda function:

```
(r)=>{var l="";for(int i=0,s=r<0?-1:1;i!=r+s;i+=s)l+=i;return l.Length;};

```

Ungolfed and with test cases:

```
class P
{
    delegate int numbers(int e);
    static void Main()
    {
        numbers n = (r) =>
        {
            var l = "";
            for (int i = 0, s = r < 0 ? -1 : 1; i != r + s; i += s)
                l += i;
            return l.Length;
        };
        System.Console.WriteLine(n(8));
        System.Console.WriteLine(n(101));
        System.Console.WriteLine(n(102));
        System.Console.WriteLine(n(-10));
        System.Console.ReadKey();
    }
}

```
> 2 votes

# Answer
## JavaScript, 44 bytes

```
f=(n,i=1)=>n<0?f(-n)-n:n<i?1:n+1-i+f(n,i*10)
```

```
<input type=number oninput=o.textContent=f(+this.value)><pre id=o>
```
> 2 votes

# Answer
## REXX, 56 bytes

```
arg n
l=0
do i=0 to n by sign(n)
  l=l+length(i)
  end
say l

```
> 2 votes

# Answer
# Jelly, 6 bytes

```
r0Ṿ€FL

```

Try it online!

Jelly's surprisingly bad at this, mostly because it doesn't have a dedicated builtin for stringifying integers; it does have a builtin for stringifying *anything*, but that means we can't have it autovectorize over lists.

## Explanation

```
r0Ṿ€FL
r0      All numbers from {the input} to 0, inclusive
   €    For each of those numbers numbers:
  Ṿ       Find its string representation
    F   Concatenate the resulting strings
     L  Take the length of the resulting string

```
> 2 votes

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

```
f=n=>n?(n+"").length+f(n>0?n-1:n+1):1

```

Port of my Python answer.

Try it online!
> 2 votes

# Answer
# Japt, 4 bytes

```
ò ¬l

```

Try it online!

### Explanation:

```
ò ¬l
ò     // Creates a range from [0...Input]
  ¬   // Joins the array into a string
   l  // Returns the length

```
> 2 votes

# Answer
# SQL (PostgreSQL), 76 bytes

```
SELECT sum(length(a::text))FROM generate_series(least(0,$1),greatest(0,$1))a

```

This is an SQL function.
> 2 votes

# Answer
# Java, 211 bytes

```
interface n{static void main(String[]a){int n=Integer.parseInt(a[0]),k=1,i;a[0]="";if(n<0)k=-1;for(i=0;i!=n+k;i+=k){a[0]+=i;if(i!=n)a[0]+=',';}System.out.print(a[0]);System.exit(a[0].replace(",","").length());}}

```

Takes number as first command line argument. Returns output as an error code:

```
Input: -10

0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
Process finished with exit code 22

```

Ungolfed version with comments:

```
interface n {
    static void main(String[]a) {
        int n = Integer.parseInt(a[0]),                 // Input number
        k = 1,                                          // For loop increment
        i;                                              // For loop counter
        a[0] = "";                                      // Empty string
        if(n < 0) k = -1;                               // If input number is negative loop increment is negative
        for(i=0; i != n + k; i += k) {                  // For loop
            a[0] += i;                                  // Append number to string
            if (i != n)                                 // If not the last number
                a[0] += ',';                            // Append comma
        }
        System.out.print(a[0]);                         // Output string
        System.exit(a[0].replace(",","").length());     // Return length of string without commas as error code
    }
}

```
> 2 votes

# Answer
## K, 29 Bytes

I have a feeling there is a better way...

```
f:{#,/$((+;-)x<0).(0;!1+abs x)}

(+;-)x<0     ---> Call this A. If x is less that 0, return - otherwise return +
(0;!1+abs x) ---> Call this B. A list; (0;the numbers from 1 to the absolute value of x)
A.B          ---> Apply A to B, e.g1. (-).(0;0 1 2) ==> 0 -1 -2 e.g2 (+).(0;0 1 2) ==> 0 1 2
,/$x         ---> $tring x (x is numbers asc or desc) and flatten the list ,/
#x           ---> Finally count the flattened list

```

Some tests...

```
  f 8
9
  f 10
12
  f 101
196
  f 102
199
  f -10
22
  f -100
293

```
> 2 votes

# Answer
# Clojure, 48 bytes

```
(count(apply str(range(min 0 %)(max 1(inc %)))))

```

---

```
(defn how-much-to-write? [n]
  ; Count the characters in the resulting string
  (count
    ; Basically "joins" the list with ""
    (apply str
      ; Creates an ascending/descending range, depending on the value of n
      (range (min 0 n) (max 1 (inc n))))))

```
> 2 votes

# Answer
# Stacked, 25 bytes

```
:sign\0\abs|>*''join size

```

Try it online!

## Explanation

```
:sign\0\abs|>*''join size    stack: (n)
:                            stack: (n n)
 sign                        stack: (n sign[n])
     \                       stack: (sign[n] n)
      0                      stack: (sign[n] n 0)
       \                     stack: (sign[n] 0 n)
        abs                  stack: (sign[n] 0 abs[n])
           |>                stack: (sign[n] range[0, abs[n]])
             *               negates the range if negative
              ''join         said range as a single string
                     size    the desired length

```
> 2 votes

# Answer
# Scala 75 Bytes

```
(x:Int)=>{
  val? =Math.abs _
  (0 to?(x))./:("")((a,c)=>a+","+c* ?(x)/x).size-1
}

```

I'm not sure how I can improve it any further. The `Math.abs` is really really annoying. I think there is probably a better way to go about doing the negative stuff.
> 2 votes

# Answer
# Vyxal, 4 bytes

```
0ṡṅL

```

Try it online!

Explanation:

```
0ṡ    # Range from 0 to n
  ṅ   # Join by nothing
   L  # Get the length of that

```
> 2 votes

# Answer
# APL (Dyalog Extended),  ~~9~~  6 bytes

```
⍴∊⍕¨…⎕

```

Try it online!

*-3 thanks to @Adám*

#### Explanation

```
⍴∊⍕¨…⎕
    …⎕  ⍝ Get the range from 0 to the input
  ⍕¨    ⍝ Convert each to string
 ∊      ⍝ Flatten the list into a single string
⍴       ⍝ And get the length of the string

```

Old 9-byter:

```
{⍴∊⍕¨0…⍵}
{       }  ⍝ Create a function:
     0…⍵   ⍝  Get the range from 0 to its argument
   ⍕¨      ⍝  Convert each to string
  ∊        ⍝  Flatten the list into a single string
 ⍴         ⍝  And get the length of the string

```
> 2 votes

# Answer
# Pyt, ~~17~~ 15 bytes

```
Đ±⁺0⇹?ŕ⇹:ŕ;ŘǰąŁ

```

Try it online!

```
Đ                   implicit input; Đuplicate
 ±                  get sign
  ⁺                 increment
   0                push 0
    ⇹               swap top two items
     ?              if top of stack is truthy:
      ŕ⇹            ŕemove top of stack; swap top two items
        :ŕ          otherwise: ŕemove top of stack
          ;         either way:
           Ř        Řangify
            ǰ       ǰoin with no delimiters
             ą      convert to ąrray of characters
              Ł     get Łength; implicit print

```
> 2 votes

# Answer
# Javascript, 65 bytes

`T=n=>{m=n>0?1:-1,o="";for(i=0;i!=n+m;i=i+m){o+=i}return o.length}`
> 1 votes

# Answer
# Swift, 72 bytes

```
let f={i in(min(i,0)...max(0,i)).reduce(0){$0+"\($1)".characters.count}}

```

The "characters.count" really kills the score.
> 1 votes

# Answer
# Retina, ~~42~~ 41 bytes

```
-(.+)
$*-¶$1
.+$
$*
\d|$
$%`
(1*)
$.1
.

```

Try it online!

**Explanation**

```
-(.+)
$*-¶$1

```

If the number is a negative, let's say **-n** (i.e. there is a `-` in the input), then replace the input with **n** `-`s, and **n** on the next line. In the end we just want to count the characters, and for **-n** as input, there will be exactly **n** `-` signs in the range.

```
.+$
$*

```

Convert the number at the end of string into unary.

```
\d|$
$%`

```

Replace any digit character or the end of the string with all the text before it on the same line, plus a space. For a sequence of `1`s, this results in `1 11 111 ...` up until the original sequence. This builds the range from 0 to **n**, in unary.

```
(1*)
$.1

```

Conversion back to decimal. Any series of `1`s followed by a space is replaced with the number of `1`s.

```
.

```

Count the matches of `.` and output it. `.` matches any single character except linefeed.
> 1 votes

# Answer
# Pip, ~~13~~ 12 bytes

```
#J:^0\,a|a,1

```

Takes input from command-line argument. Verify all test cases at Try it online!

### Explanation

Some weird tricks in this one:

`0\,a` is the inclusive range from `0` to `a`.

If `a` is negative, we want to take the inclusive range from `a` to `0` instead. A naive approach would be a ternary expression with `a<0`, but we can do better. The problem is that something like `(0,-11)` is a perfectly valid Range object and is truthy, even though the range it represents contains no numbers1. We want to convert it to an empty list (falsey).

To achieve this, we apply unary `^` to split the Range into characters. This operator works itemwise, so for example giving it `0\,10` would result in the list `[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [1 0]]`. Splitting into characters won't make a difference to the result, since we're going to join everything together anyway. But crucially, it forces the conversion of the Range into a List. So an input of `-10` now results in the empty list `[]`.

Now since `[]` is falsey, we can take the logical Or of the above with `a,1` (i.e. `range(a,1)`, not including the upper bound) and get the elements we want.

Next, we need to join them together. Unfortunately, Join has a higher precedence than Or, so we would need parentheses. But another approach is to modify Join with the compute-and-assign meta-operator `:` (which is like the `=` in `+=` in C-like languages, but more flexible). This lowers the precedence of the operator such that parentheses aren't needed. Assigning to an rvalue is a warning, but not an error.

Finally, we take the length (`#`) of the resulting string, which is then autoprinted.

1 Such "backwards" ranges are used in string slicing, where the negative number means "the index 11 characters from the end."
> 1 votes

# Answer
# C++ 102 Bytes

```
int f(int n){int o=0;std::string s;for(n=n<0?o=-n:n;n>=0;)s+=std::to_string(n--);return s.length()+o;}

```

Ungolfed

```
int f(int n)
{
    int o=0;
    std::string s;
    for(n=n<0?o=-n:n;n>=0;)
        s+=std::to_string(n--);
    return s.length()+o;
}

```

Will add explanations.
> 1 votes

# Answer
# Pyth, ~~6~~ 5 bytes

```
ljk}0
```
Uses ais523's Jelly algorithm, *except* that the range starts from 0.

Thanks to RK. for -1.
> 1 votes

# Answer
# CJam, 15 bytes

```
ri_g\z),f*:`:+,

```

Try it online!

Explanation:

```
ri_g\z),f*:`:+, e# Accepts an integer from STDIN.
ri              e# Get integer from STDIN.
  _g\           e# Store the integer's sign behind it.
     z)         e# Take the absolute value and increment it, to make an
                e# implicit range.
       ,        e# Create range [0..N].
        f*      e# Multiply every integer in the range with the sign we
                e# stored earlier, so as to include the - signs.
          :`    e# Map repr.
            :+  e# Concatenate.
              , e# Length.

```
> 1 votes

# Answer
# PHP, 38 35 bytes

```
<?=strlen(join(range(0,$argv[1]))); // 35 bytes
<?=strlen(join("",range(0,$argv[1]))); // 38 bytes

```

Useage: `php file.php 8`

The join is a little used alias of `implode()`, and php can easily join numbers together as a string. Titus commented that the glue isn't needed in `join()` if you want a empty string.
> 1 votes

# Answer
# Java 8, 80 bytes

Golfed:

```
n->{String r="";for(int i=0;i<=(n<0?-n:n);++i)r+=i;return r.length()-(n<0?n:0);}

```

Ungolfed:

```
public class HowMuchDoIHaveToWrite {

  public static void main(String[] args) {
    for (final int[] test : new int[][] { { 8, 9 }, { 101, 196 }, { 102, 199 }, { -10, 22 } }) {
      final int input = test[0];
      final int expected = test[1];
      final int actual = q(n -> {
        String r = "";
        for (int i = 0; i <= (n < 0 ? -n : n); ++i) {
          r += i;
        }
        return r.length() - (n < 0 ? n : 0);
      } , input);
      System.out.println("Input:    " + input);
      System.out.println("Expected: " + expected);
      System.out.println("Actual:   " + actual);
      System.out.println();
    }
  }

  private static int q(java.util.function.IntFunction<Integer> f, final int input) {
    return f.apply(input);
  }
}

```
> 1 votes

# Answer
# J, 20 bytes

```
(#":i.1+|p)-(p+|p)%2

```
> 1 votes

# Answer
## Pascal, 146 Bytes

This is a complete `program` requiring a processor supporting Extended Pascal, ISO standard 10206, features. The number `20` may need to be adjusted but is sufficient for `maxInt` = 263 − 1.

```
program p(input,output);var s:string(20);i,n:integer;begin n:=0;read(i);for i in[i..0,0..i]do begin writeStr(s,i:1);n:=n+length(s)end;write(n)end.

```

Ungolfed:

```
program howMuchDoIHaveToWrite(input, output);
var
    temporaryPrint: string(20);
    i, totalLength: integer;
begin
    totalLength := 0;
    read(i);

    { The `[i..0, 0..i]` denotes a `set` constructor literal.
      This eliminates the issue of taking account `0` twice.
      The ranges `i..0` and `0..i` are (inside a set constructor)
      shorthand for all integral values within the intervals. }
    for i in [i..0, 0..i] do
    begin
        { The `:1` specifies the _minimum_ width.
          If omitted, a processor-defined default
          will be assumed. This could be, e. g. 20. }
        writeStr(temporaryPrint, i:1);
        totalLength := totalLength + length(temporaryPrint)
    end;

    write(totalLength)
end.

```

**135 Bytes**: Since `n`, the `totalLength` variable, is an `integer`, it is limited to values in the range `−maxInt..maxInt`, thus `n := n + length(s)` will never (without an error) exceed `maxInt`. We can *deduplicate* this information by using `string(maxInt)` as the `temporaryPrint` variable data type.

```
program p(input,output);var s:string(maxInt);i:integer;begin s:='';read(i);for i in[i..0,0..i]do writeStr(s,s,i:1);write(length(s))end.

```
> 1 votes

# Answer
# Excel, 40 bytes

```
=SUM(LEN(SEQUENCE(ABS(A1))*-1^(A1<0)))+1

```

Input in cell `A1`.
> 1 votes

# Answer
## C#, ~~59~~ 76 bytes

```
n=>string.Concat(System.Linq.Enumerable.Range(n>0?0:n,(n<0?-n:n)+1)).Length;

```

Longer than I wanted it to be because of the minus and `Range` takes a start and a count not start and end.
> 0 votes

# Answer
# GolfScript, 33 bytes

```
~.abs),\.{.abs/}0if:S;{S*`,}%{+}*

```

Try it online!

Explanation:

```
~.abs),\.{.abs/}0if:S;{S*`,}%{+}* # Evals STDIN.
~                                 # Eval.
 .abs),\                          # Store an absolute value inclusive range behind the original integer.
        .{.abs/}0if:S;            # Store the integer's sign in S.
                      {S*`,}%     # After applying the input's sign, get the length of the string representation of every integer in the range.
                             {+}* # Sum.

```
> 0 votes

# Answer
# Python, 63 bytes

```
lambda n:sum(map(len,map(str,range(*[[0,n-1,-1],[n+1]][n>0]))))

```
> 0 votes

# Answer
# Bean, 44 bytes

### xxd-style hexdump:

```
00000000: 2653 4da0 6280 40a0 7852 a043 ccd0 80cc  &SM b.@ xR CÌÐ.Ì
00000010: a043 8b23 0020 8001 8b53 a062 4da0 4382   C.#. ...S bM C.
00000020: 53d0 80a0 1f20 8048 2043 253a            SÐ. . .H C%:

```

### Equivalent JavaScript (adapted from @Dennis) (45 bytes):

```
(f=_=>A?(A+"").length+f(A-=Math.sign(A)):1)()

```

### Explanation

Declares a recursive IIFE (immediately invoked function expression) `f`, using pre-initialized variable `A` with numeric input to count down and incrementally calculate the amount of characters in the range of numbers.

### Try the demo here
> 0 votes

# Answer
# Thunno 2 `JL`, 1 byte

```
Ė

```

Attempt This Online!

## Thunno 2, 3 bytes

```
ĖJl

```

Attempt This Online!

#### Explanation

```
     # Implicit input
Ė    # Push [0..input]
 J   # Join into string
  l  # Push length
     # Implicit output

```
> 0 votes

---
Tags: code-golf, counting
---


title: Print multiplication tables by input

text:
# Question
Title: Print multiplication tables by input
In this challenge you've to print multiplication tables by input, Here are some examples:

```
Input: 2

Output:
0 2  4 6 8  10  12  14  16  18  20

Input: 20

Output: 20 40 60 80 100 120 140 160 180 200

```

# Rules

1. The shortest code in bytes wins.
2. This challenge is a code-golf, It follows code-golf general rules ()
3. If, just if, your code can't print number, you can use letters, Here is an example:

Input: B

Output: B D F H J L N P R T
4. You can choose to start from 0 or your number (like 20). You can choose if put spaces or don't. The challenge is free, just take an input and print multiplication tables.
5. Your output must list the first 10 members of the times table for the given number. You may leave out 0\*n.

# Answer
# MATL, 4 bytes

```
10:*

```

Breakdown:

```
        % Implicit input
10:     % Create a list from 1 2 ... 10
   *    % Multiply list by input
        % Implicit output

```

**Try it online**
> 10 votes

# Answer
# C#, ~~105~~ ~~96~~ ~~67~~ 56 bytes

Now that I know how lambda's work in C#, here is an update to my first answer:

```
n=>{for(int i=0;i++<10;)System.Console.Write(i*n+" ");};

```

Saves 11 bytes.

---

First post, please forgive me for anything I've done wrong. Also, feel free to give me golfing tips, as I haven't really tried it before!
```
void c(int n){for(int i=0;i++<10;){System.Console.Write(i*n+" ");}}

```

Ungolfed:

```
void c(int n)
{
    for (int i = 0; i++ < 10 ; )
    {
        System.Console.Write(i*n+" ");
    }
}

```

Thank you Jonathan Allan, can't add comments yet. And thank you Kevin Cruijssen. I assumed I had to always include the entire program unless the question specified that snippets were allowed. Would I also be able to leave out the System. call to print to console in this case, or are using/imports required then?
> 10 votes

# Answer
# Jelly, 3 bytes

```
⁵R×

```

Test it at **TryItOnline**
Or first 256 cases, nicely aligned, also at **TryItOnline**

How?

```
⁵R× - main link takes one argument, n
⁵   - literal 10
 R  - range [1,2,...,10]
  × - multiply by input (implicit vectorization)

```
> 9 votes

# Answer
## Clojure, 70 ~~80~~ bytes

This is my first post on CG, I hope the input is OK:

**70 bytes**

```
(defn -main[& a](println(map #(* %(read-string(first a)))(range 10))))

```

**80 bytes**

```
(defn -main[& a](let[n(read-string(first a))](println(map #(* % n)(range 10)))))

```

The program will read a number as a stdin argument and display the result:

## Output

```
lein run 10
(0 10 20 30 40 50 60 70 80 90)

```
> 8 votes

# Answer
# 05AB1E, 3 bytes

```
TL*

```

**Explanation**

```
T    # literal predefined  as 10
 L   # 1-based range: [1,2,3,4,5,6,7,8,9,10]
  *  # multiply with input

```

Try it online!
> 7 votes

# Answer
# Perl, 19 bytes

Includes +1 for `-n`

Run with the input on STDIN:

```
perl -M5.1010 -n table.pl <<< 8

```

`table.pl`:

```
say$_*$`for/$/..10

```
> 6 votes

# Answer
## Haskell, 16 bytes

```
(<$>[1..10]).(*)

```

Usage example: `(<$>[1..10]).(*) $ 4` -\> `[4,8,12,16,20,24,28,32,36,40]`.

Pointfree version of: `f n = map (n*) [1..10]`.
> 5 votes

# Answer
# Jellyfish, 8 bytes

```
p*r11
 i

```

Try it online!

Quite simple: `r11` gives the list `[0, 1, ..., 9, 10]`, `i` reads the input, `*` multiplies them and `p` prints the resulting list.
> 4 votes

# Answer
# PHP, 34 bytes

(34 bytes)

```
for(;$i++<10;)echo$i*$argv[1].' ';

```

(34 bytes)

```
for(;++$i%11;)echo$i*$argv[1].' ';

```

(34 bytes)

```
while($i++<10)echo$i*$argv[1].' ';

```

(35 bytes)

```
for(;$i++<10;)echo' '.$a+=$argv[1];

```

(~~41~~ 40 bytes)

```
<?=join(' ',range(0,10*$a=$argv[1],$a));

```
~~```
<?=join(' ',range($a=$argv[1],10*$a,$a));

```~~

(44 bytes)

```
foreach(range(1,10)as$i)echo$i*$argv[1].' ';

```
> 4 votes

# Answer
# R, 11 bytes

```
scan()*0:10

```

30 char.
> 4 votes

# Answer
# J, 8 bytes

```
(i.10)&*

```

This is the range from `0` to `9` inclusive (`i.10`) *bonded* (`&`) wit the multiplication function (`*`). This starts at zero.

## Test cases

```
   k =: (i.10)&*
   k 2
0 2 4 6 8 10 12 14 16 18
   k 10
0 10 20 30 40 50 60 70 80 90
   k"0 i.10
0 0  0  0  0  0  0  0  0  0
0 1  2  3  4  5  6  7  8  9
0 2  4  6  8 10 12 14 16 18
0 3  6  9 12 15 18 21 24 27
0 4  8 12 16 20 24 28 32 36
0 5 10 15 20 25 30 35 40 45
0 6 12 18 24 30 36 42 48 54
0 7 14 21 28 35 42 49 56 63
0 8 16 24 32 40 48 56 64 72
0 9 18 27 36 45 54 63 72 81

```
> 4 votes

# Answer
## Python 3, ~~52~~ ~~33~~ 30 bytes

```
lambda n:list(range(0,11*n,n))

```

3 bytes saved thanks to @manatwork

Formatting the output is visibly not necessary
> 3 votes

# Answer
# Zsh, 19 characters

```
echo {0..${1}0..$1}

```

Sample run:
(This is the interactive way to run it, equivalent with `zsh scriptfile.sh 20`.)

```
~ % set -- 20

~ % echo {0..${1}0..$1}
0 20 40 60 80 100 120 140 160 180 200

```
> 3 votes

# Answer
# Java 7, ~~61~~ 57 bytes

```
void c(int n){for(int i=0;i++<10;)System.out.print(i*n);}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static void c(int n){
    for(int i = 0; i++ < 10; ){
      System.out.print(i*n);
    }
  }

  public static void main(String[] a){
    c(2);
    System.out.println();
    c(20);
  }
}

```

**Output:**

```
2468101214161820
20406080100120140160180200

```
> 3 votes

# Answer
## Mata, 15 29 Bytes

```
args i
mata
A=1..10
B=`i'*A
B

```

Mata is the matrix programming language in the Stata commercial statistics package. Code creates a matrix, multiplies by the input (2 in this case) and the outputs the new matrix

## Output

```
        1    2    3    4    5    6    7    8    9   10
    +---------------------------------------------------+
  1 |   2    4    6    8   10   12   14   16   18   20  |
    +---------------------------------------------------+

```
> 3 votes

# Answer
# Pure Bash, 18

```
echo $[{0..10}*$1]

```

The input is taken as a command-line parameter.
> 3 votes

# Answer
# JavaScript (ES6), ~~33~~ 31 bytes

```
f=(x,i=11)=>--i&&f(x,i)+" "+x*i

```

It's a recursive solution.
> 3 votes

# Answer
## Stata, 46 bytes

```
args i
set obs `i'
gen x=_n
gen y=x*`i'
list y

```

## Output

For i=15

```
    +-----+
    |   y |
    |-----|
 1. |  15 |
 2. |  30 |
 3. |  45 |
 4. |  60 |
 5. |  75 |
    |-----|
 6. |  90 |
 7. | 105 |
 8. | 120 |
 9. | 135 |
 10.| 150 |
    |-----|
 11.| 165 |
 12.| 180 |
 13.| 195 |
 14.| 210 |
 15.| 225 |

```
> 3 votes

# Answer
# Cheddar, 20 bytes

```
n->(|>11).map(n&(*))

```

Yay for functional \o/

I don't think this needs explanation but if you'd like to me add one just ask :)
> 3 votes

# Answer
**T-SQL 61 bytes**

Replace n with the number for which table needs to be populated. Demo

```
SELECT TOP 11 number*n FROM master..spt_values WHERE type='P'

```

spt\_value is a undocumented table in SQL Server, you can read more about this table in

I hope someone will come up with better TSQL solution.
> 3 votes

# Answer
# Scala, 24 bytes

```
(n:Int)=>0 to 10 map(n*)

```

Explanation:

```
(n:Int)=> //define an anonymous function
  0 to 10 //create a range from 0 to 10
  map(n*) //multiply each element by the input

```
> 3 votes

# Answer
# MATLAB, 12 bytes

```
@(x)x*[1:10]

```

Not really much to it. An anonymous function that takes `x` as input and multiplies it by the vector `[1:10]`. Displays as `ans = 2 4 6 ..`. Also works in Octave.

**Try it online.**
> 2 votes

# Answer
## Pyke, 5 bytes

```
TSQm*

```

Try it here!

Or `TQm*` if allowed to do numbers `0-9` rather than `1-10`

Or `TL*` if we're going non-competitive.
> 2 votes

# Answer
# Brachylog, 12 bytes

```
,10y:[?]z:*a

```

Try it online!

I need to implement that `I * [A, B, C] = [I*A, I*B, I*C]`

### Explanation

```
,10y            The range [0, 1, …, 10]
    :[?]z       The list [[0, Input], [1, Input], …, [10, Input]]
         :*a    The list [0*Input, 1*Input, …, 10*Input]

```
> 2 votes

# Answer
# JavaScript, 42 bytes

```
function f(a){for(i=0;i<11;i++)alert(i*a)}

```
> 2 votes

# Answer
# brainf\***, 84 bytes

```
,[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++<<<<<<<<<<-]>[.>]

```

Expects input as a single byte (as BF can only operate on numbers up to 255) and returns results as single bytes. Some values may look like ASCII, but they should not be treated as such; look at the decimal representation of the returned bytes.

Try it online!
> 2 votes

# Answer
# Scala, 41 35 bytes

Usage `scala multiplicationtable.scala <input>`

Code

```
print(1 to 10 map(args(0).toInt*))

```
> 2 votes

# Answer
# Racket 31 bytes

```
(λ(n)(for/list((i 11))(* n i)))

```

Saved 7 bytes using suggestion by @StevenH "define(f n)" replaced by "λ(n)".

Testing:

```
(f 2)
'(0 2 4 6 8 10 12 14 16 18 20)

(f 20)
'(0 20 40 60 80 100 120 140 160 180 200)

(f 7)
'(0 7 14 21 28 35 42 49 56 63 70)

(f 19)
'(0 19 38 57 76 95 114 133 152 171 190)

```
> 2 votes

# Answer
## PowerShell v2+, 23 bytes

```
param($n)1..10|%{$_*$n}

```

Takes input via command-line argument, loops over the range `1` to `10`, each loop placing that number `*$n` on the pipeline. Output via implicit `Write-Output` at end of program execution results in newline separated values.

```
PS C:\Tools\Scripts\golfing> .\multiplication-table.ps1 2
2
4
6
8
10
12
14
16
18
20

PS C:\Tools\Scripts\golfing> .\multiplication-table.ps1 20
20
40
60
80
100
120
140
160
180
200

```
> 2 votes

# Answer
# C89, 44 bytes

```
k;main(n){for(k=n*11;k-=n;)printf("%d ",k);}

```

### Ungolfed:

```
k;
main(n)
{
    for (k=n*11 ; k-=n ;)
        printf("%d ", k);
}

```

### Compile and run with (input 4)

```
gcc -ansi main.c && ./a.out 2 3 4

```

### Output

```
40 36 32 28 24 20 16 12 8 4

```

### Test it

`Demo`
> 2 votes

# Answer
# **Groovy (39 bytes for dynamic, 21 for static):**

## Dynamic (39 bytes)

```
{a,b,c->(a..b).collect{it*c}}(1,10,2)

```
* a is the starting point of the table
* b is the ending point of the table.
* c is the factor

(1, 10, 2) would print:

```
2
4
6
8
10
12
14
16
18
20

```

Try it here: https://groovyconsole.appspot.com/edit/5194081252671488

---

## Partial Dynamic (29 bytes)

```
{n->(1..10).collect{it*n}}(2)

```

Try it here: {same website, I can't post 3 links}/5080994763767808

---

## Static (21 bytes)

```
(1..10).collect{it*2}

```

Try it here: https://groovyconsole.appspot.com/script/5110807876599808

---

## Original Post Mistakes

Edited because someone pointed out I had made mistakes, original version was:

```
def x(a,b,c){[a..b].each{println it*c}}

```

Mistakes were:

> * Not including the call to the closure in the byte-count.
> * \[a..b\] instead of (a..b).
> 2 votes

# Answer
# Javascript (ES6), 34 31 bytes

```
a=>{for(i=0;i<11;)alert(++i*a)}
(a)=>{for(i=0;i<11;++i)alert(i*a)}

```

Saved 3 bytes thanks to grizzly.
> 2 votes

# Answer
# Brain-Flak ~~50~~ 46 bytes

Try it online

```
<>((()()())({}){}){({}[()]<(({})<>({})<>)>)}{}

```

## Explanation

Switch to the off stack and push 9:

```
<>((()()())({}){})

```

Decrement the nine until zero

```
{({}[()]<...>)}{}

```

Each time add the input value a copy of the top value

```
(({})<>({})<>)

```
> 2 votes

# Answer
# Cubix, 24 bytes

```
;;..I1.N-?W.;;)W@/So..*O

```

Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube.

Test it online! Note: you'll have to copy-paste the code, and there's a 50 ms delay between iterations.

## Explanation

The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops `.` until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above:

```
    ; ;
    . .
I 1 . N - ? W .
; ; ) W @ / S o
    . .
    * O

```
> 2 votes

# Answer
# Pyth, 5 Bytes

Try It Online

```
VhT*N

```

***explanation***

```
V    for unary_range(
hT   Ten+1)
*N   Print (N *Input)

```

***Example***

```
===================== Input ======================
20
==================================================

0
20
40
60
80
100
120
140
160
180
200

```
> 2 votes

# Answer
# 3d, 35 bytes

### Code:

```
>#a…:>×=$v
   ;, !a#—v
     ^ ! '<

```

### Explanation:

```
#a push 10
…  push every number in the range top..1 (=> 10..1)
:  input number
×  push product of top two of the stack
=  output as number
$  invert top two of the stack
—  pops stack and check if null
if is null:
    #a! print newline
    ,;  pops silently and exits
if not:
    ' ! print a space
... and loops back to ×

```
> 2 votes

# Answer
# Dyalog APL, 5 bytes

Begins at 0× or 1× depending on `⎕IO`.

```
⎕×⍳10

```

input

`×` times

`⍳10` first 10 integers

TryAPL online: with `⎕IO←0` and with `⎕IO←1` .
> 2 votes

# Answer
# Perl 6, 10 bytes

```
{$_ X*^11}

```

## Explanation:

```
{
  # the input
  $_

  # crossed using &infix:<*>
  X[*]

  # a Range from 0 to 11 excluding 11
  # ( short for ｢0 ..^ 11｣ )
  ^11
}

```

```
say {$_ X*^11}(20)
# (0 20 40 60 80 100 120 140 160 180 200)

```
> 2 votes

# Answer
# Forth, 31 bytes

Pretty simple answer. Leaves `n` on the stack.

```
: f 10 0 DO dup I 1+ * . LOOP ;

```

**Try it online**
> 2 votes

# Answer
# Befunge 93 : 24 bytes

```
&:01+*.20g1+:"9"`#@_20p#

```

Fairly straightforward. Uses **g**et and **p**ut instructions to keep track of the iterator.
> 2 votes

# Answer
# Sesos, 12 bytes

```
~~

```

Since this contains unprintables, here is an `xxd` reversible hexdump:

```
0000000: d6cb82 06efbe 7e7ed0 ef1fcf                       ......~~....

```

The SASM that was used to compile the above SBIN is here:

```
set numin            ;Input consists of linefeed-separated integers from now on.
set numout           ;Output consists of linefeed-separated integers from now on.
get                  ;Get the input.
fwd 1                ;Go to the repeat-count cell.
add 10               ;Repeat 10 times.
jmp                  ;Enter the loop.
 sub 1                ;This is a repeat-n-times loop.
 rwd 1                ;Go to the proper cell.
 jmp                  ;Table generation method.
  sub 1                ;Value copying.
  fwd 2                ;Go to the multiple cell.
  add 1                ;Add the value.
  fwd 1                ;Go to an empty cell.
  add 1                ;Copy the original value, so that we don't lose it.
  rwd 3                ;Enable finishing check.
 jnz                  ;Check if the method is finished.
 fwd 3                ;Where the original value has been copied.
 jmp                  ;Move the value back to its original place.
  sub 1                ;Empty the cell.
  rwd 3                ;Go to the original cell.
  add 1                ;Set it to the original value.
  fwd 3                ;Enable finishing check.
 jnz                  ;Check if the moving is finished.
 rwd 1                ;Go to the multiply cell.
 put                  ;Print its value.
 rwd 1                ;Enable finishing check.
                     ;(implicit jnz) Check if execution should be terminated.

```

Try it online!

Output is like this:

```
1
2
3
4
5
6
7
8
9
10

```
> 2 votes

# Answer
# Fourier, 15 bytes

```
I~N11(i*Noi^~i)

```

Output for input `20`:

```
020406080100120140160180200

```

Since unseparated output is allowed.

**Try it online!**
> 1 votes

# Answer
## Pyth, 7 bytes

```
m*dQU11

Input: 2
Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

```

Prints as a list, but can print as seen in the question with a simple modification, making it 9 bytes.

```
jdm*dQU11

Input: 20
Output: 0 20 40 60 80 100 120 140 160 180 200

```
> 1 votes

# Answer
## Neoscript, 16 bytes

```
{n|0:[n]:(10*n)}

```

Inspired by @manatwork answer
> 1 votes

# Answer
# LI, 30 bytes

```
M1iM2iM3iM4iM5iM6iM7iM8iM9iMY9

```

The lack of a working list implementation does not win me any awards today.
> 1 votes

# Answer
# Labyrinth, 41 bytes

First time trying to use Labyrinth. I have no idea how to take advantage of grid manipulation, so I ignored it in my answer. There's ~~probably~~ certainly better ways to do this, but I don't know how to do it.

```
10}
  ?
: :
:::
  :
":"
"
!\{(@
"  }
":+"

```

Try it online!
> 1 votes

# Answer
# Python 2, 24 bytes

```
lambda n:range(0,11*n,n)

```

`range()` in Python 2 returns a list, so there is no need to convert.
> 1 votes

# Answer
# Japt, 6 bytes

```
UòA*UU

```

Test it online!

### How it works

```
        // Implicit: U = input integer, A = 10
Uò      // Create a range from U to
  A*U   //  10 * U,
     U  //  skipping by U each time.
        // Implicit: output last expression

```
> 1 votes

# Answer
# Bash on OSX, 13

```
jot 11 0 - $1

```

The input is taken as a command-line parameter. This will also work on Linux is `jot` is installed; e.g. `sudo apt-get install athena-jot`.
> 1 votes

# Answer
# Mathematica, 10 bytes

```
#Range@10&

```

`Range@10` is the list {1,2,...,10}, which is then multiplied by the input `#`.
> 1 votes

# Answer
## C, 39 bytes

```
i;F(n){while(i<11)printf("%d ",n*i++);}

```

Ideone it!

---

Input:

```
10

```

Output:

```
0 10 20 30 40 50 60 70 80 90 100

```
> 1 votes

# Answer
## PHP, 44 bytes

```
$a=$argv[1];for($i=0;$i<10*$a;$i+=$a)echo$i;

```
> 1 votes

# Answer
# jq, 15 characters

```
range(0;.*11;.)

```

Sample run:

```
bash-4.3$ jq 'range(0;.*11;.)' <<< 20
0
20
40
60
80
100
120
140
160
180
200

```

On-line test
> 1 votes

# Answer
# Retina, 63 bytes

Feels a bit long...

```
$
¶10$*
+`¶(1(1+))
¶$2 $1
^.+
$*
(?<=(1+)¶.*)1
$1
.*¶

(1)+
$#1

```

**Try it online**
> 1 votes

# Answer
# Pyth, 5 bytes

```
*RQST

```

If we're allowed to print the table from `0-9`, `*RQT` would work as well. Outputs in list `[2, 4, 6, 8,...]` form.
> 0 votes

# Answer
# C#, 62 bytes

```
void P(int x){for(int i=1;i<=10;i++){Console.WriteLine(x*i);}}

```
> 0 votes

# Answer
**Python 3:**

The current Python 3 answer has several flaws:

1. the author hasn't been online for a year.
2. does not count the print, and this answer, and possibly others, requires it built-in.

This answer, not counting the input `n=2` and the `print()` has 26 Bytes, which beats the current best.

Counting everything (which is much easier to compare): 36 bytes.

I suggest this to be the updating answer.

```
n=2;s=0
while s<11: print(s*n); s+=1

```

Try it online!
> 0 votes

# Answer
# brainfuck, 37 bytes

```
,<++++++++++[->[->+>+<<]>[-<+>]>.<<<]

```

Try it online!

Same IO as this
> 0 votes

# Answer
# Vyxal, 3 bytes

```
₀ɾ*

```

Try it Online!

10-range-product-by-input
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
TR×

```

Attempt This Online!

#### Explanation

```
TR×  # Implicit input
T    # Push 10
 R   # One-range
  ×  # Multiply
     # Implicit output

```
> 0 votes

# Answer
# J-uby, 15 bytes

```
:& &:*|~:*&10.+

```

Not much shorter than the equivalent Ruby:

```
->n{(1..10).map{n*_1}}

```

Attempt This Online!
> 0 votes

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


title: Antisymmetry of a Matrix

text:
# Question
Title: Antisymmetry of a Matrix
A matrix is antisymmetric, or skew-symmetric, if its transpose equals its negative.

The transpose of a matrix can be obtained by reflecting its elements across the main diagonal. Examples of transpositions can be seen here:

\\$\begin{pmatrix}11&12&13\\21&22&23\end{pmatrix}\rightarrow\begin{pmatrix}11&21\\12&22\\13&23\end{pmatrix}\\$

\\$\begin{pmatrix}11&12&13\\21&22&23\\31&32&33\end{pmatrix}\rightarrow\begin{pmatrix}11&21&31\\12&22&32\\13&23&33\end{pmatrix}\\$

This matrix is antisymmetric because it equals its transpose when multiplied by -1:

\\$\begin{pmatrix}0&2&-1\\\-2&0&0\\1&0&0\end{pmatrix}\\$

All antisymmetric matrices exhibit certain characteristics:

* Antisymmetry can only be found on square matrices, because otherwise the matrix and its transpose would be of different dimensions.
* Elements which lie on the main diagonal must equal zero because they do not move and consequently must be their own negatives, and zero is the only number which satisfies \\$x=-x\\$.
* The sum of two antisymmetric matrices is also antisymmetric.

# The Challenge

Given a square, non-empty matrix which contains only integers, check whether it is antisymmetric or not.

# Rules

* This is so the shortest program in bytes wins.
* Input and output can assume whatever forms are most convenient as long as they are self-consistent (including output which is not truthy or falsy, or is truthy for non-antisymmetry and falsy for antisymmetry, etc).
* Assume only valid input will be given.

# Test Cases

```
In:
1 1 1
1 1 1
1 1 1

Out: False

In:
 0 0 1
 0 0 0
-1 0 0

Out: True

In:
0 -2
2  0

Out: True

```

# Answer
# APL (Dyalog Unicode), 3 bytes

```
-≡⍉

```

Try it online!

This is exactly an APLcart entry on "antisymmetric". Basically it checks if the input's negative `-` matches  the input's transpose .
> 14 votes

# Answer
# Python 2, 45 bytes

```
lambda A:A==[[-x for x in R]for R in zip(*A)]

```

Try it online!
> 12 votes

# Answer
# , 23 bytes

```
function(m)!any(m+t(m))

```

Try it online!

Checks whether there are any non-zero elements in \\$M+M^T\\$.
> 12 votes

# Answer
# Brachylog, 5 bytes

5 bytes seems to be the right length for this (unless you're Jelly). Actually, this would be three bytes if Brachylog implicitly vectorized predicates like negation.

```
\ṅᵐ²?

```

Try it online!

### Explanation

```
\      Transpose
 ṅᵐ²   Map negation at depth 2
    ?  Assert that the result is the same as the input

```
> 7 votes

# Answer
# C (gcc), ~~67~~ 64 bytes

-3 thanks to AZTECCO

```
i,j;f(m,s)int**m;{for(i=j=0;i=i?:s--;)j|=m[s][--i]+m[i][s];m=j;}

```

Try it online!

Returns `0` if the matrix is antisymmetric, and a nonzero value otherewise.
> 7 votes

# Answer
# Octave, 19 bytes

```
@(a)isequal(a',-a);

```

Try it online!

The semicolon doesn't *need* to be there, but it outputs the function otherwise, so I'll take the one-byte hit to my score for now.

# Explanation

It's pretty straightforward - it checks to see if the matrix of the transpose is equal to the negative matrix
> 6 votes

# Answer
# Io, 67 bytes

```
method(~,~map(i,\,\map(I,V,V+x at(I)at(i)))flatten unique==list(0))

```

Try it online!

## Explanation

For all `a[x][y]`, it checks whether all `a[x][y]+a[y][x]==0`.

```
method(~,                                 // Input x.
    ~ map(i,\,                            // Map all x's rows (index i):
        \ map(I,V,                        //     Foreach the rows (index I):
            V+x at(I)at(i)                //         x[i][I] + x[I][i]
        )
    ) flatten                             // Flatten the resulting list
    unique                                // Uniquify the list
    ==list(0)                             // Does this resulting list *only* contain the item 0?
)

```
> 5 votes

# Answer
# JavaScript (ES6), 42 bytes

Returns *false* for antisymmetric or *true* for non-antisymmetric.

```
m=>m.some((r,y)=>r.some((v,x)=>m[x][y]+v))

```

Try it online!
> 5 votes

# Answer
# Pyth, 5 bytes

```
qC_MM

```

Try it online!

## Explanation

```
qC_MM
q      : Check if input equals
 C     : Transpose of
  _MM  : Negated input

```
> 4 votes

# Answer
# Japt, 5 bytes

```
eUy®n

```

Try it

```
e       compare input with :
 Uy       columns of input
   ®n     with each element negated

```

Previous version `ÕeËËn` didn't work, corrected using the ® symbol
> 3 votes

# Answer
# MATL, 5 bytes

```
!_GX=

```

Try it online!

## Explanation

```
!_GX=
        // Implicit input on top of stack
!       // Replace top stack element with its transpose
 _      // Replace top stack element with its negative
  G     // Push input onto stack
   X=   // Check for equality

```
> 3 votes

# Answer
# Charcoal, 10 bytes

```
⁼θＥθＥθ±§λκ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the matrix is antisymmetric, nothing if not. Explanation:

```
  Ｅθ        Map over input matrix rows (should be columns, but it's square)
    Ｅθ      Map over input matrix rows
       §λκ  Cell of transpose
      ±     Negated
⁼θ          Does matrix equal its negated transpose?

```
> 3 votes

# Answer
# Wolfram Mathematica, ~~20~~, 7 bytes

There is a built-in function for this task:

`AntisymmetricMatrixQ`

But one can simply write a script with less byte counts:

`#==-#ᵀ&`

The  character, as it is displayed in notebooks, stands for transpose. But if you copy this into tio, it won't be recognized because these characters are only supported by Mathematica notebooks.
> 3 votes

# Answer
# Julia 1.0, 9 bytes

```
A->A==-A'

```

A straightforward anonymous function checking the equality.

Try it online!
> 3 votes

# Answer
# Ruby 2.7, 40 bytes

```
->a{a==a.transpose.map{|r|r.map{|c|-c}}}

```

Try it online!
> 2 votes

# Answer
# Scala, 32 bytes

```
l=>l.transpose==l.map(_.map(-_))

```

Finally, something that Scala has a builtin for!

The function's pretty straightforward - it compares the transpose of a `List[List[Int]]`(doesn't have to be a `List`, could be any Iterable) to the negative, found by mapping each list inside `l` and using `-` to make it negative.

Try it in Scastie
> 2 votes

# Answer
# Haskell, ~~49~~ 47 bytes

```
import Data.List
f x=x==transpose(map(0-)<$>x)

```

Try it online!

* saved 2 thanks to @Unrelated String

My first Haskell.
Function tacking a matrix and checking if input is equal to input mapped to (0-value) and transposed
> 2 votes

# Answer
# Google Sheets, ~~90~~ ~~88~~ 41

(Now with lambdas)

Closing parens discounted.

## Named Functions (name, args, and formula text all count):

| Name | args | Formula |
| --- | --- | --- |
| `P` | `a`, `b` | `a+b` |
| `Q` | `a` | `MAP(a,TRANSPOSE(a),P)` |

## Formula:

```
=SUM(Q(A1:C3))

```

No, I cannot currently use `ADD` instead of `P` as it is not a lambda.

## How it Works:

Add the matrix to its transpose. If the resulting matrix is all 0's, then the sum of all elements is 0, which means we the two are equal.

Return 0 if equal, some positive number otherwise.
> 2 votes

# Answer
# Husk, 5 bytes

```
§=T†_

```

Try it online!
> 2 votes

# Answer
# Haskell, 40 bytes

```
(==)<*>foldr(zipWith(:).map(0-))z
z=[]:z

```

Try it online!

Uses this tip for shorter transpose and the idiom of `(==)<*>` to check invariance under an operation.
> 2 votes

# Answer
# Pip, 5 bytes

```
Z_=-_

```

A function submission; pass a nested list as its argument. Try it online!

### Explanation

```
Z_     The argument, zipped together
  =    Equals
   -_  The argument, negated

```
> 1 votes

# Answer
# gorbitsa-ROM, 8 bytes

```
r1 R A1 B0 T

```

This is an awful abuse of rule

> Input and output can assume whatever forms are most convenient.

If input takes form of "arr\[i\]\[j\] arr\[j\]\[i\]", the problem becomes "is sum = 0?".
This code takes pairs of values and outputs their sum if it's not 0

Thus if you provide matrix as previously mentioned pairs, code will return some value for not-anti-symmetric ones and will not return anything for anti-symmetric ones.

```
r1 R A1 B0 T
r1           #store first number
   R         #read second number
     A1      #add first number
        B0   #if sum==0, jump to the beginning
           T #else output the sum

```
> 1 votes

# Answer
# Java (JDK), ~~89~~ ~~87~~ 86 bytes

* -2 bytes thanks to Calculuswhiz!

```
m->{int i=0,j,r=1;for(;++i<m.length;)for(j=0;++j<i;)r=m[i][j]!=-m[j][i]?0:r;return r;}

```

Try it online!

Returns 0 for `false` and 1 for `true`.
> 1 votes

# Answer
# Jelly, 3 bytes

```
N⁼Z

```

Try it online!

Posting before caird coinheringaahing finds this question.
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
ø(Q

```

Try it online or verify all test cases.

**Explanation:**

```
ø    # Zip/transpose the (implicit) input-matrix; swapping rows/columns
 (   # Negate each value in this transposed matrix
  Q  # And check if it's equal to the (implicit) input-matrix
     # (after which the result is output implicitly)

```
> 0 votes

# Answer
# Factor \+ `math.matrices`, 19 bytes

```
[ dup flip mneg = ]

```

Try it online!

* `dup` make a copy of the input
* `flip` transpose it
* `mneg` negate it
* `=` are they equal?
> 0 votes

# Answer
# Raku, 26 bytes

```
{none flat $_ »+«[Z] $_}

```

Try it online!

* `$_` is the input matrix, in the form of a list of lists of integers.
* `[Z] $_` is the transpose of the input matrix.
* `»+«` adds the input matrix to its transpose.
* `flat` flattens the matrix into a single list of numbers.
* `none` converts that list of numbers into a junction which is true if and only if none of the numbers is truthy, that is, nonzero.

The none-junction is returned. It is truthy only if adding the matrix to its transpose results in a matrix containing all zeroes.
> 0 votes

# Answer
# J-uby, 28 bytes

Port of Razetime's Ruby answer.

```
:=~&(:transpose|:*&(:*&:-@))

```

Attempt This Online!

## Explanation

```
:=~ & (:transpose | :* & (:* & :-@))

       :transpose |                   # Transpose input, then
                    :* & (        )   # Map with
                          :* & :-@    #   Map with negate
:=~ & (                            )  # Equal to input

```
> 0 votes

# Answer
# k, 7 bytes

Similar to the APL solution. Compare (x~) original matrix against negated transpose (-+x}

```
{x~-+x}

```
> 0 votes

# Answer
# Nekomata \+ `-e`, 3 bytes

```
Ť_=

```

Attempt This Online!

```
Ť     Transpose
 _    Negate
  =   Check equality

```
> 0 votes

# Answer
# , 5 bytes

```
--:|:

```

Attempt This Online!

```
--:|:
-      NB. negate
   |:  NB. transpose
 -:    NB. match?

```
> 0 votes

---
Tags: code-golf, decision-problem, matrix
---