title: Is it a valid hidden word?

text:
# Question
Title: Is it a valid hidden word?
The Universal Crossword has a set of guidelines for crossword puzzle submissions.

In this challenge we are going to be concerned with their rules for hidden word themes. A hidden word clue consists of a clue and a word. It can either be a "word break" or a "bookend".

For a word break the word must not appear as a contiguous substring of the clue, but if all the spaces are removed from the clue, then it is a contiguous substring with a non-empty prefix and suffix. Some examples:

* `POOR HOUSE`, `RHO`: is valid. Solution: `POO***R HO***USE`
* `IMPROPER USE`, `PERUSE`: is not valid. It appears separated by a space: `IMPRO***PER USE***`, but the suffix is empty.
* `SINGLE TRACK`, `SINGLET`: is not valid. It appears separated by a space: `***SINGLE T***RACK`, but the prefix is empty.
* `PLANE TICKET`, `ET`: is not valid. The word appears separated by a space: `PLAN***E T***ICKET`, but it also appears contiguously: `PLANE TICK***ET***`.

For a bookend the word must appear as a combination of a non-empty prefix and a non-empty suffix of the clue, but is not a contiguous substring. Bookends may span word breaks, but are not required to. The clue must not appear as a contiguous substring to be a valid bookend.

* `SINGLE TRACK`, `SICK`: is valid. Solution: `***SI***NGLE TRA***CK***`
* `YOU MUST DOT YOUR IS AND CROSS YOUR TS`, `YURTS`: is valid. Solution: `***Y***OU MUST DOT YOUR IS AND CROSS YO***UR TS***`
* `STAND CLEAR`, `STAR`: is valid, even though there are two solutions: `***STA***ND CLEA***R***` and `***ST***AND CLE***AR***`
* `START A WAR`, `STAR`: is not valid since the word is a prefix of the clue.
* `TO ME`, `TOME`: is valid. It can be split multiple ways including ways with empty prefixes and suffixes.
* `TWO BIRDS WITH TWO STONE`, `TONE`: is not valid since the word is a suffix of the clue
* `IMPROPER USE`, `PERUSE`: is not valid. It appears as a suffix and is not a contiguous substring: `IMPRO***PER USE***`, but the prefix needs to be non empty for a bookend.

You will take as input a word (consisting of letters `A`-`Z`) and a clue (consisting of letters `A`-`Z` and spaces) and you must determine if the word is a valid solution to the clue by the above rules.

If the input is a valid pair you must output one consistent value, if it is not you must output a distinct consistent value.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

Valid:

```
POOR HOUSE, RHO
SINGLE TRACK, SICK
YOU MUST DOT YOUR IS AND CROSS YOUR TS, YURTS
STAND CLEAR, STAR
TO ME, TOME
IN A PICKLE, NAP

```

Invalid:

```
IMPROPER USE, PERUSE
SINGLE TRACK, SINGLET
PLANE TICKET, ET
START A WAR, STAR
TWO BIRDS WITH ONE STONE, TONE

```

# Answer
> 3 votes
# Retina 0.8.2, 41 bytes

```
 |^(.+)¶.*\1

^(.+)(.+)¶(\1.*\2$|.+\1\2.)

```

Try it online! Takes input as the word and clue on separate lines but link is to test suite that splits on comma and exchanges the word and clue. Explanation:

```
 |^(.+)¶.*\1

```

Delete spaces in the clue, but delete the word if is is a contiguous substring of the clue, which prevents the following match from succeeding.

```
^(.+)(.+)¶(\1.*\2$|.+\1\2.)

```

Check that the word either bookends or is now contained in the clue.

# Answer
> 2 votes
# JavaScript (ES6), 74 bytes

*A significantly shorter version suggested by Nick Kennedy and using Neil's regular expression.*

Expects `(clue)(word)`. Returns a Boolean value.

```
c=>w=>c.match(w)</^(.+)(.+),(\1.*\2$|.+\1\2.)/.test([w,c.split` `.join``])

```

Try it online!

---

# JavaScript (ES6), 86 bytes

Expects `(clue)(word)`. Returns a Boolean value.

The "bookend" test is based on the method used by Deadcode in this answer.

```
c=>w=>c.match(w)</^(.+)(.+),\1.*\2$/.test([w,s=c.split` `.join``])+!!s.match(`.${w}.`)

```

Try it online!

### Commented

```
c =>                // outer function taking c = clue
w =>                // inner function taking w = hidden word
c.match(w)          // look for w in c; the comparison will succeed
<                   // if this is null and the right side is > 0
/^(.+)(.+),\1.*\2$/ // regular expression for the "bookend" test
.test([             // applied to this array coerced to a string:
  w,                //   the word, followed by a comma
  s = c.split` `    //   followed by s,
       .join``      //   which is c without spaces
]) +                // end of test()
!!s.match(`.${w}.`) // for word breaks, we look for w in s with at
                    // least one char. before and one char. after

```

# Answer
> 2 votes
# Jelly, 19 bytes

Uses some of Unrelated String's answer to *Is it a circumfix?* saving bytes over using the "outfix quick", `ÐƤ`.

```
ḲFŒṖḢ;ṪƊ€;ṖḊẆƊƲḟẆ{i

```

A dyadic Link that accepts the clue on the left and the answer on the right and yields a positive integer (truthy) if valid or zero (falsey) otherwise.

**Try it online!** (Some tests have been shortened in the middle since the algorithm is inefficient.)

### How?

```
ḲFŒṖḢ;ṪƊ€;ṖḊẆƊƲḟẆ{i - Link: Clue, Answer
Ḳ                   - split {Clue} on space characters
 F                  - flatten -> Squished
              Ʋ     - last four links as a monad - f(Squished):
  ŒṖ                -   all partitions (no empty parts)
       Ɗ€           -   for each: last three links as a monad - f(Partition):
    Ḣ               -     head (remove first part and yield it)
      Ṫ             -     tail (remove last part of that and yield it ...
                                                ...or integer zero* if nothing left)
     ;              -     concatenate
                         -> Bookends (plus an invalid one with a trailing zero*)
             Ɗ      -   last three links as a monad - f(Squished):
          Ṗ         -     pop (remove the tail character)
           Ḋ        -     dequeue (remove the head character)
            Ẇ       -     all sublists
                         -> Hiddens
         ;          -   {Bookends} concatenate {Hiddens} -> Potential Answers
                Ẇ{  - sublists of {Clue}
               ḟ    - {Potential Answers} filter discard {Clue sublists}
                       -> Valid Answers (plus an invalid bookend with a trailing zero*)
                  i - 1-indexed index of {Answer} in* {Valid Answers} ...
                                                 ...or zero if not found

                       * Integer zero wont match a zero character

```

# Answer
> 2 votes
# , 77 bytes

```
\(x,y,`/`=grepl)"^((.+)(.+)) (\\2.*\\3$|.+\\1.)"/paste(y,gsub(" ","",x))&!y/x

```

Attempt This Online!

A function taking two character arguments and returning a logical value. Inspired by @Neil’s Retina answer so be sure to upvote that one too! The regular expression here is slightly different because of R’s requirement to escape backslashes.

# Answer
> 1 votes
# Ruby, 95 bytes

Bookends code is a slight tweak of my old answer to Is it a circumfix?

```
->s,w{t=s.tr' ','';(t=~/.#{w}./||(1...~-z=w.size).any?{w==t[0,_1]+t[_1-z..]}&&z<t.size)&&!s[w]}

```

Attempt This Online!

# Answer
> 1 votes
# JavaScript (Node.js), 123 bytes

```
x=>y=>(z=x.split` `.join``,g=i=>z[i]==y[i]?g(i+1):y[i]&&i*z.endsWith(y.slice(i))||eval(`/.${y}./`).test(z))(0)&&!x.match(y)

```

Try it online!

-1B from noodle man

# Answer
> 1 votes
# , 52 51 45 bytes

```
-.@rxin*[e.((]#~#@[>:#\@](-.|."{[),&#)-.&' ')

```

Attempt This Online!

This approach allows us to avoid treating the two cases of bookends and word breaks as separate:

* `-.@rxin*` Not in the unaltered string
* `*` And...
* `-.&' '` Remove spaces from haystack
* `#\@]` Create the integers 1..n (where n is length of haystack)
* `,&#` Create the integers n and m, the lengths of needle and the haystack. I'll explain why below.
* `-.` Remove n and m from 1..n (again, why below). Call this our "rotation list".
* `|."{[` Do every rotation of 1..n in our rotation list. The rotations we are leaving out are precisely the ones where our haystack abuts the left or right side, which are the illegal ones. We now have a matrix, with each row representing a legal rotation.
* `#@[>:` In every row, change the numbers 1..m (where m is length of needle) to 1 and the rest to 0, so now we have a matrix of the legal rotations of, eg, `1 1 1 0 0 0 0 0` (if the needle had length 3).
* `]#~` Now use the rows of legal 0-1 masks to filter the no-spaces input. These represent all possible bookends and word breaks.
* `[e.` Is the needle in any of those?

# , 52 bytes

```
-.@rxin*[((rxin g)+.[e.-~&#(g=.}:@}.)@(]\.)])' '-.~]

```

Attempt This Online!

Another nice candidate for J's outfix adverb. Reading through other answers I was reminded that this approach is similar to my answer on Is it a cirumfix as well.

* `-.@rxin` Does not appear in unaltered string
* `*` and...
* `(rxin g)` Does appear in the no-spaces `' '-.~]` string, after that string has its first and last elements removed `g=.}:@}.`
* `+.` or...
* `-~&#(g=.}:@}.)@(]\.)` Matches one of the outfixes (of appropriate length `-~&#`) after the set of all such outfixes has its first and last elements removed `}:@}.`.

# Answer
> 0 votes
# Charcoal, 32 bytes

```
‹№θη∨№⁻θ η⊙η∧κ¬∨⌕⁻θ …ηκ⌕⮌⁻θ ⮌✂ηκ

```

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

```
 №                                  Count of
   η                                Input word in
  θ                                 Input clue
‹                                   Is less than
     №                              Count of
         η                          Input word in
       θ                            Input clue
      ⁻                             With spaces removed
    ∨                               Logical Or
           η                        Input clue
          ⊙                         Any index satisfies
             κ                      Current index
            ∧                       Logical And
                  θ                 Input clue
                 ⁻                  With spaces removed
                ⌕                   Does not start with
                     η              Input word
                    …               Truncated to length
                      κ             Current index
               ∨                    Logical Or
                          θ         Input clue
                         ⁻          With spaces removed
                        ⮌           Reversed
                       ⌕            Does not start with
                              η     Input word
                             ✂      Sliced from
                               κ    Current index
                            ⮌       Reversed
              ¬                     Logical Not

```

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


title: Maximum average ord

text:
# Question
Title: Maximum average ord
### Your task

Take a list of strings as the input, and output the maximum average `ord`.

### Example

Given the list `['hello', 'world', 'bye']`:

* The average `ord` of `'hello'` is:
    + (`ord(h)` \+ `ord(e)` \+ `ord(l)` \+ `ord(l)` \+ `ord(o)`) / `len('hello')`
    + = 106.4
* The average `ord` of `'world'` = 110.4
* The average `ord` of `'bye'` = 106.7

The maximum average `ord` is 110.4. This is your output.

### Test cases

Note: For the last two test cases, I have given the roundings for 1, 2, and 3 decimal places. As mentioned in the rules below, you can round to any number of decimal places.

```
Input                                        Output
['hello', 'world', 'bye']                    110.4
['code', 'golf', 'stack', 'exchange']        106.8
['!@#', '$%^', '&*(']                        55.7 / 55.67 / 55.667 / etc.
['qwertyuiop[', 'asdfghjkl;', 'zxcvbnm,']    110.9 / 110.91 / 110.909 / etc.

```

### Rules/clarifications

* The output must be only the average `ord`. You may not output anything else.
* It may be rounded (up or down) to any number (\\$\ge\\$ 1) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.
* Floating point innacuracies are ok.
* You may assume that the input list will always have a length of 2 or more
* You may assume that the strings will never be empty
* You may assume that the strings will not contain whitespace or non-ASCII characters
* **This is , so shortest code in bytes wins!**

# Answer
# Vyxal `G`, 3 bytes

```
Cvṁ

```

Try it Online!
> 3 votes

# Answer
# Pyth, 7 bytes

```
eSm.OCM

```

Test suite

##### Explanation:

```
eSm.OCM   | Full program
eSm.OCMdQ | with implicit variables
----------+-------------------------------
  m     Q | For each word in the input,
     CMd  |  Get the ord of each character
   .O     |  Get the average
eS        | Get the max

```
> 9 votes

# Answer
# Python, 46 bytes

```
lambda l:max(sum(map(ord,s))/len(s)for s in l)

```

Attempt This Online!

Unfortunately, the only built-in `mean` function Python has is in the `statistics` module, and that's too expensive to import.
> 7 votes

# Answer
# K (ngn/k), ~~18~~ 11 bytes

```
|/{+/x%#x}'

```

Try it online!

*Massive -7 bytes golf thanks to Steffan!*

Damn everyone is answering quick. Anyways here's my solution. Takes input as a list of strings.

Explanation:

```
|/{+/x%#x}'  Main function. Takes implicit input
          '  For each string in the input...
  {      }   Execute a function that...
   +/x       Takes sum of every character in the string
      %      And divide it by
       #x    The length of the string
|/           Get the maximum value

```
> 7 votes

# Answer
# Wren, 68 bytes

```
Fn.new{|x|x.reduce(0){|y,z|y.max(z.bytes.reduce{|a,b|a+b}/z.count)}}

```

Try it
> 6 votes

# Answer
# APL(Dyalog Unicode), ~~14~~ 13 bytes SBCS

*-1 bytes thanks to Adám*

```
⌈/+⌿∘⎕UCS¨÷≢¨

```

Try it on APLgolf!

A tacit function which finds the maximum ord. Originally wrote a dfn, but I tried random stuff to convert it to tacit and it somehow worked out.

```
⌈/+⌿∘⎕UCS¨÷≢¨
          ¨              ⍝  for each element in the input...
     ⎕UCS               ⍝  convert the characters to their ascii values...
  +⌿∘                   ⍝  and sum the resulting ascii values...
           ÷             ⍝  divided by...
            ≢¨           ⍝  the length of each element...
⌈/                       ⍝  and take the maximum of that

```
> 6 votes

# Answer
# \>\<\>, ~~80~~ ~~51~~ 48 bytes

```
0>0001.
$i:"!"(?v+$1+
(@:{:,$&/
v?(0&~$?/.02
\n;

```

Animated Version

~~Requires a extra space at the end of the input.~~ Also assumes no 2 spaces in a row. (no 0 length words). Anything with ORD of 32 or lower is considered white-space.

## Explanation

Top row: Push 3 0s on to the stack. The first is the current best ORD, the second is the length of the current word, and the last is the sum of the ord values of the current word. `01.` is a jump to the next row.

The second row sums a word. If a character is less than "!" (char value 33) go down. Otherwise sum the word and increment the length. \`$1+

In the third row, we fist push the last value to the register `&` . We use this to later check if this was the end of the string. Then we divide by the length to get the new ORD value. Then we use the `:{:@` trick to copy the stack if it has only 2 elements (which is always the case) from the stack and compare them. If the new one is better we swap the stack with `$`. In either case we delete the top item.

Lastly, we take the value of the register and check if it is negative, `&0(?`. If so, we print the maximum ord and exit. If not, we jump back to `00`. To get the correct direction we use the `00!.|` trick.
> 5 votes

# Answer
# \>\<\>, ~~65~~ ~~45~~ 44 40 bytes

```
000i:"!"(?v+$1+$20.
$~$0(?n00.>@$,:{:@(?

```

Try it online!

Takes input as a space separated string.
> 5 votes

# Answer
# 05AB1E, ~~10 9~~ 4 bytes

```
ÇÅAà

```

-5 thanks to Sʨɠɠan

Try it online!

**Explained:**

```
ÇÅAà  # Implicit input as a list
      # Implicit map over the input:
Ç     #   Get the ord of each character
 ÅA   #   Get the average of the ords
   à  # Get the maximum value

```
> 4 votes

# Answer
# Factor, 24 bytes

```
[ 0 [ mean max ] foldl ]

```

Attempt This Online!

Just fold with the max of the mean.
> 4 votes

# Answer
# PHP 8.x, ~~75~~ 73 bytes

Creates an anonymous function that returns the expect values, hopefully.

```
fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));

```

---

-2 bytes thanks to Sʨɠɠan.

## How does it work?

This uses the `unpack('C*', ...)` function to convert all characters into an unsigned char (`0`-`255`).
This assumes all characters are part of the ASCII table.

Then it calculates the average using `array_sum([...])/strlen([...])`.
The function `array_sum()` takes an array and returns the sum of all elements, and `strlen()` returns the length of the string.

The function `max()` takes the array with the averages and returns the highest value from it.

Anonymous functions implicitly return values.

## Example usage

You need to assign this to a variable, or call with `call_user_func()` or `call_user_func_array()`:

```
<?php
$fn = fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));

// Should output: float(110.4)
var_dump($fn(['hello', 'world', 'bye']));

```

You can try this here (with test examples): https://onlinephp.io/c/2a424
> 4 votes

# Answer
# , 38 bytes

```
\(x)max(sapply(Map(utf8ToInt,x),mean))

```

Attempt This Online!

```
               Map(utf8ToInt,x)        # for every string in the input, store the vector of its codepoints in a list
        sapply(                ,mean)  # apply mean to each of the list elements and return a vector
\(x)max(                             ) # take max

```
> 4 votes

# Answer
# Jelly, 4 bytes

```
OÆmṀ

```

Try it online!
> 4 votes

# Answer
# Pip, 12 bytes

```
M:$+A*_/#_Mg

```

Try It Online!
> 4 votes

# Answer
# Knight (v2), 56 bytes

```
;=mF;W=pP;=s!=i~1;W>Lp=i+1i=s+*10A Gp iTs&<m=t/sLp=m tOm

```

Try it online!

Because Knight doesn't support floating point values, it outputs the maximum average ord multiplied by \\$10\\$, as allowed by the rules:

> It may be rounded to any number (\\$\ge1\\$) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.
> 4 votes

# Answer
# Julia, 34 bytes

```
!a=max(sum.(Int,a)./length.(a)...)

```

Attempt This Online!
> 4 votes

# Answer
# Excel (ms365), 70 bytes

Formula in `F1`:

```
=MAX(MAP(A1:C1,LAMBDA(a,SUM(CODE(MID(a,SEQUENCE(LEN(a)),1)))/LEN(a))))

```
> 4 votes

# Answer
# MathGolf, 4 bytes

```
$m▓╙

```

Input as a list of lists of characters.

Try it online.

**Explanation:**

```
$     # Get the codepoint of each inner-most character of the (implicit) input-list
 m    # Map over each list of integers:
  ▓   #  Pop and push the average of the list
   ╙  # After the map: pop and push the maximum
      # (after which the entire stack is output implicitly as result)

```
> 4 votes

# Answer
# MATLAB, 39 31 bytes

```
@(s)max(cellfun(@(x)mean(x),s))

```

Matlab unfortunately doesn't convert strings ("") directly to ASCII values using the double function, and if converted to char type then a string array will be padded with spaces to make a proper matrix. As a result, the input is a cellstr type, which needs to be looped over using the cellfun function with an anonymous function that takes the average of the unicode values of the strings (''). The output is then the maximum of those values.

Try it online!

edit: -8 bytes thanks to Guiseppe
> 4 votes

# Answer
# T-SQL, 125 bytes

```
WITH C as(SELECT len(x)m,0b,*FROM @
UNION ALL SELECT m-1,b+ascii(right(x,m)),x
FROM C WHERE
m>0)SELECT max(b*1./len(x))FROM c

```

**Try it online**
> 4 votes

# Answer
# , 18 bytes

```
[:>./(1#.3&u:%#)&>

```

Accepts list of boxed strings

Attempt This Online!

```
[:>./(1#.3&u:%#)&>
[:                  NB. cap, [: f g y -> f (g y)
                &>  NB. for each input item, result will be unboxed
     (         )    NB. monadic fork
              #     NB. length
         3&u:       NB. convert input to list of char codes
             %      NB. vectorized division
      1#.           NB. sum the result to compute average
  >./               NB. max item

```
> 4 votes

# Answer
# Raku, 27 bytes

```
*».&{.ords.sum/.chars}.max

```

Try it online!

Edit: as per advice from @Steffan
> 4 votes

# Answer
# Sequences, \\$9 \log\_{256}(96) \approx 7.41\\$ bytes

```
[$v$aH]gM

```

### Explanation

```
[$v$aH]gM  // Implicit list of string input
[     ]    // Loop through the input list:
 $v$       //   Get a list of ords of each character
    aH     //   Get the average and append to `g`
       g   // Push the list `g`
        M  // Get the maximum value
           // Implicit output

```
> 3 votes

# Answer
# Ruby, 48 bytes

```
->l{l.map{_1.chars.sum(&:ord)/_1.size.to_f}.max}

```

As the division of two integers in ruby gives an integer, and what was expected was a float, it's long :/
And `.fdiv` is one byte longer

Attempt This Online!
> 3 votes

# Answer
# C (clang), ~~87~~ ~~86~~ ~~84~~ 81 bytes.

```
v;*p;f(**t,float*r){for(*r=0;p=*t;*r=fmax(*r,v*1./(p-*t++)))for(v=0;*p;)v+=*p++;}

```

Try it online!
> 3 votes

# Answer
# Japt `-h`, 9 bytes

Takes input as an array of character arrays.

```
®xc /ZlÃñ

```

Try it

```
®xc /ZlÃñ     :Implicit input of 2D array of characters
®             :Map each sub-array Z
 x            :  Reduce by addition of
  c           :    Codepoints
    /         :  Divide by
     Zl       :    Length of Z
       Ã      :End map
        ñ     :Sort
              :Implicit output of last element

```
> 3 votes

# Answer
# Mathematica, 29 bytes

```
Max[Mean/@ToCharacterCode@#]&

```

View it on Wolfram Cloud!
> 3 votes

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

```
]KemMC

```

Try it online!

```
]KemMC
     C - Charcodes
  emM  - Mean of each
 K     - Sort
]      - Last

```
> 3 votes

# Answer
# Java 8, ~~81~~ ~~79~~ 56 bytes

```
a->a.mapToDouble(s->s.chars().average().orElse(0)).max()

```

Input as a `Stream<String>` and output as an `OptionalDouble`.

Try it online.

**Explanation:**

```
a->                  // Method with String-Stream parameter & OptionalDouble return-type
   a.map             //  Map over the input-Stream
        ToDouble(s-> //  and convert them to a Stream of Doubles
      s.chars()      //   Convert the String to an IntStream of its codepoint integers
       .average()    //   Then take the average of that IntStream (as OptionalDouble)
       .orElse(0))   //   And convert the OptionalDouble to double
                     //   (`.orElse(0)` is shorter than `.getAsDouble()`)
    .max()           //  After the map: leave the maximum (again as OptionalDouble)

```
> 3 votes

# Answer
# Go, ~~132~~ 108 bytes

```
func f(S[]string)(m int){for a,s:=range S{a=0
for _,r:=range s{a+=int(r)}
if a=a*10/len(s);a>m{m=a}}
return}

```

Attempt This Online!

* -24 bytes by @Sʨɠɠan: return as an int, multiplied by 10
> 3 votes

# Answer
# BQN, ~~13~~ 12 bytes

*-1 byte inspired by Aiden Chow's APL answer*

```
⌈´+´∘-⟜@¨÷≠¨

```

Anonymous tacit function; takes a list of strings and returns a float. Try it at BQN online!

### Explanation

```
⌈´+´∘-⟜@¨÷≠¨
          ≠¨  Length of each string
         ÷    Divide the following by the above:
  +´∘           Sum of
     -⟜@       Subtract null character from (each character in)
        ¨       Each string
⌈             Get the maximum of the resulting list of averages

```
> 3 votes

# Answer
# Arturo, ~~48~~ 22 bytes

```
$=>[map&=>average|max]

```

Try it
> 3 votes

# Answer
# C++ (gcc), ~~166~~ 120 bytes

-46 thanks to the combined efforts of @ceilingcat and @jdt.

```
#import<bits/stdc++.h>
auto f(auto a,float*r){*r=0;for(char*t:a){int u=0,s=0;for(;*t;u+=*t++)s++;*r=fmax(*r,(0.+u)/s);}}

```

Try it online!

## Original Answer:

Attempting to apply general-purpose programming to code golf doesn't seem to work out well.

```
#import<bits/stdc++.h>
auto g(char*a){int t=0,s=0;for(a--;*++a;s++,t+=*a);return(0.0+t)/s;}auto f(std::list<char*>a){float m=0;for(char*t:a)m=m>g(t)?m:g(t);return m;}

```

Try it online!

### Ungolfed:

```
// Gets the average ord value of a string
auto g(char* a) {
    int t=0, s=0;             // Running total and size

    for (a--;*++a;s++,t+=*a); // Loop until a equals 0 and add a onto the running total

    return (0.0+t) / s;       // Cast to float by adding 0.0 and divide the total by the size.
}

// "Main" function
auto f(std::list<char*> a) {
    float m = 0;           // Maximum value

    for (char* t : a) {    // Loop through all the strings in the list
        m = m>g(t)?m:g(t); // If m is greater than the output from the function, return m. Otherwise, return the output of the function
    }

    return m;              // m is the final result that we want
}

```
> 3 votes

# Answer
# \>\<\>, ~~36~~ 35 bytes

```
000\&l3-,:{:@)?$&0(?n1[!
"(?\+:i:"!

```

Try it online!

Words are separated by spaces (or characters less than space like newline). This uses the length of the stack rather than a counter to get the length of the word.
> 3 votes

# Answer
# Husk, 6 bytes

```
▲moAmc

```

Try it online!

Outputs the highest average ord value as an exact fraction.

```
▲moAmc
 mo    # map 2 functions over each element of input
    mc #   get ord values of each character
   A   #   get the average of those
▲      # output the maximum.

```
> 2 votes

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

```
a=>Math.max(...a.map(s=>eval(Buffer(s).join`+`)/s.length))

```

Try it online!
> 2 votes

# Answer
# Nibbles, 8 bytes (16 nibbles)

```
`/.$/*+.$o$10,$]

```

Nibbles works only in integers, so this returns the maximum average ord multiplied by 10 (and rounded-*down* to a whole number).

```
`/.$/*+.$o$10,$]
  .$              # map over each input string
       .$         #   map over each character
         o$       #     getting it's ord
      +           #   sum them all
     *     10     #   multiply by 10
    /             #   and divide by
             ,$   #   the length of the string
`/                # finally, fold over the list
               ]  #   getting the max of each pair

```
> 2 votes

# Answer
# sclin, 38 bytes

```
"dup S>c0\+ fold rev len /"map0\| fold

```

Try it here! This might be a good case for adding sum/prod/min/max functions to sclin, the fold construct is alright but it could be better.

For testing purposes:

```
["hello" "world" "bye"] ; 30N>d n>o
"dup S>c0\+ fold rev len /"map0\| fold

```

## Explanation

Prettified code:

```
( dup S>c 0 \+ fold rev len / ) map 0 \| fold

```

Assuming input list *xs*.

* `(...) map` map over *xs*...
    + `dup S>c` get codepoints
    + `0 \+ fold` sum
    + `rev len /` divide by length (i.e. average)
* `0 \| fold` maximum
> 2 votes

# Answer
# Zsh, 63 bytes

```
for w;c=&&for a (${(s::)w})((c+=#a,o=1.*c/$#w,m=o>m?o:m))
<<<$m

```

Try it online! ~~65b~~ ~~74b~~

`for w;` implicitly iterates over the arguments `($@)`.
`for a (${(s::)w})` iterates over each letter in word `w`.
`c` accumulates the ascii sum
`o` is the average ord for `w`
`m` is the maximum `o` found

Edit: Saved 6 bytes by chaining 3 math expressions in the parentheses`((,,))`!

> 2 votes

# Answer
# J-uby, ~~43~~ ~~38~~ ~~36~~ 30 bytes

-5 bytes thanks to Steffan

Originally based on TKirishima's Ruby answer.

```
:*&:/%[:bytes|:sum,:+@|Q]|:max

```

Attempt This Online!

## Explanation

```
:* & :/ % [ :bytes | :sum, :+@ | Q ] | :max

:* &                                         # Map with...
            :bytes | :sum                    #   Sum of bytes
     :/ % [              ,         ]         #   Divided by
                           :+@ | Q           #   Length converted to float
                                     | :max  # Get max

```
> 2 votes

# Answer
# CJam, ~~19~~ 14 bytes

```
{:d_:+\,/}%$W=

```

Try it online!

A function which takes an input as an array. Link includes test cases.

# Explanation

```
{:d_:+\,/}%$W= # function which takes an array as input
{        }%    # for each value in the input array...
 :d            # short map `:` the operator `d` to convert into an array of `d`oubles
   _:+         # duplicate and sum
      \        # swap
       ,       # get the length of the array
        /      # divide, giving the average
           $   # perform a $ort on the resulting array
            W= # and get index `W` (shorthand for `-1`), which is the last value of the sort, or the max

```
> 2 votes

# Answer
# Stax, ~~10~~ 9 bytes

```
é)u6║"⌂w╙

```

Run and debug it

This is a PackedStax program, which unpacks to the following:

```
{:V}kTlE:_

```

Run and debug it

# Explanation (unpacked)

```
{  }k      # map the following over all the values in the input
 :V        # get the mean of the array
     T     # Get the maximum of this map
      l    # The output is a fraction, so it must be listified
       E   # Explode this list onto the stack
        :_ # Float division

```
> 2 votes

# Answer
# Octave, 18 bytes

```
@(x)max(mean(+x'))

```

Try it online!
> 2 votes

# Answer
# Lua, 94 bytes

I tried two approaches here, both of which ended up having the same byte count.

## List of Arguments

```
m=0 for i=1,#arg do n=0s=arg[i]s:gsub('.',load'n=s.byte(...)+n')m=math.max(m,n/#s)end print(m)

```

Try it online!

## Space Delimited String

```
m=0(...):gsub('%S+',load'n=0s=...s:gsub(".",load"n=s.byte(...)+n")m=math.max(m,n/#s)')print(m)

```

Try it online!
> 2 votes

# Answer
# Uiua, 15 bytes

```
/↥∵(÷⊃⧻/+-@\0⊔)

```

Try it!

```
/↥∵(÷⊃⧻/+-@\0⊔)
  ∵(          )  # map over input
             ⊔   # unbox a string
         -@\0    # subtract null character
    ÷⊃⧻/+        # mean
/↥               # max

```
> 2 votes

# Answer
# Charcoal, 15 bytes

```
ＷＳ⊞υ∕ΣＥι℅κＬιＩ⌈υ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
ＷＳ

```

Repeat until the end of the list is reached...

```
⊞υ∕ΣＥι℅κＬι

```

... take the ordinals of the characters in the string, and divide their sum by the string's length.

```
Ｉ⌈υ

```

Output the maximum average.
> 1 votes

# Answer
# Python 3, ~~71~~ 70 bytes

```
lambda l:max(map(lambda s:mean(map(ord,s)),l))
from statistics import*

```

Try it online!

*-1 thanks to The Thonnu*
> 1 votes

# Answer
# Thunno 2 `G`, 2 bytes

```
€m

```

Try it online!

Take the `m`ean of ach string in the (implicit) input list (this automatically converts to codepoints). Then, take the `G`reatest item.
> 1 votes

# Answer
# Nekomata, 4 bytes

```
eᵐµṀ

```

Attempt This Online!

```
eᵐµṀ
e       Ord
 ᵐ      Map
  µ     Mean
   Ṁ    Maximum

```
> 1 votes

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


title: The Squiggly Sequence

text:
# Question
Title: The Squiggly Sequence
# *All credits to Adnan for coming up with this challenge.*

My last challenge, before I go on break.

# Task

Given positive integer `n`, if `n` is odd, repeat `/` that many times; if `n` is even, repeat `\` that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

# Specs

# Testcases

```
n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\

```

# Answer
# Javascript, 22 bytes

```
n=>"\\/"[n%2].repeat(n)

```

Defines an anonymous function.

If only `*` repeated strings in Javascript. *sighs*
> 19 votes

# Answer
## Python, 20 bytes

```
lambda n:'\/'[n%2]*n

```
> 17 votes

# Answer
# 05AB1E/2sable, ~~15~~ ~~11~~ ~~9~~ 8 bytes

```
DÈ„/\sè×

```

*-2 bytes thanks to Leaky Nun*

*-1 byte thanks to Emigna*

Try it online! in 05AB1E
or in 2sable
> 12 votes

# Answer
# Perl, 20 bytes

Includes +1 for `-p`

Run with input on STDIN:

```
squigly.pl <<< 6

```

`squigly.pl`

```
#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/

```
> 10 votes

# Answer
# J, 10 bytes

```
#'\/'{~2|]

```

This is a six-train verb, consisting of:

```
# ('\/' {~ 2 | ])

```

This is a hook between `#` and `('\/' {~ 2 | ])`; a hook `(f g) y` expands to `y f (g y)`, so this expands to `y # (... y)`, which, for single-characters, yields a list of `y` characters.

The second part is a 5-train, consisting of:

```
'\/' {~ 2 | ]

```

This evaluates to two forks:

```
'\/' {~ (2 | ])

```

The inner fork, `2 | ]`, is modulus two. The outer fork, therefore, is:

```
'\/' {~ mod2

```

Which takes (`{~`) the mod2 index (`mod2`) from the string `/`.

Then, using the hook from above:

```
y # (apt char)

```

This yields what we want, and we are done.
> 8 votes

# Answer
# Retina, 21

```
.+
$*/
T`/`\\`^(..)+$

```

Try it online (First line added to allow multiple testcases to be run).
> 7 votes

# Answer
# PHP, 38 bytes

```
for(;$i++<$a=$argv[1];)echo'\/'[$a%2];

```

(variant 38 bytes)

```
while($i++<$a=$argv[1])echo'\/'[$a%2];

```

(variant 38 bytes)

```
<?=str_pad('',$a=$argv[1],'\/'[$a%2]);

```

(variant 40 bytes)

```
<?=str_repeat('\/'[($a=$argv[1])%2],$a);

```
> 7 votes

# Answer
# C#, 42 bytes

```
string f(int n)=>new string("\\/"[n%2],n);

```

Selects the correct character, then creates a new string consisting of that character repeated `n` times.
> 7 votes

# Answer
# C, 40 bytes

```
i;f(n){for(i=n;i--;)putchar(n%2?47:92);}

```

Try it on Ideone
> 6 votes

# Answer
# Jelly, 5 bytes

```
ị⁾/\x

```

Try it online! or Verify all testcases.

```
ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat

```
> 6 votes

# Answer
## Haskell, 25 bytes

```
f n=cycle"\\/"!!n<$[1..n]

```

-1 byte thanks to Damien with `cycle`.
> 6 votes

# Answer
# Mathematica, ~~34~~ ~~32~~ 28 bytes

```
If[OddQ@#,"/","\\"]~Table~#&

```

Anonymous function. Takes an integer as input and returns a list of characters as output.
> 6 votes

# Answer
# Mathematica, 29 bytes

```
"\\"["/"][[#~Mod~2]]~Table~#&

```

Cruelly exploits the fact that `[[1]]` returns the first argument of a function while `[[0]]` returns the function (head) itself, applied to the strangely valid function named `"\\"` which is being "evaluated" at `"/"`.
> 6 votes

# Answer
# Powershell, ~~30~~ 27 bytes

Update:

```
param($n)('\','/')[$n%2]*$n

```

Switching to `param`, thanks to timmyd.

---

```
"$("\/"[$args[0]%2])"*$args[0]

```

or slightly more readable

```
("\","/")[$args[0]%2]*$args[0]

```

Test:

```
> 1..10 | % { ./run.ps1 $_ }
/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\\\\\\\\\\

```
> 5 votes

# Answer
# Ruby, 15 bytes

```
->n{'\/'[n%2]*n}

```

See it on eval.in: https://eval.in/632030
> 4 votes

# Answer
# Fourier, 27 bytes

```
92~SI~N%2{1}{47~S}N(Sai^~i)

```

**Try it online!**
> 4 votes

# Answer
# Dyalog APL, 11 bytes

Requires `⎕IO←0` which is default on many systems.

```
⊢⍴'\/'⊃⍨2|⊢

```

the argument

reshapes (repeats)

`'\/'⊃⍨` the string "/" selected by

`2|⊢` the division remainder when the argument is divided by two

TryAPL online!
> 4 votes

# Answer
# Brachylog, 15 bytes

```
:2%:"\/"rm:?jbw

```

Try it online!

### Explanation

```
:2%                Input mod 2…
   :"\/"rm         …is the index of the element in string "\/",…
          :?j      …element that we juxtapose Input times to itself…
             bw    …and print to STDOUT after removing one slash/backslash

```
> 4 votes

# Answer
# Java 11, ~~68~~ ~~65~~ 29 bytes

```
n->(n%2<1?"\\":"/").repeat(n)

```

-3 bytes saved thanks to *@user902383* and *@SeanBean*
-36 bytes switching from Java 7 to Java 11+

Try it online.

**Explanation:**

```
n->                     // Method with integer parameter and String return-type
  (n%2<1?               //  If `n` is even:
         "\\"           //   Use String "\"
        :               //  Else (`n` is odd):
         "/")           //   Use String "/" instead
             .repeat(n) //  Repeat it `n` amount of times

```
> 4 votes

# Answer
# CJam, 9 bytes

```
ri_"\/"=*

```

Try it online!

### Explanation

```
ri     e# Read input and convert to integer N.
_      e# Duplicate N.
"\/"=  e# Use N as cyclic index into "\/", giving '\ for even and '/ for odd inputs.
*      e# Repeat N times.

```
> 4 votes

# Answer
# \>\<\> (Fish), 30 Bytes

```
:2%?'/'o1-:?!;30.
30.  >'\'50p

```

First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.

Input is the initial stack, output is `stdout`

Try it online!
> 4 votes

# Answer
## Pip, 8 bytes

```
"\/"@aXa

```

Straightforward. Uses modular indexing to select the character and string repetition to multiply it. Try it online!

---

This question presents an interesting comparison between Pip, Pyth, and Jelly, the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:

1. Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;
2. Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as Maltysen explained to me).

Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.

1 Although, single-character strings in Pip use a single `'` delimiter, inspired by CJam and by quoting in Lisp.
> 3 votes

# Answer
# Julia, 20 bytes

```
!x="$("/\\"[x%2])"^x

```
> 3 votes

# Answer
# R, ~~47~~ 46 bytes

```
n=scan();cat(rep(c("\\","/")[n%%2+1],n),sep="")

```

In R, you have to escape backslashes. the argument `sep` also has to be fully specified since it comes after `...`. Thus annoyingly few opportunities to save chars :(

Thanks to bouncyball for golfing away a byte.
> 3 votes

# Answer
# T-SQL 50 bytes

Of course no `STDIN` here, so let's assume a hardcoded `INT` variable like this: `DECLARE @ INT` then the solution is:

```
PRINT IIF(@%2=0,REPLICATE('\',@),REPLICATE('/',@))

```
> 3 votes

# Answer
# Psithurism, 11 bytes

```
*(%2?"/:"\)

```

This is a language I'm still developing, but I'm going to start posting answers here to get a feeling of what kind of built-in functions might be useful to have. (This one has taught me I really need some way to index into arrays/strings lol.)

explained:

```
*(        # implicitly multiply the input by
  %2      # implicitly take input mod 2
    ? "/  # / if truthy (1)
    : "\  # \ if falsy (0)
)

```

Curious about Psithurism?
Github: https://github.com/AroLeaf/psithurism/
Docs (soon™): https://psithurism.leaf.moe/
> 3 votes

# Answer
# Pyth, 5 bytes

```
*@"\/

```

Test suite.

Modular-indexing into the string `\/` and then repeat.
> 2 votes

# Answer
# Perl 6, 16 bytes

```
{<\ />[$_%2]x$_}

```

## Usage:

```
for 1..6 {
  say $_, {<\ />[$_%2]x$_}( $_ )
}

```

```
1/
2\\
3///
4\\\\
5/////
6\\\\\\

```
> 2 votes

# Answer
# SpecBAS - 28 bytes

```
1 INPUT n: ?"\/"(ODD(n)+1)*n

```

`ODD` returns 1 if number is odd, then uses that as an index to print the correct character n number of times. Have to add 1 as SpecBAS strings start at character 1.
> 2 votes

# Answer
# **Python 3, 43 Bytes**

```
n=int(input())
a='\\'*n
if n%2:a='/'*n
print(a)

```

In python the `\` symbol is also used as an operator when inside a string (e.g: `\n` means newline) so `\\` has to be used to get the backslash symbol.

This code works by assuming the input (`n`) is odd, and then checks if it is even. If so, then it redefines the variable `a` (the output) before displaying it.

This is shorter than using an `if-else` statement by 5 bytes as it does the checking after defining the variable, meaning that the `else` command is not needed.
> 2 votes

# Answer
# Java 8, 56 bytes

```
(i,j)->{for(j=i;j-->0;)System.out.print(i%2<1?92:'/');};

```

I'd like to thank @Kevin Cruijssen in advanced for golfing my answer further.

# Ungolfed Test Program

```
public static void main(String[] args) {
    BiConsumer<Integer, Integer> consumer = (i, j) -> {
        for (j = i; j-- > 0;) {
            System.out.print(i % 2 < 1 ? 92 : '/');
        }
    };

    consumer.accept(5, 0);
    consumer.accept(1, 0);
    consumer.accept(8, 0);
}

```
> 2 votes

# Answer
## Bash + coreutils, ~~29~~ 28 bytes

```
yes $1_45r2%*92+P|sed $1q|dc

```

Previous answer, easier to understand:

```
yes $[92-$1%2*45]P|sed $1q|dc

```

In the new script I just transferred the calculation of the ASCII code from bash to dc entirely.
> 2 votes

# Answer
## PHP, ~~63~~ 52 bytes

**Version 1** \- 63 bytes

```
$i=$argv[1];$x=($i%2?"/":"\\");echo sprintf("%'".$x.$i."s",$x);

```

**Version 2** \- 52 bytes

Thanks to manatwork for saving 11 bytes

```
$i=$argv[1];$x=$i%2?"/":"\\";printf("%'$x{$i}s",$x);

```

Run with `php -f squiggle.php <number>`

https://repl.it/DFdi/2 (remember to change the input on repl)
> 2 votes

# Answer
# Actually, 10 bytes

Golfing suggestions welcome. Try it online!

```
;'\'/2(%I*

```

**How it works**

```
       Implicit input of n
;      Duplicate n
'\'/   The strings "/" and "\"
2(%    n mod 2
I      If n mod 2, then "/", else "\"
*      Multiply by n. Implicit print at the end.

```
> 2 votes

# Answer
## \>\<\>, 15 + 3 = 18 bytes

```
\/:l2-),:2%0go:

```

+3 bytes for the `-v` flag to initialise the stack with the input. Try it online!

\>\<\> is a toroidal 2D language, so the following runs in a loop:

```
\/          Mirrors that reflect the instruction pointer. Since the code is
            one row high, the reflection wraps and the IP ends up moving in the
            same direction anyway, so these are no-ops.

:l2-)       Push (input > length of stack - 1) - note that the actual subtraction
            is by 2 to account for the fact that we duplicated an element with :

,           Divide the input by the above. If (input == length of stack - 1),
            then the program errors out due to division by 0. Otherwise, the
            input is unchanged.

:2%0g       Push the char at (input % 2, 0), which will be one of the two slashes
            at the beginning of the code

o           Output this char

:           Duplicate the input, increasing the length of the stack by 1

```
> 2 votes

# Answer
# Husk, 6 bytes

```
R¹!"/¦

```

Try it online!

-4 bytes from Zgarb.

`¦` is an alias for `\` in a string.

# Husk, 10 bytes

```
*⁰;!⁰"/\\"

```

Try it online!

## Explanation

```
*⁰;!⁰"/\\"
   !⁰"/\\" get element at index n in string "/\" (wraps around)
  ;        create singleton list from it
*⁰         repeat list n times

```
> 2 votes

# Answer
# Japt, 7 bytes

```
çUg"\\/

```

Try it
> 2 votes

# Answer
# Forth (gforth), 55 bytes

```
: b 1- dup for dup 2 mod if 92 else 47 then emit next ;

```

Try it online!

called as `<number> b`.
> 2 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

*-2 bytes thanks to @Neil.*

```
„\/è×

```

Try it online!

```
     è   # 0-based index...
         # implicit input...
     è   # implicit mod 2 in...
 „\/     # "\/"
      ×  # repeat implicit input times
         # implicit output

```
> 2 votes

# Answer
# Vyxal, 31 bits1, 3.875 bytes

```
‛\/iẋ

```

Try it Online!

```
'\/    # string literal "\\/"
   i   # modular index
    ẋ  # repeat

```
> 2 votes

# Answer
# Vyxal, 8 bytes

```
?£₂k/i¥ẋ

```

Try it Online!
> 2 votes

# Answer
# TypeScript's Type System, No Ignore, 541 311 155 148 140 118 bytes

*Based off of a previous even/odd answer*

```
type E<N>=N extends`11${infer R}`?R extends""?"/":E<R>:"\\"
type X<A,B=A>=B extends`1${infer R}`?`${E<A>}${X<A,R>}`:""

```

X takes in a repeated 1 N times to represent the number N, for example `X<"11111">` represents 5 passed to the `X` function.

TypeScript Playground && Tests

* Drastic improvements by Jacob via even/odd, input simplification, and joining together types
> 2 votes

# Answer
# Uiua, 11 bytes

```
▽∶?@/@\\◿2.

```

Try it!

```
▽∶?@/@\\◿2.
          .  # duplicate
        ◿2   # modulo two
  ?@/@\\     # choose slash depending on result
▽∶           # repeat it input times

```
> 2 votes

# Answer
# S.I.L.O.S, 55 bytes

```
readIO
c=i
c%2
c*45
c-92
c|
lbla
printChar c
i-1
if i a

```

Try it online!

Port of this answer in C.
> 1 votes

# Answer
## Haskell, 32 bytes

```
f n=replicate n$"\\/"!!(mod n 2)

```
> 1 votes

# Answer
# RETURN, 21 bytes

```
[$2÷%'/'\2øø4ø2␂{␋},]

```

`Try it here.`

Anonymous lambda. Usage:

```
5[$2÷%'/'\2øø4ø2␂{␋},]!

```

# Explanation

```
[                    ]  [lambda]%
 $2÷%                   [copy input and mod 2]%
     '/'\2øø            [choose either / or \ depending on input mod 2]%
            4ø          [get input again]%
              2␂{      [copy the /\ char and the input into a new stack]%
                  ␋},   [repeat the stack by the input and output the stack]%

```
> 1 votes

# Answer
# Bash, 63 bytes

```
q(){ seq -s0 0 $1|cut -c-$1|tr 0-9 $(($1%2))|sed 'y/10/\/\\/';}

```
> 1 votes

# Answer
# Rust, ~~210~~ 190 Bytes

```
fn main(){let x:usize=std::env::args().nth(1).unwrap().parse::<usize>().unwrap();let l:&str=match x%2{0=>"\\",1=>"/",_=>"",};println!("{}",std::iter::repeat(l).take(x).collect::<String>());}

```

Ungolfed:

```
fn main() {
    let x : usize = std::env::args().nth(1)
                                    .unwrap()
                                    .parse::<usize>()
                                    .unwrap();
    let l : &str = match x % 2 {
        0 => "\\",
        1 => "/",
        _ => "",
    };
    println!("{}", std::iter::repeat(l).take(x)
                                       .collect::<String>());
}

```

I don't usually golf (so I bet this isn't a great score, at least for Rust), but I figured this would be good Rust practice. This compiles into an executable run as `squiggly.exe x` where x is the number of times to repeat the character.
> 1 votes

# Answer
# awk, 26 bytes

```
NF=$1,$1=OFS=$1%2?"/":"\\"

```

`$1` is the input and then part of the output

`NF` is the number of fields

`OFS` is the output field separator

It prints if the expression before the comma is truthy.
> 1 votes

# Answer
# Lua (~~33~~ 44 Bytes)

Never tried golfing with Lua before.

Shortest program I could come up with:

`n=io.read()print(({'\\','/'})[n%2+1]:rep(n))`
> 1 votes

# Answer
# Forth, ~~58~~ 54 bytes

Leaves `n%2` as junk on the stack. Output is sent to stdout. `47` is `/`, and `92` is `\`. Computes `y=92-45*x`, where `x` is `n%2` and emits (outputs) the character with that codepoint.

```
: f dup 2 mod swap 0 DO dup 92 swap 45 * - emit LOOP ;

```

**Try it online**
> 1 votes

# Answer
# PL-SQL (Oracle), 530 characters

```
DECLARE
-- Enter your input here, here example is taken as 3 ---
  n number := 3 ;
  k varchar2(20);
BEGIN
     -- Checking the input number for odd --
     if mod(n,2)=1 then
     for j in 1..n loop
      k := k||'/';
      end loop;
      DBMS_OUTPUT.PUT_line (n||' '||k);
     end if;

     -- Checking the input number for even --
         if mod(n,2)=0 then
         for j in 1..n loop
         k := k||'\';
          end loop;
          DBMS_OUTPUT.PUT_line (n||' '||k);
         end if;
END;

```
> 1 votes

# Answer
# *Acc!!*, 90 bytes

```
N
Count i while _%60-10 {
_*10+_%60*50-2880+N
}
_/60
Count j while _-j {
Write 92-_%2*45
}

```

Try it online!

### With comments

```
# Read a line of stdin, convert it to a decimal number, and store it in the accumulator
N
Count i while _%60-10 {
    _*10+_%60*50-2880+N
}
_/60
# Loop that many times
Count j while _-j {
    # Output \ if accumulator mod 2 is 0, or / if it is 1
    Write 92-_%2*45
}

```
> 1 votes

# Answer
# MAWP, 38 bytes

```
%@!!2P2WA{~[67W5M;1A].}~[99W25W1MM;1A]

```

Made using Dion's modulus function from here.

Try it!
> 1 votes

# Answer
# x86-16 machine code, PC DOS, 18 bytes

Binary:

```
00000000: a082 002c 30a8 0191 b85c 0a74 02b0 2fcd  ...,0....\.t../.
00000010: 10c3                                     ..

```

Listing:

```
A0 0082     MOV  AL, BYTE PTR[82H]  ; first char of command line into AL
2C 30       SUB  AL, '0'            ; ASCII convert input char
A8 01       TEST AL, 1              ; set ZF if even
91          XCHG AX, CX             ; CL = number of times to repeat
B8 0A5C     MOV  AX, 0A5CH          ; AL = '\', AH = 0AH (BIOS write char)
74 02       JZ   WRITE              ; if even, write with a '\'
B0 2F       MOV  AL, '/'            ; otherwise change to a '/'
        WRITE:
CD 10       INT  10H                ; write AL to console CX number of times
C3          RET                     ; return to DOS

```

Standalone PC DOS executable (COM) program. Input `n` on command line (note: this is limited to single digit values).
> 1 votes

# Answer
# Pyth, 5 bytes

```
*@"\/

```

Try it online!

```
*@"\/
@("\/", Q) * Q  // After implicit input is read and re-structured to appear more readable.
@("\/", Q)      // Get element at index Q(input)
@("\/", Q) * Q  // Repeat Q times.

```
> 1 votes

# Answer
# Arturo, 31 bytes

```
$->n->repeat(0=n%2)?->{\}->"/"n

```

or

```
$->n[s:[{\}"/"]repeat s\[n%2]n]

```

Try it
> 1 votes

# Answer
# Scala, 56 bytes

Golfed version. Try it online!

```
def c(i:Int)=for(_<-1 to i){print(if(i%2<1)"\\"else"/")}

```

Ungolfed version. Try it online!

```
object M {
  implicit class IntExtensions(val i: Int) extends AnyVal {
    def times[T](f: => T): Unit = {
      for (_ <- 1 to i) {
        f
      }
    }
  }
  //def c(i:Int)=print(Iterator.fill(i)(if(i%2<1)"\\"else"/").mkString)
  //def c(i:Int)=Iterator.fill(i)(if(i%2<1)"\\"else"/").foreach(print)
  def c(i: Int) = i.times { print(if (i % 2 < 1) "\\" else "/") }
  def main(args: Array[String]): Unit = {
    for (i <- 0 until 10) {
      c(i)
      println()
    }
  }
}

```
> 1 votes

# Answer
# Rust, 28 bytes

```
|n|[r"\","/"][n%2].repeat(n)

```

Attempt This Online!
> 1 votes

# Answer
# , 32 bytes

```
\(n)intToUtf8(rep(92-45*n%%2,n))

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
`\/i×

```

#### Explanation

```
`\/i×  # Implicit input
`\/    # Two character string "\\/"
   i   # Modularly index in
    ×  # Repeat input times
       # Implicit output

```

#### Screenshot
> 1 votes

# Answer
# Regenerate, 22 bytes

```
(/{1/($~1%2)}|\\){$~1}

```

Attempt This Online!

### Explanation

```
(/{1/($~1%2)}|\\){$~1}
 /                      Match a forward slash
  {         }           repeated this many times:
   1/(     )             Invert:
      $~1                 Command-line argument
         %2               mod 2
                         (For odd arguments, this gives one forward slash; for even
                         arguments, it fails due to division by zero)
             |          If the previous alternative failed,
              \\        match a backslash instead
(               ){$~1}  Repeat the above (command-line argument) times

```
> 1 votes

# Answer
# Ly, 17 bytes

```
'\'/n:2%Isp[,lo];

```

Try it online!

I tried a couple variations and this one was the shortest. It's uses the eveness/oddness of the number to pick the character from a list on the stack, then stashes it away before looping "N" times and printing the saved character. The stack ends up with junk on it so it explicitly exits to avoid printing it. That proved shorter than cleaning the stack.

```
'\'/               - push "\/" onto the stack
    n:             - get number "N" from STDIN and duplicate
      2%           - get 0|1 depending on whether it's even or odd
        I          - copy top "\" or one-down "/" entry from stack
         sp        - stash the char and delete
           [,  ]   - loop "N" times
             lo    - load char to print, print it
                ;  - exit to avoid printing junk on the stack

```
> 0 votes

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


# Question
Title: Calculate the aspect ratio of the Nepal flag
Above is the picture of the flag of the country Nepal. Pretty cool.

What's cooler, is the aspect ratio, which is defined under the constitution as:

That formula in copyable form:

$$ 1 : \frac{6136891429688-306253616715\sqrt{2}-\sqrt{118-48\sqrt{2}}(934861968+20332617192\sqrt{2})}{4506606337686} $$

Your task is to output at least the first 113 digits of the decimal expansion, in any format of your choosing. These digits are:

1.2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441

These digits form can be found in sequence A230582.

This constant is algebraic, specifically quartic. In particular it is the least root of `243356742235044x⁴ - 1325568548812608x³ + 2700899847521244x² - 2439951444086880x + 824634725389225`.

This is `code-golf`, so shortest answer wins.

Related: Let's draw the flag of Nepal

# Answer
> 10 votes
# Python 3, 100 bytes

```
from sympy import*
r=sqrt(2)
print(N((4-3/((7*r-3-sqrt(59-24*r))*(23-9*r)*16/9/(33-20*r)+r))/3,113))

```

Try it online!

This is longer than compressed hardcoding and definitely golfable, but I want to share a formula I simplified from one in this thumbnail of this video:

$$\begin{aligned} v &= \frac{16 \cdot (7\sqrt{2}-3-\sqrt{59-24\sqrt{2}}) \cdot (23-9\sqrt{2})}{9 \cdot (33-20\sqrt{2})} \\ \text{ratio} &= \frac{4}{3}-\frac{1}{v+r} \end{aligned} $$

**92 bytes**

```
from sympy import*
r=5-sqrt(8)
print(N((4-6/((29-7*r-sqrt(48*r-4))*(8/r/9+8)/r+5-r))/3,113))

```

Try it online!

**95 bytes** (@dingledooper)

```
from sympy import*
r=sqrt(2)
print(N((4-3/((7*r-3-sqrt(59-24*r))*(6384+2608*r)/2601+r))/3,113))

```

Try it online!

# Answer
> 8 votes
# Vyxal, 48 bytes

```
»ʀ⌈S«A0ẇ⟨Ė^Ṗ*«)Πṙvp≈›≥›BĖ≥ẇ₈ḋẇβẋV¼»16↵τyNY∆Ph⁺°Ḟ

```

Try it Online!

Solves the stated polynomial.

```
»...»              # Giant number
        τ          # Decompress from base
     16↵           # 10^16
         yNY       # Negate every other term to get coefficients
            ∆P     # Solve polynomial
              h    # First root
               ⁺°Ḟ # Format to 113 decimal places

```

# Answer
> 4 votes
# Charcoal, 52 bytes

```
1.”)¶⌊G U9ι[abN↧Ｑ∧≡⁻w⁼Ka5↧χ±ν∕§G\`U⊙Gφ2Ｓ4↖gλo0θ｜Sψ◨N➙

```

Try it online! Link is to verbose version of code, for what it's worth. Explanation: Prints `1.` separately, because that improves the string compression of the remaining 112 digits.

120 bytes to actually calculate the 113 digits:

```
≔Ｘχ¹¹²θ≔▷math.isqrt⊗×θθη1.✂Ｉ÷⁻⁻×Ｉ”)¶↷ωrＮL@”θ×Ｉ”)⧴↧≔Ｍmχ”η÷×▷math.isqrt⁻×¹¹⁸×θθ×⁴⁸×θη⁺×Ｉ”)¶u⁰»～”θ×Ｉ”)¶↗v⌊Hq”ηθＩ”)″“▷←ι2⊖”¹

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
≔Ｘχ¹¹²θ

```

Effectively set the calculation precision to `112` digits after the decimal point by multiplying everything by `10¹¹²`.

```
≔▷math.isqrt⊗×θθη

```

Calculate the square root of `2` to that precision.

```
1.

```

Output the `1.` separately as it's easier.

```
✂Ｉ÷⁻⁻×Ｉ”...”θ×Ｉ”...”η÷×▷math.isqrt⁻×¹¹⁸×θθ×⁴⁸×θη⁺×Ｉ”...”θ×Ｉ”...”ηθＩ”...”¹

```

Calculate and output the `112` digits after the decimal point, using compressed strings for the large numbers.

~~105~~ ~~96~~ ~~81~~ ~~80~~ ~~72~~ 71 bytes by importing `sympy` and using a golfed version of @xnor's original sympy answer:

```
≔⁻⁸▷sympy.sqrt¹⁸θ≔∕×⁻×²⁰θ⁶¹⁺⁺⁶θＸ⁻×¹⁶θχ·⁵⁻×⁹⁶θ³²η▷sympy.N⟦∕∕⁺⁸η⁶⁺¹∕ηθ¹¹³

```

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

```
≔⁻⁸▷sympy.sqrt¹⁸θ

```

Save \\$ 8 - \sqrt { 18 } \\$ in a variable.

```
≔∕×⁻×²⁰θ⁶¹⁺⁺⁶θＸ⁻×¹⁶θχ·⁵⁻×⁹⁶θ³²η

```

Save \\$ \frac { 3 ( 33 - 20 \sqrt 2 ) ( 14 - 3 \sqrt 2 + \sqrt { 118 - 48 \sqrt 2 } ) } { 32 ( 23 - 9 \sqrt 2 ) } \\$ in a variable. \\$ 3 ( 33 - 20 \sqrt 2 ) = 20 ( 8 - \sqrt { 18 } ) - 61 \\$, \\$ 14 - 3 \sqrt 2 = 6 + 8 - \sqrt { 18 } \\$, \\$ 118 - 48 \sqrt 2 = 16 ( 8 - \sqrt { 18 } ) - 10 \\$ and \\$ 32 ( 23 - 9 \sqrt 2 ) = 96 ( 8 - \sqrt { 18 } ) - 32 \\$. Also, I can use `Power(, 0.5)` instead of `sympy.sqrt` on an expression based on \\$ \sqrt 2 \\$.

```
▷sympy.N⟦∕∕⁺⁸η⁶⁺¹∕ηθ¹¹³

```

Calculate the desired result.

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~69~~ ~~62~~ 57 bytes

Saved so many bytes thanks to the comment of @Greg Martin and the comment of @att

Try it online!

```
r=√2;4/3-1`99/(r+(7r-3-√(59-24r))(23/9-r)16/(33-20r))

```

# Answer
> 2 votes
# Ruby, 86 bytes

```
"%,}#:g6F.mR}}1o|7{n[TK%::,QFb`_xTj3br9F;As}^_2]S%}Soe()xyYB".bytes{|i|$><<(i-25)%100}

```

Try it online!

Prints `the digits of the decimal expansion, in any format.` I interpret that to mean the decimal point is not required. It would cost a few bytes to add it in.

This simply decodes the ASCII codes of each character in the magic string to a number between `35-25`=10 and `125-25`=100, takes a modulo to convert the `100` into `0` where necessary, and prints the output, concatenated.

# Answer
> 2 votes
# Python 3, 80 bytes

Obligatory compressed hardcoding method. See @xnor's answer for an actual mathematical computation.

```
print(1.2,*b'Zg%R^4-F\0VcbUB;2{!_@9%F_;QIY -"(Z\0EFD:x:VL_`@)',sep='')

```

Try it online!

# Answer
> 2 votes
# Nibbles, 50 bytes (100 nibbles)

```
"1."$ ~3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9

```

Attempt This Online!

Same approach as Neil's first Charcoal answer.
Nibbles can only handle integers, so outputting the initial `1.` and the decimal digits separately is essential.

# Answer
> 1 votes
# Python 3, 109 bytes

```
print(f"1.{0x3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9}")

```

Try it online!

Stores the decimal part in hex (thanks @xnor).

# Answer
> 1 votes
# Thunno 2 `j`, 52 bytes

```
»¥\!ĖẸæṭṙ|«ɦ⁾‘cạḍ¬ṣ“},ịḤ)ṣ3_ßịạ⁷ƇR×XẏṢḋyi¡ẹ¿pĿ⁴8»`1.

```

Try it online!

Just a compressed number with `1.` prepended.

# Answer
> 1 votes
# 05AB1E, 53 bytes

```
•4₅XÃ¯Máô|û¡Žü%ÔÖ7àþ}iÙ°fàp!LÙÔ‡ĀΣH₁ù¸ê_+0×B<È„u•„1.ì

```

Try it online.

**Explanation:**

Straight-forward hard-coded approach. 05AB1E also only has 16 bits floating point precision anyway.

```
•4₅XÃ¯Máô|û¡Žü%ÔÖ7àþ}iÙ°fàp!LÙÔ‡ĀΣH₁ù¸ê_+0×B<È„u•
      # Push compressed integer 2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441
„1.ì  # Prepend "1." in front of it
      # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand how the compression works.

# Answer
> 1 votes
# CellTail, 133 Bytes

```
I=1,219010337,829452184,570024869,930988566,595012333,319564573,717095598,126738932,453440900,697025685,812058867,615169596,6441;O=N;

```

Outputs as a list of numbers, starting with the integer component.

`I="Try it online!";O=C;`

# Answer
> 1 votes
# Jelly, 53 bytes

```
“µŻ5(_PṛØY⁺Ɲ>Ŀḣ¦ḲḶaİçẸẒḋƙ⁷\ø%Sfø*ḤÑ[F]€ȮĠṆ5]Ẇ⁶rȦ’⁾1.;

```

Try it online!

Straightforward hardcoding of the digits after the decimal point as a base-250 integer, then prepend "1."

Any calculation would have to be done using integers and fixed point arithmetic which is almost certainly longer than this.

Alternatively, Python and sympy can be used within Jelly. Here’s one version using @xnor’s Python code:

# Jelly, 99 bytes

```
“YSZprint(ZN((4-3/((7*Y-3-S59-24*Y))*(23-9*Y)*16/9/(33-20*Y)+Y))/3,113))“S2)“Zsqrt(“sympy.”ṣḢ$j¥/ŒV

```

Try it online!

And here’s an approach that uses sympy to solve the aquatic equation in the OEIS, as suggested by @UnrelatedString:

# Jelly, 113 bytes

```
“ẏ0P|Ẓ+“¥j^⁸øżk“½ÇṂY;Sṙ“®ẋ~⁽h`¹“£]iyi7ṭ’NÐeŒṘ“print(sympy.N(from_base(“,sympy.poly('x')).all_roots()[0],113))”jŒV

```

Try it online!

# Answer
> 0 votes
# Vyxal , 52 bytes

```
‛1.»⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9»

```

String sum magic! La la la!

Ties with Thunno 2 and Charcoal. This seems optimal.

Try it Online!

## Explanation

```
‛1.»⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9»
‛1.                                                   # The two character string "1.".
   »⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9»  # The compressed number 2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441.
# Due to some niece witchcraft, the Ṫ flag sums the string and the number to get the constant and then implicitly prints the result. String sum magic! La la la!

```

Created with the help of Luminespire.

# Answer
> 0 votes
# dc, 78 bytes

```
16iFFk594DB3BD338 2v474E23564B*-2v4BBEB1DE8*37B8DC90+76 2v30*-v*-41946AB7E96/p

```

It's a straight calculation, but with the constants specified in hexadecimal for brevity

Explanation:

```
16i                         # input in base 16
FFx                         # 255-digit precision
594DB3BD338 2v474E23564B*-  # 6136891429688 - 306253616715√2
2v4BBEB1DE8*37B8DC90+       # 934861968 + 20332617192√2
76 2v30*-v                  # √(118 - 48√2)
*-                          # complete the numerator
41946AB7E96/p               # divide by 4506606337686 and print

```

Output:

```
1.2190103378294521845700248699309885665950123333195645737170955981267\
389324534409006970256858120588676151695966441384905283150985491649927\
585413642430469766180971720219688119745626955249584071432721758804516\
12949021847336692342653120129739301327854858381983

```

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

```
a=>'1.'+0x3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9n

```

Try it online!

Quite but not completely trivial

---
Tags: code-golf
---


title: Number to String in aaaaa way!

text:
# Question
Title: Number to String in aaaaa way!
In this challenge, you are going to take a number and turn it into a string, but not in the common way. You will use the `aaaaa` way!

The `aaaaa` way is simply replacing each digit of the input number with the letter at that position in the alphabet. For example, `11111` would become `aaaaa` and `21223` would become `babbc`. If the number is less than 5 digits you need to left-pad it with an "A". For example, `12` would be `AAAab`.

## Rules

* Your code can be a function or a complete program that outputs to STDOUT.
* The returned string must be 5 letters.
* It's obvious that the input would be a 1 to 5 digits number that has digits from 1 to 9.
* You can get both input and output in number and strings or in array form like \[1,2,1,3,1\] and \['a','b','a','c','a'\].

---

## Test cases

```
In: 43213 -> Out: dcbac
In: 8645  -> Out: Ahfde
In: 342   -> Out: AAcdb
In: 99991 -> Out: iiiia

```

This is , so smallest program wins!

# Answer
> 14 votes
# Python, 44 bytes

```
lambda s:f"{s:05}".translate("bcdefghiAa"*9)

```

Attempt This Online!

Takes an integer and returns a string.

# Answer
> 9 votes
# JavaScript (ES6), 48 bytes

Expects an integer and returns a string.

```
f=(n,k=5)=>k?f(n/10|0,k-1)+"Aabcdefghi"[n%10]:''

```

Try it online!

---

# C (gcc), 48 bytes

```
k;f(n){k++>4?k=0:f(n/10)|putchar(n?n%10+96:65);}

```

Try it online!

## 47 bytes

This version was suggested by @jdt.

```
i;f(*o,x){for(i=5;i;x/=10)o[--i]=x?96+x%10:65;}

```

Try it online!

# Answer
> 7 votes
# C (clang), ~~69~~ ~~67~~ ~~63~~ 61 bytes

```
f(x,o,i)char*o;{for(memset(o,65,i=5);x;x/=10)o[--i]=x%10+96;}

```

Try it online!

# Answer
> 6 votes
# Japt, 9 bytes

Takes input as a string.

```
c+48 ù'A5

```

Try it

```
c+48 ù'A5     :Implicit input of string
c+48          :Map charcodes, adding 48 to each
     ù'A5     :Left pad with "A" to length 5

```

# Answer
> 6 votes
# Python 3, 50 bytes

```
lambda l:''.join(chr(96+i)for i in l).rjust(5,'A')

```

Takes a list of integers as input

Try it online!

# Answer
> 6 votes
# Factor, 29 bytes

```
[ >dec 48 v+n 5 65 pad-head ]

```

Attempt This Online!

-6 from chunes.

# Answer
> 6 votes
# Nibbles, 5 bytes (10 nibbles)

```
&"A"5+'`'

```

```
     +     # add each element of input
      '`'  # to '`' character
&          # then justify the text
 "A"       # using the "A" character
    5      # to a width of 5

```

# Answer
> 6 votes
# Fig, \\$14\log\_{256}(96)\approx\\$ 11.524 bytes

```
$t5$J*/A5OC+96

```

Try it online!

# Answer
> 5 votes
# Excel (ms365), ~~63~~ 61 bytes

-2 Thanks to @EngineerToast for 61 bytes:

```
=RIGHT(CONCAT("AAAA",CHAR(96+MID(A1,SEQUENCE(LEN(A1)),1))),5)

```

Or, the original answer for 63 bytes:

```
=CONCAT(MID("Aabcdefghi",MID(TEXT(A1,"00000"),ROW(1:5),1)+1,1))

```

---

Note that it can probably be done with less bytes if input is an array of numbers but thought I'd take a single integer as startpoint.

# Answer
> 5 votes
# Julia, 48 bytes

```
~x=replace(lpad(x,5,'A'),('1':'9'.=>'a':'i')...)

```

Attempt This Online!

# Julia 1.0, ~~67~~ 65 bytes

```
~x=getindex.([Dict(0:9 .=>['A';'a':'i'])],[0;0;0;0;x][end-4:end])

```

Try it online!

-2 bytes thanks to @MarcMush: replace `[[0,0,0,0];x]` with `[0;0;0;0;x]`

* Function is defined with the unary operater `~`
* The dictionary is wrapped in an array to allow passing multiple values.
* For padding, I concatenate a zero array and the input array. Only the last five elements `[end-4:end]` are used.

# Answer
> 5 votes
# sed, 42 bytes

```
y/123456789/abcdefghi/
:a
s/^.{,4}$/A&/
ta

```

Attempt This Online!

# Answer
> 4 votes
# POSIX Shell Command Language + Utilities, 26 bytes

```
printf %05d $1|tr 0-9 Aa-i

```

Self-explanatory: printf renders the argument padded to five columns with zeroes, then tr does the transformation per spec.

Transcript of test cases:

```
$ cat a.sh; echo; wc -c a.sh
printf %05d $1|tr 0-9 Aa-i
26 a.sh
$ ./a.sh 8645; echo
Ahfde
$ ./a.sh 43213; echo
dcbac
$ ./a.sh 8645; echo
Ahfde
$ ./a.sh 342; echo
AAcdb
$ ./a.sh 99991; echo
iiiia

```

# Answer
> 3 votes
# APL (Dyalog Extended), 13 bytes

Full program prompting for digit number list

```
'A'@=¯5↑⎕⊇⌊⎕A

```

Try it online!

`⎕A` uppercase **A**lphabet

Lowercase that

`⎕⊇` use the input to select from that (1-indexed)

`¯5↑` take the last 5 elements of that, adding padding elements on the left

`'A'` put "A"s where equal to the padding element

# Answer
> 3 votes
# Vyxal, 8 bytes

```
øA∑\A5ø↳

```

Try it Online!

Finally, a use for some of the more niche string digraphs. Takes input as a list of digits, outputs a single string.

## Explained

```
øA∑\A5ø↳
øA        # Get the nth letter of the alphabet for each digit in the input
  ∑       # Join as a single string
   \A     # Push the string "A" to the stack
     5    # Push the number 5 to the stack
      ø↳  # And left pad the single string from early with "A"s until it's 5 characters long

```

# Answer
> 3 votes
# Thon, 19 bytes

```
n"Aabcdefghi"b5"A"J

```

Input as a number (e.g. `824`). Output as a string (e.g. `AAhbd`).

**Explanation**

```
n"Aabcdefghi"b5"A"J
n                    // Input a number
 "Aabcdefghi"        // Push the string of letters
             b       // Convert the number to Base-"Aabcdefghi" (see below)
              5"A"J  // Fill with "A" up to 5 characters
                     // (implicit output)

```

Converting to base-`"Aabcdefghi"` is a trick to replace every `"1"` with `"a"`, every `"2"` with `"b"`, etc.

# Thon (Symbols), 16 bytes

(Note: this language is newer than the challenge)

```
)ş{í1-å`;}""]5AṚ

```

**Explanation**

```
)ş{í1-å`;}""]5AṚ
)                 // Create an empty list
 ş                // Get input as a string
  {      }        // For each character in the input:
   í              //   Convert to an integer
    1-            //   Subtract 1
      å`          //   Push the lowercase alphabet and get the character
        ;         //   Append to the list
          ""]     // Join the list by an empty string
             5AṚ  // Fill the string with "A" up to 5 characters
                  // (implicit output)

```

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
₃+>çΔ'Aš5.£

```

Input as a list of digits; output as a list of characters.
(If the inputs would have been 0-based (digits `0-9` mapping to `a-j`) instead of 1-based, the `>` could have been dropped.)

Try it online or verify all test cases.

Or alternatively:

```
5j9LðšA¬uì‡

```

Both input and output as a string.

Try it online or verify all test cases.

**Explanation:**

Unfortunately 05AB1E lacks a left-pad up to length builtin (unless by spaces), so most of the bytes are to account for that in the first program..

```
₃+>          # Add 96 to each value
   ç         # Convert each from a codepoint-integer to a character
    Δ        # Loop until the result no longer changes:
     'Aš    '#  Prepend an "A"
        5.£  #  Leave (up to) the last 5 characters from the list
             # (after which the result is output implicitly)

```

```
5j           # Left-pad the (implicit) input-string with spaces up to length 5
  9L         # Push list [1,2,3,4,5,6,7,8,9]
    ðš       # Prepend a space: [" ",1,2,3,4,5,6,7,8,9]
  A          # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
   ¬         # Push its first character (without popping): "a"
    u        # Uppercase it: "A"
     ì       # Prepend it: "Aabcdefghijklmnopqrstuvwxyz"
      ‡      # Transliterate the space-padded input from [" ",1,2,3,4,5,6,7,8,9] to
             # "Aabcdefghij..."
             # (after which the result is output implicitly)

```

# Answer
> 3 votes
# simply 0.11, 66 bytes

This abuses bugs in the parser, to save bytes.
It works with the commit 98783927a8a232b8e0afb46f380e02348b0f7cbb \- current commit at the time.
The behaviour will, VERY LIKELY, change in the future.

Creates an anonymous function that receives an array of numbers, and outputs the value.

```
fn($L){if$l=&len($L)<5for$_ in$l..4out'A'each$L as$i;out!ABCL[$i]}

```

## Example of usage:

This should output `"AAfcf"`.

```
$fn = fn($L){if$l=&len($L)<5for$_ in$l..4out'A'each$L as$i;out!ABCL[$i]}
call $fn([5,2,5]);

```

## How it works?

It simply checks the length of the array, and if it is lower than 5, it outputs 1 to 5 `'A'`s.

It goes from 0 to 4 because it uses a range operator.
Going from 4 to 4, is just 1 iteration - the number 4 itself.
Going from 0 to 4, is 5 iterations - the number 0, number 1, number 2, number 3 and number 4.

Then, it uses the pre-existing constant `!ABCL`, which contains the letters from `a` to `z`, in lowercase.
The values in the array are used as indexes into the constant.

## Ungolfed

Very code-y looking:

```
$fn = fn($list) => {
    $len = &len($list);
    if $len < 5 then {
        for $_ in $len..4 {
            echo 'A';
        }
    }

    foreach $list as $index {
        echo !ABCL[$index];
    }
};

```

Pseudo-code looking:

```
Set $fn to an anonymous function($list)
Begin.
    Set $len to the result of calling &len($list).
    In case $len < 5 then
    Begin.
        Loop from $len to 4 as $_
        Begin.
            Show the value 'A'.
        End.
    End.

    Loop through $list as $index
    Begin.
        Show the contents of !ABCL[$index].
    End.
End.

```

All versions do the exact same.

# Answer
> 3 votes
# MathGolf, 12 bytes

```
(h5,'A*\É▄\§

```

Input as a list of digits; output as string.

Try it online.

Or alternatively:

```
▄▒\(§y♫α'A═╡

```

Input as a list of digits; output as a string wrapped inside a list.

Try it online.

**Explanation:**

```
(        # Decrease each digit in the (implicit) input-list by 1
         # (because MathGolf uses 0-based indexing)
 h       # Push the length of the list (without popping)
  5,     # Calculate 5-length
    'A* '# Repeat "A" that many times
 \       # Swap so the list as at the top again
  É      # For-each over the digits, using 3 characters as inner code-block:
   ▄     #  Push the lowercase alphabet
    \    #  Swap so the current digit is at the top
     §   #  Index the digit into the alphabet
         # (after which the entire stack joined together is output implicitly as result)

```

```
▄        # Push the lowercase alphabet
 ▒       # Convert it to a list of characters
  \      # Swap so the (implicit) input-list is at the top
   (     # Decrease each digit by 1 (because MathGolf uses 0-based indexing)
    §    # Index each digit in the list into the alphabet list
     y   # Join it back together again
♫        # Push 10000
 α       # Pair it with the earlier string
  'A═   '# Pad both to an equal length by left-padding with "A"
     ╡   # Remove the last item from the pair (the 10000)
         # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 3 votes
# Retina 0.8.2, 21 bytes

```
T`d`_l
^
AAAA
!`.{5}$

```

Try it online! Link includes test cases. Explanation:

```
T`d`_l

```

Translate digits to lowercase letters.

```
^
AAAA

```

Prefix four `A`s.

```
!`.{5}$

```

Take the last 5 letters.

A port of @Jiří's sed answer is also 21 bytes:

```
T`d`_l
+`^.{0,4}$
A$&

```

Try it online! Link includes test cases.

# Answer
> 3 votes
# BQN, ~~17~~ 15 bytes

*Edit: -2 bytes thanks to Razetime*

```
¯5↑"AAAA"∾+⟜'`'

```

Try it at BQN REPL

```
          +⟜'`'     # add each element of input to the '`' character
         ∾          # join this to
   "AAAA"           # "AAAA" (shorter than (5⥊'A'))
_5↑                 # take -5 elements
                    # (which takes 5 elements from the end)

```

# Answer
> 3 votes
# brainfuck, 64 bytes

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

```

Try it online!

## Explanation

```
>>>>>+>

```

Move to position 5, make the value there 1, and move to position 6.

```
,[>,]

```

Read the digits into consecutive positions from there onward.

```
<<<<<<

```

Move 6 positions to the left. From here, each 0 before the 1 in position 5 indicates an `A` to be output.

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

```

Subtract 1. Loop while it's not 0 (thus was not 1):

* Subtract 3 more, making −4.
* Loop subtracting 4 and adding 1 to the left, producing (256-4)/4=63 in the cell to the left.
* Move left, add 2 more for 65, and output that (`A`).
* Move right twice, for a net movement of 1 to the right, and subtract 1 (and repeat).

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

```

Move right. Loop while it's not 0 (over all the digits):

* Move left and subtract 1, making −1.
* Loop subtracting 5 and adding 1 to the right, adding (256-1)/5=51 to the digit's character code.
* Move right and subtract 3, for a net +48 to the digit's character code. 48 is the difference between `1` and `a`, and likewise for the other digits (as both digits and letters are contiguous in ASCII).
* Output the letter produced from the digit.
* Zero that position (as it will be reused in the next iteration) and move right (and repeat).

# Answer
> 3 votes
# , 38 bytes

```
\(d)intToUtf8(tail(c(!1:5,d+31),5)+65)

```

Attempt This Online!

Takes input as a vector of digits, outputs a string.

# Answer
> 3 votes
# Python,  ~~42~~  41 bytes

-1 thanks to loopy walt's suggestion to use XOR, `^`, instead of addition.

```
lambda a:[chr(96^d)for d in[33]*5+a][-5:]

```

An unnamed function that accepts a list of integers from \\$\[1,9\]\\$ and returns a list of characters.

**Try it online!**

# Answer
> 3 votes
# Pyth, 9 bytes

```
.[\A5m@Gt

```

Test suite

This answer uses a sufficiently different approach from the existing Pyth answer(s).

##### Explanation:

```
.[\A5m@Gt   | Full code
.[\A5m@GtdQ | with implicit variables
------------+----------------------------------------------------
     m    Q | Replace each number d in the input with
      @G    |  the character of the lowercase alphabet with index
        td  |  d minus 1
.[\A5       | Pad the array on the left with A to a length of 5

```

# Answer
> 3 votes
# K (ngn/k), 13 bytes

```
"A"^-5$`c$96+

```

Try it online!

* ``c$96+` convert input of digits to corresponding letters
* `-5$` left-pad to length 5 with spaces
* `"A"^` fill spaces with "A" (and implicitly return)

# Answer
> 2 votes
# Ruby, 37 bytes

-3 bytes thanks to Dingus

```
->a{a.map{''<<_1+96}.join.rjust 5,?A}

```

Attempt This Online!

# Answer
> 2 votes
# Pyth, 18 bytes

```
V-5lzp"A")Vzp@GtsN

```

Try it online!

### Explanation

```
V-5lzp"A")Vzp@GtsN
V                   # For loop with N as variable
    z               # Input
   l                # Length
 -5lz               # Subtract length of input from 5
     p"A"           # Prints "A"
         )          # End of for loop
            p       # Print without any additional newline
              G     # Initialized to "abcdefghijklmnopqrstuvwxyz"
                sN  # Cast N to an integer
               t    # Subtract 1
             @      # Get element at index

```

# Answer
> 2 votes
# Charcoal, 13 bytes

```
✂⁺×⁴A⭆Ｓ§β⊖ι±⁵

```

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

```
    A           Literal string `A`
  ×             Repeated
   ⁴            Literal integer `4`
 ⁺              Concatenated to
      Ｓ         Input as a string
     ⭆          Map over digits
        β       Predefined variable lowercase alphabet
       §        Indexed by
          ι     Current digit
         ⊖      Decremented
✂               Sliced from
            ⁵   Literal integer `5`
           ±    Negated

```

# Answer
> 2 votes
# PowerShell, 39 bytes

```
-join($args|%{[char](96+$_)})|% *ft 5 A

```

Try it online!

Takes integers as unnamed arguments. Nothing fancy, just adds 96 to get to the ASCII code of 'a', casts to a char, joins the chars to a string, then pipes the string to % (an alias for ForEach-Object), which will call the string's member "PadLeft". Output is implicit.

# Answer
> 2 votes
# J-uby, 34 bytes

I think I’m finally starting to get the hang of J-uby. A few bytes shorter than my Ruby answer.

```
:*&(:+&96|:chr)|:join|~:rjust&?A&5

```

Attempt This Online!

# Answer
> 2 votes
# Perl 5 `-plF`, 24 bytes

```
$_=A x(5-@F).y/1-9/a-i/r

```

Try it online!

# Answer
> 2 votes
# Pyth, ~~14~~ ~~13~~ 12 bytes

```
@L+\AG+mZ-5l

```

Try it online!

**Explanation:**

```
@L+\AG+mZ-5l # whole program

             # implicit output
 L           # left map with lambda d:
@            # using index
  +          #  concatenate
   \A        #   literal "A"
     G       #   and literal "abc...xyz"
      +      # into a concatenation of:
       mZ    #  a constructed list of n zeroes
             #   where n is: (the 2nd argument for m is supplied an int)
         -5  #    the difference of 5
           l #    and the length of implicit input (Q)
             #  and the implicit input (Q)

```

# Answer
> 2 votes
# Red, 62 bytes

```
func[s][forall s[s/1: #"`"+ s/1]pad/left/with rejoin s 5 #"A"]

```

Try it online!

# Answer
> 2 votes
# Red, 50 bytes

```
func[v][insert/dup v 17 5 take/last/part v + 48 5]

```

Try it online!

Takes input as a vector of code points and returns output as the same.

* `insert/dup v 17 5` Insert five 17s at the beginning
* `v + 48` Add 48 to each element
* `take/last/part v 5` Take the last five elements

# Answer
> 2 votes
# Raku, 31 bytes

```
{TR/0..9/Aa..i/}o*.fmt('%05d')

```

Try it online!

`*.fmt('%05d')` is an anonymous function that formats its integer argument to five digits, padded on the left with zeroes. `{ TR/0..9/Aa..i/ }` is a second anonymous function that transliterates its string argument, turning 0 into A and 1-9 into a-i. The `o` operator composes those two functions.

# Answer
> 2 votes
# Rust, 67 bytes

```
|a|format!("{:A>5}",a.map(|d|char::from(d+96)).collect::<String>())

```

Try it online!

# Answer
> 2 votes
# C++ (gcc), ~~142~~ ~~138~~ 137 bytes

-4 thanks to @ceilingcat.

First time golfing in C++, there are probably many places where improvements could be made. `#include <bits/stdc++.h>` was really expensive in terms of bytes.

```
#include<bits/stdc++.h>
int f(int n){for(int i=5;i--;){putchar(((n%(int)exp10(i+1))/(int)exp10(i))?(n%(int)exp10(i+1))/exp10(i)+96:65);}}

```

Try it online!

Takes integer inputs and outputs as string.

# Answer
> 2 votes
# C#, 43 bytes

```
x=>x.PadLeft(5,'').Select(y=>(char)(y+48))

```

represents the character with code `17`; `48` is added to this to produce `A`.

Try it online!

# Answer
> 2 votes
# Elixir, 41 bytes

```
&for<<x<-String.rjust(&1,5,17)>>,do: x+48

```

Try it online!

# Answer
> 2 votes
# x86-16 machine code, ~~20~~ 17 bytes

```
00000000: fcb8 4141 abab fd03 f14e ac04 30aa e2fa  ..AA.....N..0...
00000010: c3

```

Callable function, custom calling convention. Input string at `DS:[SI]`, `CX` = input string length (1-5), output string buffer at `ES:[DI]`.

Listing:

```
FC          CLD                 ; string direction forward
B8 4141     MOV AX, 'AA'        ; AL and AH = pad char
AB          STOSW               ; pad only first 4 chars
AB          STOSW
FD          STD                 ; string direction reverse
03 F1       ADD  SI, CX         ; SI = end of input string
4E          DEC  SI             ; SI = last char of input
    A_LOOP:
AC          LODSB               ; load next char
04 30       ADD  AL, 'a'-'1'    ; aaaaaa convert
AA          STOSB               ; write to output
E2 FA       LOOP A_LOOP
C3          RET                 ; return to caller

```

#### Test program output:

**Props:** -3 bytes thx to @l4m2!

# Answer
> 2 votes
# \>\<\>, ~~17~~ 16 bytes

```
r5l6=.a7+!
68*+o

```

Try it online

**Explanation**

```
r        !    # reverse stack on first iteration
 5l6=.        # if stack length is 5, move to next row
      a7+     # else add 17 to stack
68*+o         # add 48 to each item on stack and print as char

```

# Answer
> 2 votes
# k, 18 bytes

```
"A"^-5$10h$96+10\:

```

# Answer
> 2 votes
# Uiua, ~~11~~ ~~10~~ 9 bytes

```
⬚@A↙¯5+@`

```

Try it!

* -1 byte from Dominic van Essen
* -1 byte from Bubbler

```
 ⬚@A↙¯5+@`
       +@`  # add backtick character
 ⬚@A↙¯5     # take the last five characters, filling any excess with A

```

# Answer
> 1 votes
# Ly, 25 bytes

```
iry5L[f5f-['Ao,]]pp['0+o]

```

Try it online!

Pretty straight forward reading of the rules...

```
ir                        - read the digits in a codepoints, reverse stack
  y5                      - push digit count, push "5"
    L                     - check: digitCount<5
     [          ]pp       - exec block if digit count < 5
      f5f-                - subtract digit count from 5, get pad count
          [   ,]          - loop once for each pad digit...
           'Ao            - print "A"
                   [    ] - loop or all the codepoints on the stack
                    '0+   - convert from 0-9 to a-i
                       o  - print as character

```

# Answer
> 1 votes
# Jelly, 15 bytes

```
DịØa;@”Ax5¤Uḣ5U

```

Try it online!

Almost certainly I'm missing some atoms or syntax tricks that can get this down further. 11 bytes are spent to handle the padding.

Explanation:

```
DịØa;@”Ax5¤Uḣ5U
D               get decimal representation
 ịØa            index into lowercase alphabet
      ”Ax5¤     repeat "A" 5 times
    ;@          prepend "A"s to the other string
           Uḣ5U take the last 5 characters

```

# Answer
> 1 votes
# , 29 bytes

There probably is a shorter way (perhaps with `a.`) than a hard-coded string mapping, but everything I tried ended up being longer.

```
'Aabcdefghi'{~],~[:0"0[:i.5-#

```

Try it online!

Takes input as array of numbers and outputs a string.

# Answer
> 1 votes
# Knight (v2), 41 bytes

```
;=iP;=s*'A'5;Wi;=s+sA+96[i=i]iO Gs-Ls 5 5

```

Try it online!

# Answer
> 1 votes
# Ruby `-nl`, 28 bytes

```
p$_.rjust(5).tr" 1-9","Aa-i"

```

Attempt This Online!

# Answer
> 1 votes
# Arturo, ~~62~~ 45 bytes

```
$[s][pad.with:`A`join map s=>[to :char 96+]5]

```

Try it

# Answer
> 1 votes
ultra verbose `awk` solution:

```
echo '43213
8645
342
99991' |

```

> ```
> awk '$!NF=sprintf("%c%c%c%c%c",___+(__+$(_=($(_<_)=sprintf("%.*d%s",5-NF,
>          _=_<_,$_))^_))^!!$_,___+(__+$++_)^!!$_,(__+$++_)^!!$_+___,
>         ___+(__+$++_)^!!$_,___+(__+$++_)^!!$_)' __=32 ___=64 FS=
>
> ```

```
dcbac
Ahfde
AAcdb
iiiia

```

# Answer
> 1 votes
# Thunno 2, 7 bytes

```
ÄLJ'A5ṙ

```

Try it online!

#### Explanation

```
ÄLJ'A5ṙ  '# Implicit input
Ä         # Number to alphabet
 L        # Lowercase each
  J       # Join into a string
   'A    '# Using "A" as a filler,
     5ṙ   # pad the string to length 5
          # Implicit output

```

# Answer
> 1 votes
# Rust, 110 bytes

Takes the number and returns the converted string in the aaaaa way.

```
|x:u64|"A".repeat((4-x.ilog(10))as _)+&x.to_string().bytes().fold(format!(""),|mut s,b|{s.push((48+b)as _);s})

```

Attempt This Online!

# Rust, 93 bytes

Returns a byte slice, i.e. `Vec<u8>` instead that corresponds to the ASCII-encoded aaaaa string.

```
|x:u64|{let mut v=vec![65;(4-x.ilog(10))as _];v.extend(x.to_string().bytes().map(|b|48+b));v}

```

Attempt This Online!

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