title: Uncomment a COBOL program!

text:
# Question
Title: Uncomment a COBOL program!
COBOL is a very old language, at the time of writing it is 58 years old. It is so old, in fact, that it has a very interesting quirk: the first six characters of each line are comments.

Why is this, you ask? Well, those 6 characters were intended to be used as line numbers, back in the day where programs weren't completely digital and typed out on a computer.

In addition, the seventh character could only be part of a very small set (it is usually `*` to comment out the line or a space to separate the line number from the code)

But what if you're on a more digital system, and you just want the raw program?

## The comment system

There are two types of comments in COBOL: line comments and the aforementioned "line number" comments.

Uncommenting line numbers is simple: just take the first seven (six plus a single space) characters off each line.

```
000000 apple
000001 banana
celery donuts

```

would become:

```
apple
banana
donuts

```

Line comments make it a bit more difficult. A line comment is started with an asterisk `*` placed in the seventh character position on the line, like so:

```
000323* this is a comment

```

This is not a line comment:

```
*00000 this isn't a comment

```

To uncomment a line comment, just remove the whole line.

An example commented "program":

```
000000 blah blah
000001* apples
000002 oranges?
000003* yeah, oranges.
000*04 love me some oranges

```

The uncommented version:

```
blah blah
oranges?
love me some oranges

```

In other words, to uncomment a string, remove the first six characters of each line, then return all but the first character of every line that does not begin with a star.

## The challenge

Create a program or function that takes a commented program and returns its uncommented variant.

## Clarifications

* Asterisks (`*`) will never be found anywhere outside the first seven characters on a line (we're not asking you to verify syntax)
* Each line will always have at least 7 characters.
* You may assume the seventh character is always an asterisk or a space.
* Input or output may be a matrix or list.
* Only printable ASCII characters (plus newline) must be handled.
* You may output with a trailing newline. You may also assume that the input will have a trailing newline, if you so choose.

## Scoring

Since this is , the answer with the least bytes wins!

DISCLAIMER: I do not actually know COBOL and do not claim to. If any of the claims about COBOL I have made in this question are incorrect, I take no responsibility.

# Answer
# COBOL (GnuCOBOL), 191 + 17 = 208 bytes

I "learned" COBOL for this answer, so it's probably not fully golfed.

This is a full program, taking input on what I presume to be standard input and writing to what I presume to be standard output. Perhaps one day I'll return to this and (1) determine whether COBOL has functions and, if so, (2) see whether a function solution would be shorter.

Byte count includes program and compiler flags (`-free` and `-frelax-syntax`).

```
program-id.c.select i assign keyboard line sequential.fd i. 1 l pic X(80). 88 e value 0.open input i perform until e read i end set e to true end-read if not e and l(7:1)<>'*'display l(8:73).

```

Try It Online

## Ungolfed program

```
program-id. c.

select i assign to keyboard organization line sequential.

fd i.
    1 l pic X(80).
    88 e value 0.

open input i
perform until e
    read i
        end set e to true
    end-read
    if not e and l(7:1) <> '*'
        display l(8:73).

```

## Limitations

The output is, technically speaking, not correct. From my cursory research, it seems the only practical way to store a string in COBOL is in a fixed-size buffer. I have chosen a buffer size of 80 characters, since this is the line length limit for fixed-format programs. This presents two limitations:

* Lines longer than 80 characters are truncated.
* Lines shorter than 80 characters are right-padded with spaces.

I'm guessing this is acceptable since, well, it's COBOL. If not, I'd be willing to look into alternatives.

## Acknowledgments

* -166 bytes thanks to Edward H
* -2 bytes thanks to *hornj*
> 112 votes

# Answer
# Python 2, ~~39~~ ~~38~~ 37 bytes

*-1 byte thanks to LyricLy. -1 byte thanks to Mego.*

```
lambda s:[i[7:]for i in s if'*'>i[6]]

```

Try it online!

I/O as lists of strings.
> 22 votes

# Answer
# Perl 5, ~~19~~ \+ 1 (-p) = ~~20~~ 16 bytes

*-4 bytes with Pavel's suggestions*

```
s/.{6}( |.*)//s

```

Try it online!
> 13 votes

# Answer
# , ~~13~~ ~~11~~ 10 bytes

```
Î6x<<
çª/d

```

Try it online!

### Explanation

```
Î       ' On every line
  x     ' delete the first...
 6      ' 6 characters
   <<   ' and unindent the line (removes the leading space)
ç /     ' on every line
 ª      ' matching \*
   d    ' delete the line

```

Hexdump:

```
00000000: ce36 783c 3c0a e7aa 2f64                 .6x<<.../d

```
> 11 votes

# Answer
# Paradoc (v0.2.8+), 8 bytes (CP-1252)

```
µ6>(7#;x

```

Takes a list of lines, and results in a list of uncommented lines.

Explanation:

```
μ        .. Map the following block over each line (the block is terminated
         .. by }, but that doesn't exist, so it's until EOF)
 6>      .. Slice everything after the first six characters
   (     .. Uncons, so now the stack has the 6th character on top
         .. and the rest of the line second
    7#   .. Count the multiplicity of factors of 7 in the character
         .. (treated as an integer, so '*' is 42 and ' ' is 32)
      ;  .. Pop the top element of the stack (the rest of the line)...
       x .. ...that many times (so, don't pop if the 6th character was a
         .. space, and do pop if it was an asterisk)

```

Hi, I wrote a golfing programming language. :)

I'm still developing this and added/tweaked a bunch of built-ins after trying to write this so that there are more reasonable ways to differentiate between a space and an asterisk than "`7#`", but I feel like that would make this noncompeting. It's fortunate that it still worked out (this only uses features from v0.2.8, which I committed three days ago).
> 9 votes

# Answer
# Octave, 23 bytes

```
@(s)s(s(:,7)~=42,8:end)

```

Try it online!
> 7 votes

# Answer
# Jelly, ~~11~~ 9 bytes

```
ṫ€7Ḣ⁼¥Ðf⁶

```

Try it online!

Inputs and outputs as a list of lines.

*-2 bytes thanks to @EriktheOutgolfer and @JonathanAllan*

**How it works**

```
ṫ€7Ḣ=¥Ðf⁶
 €           On each line:
ṫ 7            Replace the line with line[7:]
      Ðf     Keep all lines that meet condition:
     ¥         Dyad:
   Ḣ             First Element (modifies line)
    =            Equals
        ⁶    Space

```
> 6 votes

# Answer
# PowerShell, 32 bytes

```
$input-replace'^.{6}( |.*)'-ne''

```

Try it online!

Pipeline input comes in as an array of strings, `-replace` works on every string, and `-ne ''` (not equal to empty string) applied to an array, acts to filter out the blank lines.
> 5 votes

# Answer
# Vim, 14 bytes

`Ctrl-V``G5ld:%g/\*/d``Enter`

Loading the input file as the buffer to edit, then enter the above commands. Output is the new buffer.
> 5 votes

# Answer
# Pyth, 9 bytes

Note that this only works if at least 1 line is *not* a comment and at least 1 line *is* a comment. All the other solutions work in all cases.

*-2 bytes thanks to @pizzakingme!*

```
m>d7.m@b6

```

**Try it here!**

### Explanation

```
m>d7.m@b6     - Full program with implicit input. Takes input as a list of Strings.

m>d7          - All but the first 7 letters of
    .m   (Q)  - The input, filtered for its minimal value using the < operator on
      @b6     - the 7th character -- note that "*" is greater than " "
              - Implicitly Output the result.

```

---

# Pyth, 11 bytes

```
tMfqhTdm>d6

```

**Try it here!**

### Explanation

```
tMfqhTdm>d6 - Full Program with implicit input. Takes input as a list of Strings.

       m>d6 - Remove the first 6 characters of each line.
    hT      - Get the first character of each.
  fq  d     - Keep those that have the first character an asterisk.
tM          - Remove the first character of each.
            - Output Implicitly.

```

---

# Pyth, 11 bytes

```
m>d7fqd@T6Q

```

**Try it here!**

### Explanation

```
m>d7fq@T6dQ  - Full program. Takes input as a list of Strings.

      @T6    - The sixth character of each.
    fq   dQ  - Keep the lines that have a space as ^.
m>d7         - Crop the first 7 characters.
             - Output implicitly.

```

---

# Pyth, 12 bytes

```
tMfnhT\*m>d6

```

**Try it here!**

### Explanation

```
tMfnhT\*m>d6 - Full Program with implicit input. Takes input as a list of Strings.

        m>d6 - Remove the first 6 characters of each line.
    hT       - Get the first character of each.
  fn  \*     - Filter those that aren't equal to an asterisk.
tM           - Remove the first character of each.
             - Output Implicitly.

```

---

# Pyth, 12 bytes

```
m>d7fn@T6\*Q

```

**Try it here!**

### Explanation

```
m>d7fn@T6\*Q  - Full program. Takes input as a list of Strings.

      @T6     - Get the sixth character of each string
    fn   \*Q  - And filter those that aren't equal to an asterisk.
m>d7          - Crop the first 7 characters.
              - Output implicitly.

```
> 4 votes

# Answer
# C, ~~63~~ ~~59~~ ~~55~~ ~~48~~ ~~47~~ 46 bytes

Thanks to "*an anonymous user*" for getting rid off yet another byte.

Thanks to Felix Palmen for reminding me of "*You may assume the seventh character is always an asterisk or a space.*", which shaved off one more byte.

```
f(char**a){for(;*a;++a)(*a)[6]&2||puts(*a+7);}

```

Use like:

```
char** program = { "000000 apple", "000001 banana", "celery donuts", 0 };
f(program);

```

Try it online!
> 4 votes

# Answer
# C (gcc), 53 48 46 bytes

```
x;main(y){for(y=&x;gets(y-6);x&2||puts(y+1));}

```

Try it online!

*-5 bytes:* It was very tricky to get this "*whole program*" down to the same size as gurka's function. It's now writing out of bounds (in both directions) of an array of wrong type and relies on *little endian* and *4 byte integers* to find the asterisk ... but hey, it works ;)

*-2 bytes:* Well, if we already write to some "random" `.bss` location, why bother declaring an *array* at all! So here comes the string handling program that uses *neither* the `char` type *nor* an array.
> 4 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~72~~ ~~70~~ ~~66~~ 50 bytes

```
R	INPUT POS(6) (' '  REM . OUTPUT | '*') :S(R)
END

```

Try it online!

Pattern matching in SNOBOL is quite different from regex but the idea here is still the same: If a line matches "six characters and then an asterisk", remove it, otherwise, remove the first seven characters of the line and print the result.

This now actually takes better advantage of SNOBOL's conditional assignment operator.

The pattern is `POS(6) (' ' REM . OUTPUT | '*')` which is interpreted as:

Starting at position 6, match a space or an asterisk, and if you match a space, assign the rest of the line to `OUTPUT`.
> 4 votes

# Answer
# Ruby, ~~39~~ ~~38~~ ~~36~~ ~~29~~ ~~23~~ ~~22~~ 20 + 1 = 21 bytes

```
$_[/.{6}( |.*
)/]=''

```

Try it online!

Uses `-p` flag.

Explanation:

The `-p` flag adds an implicit block around the code, so the code that actually gets run looks like this:

```
while gets
    $_[/.{6}( |.*
)/]=''

    puts $_
end

```

`gets` reads a line of text and stores its result in `$_`.

`$_[/.../]=''` removes the first occurence of the regex `...` in `$_`.

`/.{6}( |.*\n)/` matches 6 of any character at the start of a line, followed by either a space or the rest of the line. Because the space appears first, it will try to remove only the first 6 characters and a space before attempting to remove the entire line.

`$_` is then printed out, and this process is repeated for each line.
> 3 votes

# Answer
# Actually, 13 bytes

```
⌠6@tp' =*⌡M;░

```

Input and output is done as a list of strings.

Explanation:

```
⌠6@tp' =*⌡M;░
⌠6@tp' =*⌡M    for each line:
 6@t             discard the first 6 characters
    p            pop the first character of the remainder
     ' =         is it a space?
        *        multiply the string by the boolean - returns the string if true, and an empty string if false
           ;░  filter out empty strings

```

Try it online!
> 3 votes

# Answer
# Gaia, 9 bytes

```
6>¦'*«⁈ḥ¦

```

A function accepting a list of strings and returning a list of strings.

Try it online!

### Explanation

```
6>¦        Remove the first 6 characters of each string
   '*«⁈    Filter out ones that start with *
       ḥ¦  Remove the initial space from each

```
> 3 votes

# Answer
## R, 47 45 bytes

```
function(x)gsub("(?m)^.{6}( |.*\\n)","",x,,T)

```
> 3 votes

# Answer
# Haskell, ~~27~~ 25 bytes

Laikoni's version is shorter than mine:

```
f n=[x|' ':x<-drop 6<$>n]

```

Try it online!

My version:

```
f n=[drop 7x|x<-n,x!!6<'*']

```

Try it online!
> 3 votes

# Answer
# Java 8, 40 bytes

Regular expressions: just about, but not quite, the wrong tool for the job. Lambda from `String` to `String` (assign to `Function<String, String>`). Input must have a trailing newline.

```
s->s.replaceAll("(?m)^.{6}( |.*\\n)","")

```

Try It Online

## Acknowledgments
> 3 votes

# Answer
# GNU Sed, 19 + 2 = 21 characters

Requires `-E` argument to `sed` to enable extended regular expressions.

```
/^.{6}\*/d;s/^.{7}/

```
> 3 votes

# Answer
# APL, 23 bytes

* 23 bytes assuming SBCS. In UTF-8 it'll be **42 bytes**

This is my first ever attempt at a code golf challenge, feel free to improve, i'm sure i could have saved one or two characters if i wasn't so adamant on making this code *'tacit'*

This assumes the input is a list of lines and return a list of uncommented lines, this makes everything a bit easier since APL was explicitly made to work on list!

```
(('*'≠7∘⌷)⊢⍤/(8≤⍳8)∘⊂)¨

```

Go ahead and try it! (Thanks @Sʨɠɠan)
> 3 votes

# Answer
# JavaScript, ~~44~~ 34 bytes

*Crossed-out 44 is still regular 44.*

*6 bytes saved thanks to tsh*

```
a=>a.replace(/^.{6}( |.*\n)/gm,'')

```

Try it online!
> 2 votes

# Answer
# Retina, ~~23~~ 15 bytes

*5 bytes saved thanks to nmjcman101
1 byte saved thanks to Neil*

```
m`^.{6}( |.*¶)

```

Try it online!
> 2 votes

# Answer
# C#, ~~160 145 90~~ 89 bytes

```
t=>{var o="";foreach(var s in i.Split('\n'))if(s[6]!=42)o+=s.Substring(7)+"\n";return o;}

```

Thanks to Pavel & auhmaan for reducing the size.
> 2 votes

# Answer
# Pyke, 9 bytes

```
36 4C 3E 23 64 DE 29 6D 74

```

Try it here!

Readable:

```
6L>#d.^)mt

```

Try it here!

```
6L>        -   [i[6:] for i in input]
   #d.^)   -  filter(i.startswith(" ") for  i in ^)
        mt - [i[-1:] for i in ^]

```
> 2 votes

# Answer
# JavaScript (ES6), 48 bytes

```
s=>s.map(c=>c[6]<"*"?console.log(c.substr(7)):1)

```

Try it online!
> 2 votes

# Answer
# \>\<\>, ~~57~~ 53 Bytes

```
>i~i~i~i~i~i~i67*=\
<o$/?:$/?=a:;?(0:i<
\~$/~\ $
/  <o\?/

```

try it online

## Explanation

```
>i~i~i~i~i~i~i67*=    Read in the first seven bytes of the line
 i~i~i~i~i~i~         Read, and discard 6 characters
             i        Read the seventh
              67*=    Check if the seventh character was an
                      asterisk (and leave that value on the stack );

<o$/?:$/?=a:;?(0:i<    Read characters until a newline or eof
                 i     Read the next character of the line
            ;?(0:      If it's a -1, terminate the program
       /?=a:           If it's a newline, break out of the loop
   /?:$                If the seventh character was not an asterisk
<o$                    Output this character
\~$/                   otherwise discard it

   /~\ $    Having reached the end of the line, output
/  <o\?/    the newline only if it was not a comment

```

# Edit: 53 bytes

```
>   i~i~i~i~i~i~i67*=\
/?=a<o/?$@:$@:$;?(0:i<
~   \~/

```

Basically the same stuff as before, but restructured slightly

~~As a side note: I'm disappointed no-one's done this in cobol yet.~~
> 2 votes

# Answer
## Python 3, 62 bytes (no regex)

```
def f(s):
 for w in s.split('\n'):
  if w[6]!='*':print(t[7:])

```

It works!

```
>>> s="""000000 blah blah
000001* apples
000002 oranges?
000003* yeah, oranges.
000*04 love me some oranges"""
>>> f(s)
blah blah
oranges?
love me some oranges

```
> 2 votes

# Answer
# Zsh (builtins only), 35 bytes

```
for l ("${(f)$(<p)}")<<<${l:7$l[7]}

```

Try it Online

Scans file `p` per this tip. Other solutions: ~~45 bytes~~, ~~27b (illegal)~~
> 2 votes

# Answer
# sed, 11 bytes + 3 bytes option `-nr` = 14 bytes.

```
s/^.{6} //p

```

Try it online!

# sed, 16 bytes

```
#n
s/^.\{6\} //p

```

Try it online!

`#n` on top of line is for `-n`, which is ~~GNU-extension~~ POSIX-compatible.
> 2 votes

# Answer
# CLC-INTERCAL, 116 bytes.

```
DO;1<-#6DO,1<-#999DOCOMEFROM.1DOWRITEIN;1+,1(91)DO.1<-,1SUB#2(1)DO.2<-.1~#1DDOCOMEFROM.2DO,1SUB#3<-#0(95)DOREADOUT,1

```

Try it online, although you need to copy and paste!

## Assumption

* Each line should have \<=80 characters except trailing newline character(s), although this program can handle up to 339 characters per line (or more, depending on what kind of characters are used).
* Does not matter whether input has trailing newline or not.

## Explaination

```
DONOTE stores first six characters of line
DO;1<-#6
DONOTE stores rest of characters of line except trailing newline
DO,1<-#999
DONOTE label one
DOCOMEFROM.1
DOWRITEIN;1+,1
DONOTE goto label one if tail one is asterisk
DONOTE first two items of tail one shall be
DONOTE 91 and 95 if space, or
DONOTE 91 and 95 if asterisk
(91)DO.1<-,1SUB#2
DONOTE goto label two if line is not empty
DONOTE obtw every item of tail will be zero
DONOTE if empty line
(1)DO.2<-.1~#1
DONOTE die here
D
DONOTE label two
DOCOMEFROM.2
DONOTE erase the space
DONOTE obtw zeros on tail are ignored
DONOTE when reading out
DONOTE see source code for more info
DO,1SUB#3<-#0
DONOTE goto label 1 after reading out
(95)DOREADOUT,1

```
> 2 votes

# Answer
# Pure Bash, 42 + 1 = 43 bytes

Filename must be `x`; it is for extra one byte.

```
read x||>x
((1${x:6:1}1))||echo ${x:7}
. x

```

Try it online!

## Usage

* Input from stdin.
* Optional trailing LFs.
* Output to stdout.
> 2 votes

# Answer
# AWK, 34 24 15 bytes

```
sub(/^.{6} /,_)

```

Attempt This Online!
> 2 votes

# Answer
# Japt, ~~11~~ 10 bytes

Takes input as an array of strings and outputs an array of strings.

```
k_g6 x
®t7

```

Test it (`-R` flag for visualisation purposes only)

* Saved a byte thanks to ETH.

---

## Explanation

Implicit input of array `U`.

```
f_

```

Filter (`f`) by passing each element through a function.

```
g6

```

Get the character at index (`g`) 6 (0-indexed).

```
x

```

Trim, giving either `*` (truthy) or an empty string (falsey).

```
®t7

```

Map (`®`) over the array and get the substring (`t`) of each element from the 7th character. Implicitly output the resulting array.
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
|ʒ6èðQ}ε7F¦

```

Try it online!
> 1 votes

# Answer
# C++ (GCC), ~~121~~ 112 bytes

*Thanks to @gurka for saving 9 bytes!*

```
#import<bits/stdc++.h>
void f(std::list<std::string>l){for(auto s:l)if(s[6]-42)std::cout<<s.substr(7,s.size());}

```

Takes input as a list of lines.

Try it online!
> 1 votes

# Answer
# Java 8, ~~95~~ ~~54~~ 53 bytes

```
s->s.filter(x->x.charAt(6)<33).map(x->x.substring(7))

```

-42 bytes thanks to *@OliverGrégoire*, by using a `Stream<String>` instead of `String` as in- and output.

**Explanation:**

Try it here.

```
s->                          // Method with Stream<String> as parameter and return-type
  s.filter(x->x.charAt(6)<33)//  Filter out all lines containing an asterisk as 7th char
   .map(x->x.substring(7))   //  And remove the first 7 characters from the remaining lines
                             // End of method (implicit / single-line body)

```
> 1 votes

# Answer
# TeX - 139 bytes

```
\let~\def~\a#1#2#3#4#5#6{\b}~\d#1{\catcode`#1=12}\obeylines\d\ ~\b#1#2
{\if#1*\else\write1{#2}\fi\egroup
}\everypar{\bgroup\d\\\d\{\d\}\a}

```

Eats up the first six characters of each line, then checks if the next one is an asterisk or something else. Recurses over lines by eating up anything that tries to get typeset. The rest of my bytes are spent on changing category codes of syntax related characters so it's robust.
> 1 votes

# Answer
# Javascript, 37 bytes

Regexp-based solution

```
s=>s.replace(/^.{6}( |(\*.+$\n?))/gm,'')

```
> 1 votes

# Answer
# Jq 1.5, 24 bytes

```
select(.[6:]<"*")|.[7:]

```

Explanation

```
  select(.[6:] < "*")          # discard if '*' in column 7
| .[7:]                        # keep remaining portion

```

Sample run with `paste` to show input vs output

```
$ paste input <(jq -MRr 'select(.[6:]<"*")|.[7:]' input)
000000 blah blah                blah blah
000001* apples                  oranges?
000002 oranges?                 love me some oranges
000003* yeah, oranges.
000*04 love me some oranges

$ wc -c <<<'select(.[6:]<"*")|.[7:]'
      24

```

Try it online
> 1 votes

# Answer
# Dash, 26 bytes

```
cut -c7-|grep ^\ |cut -c2-

```

Try it online!

---

# Dash, 29 bytes

```
cut -c7-|grep -vF \*|cut -c2-

```

Try it online!

OBTW it's POSIX-compatible, if I remember the specs correctly.
> 1 votes

# Answer
# Pxem, 88 bytes (filename) + 0 bytes (content) = 88 bytes, with non-printable characters.

* Filename (some unprintables are escaped): `\001.t.i.m.+.w.i.s.i.s.i.s.i.s.i.s.i*.zAB.z.i.c.o\n.a\002.tXX.a.m\002.zAB.i\n.z.i\n.aXX.a\001.t.i.m.+.a`
* Content: empty.

Try it online!

## Usage

```
/path/to/pxem/interpreter THAT_PROGRAM_AS_IN_ABOVE <input.txt

```

COBOL program to be input must be fed from stdin, with LF-styled newlines, whose last line is terminated with LF.

## Alternative: Pxem, 100 bytes (filename) + 0 bytes (content) = 100 bytes, printables and LF only.

Filename is as follows:

```
ab.-.t.i.m.+.w.i.s.i.s.i.s.i.s.i.s.i*.zAB.z.i.c.o
.a02.-.tXX.a.mac.-.zAB.i
.z.i
.aXX.aab.-.t.i.m.+.a

```

## Commented version

```
XX.z (this is just to format well
.a<0x01>.tXX.z (reg=1
.a.i.m.+.wXX.z (while getchar()!=EOF; do (obtw EOF is -1
   .a.i.s.i.s.i.s.i.s.i.sXX.z (5.times { getchar(); }
   .a.i*.zXX.z (while getchar()!='*'; do
      .aAB.z.i.c.o<0x0A>.aXX.z (do print(c=getchar()) while c!=newline
      .a<0x02>.tXX.z (reg=2
   .aXX.aXX.z ( break; done
   .a.m<0x02>.zXX.z (while reg!=2; do
      .aAB.i<0x0A>.z.i<0x0A>.aXX.z (do c=getchar() while c!=newline
   .aXX.aXX.z ( break; done
   .a<0x01>.tXX.z (reg=1
.a.i.m.+.aXX.z (done
.a

```
> 1 votes

# Answer
# GFortran, 84 bytes

Try it Online!

Yet again, Fortran beats Cobol ☺. Borrows stuff from this solution.

```
character(99)C;read*,n;do i=1,n;read'(A)',C
if(C(7:7)<'*')print'(A)',C(8:);enddo;end

```

Previously: ~~95 bytes~~ ; ~~98 bytes~~(-47 by removing array) ; ~~145 bytes~~
> 1 votes

# Answer
# Scratch, 277 bytes.

```
define g[x
set[s v]to(
set[j v]to((x)+(1
repeat(length of(item(i)of[l v
set[s v]to(join(s)(letter(j)of(item(i)of[l v
change[j v]by(1
end
replace item(i)of[l v]with(s
define f
set[i v]to(1
repeat(length of[l v
g(6
if<(s)contains[*]?>then
delete(i)of[l v
else
g[1
change[i v]by(1

```

Try it on Scratch!
> 1 votes

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

```
{$["*"=x@6;"";" "/1_" "\x]}'

```

Try it online!

Takes a list of strings and returns a list of strings.

Explanations:

```
{$["*"=x@6;"";" "/1_" "\x]}'  Main function. Takes implicit input
                           '  For each string in the lists...
{                         }   Execute a function that
 $[                      ]    Checks if
       x@6                    The character at the 6th position (0-indexed)
   "*"=   ;                   Is equal to an asterisk
           "";                If it does, return an empty string
                        x     Else, return the string
                    " "\      Splitted by whitespace
                  1_          Trim the first element (i.e. the line numbers)
              " "/            Join together by whitespace (to preserve the original text)

```
> 1 votes

# Answer
# J, 20 bytes

```
7&}."1(#~'*'~:6&{"1)

```

This assumes the input is a matrix of equal-length space-padded lines.
> 0 votes

# Answer
# PHP, 50 bytes

```
foreach(file(C)as$s)$s[6]>" "||print substr($s,7);

```

same length:

```
foreach(file(C)as$s)$s[6]^a^q||print substr($s,7);
foreach(file(C)as$s)$s[6]^b^x&&print substr($s,7);
foreach(file(C)as$s)echo$s[6]^b^x?substr($s,7):"";

```

regex solution, 51 bytes:

```
<?=join(preg_filter("#^.{6} (.*)$#","$1",file(C)));

```

builtins only, 108 bytes:

```
<?=join(array_map(function($s){return substr($s,7);},array_filter(file(C),function($s){return$s[6]^b^x;})));

```

take code from a file named `C`. Run with `-nr` or try them online.
> 0 votes

# Answer
# CJam, 13 bytes

```
{{6>'*#},7f>}

```

Try it online!

Explanation:

```
{           }  e# Block. Input:                ["000000 blah blah" "000001* apples" "000002 oranges?" "000003* yeah, oranges."]
 {     },      e# Filter on the following:
  6>           e#   Remove first 6 characters: [" blah blah" "* apples" " oranges?" "*yeah, oranges"]
    '*#        e#   Find a '*':                [-1 0 -1 0]
               e# End filter:                  ["000000 blah blah" "000002 oranges?"]
         7f>   e# Remove first 7 characters:   ["blah blah" "oranges?"]

```
> 0 votes

# Answer
# Implicit, 22 bytes

```
('\6¯_0=`*!{]\1%ß1}]^ö

```

No explanation, sorry. I forgot how this works.
> 0 votes

# Answer
# Pyth - 15

```
V.z*.DNU7n@N6\*

```

Explanation:

```
V.z*.DNU7n@N6\*
V.z              For each line N in input
                  Print
     N             N
   .D U7           but with characters 0-6 removed
  *                times
          @N6       Item six of N
         n          Does not equal
             \*     "*"

```
> 0 votes

# Answer
# Husk, 9 bytes

```
fo≠' ←m↓7

```

Try it online!

same idea as Jelly.
> 0 votes

# Answer
# Excel, 40 bytes

```
=FILTER(MID(A:A,8,73),MID(A:A,7,1)<>"*")

```

COBOL has a max line length of 80.
> 0 votes

# Answer
# Stax, 7 bytes

```
ê┬|Y¶à6

```

Run and debug it

## Explanation

```
m6%B42=C
m        map each line:
 6%      split at index 6, push both parts
   B     uncons, pop and push first element
    42=C if equal to 42, cancel

```
> 0 votes

# Answer
# C++ (gcc), 68 bytes

```
[](auto&l){l.remove_if([](auto&s){int c=s[6];s=&s[7];return c&2;});}

```

Input is a `std::list<std::string>`, it's modified in place.

Try it online!
> 0 votes

# Answer
# Pascal, 122 B

This is a complete `program` requiring a processor complying to ISO standard 10206 “Extended Pascal”:

```
program p(input,output);var l:string(80);begin while not EOF do begin readLn(l);if''=l[7]then writeLn(subStr(l,8))end end.

```

Ungolfed version with some explanatory comments:

```
program uncommentFixedFormatCobol(input, output);
    var
        { This “discriminates” the built-in schema data type `string`
          to have a capacity of up to 80 characters, i.e. the maximum
          width of one COBOL _fixed-format_ source code line. }
        line: string(80);
    begin
        { `EOF` is shorthand for `EOF(input)`. }
        while not EOF do
        begin
            { `readLn(line)` is shorthand for `readLn(input, line)`. }
            readLn(line);
            { Similarly, `write(x)` is shorthand for `write(output, x)`. }

            { ---- Remember, in Pascal `string` indices are 1-based. ----- }
            { This may look like an empty string check, and `''` is indeed
              an empty string, yet in Pascal the `=`-comparison first pads
              both operands  to the same length using `' '`.  This line is
              in fact doing `if line[7] = ' ' then`, but one byte shorter. }
            if line[7] = '' then
            begin
                { `subStr(line, 8)` shorthand for
                  `subStr(line, 8, length(line) - 8 + 1)` }
                writeLn(subStr(line, 8))
                { Wait! What if `line[8]` does not exist? The standard
                  says it shall be an error if `firstCharacterIndex +
                  substringLength − 1` is greater than the length of the
                  supplied string. If `length(line)` equals seven, then
                  we’re calling `subStr(line, 8, 0)` which is fine. }
            end
        end
    end.

```
> 0 votes

# Answer
# Knight (v2), 19 bytes

```
W=xP|?42A=xSxF6@O]x

```

There are a few ways to do this that all are 19 bytes, but the theoretically optimal way (`= x SUBST(PROMPT 0 6 @)`) suffers from keyword clashing, meaning it has to be `=xS P0 6@`, wasting two separators.

```
# for each line in stdin
WHILE (= x PROMPT)
    #  If not equal to to 42 (ASCII("*"))
    #   |    | ASCII value of first char
    #   |    |     | Strip the first 6 chars of x
    : | ? 42 ASCII (= x SUBST (x FALSE 6 @))
      # Output the tail (all but the first char) of x
      : OUTPUT (] x)

```

This uses the new `]` and `@` operators to simplify string operations, as `]` replaces `SxF1""` and `@` replaces `""` when coerced to String since empty list is empty string.

Input is in stdin, output is in stdout.

Try it online!
> 0 votes

# Answer
# Pyth, 12 bytes

```
tMfqdhT>R6.z

```

Try it here.

##### Explanation:

```
tMfqdhT>R6.z | Full program
-------------+----------------------------------------
        R .z | For each line of input
       > 6   |  Remove the first 6 characters
  f  hT      | Filter over whether the first character
   qd        |  is a space
tM           | Remove the first character of each

```
> 0 votes

# Answer
# Pure Bash, 39 bytes

Outgolfed user100411's answer

```
for x
{ ((1${x:6:1}1))||echo "${x:7}"
}

```

Attempt This Online!

## Usage

Each argument represents a line. e.g.

```
cat<<'EOF'>f
for x
{ ((1${x:6:1}1))||echo "${x:7}"
}
EOF
bash f '000000 blah blah' '000001* apples' '000002 oranges?' '000003* yeah, oranges.' '000*04 love me some oranges'

```
> 0 votes

# Answer
# Thunno 2 `N`, 10 bytes

```
¤æ6ið=;ı7ỵ

```

Attempt This Online!

#### Explanation

```
¤æ6ið=;ı7ỵ  # Implicit input
¤           # Split the multi-line input on newlines
 æ    ;     # Filter this list of strings by:
  6i        #  The 6th character (0-indexed)
    ð=      #  Is a space
       ı    # Map over this new list of strings:
        7ỵ  #  Remove the first 7 characters
            # Implicit output, joined on newlines

```
> 0 votes

# Answer
# Erlang, 52 bytes

```
a(A)->[lists:nthtail(7,X)||X<-A,lists:nth(7,X)/=42].

```

Try it online!
> 0 votes

# Answer
# sed 4.2.2, 29 bytes

```
/^.{6}\*.*$/d
s/^.{7}//
/^$/d

```

Try it online!
> 0 votes

# Answer
# Rockstar, 94 bytes

```
listen to S
while S
cut S in N
cut S
while N-S-7
roll S in C

if C-1
join S
say S

listen to S

```

Try it (Code will need to be pasted in)
> 0 votes

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


title: Print the digital root

text:
# Question
Title: Print the digital root
This is different from My Word can beat up your Word as it is less complex and only requires you to calculate it, and not compare them.

To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was `12345`, you would add `1`, `2`, `3`, `4`, and `5`, getting `15`. You would then add `1` and `5`, giving you `6`.

### Your task

Given an integer ***N*** (0 \<= ***N*** \<= 10000) through **STDIN**, print the digital root of ***N***.

### Test cases

```
1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7

```

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
## Pyke, 1 byte

```
s

```

Try it here!

Takes the digital root of the input
> 28 votes

# Answer
# Jelly, ~~7 5 4~~ 3 bytes

```
ḃ9Ṫ

```

**TryItOnline!** or all test cases

### How?

The digital root is known to obey the formula (n-1)%9+1.
This is the same as the last digit in bijective base 9
(and due to implementation that `0ḃ9=[]` and `[]Ṫ=0` this handles the edge-case of zero).

```
ḃ9Ṫ - Main link: n
ḃ9  - convert to bijective base 9 digits (a list)
  Ṫ - tail (get the last digit)

```
> 22 votes

# Answer
# JavaScript (ES6), ~~16~~ 10 bytes

```
n=>--n%9+1

```

Test cases

```
let f =

n=>--n%9+1

console.log(f(1)); // -> 1
console.log(f(45)); // -> 9
console.log(f(341)); // -> 8
console.log(f(6801)); // -> 6
console.log(f(59613)); // -> 6
console.log(f(495106)); // -> 7
```
> 15 votes

# Answer
# Python, ~~16~~ 20 bytes

+4 bytes to handle edge case of zero.

```
lambda n:n and~-n%9+1

```

**repl.it**
> 8 votes

# Answer
# MATL, 3 bytes

```
9X\

```

Try it online!

A lot of (now deleted answers) tried using modulo 9 to get the result. This is a great shortcut, but unfortunately does not work for multiples of 9. MATL has a function for modulo on the interval `[1, n]`. Using this modulo, we have `1 % 3 == 1, 2 % 3 == 2, 3 % 3 == 3, 4 % 3 == 1`, etc. This answer simply takes the input modulo nine using this custom modulo.
> 7 votes

# Answer
## Mathematica, ~~27~~ 11 bytes

```
Mod[#,9,1]&

```

Mathematica's `Mod` takes a third parameter as an offset of the resulting range of the modulo. This avoids decrementing the input and incrementing the output.
> 7 votes

# Answer
## Julia, 12 bytes

```
!n=mod1(n,9)

```

or

```
n->mod1(n,9)

```

`mod1` is an alternative to `mod` which maps to the range `[1, n]` instead of `[0, n)`.
> 7 votes

# Answer
# PHP, 15 Bytes

```
<?=--$argn%9+1;

```

Previous version PHP, 55 Bytes

```
$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;

```
> 6 votes

# Answer
# R, 72 67 29 bytes

Edit: Thanks to @rturnbull for shaving off two bytes.

```
n=scan();`if`(n%%9|!n,n%%9,9)

```
> 5 votes

# Answer
# Retina, 7 bytes

```
{`.
*
.

```

Try it online!

I see lots of mathematical solutions, but in Retina the straightforward approach seems to be the best one.

### Explanation

`{`` makes the whole program run in a loop until the string doesn't change anymore. The loop consists of two stages:

```
.
*

```

Convert each digit to unary.

```
.

```

Count the number of characters (=convert the unary number to decimal).

This works because converting each digit to unary with no separator between digits creates a single unary number which is equal to the sum of all digits.
> 5 votes

# Answer
# Haskell, ~~35~~ 34 bytes

```
until(<10)$sum.map(read.pure).show

```

Try it on Ideone.

**Explanation:**

```
until(<10)$sum.map(read.pure).show
                              show  -- convert int to string
               map(         ).      -- turn each char (digit) into
                        pure        --    a string
                   read.            --    and then a number
           sum.                     -- sum up the list of numbers
until(<10)$                         -- repeat until the result is < 10

```
> 4 votes

# Answer
# Perl, 15 bytes

Includes +2 for `-lp`

Give input on STDIN

```
root.pl <<< 123

```

`root.pl`

```
#!/usr/bin/perl -lp
$_&&=~-$_%9+1

```

This is the boring solution that has already been given in many languages, but at least this version supports `0` too

More interesting doing real repeated additions (though in another order) is in fact only 1 byte longer:

```
#!/usr/bin/perl -p
s%%$_+=chop%reg

```
> 4 votes

# Answer
# Husk, 4 bytes

### Recursive method (4 bytes) (Credit to @ovs)

```
ωoΣd

```

```
      # implicit parameter ⁰ (refers to the last parameter)
   d  # list of digits in base 10
  Σd  # sum of list
 oΣd  # compose the two functions
ωoΣd  # repeat until the function returns the same result as the previous one

```

Try it online!

### Modulus method (4 bytes)

```
→%9←

```

```
      # implicit parameter ⁰ (refers to the last parameter)
   ←  # previous number (n - 1)
 %9←  # modulus by 9
→%9←  # next number (n + 1)

```

Try it online!
> 4 votes

# Answer
## Java 7, 63 bytes

```
int f(int n){int s=0;for(;n>0;n/=10)s+=n%10;return s>9?f(s):s;}

```

Recursive function which just gets digits with mod/div. Nothing fancy.

## Cheap port

of Jonathan Allan's would be a measly 28 bytes:

```
int f(int n){return~-n%9+1;}

```
> 3 votes

# Answer
## Labyrinth, 8 bytes

```
?(_9%)!@

```

using the equation `(n-1)%9+1`:

* `?` reads the input as decimal and pushes it to the stack
* `(` decrements the top of the stack
* `_` pushes a zero onto the top of the stack
* `9` push the top of the stack popped times 10 the digit (in this case, 9)
* `%` pops y, pops x, pushes x%y
* `)` increments the top of the stack
* `!` pops the top of the stack and out puts it as a decimal string
* `@` terminates the program
> 3 votes

# Answer
## Hexagony, ~~19~~ 15 bytes

```
.?<9{(/>!@!/)%'

```

More Readable:

```
  . ? <
 9 { ( /
> ! @ ! /
 ) % ' .
  . . .

```

Try it online!

-3 bytes by taking a different approach, making the 0 edge case trivial.
-1 byte by fixing 0 edge case bug

Using the formula ((n-1) mod 9) + 1 like a lot of other solutions aswell.
> 3 votes

# Answer
# Japt `-h`, ~~6~~ 4 bytes

```
Æ=ìx

```

Try it

```
Æ=ìx     :Implicit input of integer U
Æ        :Map the range [0,U)
 =       :  Reassign to U
  ì      :  Convert to digit array
   x     :  Reduce by addition
         :Implicit output of last element

```
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
[SODg#

```

Try it online!

**Explanation**

```
[        # infinite loop
 S       # split into digits
  O      # sum digits
   Dg#   # if length == 1: break

```
> 2 votes

# Answer
## JavaScript (ES6), ~~41~~ 38 bytes

*Saved 3 bytes, thanks to Bassdrop Cumberwubwubwub*

Takes and returns a string.

```
f=s=>s[1]?f(''+eval([...s].join`+`)):s

```

### Test cases

```
f=s=>s[1]?f(''+eval([...s].join`+`)):s

console.log(f("1")); // -> 1
console.log(f("45")); // -> 9
console.log(f("341")); // -> 8
console.log(f("6801")); // -> 6
console.log(f("59613")); // -> 6
console.log(f("495106")); // -> 7
```
> 2 votes

# Answer
# Brachylog, 9 bytes

```
#0|@e+:0&

```

Try it online!

### Explanation

```
#0            Input = Output = a digit
  |           OR
   @e         Split the input into a list of digits
     +        Sum
      :0&     Call this predicate recursively

```

### Alternative approach, 11 bytes

```
:I:{@e+}i#0
```

This one uses the meta-predicate `i - Iterate` to call `I` times the predicate `{@e+}` on the input. This will try values of `I` from `0` to infinity until one makes it so that the output of `i` is a single digit which makes `#0` true.
> 2 votes

# Answer
## Ruby, 12 bytes

```
->n{~-n%9+1}

```
> 2 votes

# Answer
# CJam, ~~19~~ 13 bytes

```
r{:~:+_s\9>}g

```

Interpreter

Explanation:

```
r{:~:+_s\9>}g Code
r             Get token
 {:~:+_s\9>}  Block: :~:+_s\9>
   ~          Eval
  :           Map
     +        Add
    :         Map
      _       Duplicate
       s      Convert to string
        \     Swap
         9    9
          >   Greater than
            g Do while (pop)

```

Thanks to 8478 (Martin Ender) for -6 bytes.

---

# CJam, 6 bytes

```
ri(9%)

```

Suggested by 8478 (Martin Ender). Interpreter

I was thinking about it, but Martin just got it before me. Explanation:

```
ri(9%) Code
r      Get token
 i     Convert to integer
  (    Decrement
   9   9
    %  Modulo
     ) Increment

```
> 2 votes

# Answer
# Factor, 24

*Smart*, *mathy* answer.

```
[ neg bitnot 9 mod 1 + ]

```

**63** for dumb iterative solution:

```
[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]

```
> 2 votes

# Answer
# Pyth - ~~7~~ ~~4~~ ~~6~~ 7 bytes

Not the best one, but still beats a decent amount of answers:

```
|ejQ9 9

```

Like the previous version, but handling also cases of multiples of 9, using logical or.

---

**This version fails the 45 testcase**:

```
ejQ9

```

**Explanation:**

```
 jQ9  -> converting the input to base 9
e     -> taking the last digit

```

Try it here

Try the previous version here!

---

**Previous solutions:**

```
&Qh%tQ9

```

**Explanation**:

```
    tQ    -> tail: Q-1
   %tQ9   -> Modulo: (Q-1)%9
  h%tQ9   -> head: (Q-1)%9+1
&Qh%tQ9   -> Logical 'and' - takes the first null value. If Q is 0 - returns zero, otherwise returns the (Q-1)%9+1 expression result

```

You're invited to try it here!
> 2 votes

# Answer
# J, 8 bytes

```
**1+9|<:

```

Uses the formula `d(n) = ((n-1) mod 9) + 1` with the case `d(0) = 0`.

## Usage

```
   f =: **1+9|<:
   (,.f"0) 0 1 45 341 6801 59613 495106
     0 0
     1 1
    45 9
   341 8
  6801 6
 59613 6
495106 7

```

## Explanation

```
**1+9|<:  Input: integer n
      <:  Decrement n
    9|    Take it modulo 9
  1+      Add 1 to it
*         Sign(n) = 0 if n = 0, else 1
 *        Multiply and return

```
> 2 votes

# Answer
# APL (Dyalog), ~~15~~ 9 bytes bytes

```
××1+9|-∘1

```

Try it online!
> 2 votes

# Answer
## Python 2, 54 51 bytes

```
i=input()
while~-len(i):i=`sum(map(int,i))`
print i

```

Thanks to Oliver and Karl Napf for helping me save 3 bytes
> 1 votes

# Answer
# C, ~~64~~ 29 bytes

C port from Jonathan Allan's answer (with special case 0).

```
f(i){return i>0?~-i%9+1:0;}

```

Previous 64 byte code:

```
q(i){return i>9?i%10+q(i/10):i;}
f(i){i=q(i);return i>9?f(i):i;}

```

`q` takes the cross sum and `f` repeats taking the cross sum until a single digit.
> 1 votes

# Answer
# Python, 45 bytes

```
f=lambda x:x[1:]and f(`sum(map(int,x))`)or x

```

Takes the argument as a string.
> 1 votes

# Answer
# Retina, 15 bytes

```
.+
$*
1{9}\B

1

```

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

```
.+
$*

```

Convert input to unary.

```
(1{9})*\B

```

Take 1-based modulo by removing nines that have at least one more character after them.

```
1

```

Count the remaining number of 1s to convert back to decimal.
> 1 votes

# Answer
# Perl 6, 29 bytes

```
{($_,*.comb.sum...10>*)[*-1]}

```

# Expanded:

```
{ # bare block lambda with implicit parameter ｢$_｣
  ( # generate a sequence

    $_,         # starting with the input
    *.comb.sum  # Whatever lambda that splits into digits, and finds sum
    ...         # keep doing that
    10 > *      # until it is less than 10

  )[ * - 1 ] # get the last value
}

```
> 1 votes

# Answer
# braingolf, ~~20~~ 13 bytes

```
[Rdl1-M&+v>]R

```

Try it online!
Links to the braingolf JS interpreter in TIO

### Explanation

```
[Rdl1-M&+v>]R   Implicit input from command-line args to stack
[..........]R   Loop. Always runs once, will continue to run as long as the bottom value on the active stack is > 0
 R              Return to main stack, does nothing if already on main stack
  d             Pop top of stack, split into digits, push digits
   l            Push length of stack
    1-          Decrement top of stack
      M         Pop top of stack and push to next stack
       &+       Sum entire stack (all digits of input)
         v      Switch active stack to next stack
          >     Move top of stack to bottom

```

Decrementing the stack length, moving it to the second stack, and switching to the second stack before the end of the loop serves to use the decremented length as the loop counter. ie when the length is `1` (decremented to `0`) the loop terminates.
> 1 votes

# Answer
# Tcl, 57 bytes

```
while \$v>9 {set v [expr [join [split $v ""] +]]}
puts $v

```

Try it online!
> 1 votes

# Answer
# dc, 37 bytes

```
[[A~rdZ1<D]dsDx[+z1<S]dsSxdZ1<M]dsMxp

```

Try it online!

`[A~rdZ1<D]dsDx` decompose. Divide by 10 leaving quotient & remainder on stack until the value on the top of the stack is a single digit.

`[+z1<S]dsSx` sum. Add two topmost stack values until stack depth is one.

Macro `M` contains both of those, and `dZ1<M` to keep running itself until the final result is a single digit. `p` to print.
> 1 votes

# Answer
# JavaScript, 37 bytes

Input is taken as a string.

```
f=n=>n>9?f(eval([...n].join`+`)+""):n

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 69 bytes

```
: f begin 0 swap begin 10 /mod >r + r> ?dup 0= until dup 10 < until ;

```

Try it online!

### Explanation

1. Place sum (starting at 0) on stack
2. Get remainder of number divided by 10
3. Add to sum
4. Replace number with itself divided by 10
5. Repeat steps 2-4 until number equals 0
6. Using sum as new starting number, repeat steps 1-5 until result is less than 10

### Code Explanation

```
begin               \ start outer loop
  0 swap            \ place sum variable and move it down the stack
  begin             \ start inner loop
    10 /mod         \ get quotient and remainder of number/10
    >r +            \ temporarily "hide" quotient on return stack and add remainder to sum
    r> ?dup         \ retrieve quotient from return stack and duplicate if != 0
  0= until          \ end inner loop if sum is equal to 0
  dup 10 <          \ duplicate current "root" and check if less than 10
until               \ end outer loop if < 10

```
> 1 votes

# Answer
# K (oK), 9 bytes

**Solution:**

```
(+/.:'$)/

```

Try it online!

**Explanation:**

Super straightforward. Break number into digits and sum up - do this until the result converges:

```
(+/.:'$)/ / the solution
(      )/ / do this until result converges
      $   / string, 1234 => "1234"
   .:'    / value each, "1234" => 1 2 3 4
 +/       / sum over, 1 2 3 4 => 10

```
> 1 votes

# Answer
# Excel VBA, 69 bytes

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

```
n=[A1]:While n>9:s=0:For i=1To Len(n):s=s+Mid(n,i,1):Next:n=s:Wend:?n

```

### Test Function

```
For each x in Array(1,45,341,6801,59613,495106):[A1]=x:n=[A1]:While n>9:s=0:For i=1To Len(n):s=s+Mid(n,i,1):Next:n=s:Wend:?x"->"n:Next
 1 -> 1
 45 -> 9
 341 -> 8
 6801 -> 6
 59613 -> 6
 495106 -> 7

```
> 1 votes

# Answer
# QBasic 1.1, 66 bytes

```
INPUT N
WHILE N>9
M=N
N=0
WHILE M
N=N+M MOD 10
M=M\10
WEND
WEND
?N

```
> 1 votes

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

```
(+/10\)/

```

Try it online!

this is based on @streetster's oK answer but uses a feature specific to ngn/k: `10\x` is the list of digits of `x`
> 1 votes

# Answer
# Ohm v2, 5 bytes

```
ì‹9%›

```

Explanation:

```
ì‹9%›
ì     Takes input as integer
 ‹    Decrements
  9%  Modulus 9
    › Increment

```

Try it online!
> 1 votes

# Answer
# MBASIC, ~~105~~ 94 bytes

```
1 INPUT N
2 A$=STR$(N):N=0:FOR I=1 TO LEN(A$):N=N+VAL(MID$(A$,I,1)):NEXT:IF N>9 THEN 2
3 PRINT N

```

Output:

```
? 495106
 7

? 59613
 6

? 6801
 6

```

Explanation:

Convert input to a string, then walk the string, adding each digit to a total. If the resulting total has more than 1 digit, repeat the process. Otherwise, print the total.

Okay, so it's not APL. But it will run on an 8-bit CP/M system. :-)
> 1 votes

# Answer
## Keg, 6 bytes(SBCS on Keg wiki)

```
¿;9%1+

```

## Explanation:

```
¿#      Take implicit input
 ;9%1+# Digital Root Formula
# Implicit output

```
> 1 votes

# Answer
# TI-Basic, 11 bytes

```
1+9fPart((Ans-1)/9

```

Takes input in `Ans`.
> 1 votes

# Answer
# Vyxal, 3 bytes

```
⁽∑Ẋ

```

Try it Online!

```
⁽ Ẋ # Until the result converges...
 ∑  # Sum digits

```
> 1 votes

# Answer
# APL (Dyalog Classic), 3 bytes

```
9⊤⊢

```

Try it online!

Anonymous tacit prefix fork train.

```
 ⊤      ⍝ Tail of base conversion of
   ⊢    ⍝ right argument to
9       ⍝ base 9

```
> 1 votes

# Answer
# COBOL (GNU), 131 bytes

```
PROGRAM-ID.A.DATA DIVISION.
	WORKING-STORAGE SECTION.
	01 N PIC 9(9).
PROCEDURE DIVISION.ACCEPT N.COMPUTE N=FUNCTION REM(N- 1,9)+ 1

```

Try it online!

# Explanation :

```
PROGRAM-ID.A.DATA DIVISION.
       * The first line is necessary and can't be removed
        WORKING-STORAGE SECTION.
       * sadly so is this (accept input / output)
        01 N PIC 9(9).
       * This accepts input N that is upto 999,999,999 (output is via same)
        PROCEDURE DIVISION.
       * Time to start working on program itself.
        ACCEPT N.
       * Accepts the input from stdin.
        COMPUTE N = FUNCTION REM(N - 1, 9) + 1
       * compute n such that it is mod of n - 1 and 9 and then add one (standard forumla of --N%9+1

```

Output is via display N.
> 1 votes

# Answer
# Charcoal, 9 bytes

```
⁺﹪⁻Ｎ¹¦⁹¦¹

```

**TryItOnline!**

### Explanation:

```
⁻Ｎ¹  - take a integer input and subtract one from it
﹪     - modulo function
⁺     - addition function which given to it n-1%9 and 1
⁹     - number 9 which is like 10-1
¦     - just a argument separator

```

PS: You could have reduced the argument separator by writing it in this order: `⁺¹﹪⁻¹Ｎ⁹` but 7 is not a cool length to have, Also you could put a  before the whole thing to cast the result to printable integer value but since the numbers are represented as `-` characters in charcoal i ignored that.
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
ΔSO

```

Try it online or verify all test cases.

Or a minor alternative:

```
Δ1ö

```

Try it online or verify all test cases.

**Explanation:**

```
Δ    # Loop until the result no longer changes,
     # using the (implicit) input-integer in the first iteration
 S   #  Convert it to a list of digits
  O  #  Sum those together
     # (after which the resulting digit is output implicitly)

Δ    # Loop until the result no longer changes,
     # using the (implicit) input-integer in the first iteration
 1ö  #  Convert it from base-10 to base-1
     #  (which is a non-vectorizing way to sum an integer's digits in 05AB1E)
     # (after which the resulting digit is output implicitly)

```
> 1 votes

# Answer
# Vyxal, 4 bytes

```
‹9%›

```

Try it Online!
> 1 votes

# Answer
# Go, 75 bytes

```
func f(n int)int{if n<10{return n}
k:=0
for;n>0;n/=10{k+=n%10}
return f(k)}

```

Attempt This Online!

# Go, Modulus solution, 29 bytes

```
func(n int)int{return^-n%9+1}

```

Attempt This Online!
> 1 votes

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

```
}%9{

```

Try it online!

```
}%9{
   {  # decrement with implicit input
 %9   # mod 9
}     # increment

```
> 1 votes

# Answer
# \>\<\> (Fish), 36 bytes

```
>0$:1(?v:&a%+&a,:1%-20.
^v?(a:~<
n<;

```

Try it online! \- Interactive Version

Expects input as a number pushed onto the stack in advance.

## Explanation

There are 2 basic loops, one for summing the digits and one for checking if the number is less than 10 yet.

```
   :1(?v

```

Checks if the number is less than 1, if not all the digits are summed.

```
        :&a%+&a,:1%

```

Add the modulo to the accumulator, and then push the division again. We subtract the number %1 to make it a integer.

```
                   20.

```

Skip the first 3 letters of the bottom row.

```
^v?(a:~<
n<;

```

If the number is less than 10 (a is 10 in fish, it uses hexadecimal), print it and exit. Otherwise, go back to the start of the program with the number pushed to the stack.

```
>0$

```

Push the accumulator to the second from first spot on the stack.
> 1 votes

# Answer
# Perl ~~34~~ 28 bytes

Includes +1 for -p

```
s/./+$&/g,$_=eval while/../

```

Uses the method described in the question.

**Example:**

```
$ echo -n 495106 | perl -p DigitalRoot.pl
7

```
> 0 votes

# Answer
# Groovy, 57 Bytes

```
{n->for(;(n=(""+n).collect{(int)it-48}.sum())/10>1;){};n}

```

Repeatedly converts to string, sums the ascii conversion of the digits and continues while the resultant integer divided by 10 is greater than 1. Then it returns the mutated input.

Tried recursion too, cost more bytes though:

```
x={i->i?i%10+x(i.intdiv(10)):0};y={i->x(i)/10<1?x(i):y(x(i))}

```
> 0 votes

# Answer
# C#, 79 Bytes

Golfed:

```
string R(string i){while(i.Length>1){i=i.Sum(o=>int.Parse(o+""))+"";}return i;}

```

Ungolfed:

```
string R(string i)
{
  while (i.Length > 1)
  {
    i = i.Sum(o => int.Parse(o + ""))+"";
  }

  return i;
}

```

Testing:

```
var printTheDigitalRoot = new PrintTheDigitalRoot();
Console.WriteLine(printTheDigitalRoot.S("1")); //1
Console.WriteLine(printTheDigitalRoot.S("45")); //9
Console.WriteLine(printTheDigitalRoot.S("341")); //8
Console.WriteLine(printTheDigitalRoot.S("6801")); //6
Console.WriteLine(printTheDigitalRoot.S("59613")); //6
Console.WriteLine(printTheDigitalRoot.S("495106")); //7

```
> 0 votes

# Answer
# Element, 32 bytes

```
_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`

```

Try it online!

This is using the typical closed-form formula, although it is noticeably more painful since Element lacks any rounding functionality.

```
_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
_2:                               make two copies of input
   1-+9/                          for one copy, subtract 1 and divide by 9
        3:0<!{1-+2:0<!}1+-+       floor it
                           9-*    multiply by -9
                              +`  add to the original input value, then output

```
> 0 votes

# Answer
## Racket 152 bytes

```
(let p((ol'())(n n))(let*-values(((q r)(quotient/remainder n 10))((l)(cons r ol)))
(if(= q 0)(begin(let((s(apply + l)))(if(< s 10)s(p'()s))))(p l q)))))

```

Ungolfed:

```
(define (f n)
  (let loop ((ol '())
             (n n))
    (let*-values (((q r) (quotient/remainder n 10))
                 ((l) (cons r ol)))
      (if (= q 0)
          (begin
            (let ((s (apply + l)))
              (if (< s 10)
                  s
                  (loop '() s))))
          (loop l q))
      )))

```

Simpler version:

```
(define (f1 N)
  (define (getDigitList n)                   ; sub-fn  to get digits
    (let loop ((ol '())
               (n n))
      (let-values (((q r) (quotient/remainder n 10)))
        (if (= q 0) (cons r ol)
            (loop (cons r ol) q)))))

    (let loop2 ((n N))                       ; actual fn
      (define s (apply + (getDigitList n)))  ; get sum of digits
      (if (< s 10)
          s
          (loop2 s))))

```

Testing:

```
(f 1)
(f 45)
(f 341)
(f 6801)
(f 59613)
(f 495106)

```

Output:

```
1
9
8
6
6
7

```
> 0 votes

# Answer
# Thunno 2 `t`, 2 bytes

```
9B

```

Attempt This Online!

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
9B  # Implicit input
 B  # Convert the input to a
9   # list of digits in base 9
    # Implicit output of last item

```
> 0 votes

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


# Question
Title: Positioning a fake mirror for best effect
# Challenge

## Premise

Consider a mosaic of \\$m\times n\\$ tiles, in \\$k\\$ unique colours designated by integers. Example (\\$3\times6\\$, four colours):

```
4 1 3 2 4 2
1 2 4 2 1 3
4 3 2 1 4 4

```

My poor man's mirror is a pane of glass of width \\$\sqrt{2}\cdot\min(m,n)\\$. I stand it diagonally on the mosaic, like so:

```
4 1 3 M 4 2
1 2 M 2 1 3
4 M 2 1 4 4

```

For this example I can pretend it reflects exactly two full tiles:

```
x 1 x M x x
x 2 M x x x
x M 2 1 x x

```

No matter what diagonal I choose, this is the **greatest number** of full tiles I can fake-reflect. Yay.

## Task

Input: an integer matrix of \\$m\\$ rows and \\$n\\$ columns where \\$2\leq m\leq1000,2\leq n\leq1000\\$. The number of unique values is \\$k\\$ where \\$3\leq k\ll mn\\$.

Output: three integers, in any format. The first and second respectively represent the row coordinate and column coordinate of the matrix element ('mosaic tile') at the **left** end of the 45-degree diagonal where the fake mirror should be placed for 'best effect', effectiveness being defined as shown above. The third integer is 0 or 1, respectively meaning a rising (bottom left to top right) or falling (top left to bottom right) diagonal.

For clarity's sake, here are some simple test cases.

### Example 1

Input:

```
4 1 3 2 4 2
1 2 4 2 1 3
4 3 2 1 4 4

```

Output: `3 2 0`

### Example 2

Input:

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

```

Output: `4 1 1` or `5 1 0` (not both)

As you can see, **a unique solution isn't guaranteed**.

### Example 3

Input:

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

```

Output: `1 10 1`

## Edit - indexing

The example outputs are 1-indexed, but **0-indexing is allowed**.

# Remarks

# Answer
> 3 votes
# Charcoal, 91 bytes

```
≔⟦⟧θＷＳ⊞θＩ⪪ι ≔Ｌ§θ⁰η≔⊖⌊⟦Ｌθη⟧ζＦ⁻ＬθζＦ⁻ηζＦ²⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧Ｉ✂⌈υ¹

```

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

```
≔⟦⟧θＷＳ⊞θＩ⪪ι

```

Input the mosaic. (These 12 bytes could be avoided by requiring the input to be in JSON format, but I was too lazy to punctuate the example.)

```
≔Ｌ§θ⁰η

```

Get the width of the mosaic.

```
≔⊖⌊⟦Ｌθη⟧ζ

```

Get the inner size of the mirror, i.e. the distance from the first to the last character of the mirror in terms of diagonal steps.

```
Ｆ⁻Ｌθζ

```

Loop over the possible row(s) of the top left corner of the mirror's enclosing square.

```
Ｆ⁻ηζ

```

Loop over the possible column(s) of the top left corner of the mirror's square.

```
Ｆ²

```

Loop over the possible rotations of the mirror.

```
⊞υ⟦Σ⭆⊕ζ⭆⊕ζ⁼§§θ⁺ι⎇λμ⁻ζμ⁺κξ§§θ⁺ι⎇λξ⁻ζξ⁺κμ⎇λι⁺ιζκλ⟧

```

Calculate the number of tiles it reflects exactly. Exact matches are counted twice and the diagonal is also counted but this doesn't affect the relative score. Push this number along with the potential solution to the predefined empty list.

```
Ｉ✂⌈υ¹

```

Output the solution with the highest number of exactly reflected tiles.

# Answer
> 0 votes
# Python3, 557 bytes:

```
E=enumerate
V=lambda x,y,n,m:0<=x<n and 0<=y<m
U=lambda j,k,J,K,b,n,m:b[j][k]==b[J][K]if V(j,k,n,m)and V(J,K,n,m)else 0
def f(b):
 n,m=len(b),len(b[0])
 q,r=[i for x,u in E(b)for y,_ in E(u)for i in[(x,y,0,0,x,y)]*(x+1>=min(n,m)and y+min(n,m)<=m)+[(x,y,1,0,x,y)]*(x+1>=min(n,m)and y+1>=min(n,m))],[]
 while q:
  x,y,d,c,X,Y=q.pop(0)
  if abs(X-x)+1==min(n,m):r+=[(*[[x,y],[X,Y]][d],d,c)];continue
  q+=[(x,y,d,c+U(*[[X+1,Y+1,X-1,Y-1],[X+1,Y-1,X-1,Y+1]][d],b,n,m)+U(*[[X,Y+1,X-1,Y],[X,Y-1,X+1,Y]][d],b,n,m),X-1,Y+[1,-1][d])]
 return max(r,key=lambda x:x[-1])

```

Try it online!

---
Tags: code-golf, matrix
---


# Question
Title: Alphabet to Number and Number to Alphabet
# Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 \<=\> A, 2 \<=\> B) etc.

```
1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26

```

# Rules

* This is , so shortest code in bytes wins.
* The input will only consist of either an uppercase letter from `A` to `Z` or an integer from `1` to `26` inclusive.
* Trailing whitespaces (space and newline) are allowed.

# Answer
> 7 votes
## Actually, 7 bytes

```
ú' +ûEí

```

Try it online!

Explanation:

```
ú' +ûEí
ú' +     lowercase English alphabet, prepend space
    û    uppercase
     E   element (pushes the nth letter if input is an integer, leaves stack alone otherwise)
      í  index (pushes index of input if input is a string, leaves stack alone otherwise)

```

If lowercase is acceptable, this is 6 bytes:

```
ú' +Eí

```

Try it online!

# Answer
> 11 votes
# Pure Bash, 51

Most of the rest of the answers use some sort of conditional. This one dispenses with conditionals entirely, and instead treats the input as a base-36 number which indexes into an appropriately constructed bash-brace-expansion array:

```
a=(_ {A..I} {1..26} {J..Z} {A..Z})
echo ${a[36#$1]}

```

Ideone.

# Answer
> 9 votes
# Erlang, 26 bytes

```
f([X])->X-64;f(X)->[X+64].

```

One of the few times where Erlang's string behavior is useful.

# Answer
> 7 votes
# Python 2, 38 bytes

```
lambda x:x>''and 64^ord(x)or chr(64^x)

```

Test it on Ideone.

# Answer
> 7 votes
# Python 3, 43 bytes

```
lambda x:x!=str(x)and chr(64|x)or ord(x)^64

```

The interesting thing about this solution is that it incorporates all the senses of OR, bitwise OR `|`, logical OR `or`, bitwise XOR `^` and logical XOR `!=` ...

# Answer
> 6 votes
# 2sable, ~~9~~ 8 bytes

Code:

```
.bAu¹kr,

```

Explanation:

```
.b        # Convert 1 -> A, 2 -> B, etc.
  A       # Push the alphabet.
   u      # Convert it to uppercase.
    ¹k    # Find the index of the letter in the alphabet.
      r   # Reverse the stack.
       ,  # Pop and print with a newline.

```

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

# Answer
> 6 votes
# Ruby, ~~47 39 + `n` flag = 40 bytes~~ ~~33~~ ~~34~~ 31 bytes

Anonymous function. Uses an exception handling trick like in @KarlNapf's Python solution.

-3 bytes from @manatwork

Try it online

```
->i{(64+i).chr rescue i.ord-64}

```

Original full program version with the `n` flag for 40 bytes and reads from STDIN:

```
puts$_!~/\d/?$_.ord-64:(64+$_.to_i).chr

```

# Answer
> 5 votes
# Cheddar, ~~34~~ 32 bytes

*Saved 2 bytes thanks to @LeakyNun*

```
n->"%s"%n==n?n.ord()-64:@"(n+64)

```

I wish there was shorter way to check if string or number.

Try it online! or Test Suite

## Explanation

```
n ->                // func with arg `n`
    "%s"%n==n ?     // if n is string... (see below)
       n.ord() - 64  // return code point - 64
    :               // else...
    @"(n+64)         // chr(n+64)

```

`"%s"%n==n` checks if it is a string in a simple way. `"%s"` is a string format, I can format with `%` e.g. `"a %s c" % "b"` is equal to `"a b c"`. `%s` specifies it is a string, if a digit is passed it'll remain as `%s`.

# Answer
> 5 votes
# Mathematica ~~54~~ 41 Bytes

With an absolutely clever suggestion from LegionMammal978 that saves 13 bytes.

```
If[#>0,FromLetterNumber,,LetterNumber]@#&

```

`If[#>0,FromLetterNumber,,LetterNumber]` serves the sole purpose of deciding whether to apply `FromLetterNumber` or `LetterNumber` to the input.

`#>0` will be satisfied if the input, `#`, is a number, in which case `FromLetterNumber`will be selected.

However `#>0` will be neither true nor false if `#` is a letter, and `LetterNumber` will be selected instead.

---

```
If[#>0,FromLetterNumber,,LetterNumber]@#&["d"]

```

4

---

```
If[#>0,FromLetterNumber,,LetterNumber]@#&[4]

```

d

---

In Mathematica, `FromLetterNumber` and `LetterNumber` will also work with other alphabets. This requires only a few more bytes.

```
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Greek"]
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Russian"]
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Romanian"]

```

δ
г
b

```
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[δ, "Greek"]
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[г, "Russian"]
If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[b, "Romanian"]

```

4
4
4

# Answer
> 4 votes
## Haskell, 54 bytes

```
f s|s<"A"=[['@'..]!!read s]|1<2=show$fromEnum(s!!0)-64

```

Usage example: `map f ["1","26","A","Z"]` -\> `["A","Z","1","26"]`.

Haskell's strict type system is a real pain here. Additionally all the short char \<-\> int functions like `chr` and `ord` need an import, so I have to do it by hand. For the letter -\> int case, for example I need to convert `String` -\> `Char` (via `!!0`) -\> `Integer` (via `fromEnum`) -\> `String` (via `show`).

# Answer
> 4 votes
# C, 55 bytes

```
i;f(char*s){i=atol(s);printf(i?"%c":"%d",64^(i?i:*s));}

```

# Answer
> 4 votes
# Perl 6, 25 bytes

```
{+$_??chr $_+64!!.ord-64}

```

## Explanation:

```
# bare block lambda with implicit parameter of ｢$_｣
{
    +$_         # is the input numeric
  ??
    chr $_ + 64 # if it is add 64 and get the character
  !!
    $_.ord - 64 # otherwise get the ordinal and subtract 64
}

```

## Example:

```
say ('A'..'Z').map: {+$_??chr $_+64!!.ord-64}
# (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26)

say (1..26).map: {+$_??chr $_+64!!.ord-64}
# (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

```

# Answer
> 3 votes
# C#, 32 bytes

```
n=>(n^=64)>26?(object)(char)n:n;

```

Casts to `Func<int, object>`.

Input: `char` implicitely converts to `int` so can be called with `int` (1-26) or `char` ('A'-Z').

Output: Either a `char` or `int`.

# Answer
> 3 votes
## PHP, 49 41 40 bytes

```
<?=+($i=$argv[1])?chr($i+64):ord($i)-64;

```

I do not think there is a good alternative to `is_numeric` right?

This is executed from command line (`$argv[1]` is the first variable given)

## Thanks to:

@insertusernamehere: Golfed 8 bytes. Replacing `is_numeric($i=$argv[1])` with `0<($i=$argv[1])`.This works because `(int)"randomLetter" == 0`.

@manatwork: Reduced with 1 byte. Replace `0<` with `+`. What happens in this case is that the + signal will cast the "Z" (or whatever letter) to an 0. This will result in false. Therefor any letter is always false and a number is always true.

# Answer
> 3 votes
# Excel, 33 bytes

```
=IFERROR(CHAR(A1+64),CODE(A1)-64)

```

# Answer
> 2 votes
# Python 2, 61 bytes

```
i=raw_input()
try:o=chr(int(i)+64)
except:o=ord(i)-64
print o

```

Yes I could switch to Python 3 for `input`

# Answer
> 2 votes
# Java, ~~104~~ ~~98~~ ~~97~~ ~~83~~ ~~54~~ ~~53~~ ~~51~~ ~~50~~ 30 bytes

`x->(x^=64)>64?(char)x+"":x+"";`

**Test Program**:

```
IntFunction<String> f = x -> (x ^= 64) > 64 ? (char) x + "" : x + "";
out.println(f.apply('A')); // 1
out.println(f.apply('Z')); // 26
out.println((f.apply(1))); // A
out.println((f.apply(26))); //Z

```

# Answer
> 2 votes
## Befunge 93, 144 90 66 54 36 19 bytes

Not 100% sure if this is allowed, but if you are allowed to type A as 65, B as 66, etc., then (for \[my\] convenience's sake):

```
&:"@"`"@"\#. #-_+,@

```

Otherwise, at 36 bytes:

```
~:0\"A"-`#v_88*-.@
**~28*++,@>68*-52

```

(Thanks to tngreene for the suggestions!)

```
~:0\567+*-`#v_88*-.>$28*+,@
52**\28*++,@>~:0`!#^_\68*-

```

(Thanks to Sp3000 for saving 12 bytes by rearranging!)

```
~:0\567+*-`#v_88*-.>$82*+,@
            >~:0`!#^_\68*-52**\28*++,@

v                   >$28*+,@
             >~:0`!#^_\68*-52**\28*++,@
>~:0\567+*-`#^_88*-.@

v                    >$28*+,@
~           >11g~:0`!|
1                    >\68*-52**\28*++,@
1
p
>011g567+*-`|
            >11g88*-.@

```

Ungolfed:

```
v                       >$ 28* + , @
                 >~:0 `!|
                        >\ 68* - 52* * \ 28* + + , @
>~:0\ 5 67+ * - `|
                 >88* - . @

```

This is my first working Befunge program ever, and I feel the need to golf this further. Any help would be greatly appreciated.

You can test Befunge code here.

# Answer
> 2 votes
## PowerShell v2+, 42 bytes

```
param($n)([char](64+$n),(+$n-64))[$n-ge65]

```

Takes input `$n` (as an integer or an explicit char) and uses a pseudo-ternary to choose between two elements of an array. The conditional is `$n-ge65` (i.e., is the input ASCII `A` or greater). If so, we simply cast the input as an int and subtract `64`. Otherwise, we add `64` to the input integer, and cast it as a `[char]`. In either case, the result is left on the pipeline and printing is implicit.

## Examples

```
PS C:\Tools\Scripts\golfing> ([char[]](65..90)|%{.\alphabet-to-number.ps1 $_})-join','
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26

PS C:\Tools\Scripts\golfing> (1..26|%{.\alphabet-to-number.ps1 $_})-join','
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z

```

# Answer
> 2 votes
# Befunge-98\*, 19 bytes

```
&:39*\`'@\j;+,@;-.@

```

Because the question said you'll receive a `1-26` or an `A-Z` I assumed this meant the number 26 or the character A-Z. Most interprets struggle with entering alt-codes, so it is easier to use `&` and enter values like 26 for 26 or 90 for 'Z', as opposed to `~`.

## Pseudo-code

```
int c = get stdin
push the value of 27
bool is_number =  27 > c
push the value of `@` (64)
if is_number == 1
   jump to adding 64 to c //putting it the ASCII range
   print as ASCII
   end
else
   jump to subtracting 64 from c //putting it in the numerical range
   print as number
   end

```

Test it out (on Windows) here!

\*This is technically Unefunge-98 because it only uses 1 dimension, but that name might be unfamiliar.

# Answer
> 2 votes
# Brainfuck, 445 Characters

More a proof of concept than a golfed code. Requires Unsigned, Non-wrapping Brainfuck.

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

```

With Comments

```
,[>+>+<<-] Firstly Duplicate it across two buffers
>[<+>-] Move the second buffer back to the first buffer
>>++[->++++++<]>[-<<<+++++>>>] Establish 60 in the second buffer
<<<<
Compare Buffers 1 and 2
[->-<]
>
[ If there's still data in buffer 2
, Write the value in the units column to buffer two
<
++++
[->------------<] Subtract 12 from the units buffer
++++
[->>------------<<] Subtract 12 from the tens buffer
[-<<++++++++++>>] Multiply buffer three by ten into buffer 1
>
[-<+>] Add the units
>
[-<<++++++++++>>] Add the tens
>++ Add 65 to the buffer
[->++++++<]>+
[-<+++++>]
<- Actually we need 64 because A is 1
[-<<<+>>>] Add 64 to the first buffer
<<<
. Print the new letter
> Move to blank buffer
]
>
[ Otherwise we're a letter
[-<+<+>>] Copy it back over the first two buffers
>++ Write 64 to the buffer
[->++++++<]>+
[-<+++++>]
<-
[-<<->>] Subtract 64 from the letter
<<[->+>+<<]
>>>++++++++++< Copy pasted Division step x = current buffer y = 10 rest of the buffers are conveniently blank

+
[>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<<
-
[->+>+<<]
>[-<++++++++++>]
<[-<->]
++++
[-<++++++++++++>]
++++
[->>++++++++++++<<]
>>.<<<.>
]

```

# Answer
> 2 votes
# Japt, ~~11~~ 10 bytes

```
¤?UdI:InUc

```

Try it

```
¤?UdI:InUc     :Implicit input of integer or string U
¤              :Convert to binary string if integer (always truthy)
¤              :Slice off first 2 character if string (always falsey)
 ?             :If truthy
  Ud           :  Get character at codepoint U
    I          :  After first adding 64
     :         :Else
      In       :  Subtract 64 from
        Uc     :  Codepoint of U

```

# Answer
> 2 votes
# Forth (gforth), 67 bytes

```
: f 2dup s>number? if d>s 64 + emit else 2drop d>s c@ 64 - . then ;

```

Try it online!

Input is passed as a string to the function

### Code Explanation

```
: f             \ start a new word definition
  2dup          \ make a copy of the input string
  s>number?     \ attempt to convert to a number in base 10
  if            \ check if successful
    d>s         \ drop a number (don't need double-precision)
    64 + emit   \ add to 64 and output the ascii letter at that value
  else          \ if not successful (input was a letter)
    2drop d>s   \ get rid of garbage number conversion result and string-length
    c@ 64 - .   \ get ascii value of char, subtract 64 and output
  then          \ end the if block
;               \ end the word definition

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
i@ịe?ØA

```

Try it online!

## How it works

```
i@ịe?ØA - Main link. Takes an input A on the left
     ØA - Set the right argument to "ABC...XYZ"
    ?   - If statement:
   e    -   Condition: left in right; is A in the alphabet?
i@      -   If so: return the 1-index of A in the alphabet
  ị     -   Else: yield the A'th element of the alphabet

```

# Answer
> 2 votes
# \>\<\> (Fish), ~~27~~ ~~24~~ ~~21~~ 19 bytes

```
<o+v?)0-}:"@":
n-$<

```

Try it with a number test case

Try it with a letter test case

Takes input on the stack, which is a default input method for stack-based languages, and outputs with error.

# Answer
> 2 votes
# q, 29 bytes

```
{@[1+.Q.A?;x;{.Q.A y-1}[;x]]}

```

Find the index at which our letter occurs in the built-in list of uppercase letters

If it errors, index into the same list with the input instead

Adding and taking away ones as q indexing starts at 0, not 1

# Answer
> 1 votes
# Fourier, 30 bytes

```
I~F<64{1}{F+64a}F>64{1}{F-64o}

```

**Try it online!**

# Answer
> 1 votes
# Python 3, ~~49 48 53~~ 50 bytes

Somehow I got the byte count wrong ;\_; thanks dahuglenny

`isalpha` is shorter than `isnumeric`

```
lambda x:x.isalpha()and ord(x)-64or chr(int(x)+64)

```

takes input as string, which could be a letter or number

# Answer
> 1 votes
## JavaScript (ES6), 49 bytes

```
s=>s>0?String.fromCharCode(s|64):parseInt(s,36)-9

```

Accepts integers in either number or string format, always return integers as a number. 42 bytes if I can return lower case and don't need to handle integers in string format:

```
s=>s>0?(s+9).toString(36):parseInt(s,36)-9

```

# Answer
> 1 votes
## R, 73 bytes

```
f=function(x){L=LETTERS;if(is.numeric(x)){i=L[(x)]}else{i=which(L==x)};i}

```

# Answer
> 1 votes
## Javascript ~~86~~ ~~77~~ ~~66~~ 60 bytes

```
i=>typeof i<'s'?String.fromCharCode(i+64):i.charCodeAt(0)-64

```
* *saved 7 bytes after comments about using arrow functions*
* *saved another 11 bytes by removing return / brackets as noted by @manatwork*
* *saved another 6 bytes thanks to @manatwork*

# Answer
> 1 votes
# MATL, 10 bytes

```
6WZ~t42>?c

```

Explanation:

```
6W              % 2**6 = 64, but golfier looking
  Z~            % bit-wise XOR with input
    t42>?       % if result is greater than 42
         c      % convert it to a character
                % else, don't

```

Try it online! with numeric inputs.
Try it online! with alphabetic inputs.

# Answer
> 1 votes
**ASM: 10 bytes**

```
3C 40 77 04 2C 40 EB 02 04 40

```

Explanation: This is the assembled representation of a program that does exactly what is asked. It is not fully functional, because it needs some directives, but if it is added to the code segment of an assembly program it should work. It receives the input in the AL register, and if its a letter it subtracts 40h from the ASCII code value, leaving just the number(i.e B=42h, 42h-40h=2h). If the input is a number it does the opposite procedure by adding 40h. It leaves the result in the AL register. Below is the assembly source code

```
cmp al,40h
ja letter_to_number
sub al,40h
jmp continue
letter_to_number: add ax,40h
continue:

```

Also, if you convert all the other answers to machine code, I am positive that mine would be the smallest.

# Answer
> 1 votes
## Java, 61 bytes

```
int f(char c){return c^64;}char f(int i){return(char)(i^64);}

```

Ungolf'd:

```
int f(char c) {
    return c^64;
}

char f(int i) {
    return (char) (i^64);
}

```

Calling `f('A')` invokes the first function, retuning an `int` 1; calling `f(1)` invokes the second function, returning the `char` "A".

# Answer
> 1 votes
# Brachylog, 10 bytes

```
;.L∧Ṇi₁pL∧

```

Try it online!

The core of this is only 4 bytes, but the I/O for that version is a bit less than sane.

# Answer
> 1 votes
# 05AB1E (legacy), 9 bytes

```
di.bëÇ64-

```

Try it online or verify all test cases.

Also works in the new version of 05AB1E instead of the legacy, but the `Ç` wraps in a list: Try it online or verify all test cases.

**Explanation:**

```
di      # Legacy 05AB1E version: If the (implicit) input is an integer:
        # New 05AB1E version: If the (implicit) input is a positive (>= 0) integer:
  .b    #  Builtin to convert the integer to its 1-based uppercase alphabetic letter
 ë      # Else:
  Ç     #  Get the codepoint of the uppercase letter
   64-  #  And subtract 64 to convert it to its 1-based index
        # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Vyxal, ~~12~~ 4 bytes

```
øAɾt

```

Try it Online!

* -8 thanks to @lyxal

#### Explanation

Of course there's a built-in

```
øAɾt # Implicit input
øA   # Letter to number or number to letter
  ɾ  # Range or uppercase (overloaded)
   t # Last item

```

Old:

```
‹kA:?c[?ḟ›|i  # Implicit input
‹             # Decrement (no effect on strings)
 kA:          # Push uppercase alphabet and duplicate
    ?c        # Is the input alphabetic?
      [       # If it is:
       ?ḟ     #  Find the 0-based index of the input in the alphabet
         ›    #  And increment it to make it 1-based
          |   # Otherwise:
           i  #  Index input-1 into the alphabet

```

# Answer
> 1 votes
# Lua, ~~76~~ ~~53~~ 50 bytes

```
x=...y=x:byte()print(64<y and y-64or x.char(x+64))

```

Try it online!

# Explanation

```
x=... -- unpack command line arguments into x
y=x:byte()
print(
64<y -- if the first byte of the string > 64:
and y-64 -- print the first byte-64
or x.char(x+64) -- else, print chr(x+64)
)

```

# Answer
> 1 votes
# Julia 1.0, 22 bytes

```
~a=a-'@'
~n::Int=n+'@'

```

Try it online!

This solution involves a single function with 2 methods.

# Answer
> 0 votes
# R, 75 bytes

```
f=function(l,a=which(LETTERS==l))ifelse(length(a),a,LETTERS[as.numeric(l)])

```

This function technically has two inputs. But the second one is merely there because by setting `a` through a default, I can get rid of 2 bytes. Give the function a quoted letter or number, or just a number, and it will return the opposite.

Explanation: `a` tests if it is a letter and which one it is. If it isn't it pulls the relevant letter.

# Answer
> 0 votes
# Python 2, ~~45~~ 44 bytes

Code:

```
lambda x:chr(x+64)if`x`[0]>"("else ord(x)-64

```

# Answer
> 0 votes
# Pyth, 13 bytes

```
.xC+64sQhxr1G

```

Test suite.

# Answer
> 0 votes
# Gema, 53 characters

```
<K>=@sub{@char-int{$0};64}
<D>=@int-char{@add{$0;64}}

```

Sample run:

```
bash-4.3$ gema '<K>=@sub{@char-int{$0};64};<D>=@int-char{@add{$0;64}}' <<< 'M'
13

bash-4.3$ gema '<K>=@sub{@char-int{$0};64};<D>=@int-char{@add{$0;64}}' <<< '13'
M

```

# Answer
> 0 votes
# R, 62 Bytes

```
f=function(x)ifelse(is.finite(x),LETTERS[x],which(LETTERS==x))

```

Takes the input *x* and checks if it is finite, which is one byte shorter than checking if it is numeric and equivalent in this case. If yes, output the letter, if no, output the position in the alphabet equal to the character input.

# Answer
> 0 votes
# Dyalog APL, 14 bytes

```
{0::⎕A⍳⍵
⍵⊃⎕A}

```

`0::` if any error happens:
`⎕A⍳⍵` return the index of the argument in the alphabet

`⍵⊃⎕A` use the argument to pick an element from the alphabet (errors if the argument is character)

TryAPL online!

# Answer
> 0 votes
# SQF, 72 bytes

Using the function-as-a-file format:

```
i=_this;if((str i)==i)then{toString[i+64]}else{((toArray i)select 0)-64}

```

Call as: `ARG call NAME_OF_COMPILED_FUNCTION`

# Answer
> 0 votes
# q, 44 bytes

Reads from `stdin`

```
{$[0N~i:"J"$x;1+.Q.A?x 0;.Q.A i-1]}[read0 0]

```

# Answer
> 0 votes
# JavaScript, 41 bytes

```
x=>-x?(9+x).toString(36):parseInt(x,36)-9

```

# Answer
> 0 votes
## Racket 58 bytes

```
(if(char? i)(-(char->integer i)64)(integer->char(+ 64 i)))

```

Ungolfed:

```
(define (f i)
  (if (char? i)
      (-(char->integer i) 64)
      (integer->char (+ 64 i))))

```

Testing:

```
(f 1)
(f 3)
(f #\A)
(f #\D)

```

Output:

```
#\A
#\C
1
4

```

# Answer
> 0 votes
# DASH, 33 bytes

```
@[="num"type#0?fc +64#0?-(tc#0)64

```

Woo-hoo, first PPCG answer in my new functional programming language!

Installation and other info is all on the Github.

# Usage

```
(@[="num"type#0?fc +64#0?-(tc#0)64])"A"  #. strings
(@[="num"type#0?fc +64#0?-(tc#0)64])26   #. numbers

```

# Explanation

```
@                      #. lambda
  [                    #. start of conditional block
    = "num" (type #0)  #. check if argument is a number
      ? fc (+ 64 #0)   #. if so, add 64 to argument and convert from charcode
      ? - (tc #0) 64   #. otherwise, convert argument to charcode and subtract 64
                       #. we can actually leave off the closing bracket for now

```

# Answer
> 0 votes
# tcl, 68

Not a champion by any measure, but I had to do it.

```
puts [expr {[string is di $a]?[format %c [incr a 64]]:[scan $a %c]}]

```

demo

# Answer
> 0 votes
# q/kdb+, ~~28~~ 26 bytes

**Solution:**

```
{((?;@) -7=(@)x)[`,.Q.A]x}

```

**Examples:**

```
q){((?;@) -7=(@)x)[`,.Q.A]x}1
"A"
q){((?;@) -7=(@)x)[`,.Q.A]x}2
"B"
q){((?;@) -7=(@)x)[`,.Q.A]x}26
"Z"
q){((?;@) -7=(@)x)[`,.Q.A]x}"A"
1
q){((?;@) -7=(@)x)[`,.Q.A]x}"B"
2
q){((?;@) -7=(@)x)[`,.Q.A]x}"Z"
26

```

**Explanation:**

Check the type of the input, if it's a `long` (-7h) then use the apply `@` operator to index into the alphabet `.Q.A`, otherwise use `?` to lookup the input in the alphabet. Note that we add null to the start of the alphabet to fake the 1-indexing:

```
{((?;@) -7h=type x)[`,.Q.A;x]} / ungolfed solution
{                            } / lambda function
                   [      ; ]  / apply a function to this
                    `,.Q.A     / join ` (null) to the string "ABC...XYZ"
                           x   / implicit input (e.g. "A" or 13)
 (                )            / do all this together
        -7h=type x             / is the type of parameter x a long (-7)
  (?;@)                        / ? (lookup) if true, @ (index) if false

```

**Notes:**

* -2 bytes by using indexing instead of switch statement.

# Answer
> 0 votes
# C++ (gcc), 27 bytes

As unnamed generic lambda, accepting `char` or `int` and returning via reference parameter (input=output)

```
[](auto&r){r+=r<64?64:-64;}

```

Try it online!

# Answer
> 0 votes
# Commodore BASIC (C64/128/TheC64, VIC-20, PET) - 90 48 (tokenized) bytes

```
 0inputa$:ifval(a$)>0then?chr$(64+val(a$)):end
 1?asc(a$)-64

```

Explanation and screen shot later.

# Answer
> 0 votes
# MathGolf, 13 bytes

```
▄l!╧¿É$♦-É♦+$

```

Try it online.

**Explanation:**

```
 l         # Push the input as string
  !        # Convert it to lowercase
    ¿      # If
▄          #    the lowercase alphabet
   ╧       #                           contains this value:
     É     #  Execute the following three operations:
      $    #   Convert the (implicit) input to its unicode value
       ♦-  #   Subtract 64
           # (Implicit else:)
     É     #  Execute the following three operations:
      ♦+   #   Add 64
        $  #   And convert it to the character with this unicode value
           # (after which the entire stack joined together is output implicitly)

```

# Answer
> 0 votes
# Haskell, ~~63~~ 62 bytes

This uses the rule that wrapping the output in an optional type is allowed. We just use the standard `lookup` function to search in a list of tuples that define the input/output relationship.

```
(`lookup`zip(c++n)(n++c))
c=pure<$>['A'..'Z']
n=show<$>[1..26]

```

Try it online!

# Answer
> 0 votes
# Stax, 15 bytes

```
Ö└╝╨→ε/óo↕[▄╢▐W

```

Run and debug it

This unpacks to the following 18 bytes:

```
cc%!{64+z+}{E64-}?

```

Run and debug it

# Answer
> 0 votes
# Thunno 2, 1 byte

```
Ä

```

Attempt This Online!

Overloaded built-in that works on both numbers (`1 -> A`, `2 -> B`, ...) and letters (`A -> 1`, `B -> 2`, ...).

---
Tags: code-golf, string, number, alphabet
---