title: Spell out an integer... in NDos' way

text:
# Question
Title: Spell out an integer... in NDos' way
# Objective

Given a **positive** integer, spell it out in the conlang I made.

# Specification

Let \\$n\\$ be the inputted integer. \\$n\\$ shall be spelled out in the following specification. **The entire spelling is case sensitive.**

With the decimal expansion of \\$n\\$, let **d** be the least significant nonzero digit of \\$n\\$.

First, **d** shall be spelled out like this:

* 1 = `Qun`
* 2 = `Pis`
* 3 = `Tel`
* 4 = `Kal`
* 5 = `Pan`
* 6 = `Soh`
* 7 = `Set`
* 8 = `Qok`
* 9 = `Nof`

Second, an appropriate suffix (or a "particle" in linguistic sense?) will immediately follow. This is judged by two boolean conditions: (A) Whether **d** has any trailing zeros, and (B) whether **d** is ***not*** the only nonzero digit.

* If neither holds, the suffix shall be `em`.
* If only (A) holds, the suffix shall be `eh`.
* If only (B) holds, the suffix shall be `at`.
* If both hold, the suffix shall be `om`.

Third, if (A) held, the length of the trailing zeros shall be spelled out recursively.

Finally, if (B) held, **d** and the trailing zeros shall be stripped off, and the remaining digits shall be spelled out recursively.

All words shall be intercalated by a single ASCII 0x20 whitespace.

# Examples

* 1 = `Qunem`
* 2 = `Pisem`
* 7 = `Setem`
* 10 = `Quneh Qunem`
* 11 = `Qunat Qunem`
* 12 = `Pisat Qunem`
* 19 = `Nofat Qunem`
* 20 = `Piseh Qunem`
* 42 = `Pisat Kalem`
* 69 = `Nofat Sohem`
* 100 = `Quneh Pisem`
* 109 = `Nofat Quneh Qunem`
* 440 = `Kalom Qunem Kalem`
* 666 = `Sohat Sohat Sohem`
* 1945 = `Panat Kalat Nofat Qunem`
* 2000 = `Piseh Telem`
* 2022 = `Pisat Pisat Piseh Qunem`
* 44100 = `Qunom Pisem Kalat Kalem`
* 144000 = `Kalom Telem Kalat Qunem`
* \\$10^{60}\\$ = `Quneh Soheh Qunem`
* \\$10^{63}\\$ = `Quneh Telat Sohem`

# Rules

I/O format is flexible. Standard loopholes apply.

As for input, those that are not positive integers fall in *don't care* situation.

As for output, trailing whitespaces are permitted, but leading whitespaces are not.

# Ungolfed solution

## Haskell

```
import Data.List
import Numeric.Natural

spellNDos :: Natural -> String
spellNDos 0 = ""
spellNDos n = go (reverse (show n)) where
    go "" = ""
    go str = let
        (zeros, digit:remaining) = partition ('0'==) str
        digitSpell = case digit of
            '1' -> "Qun"
            '2' -> "Pis"
            '3' -> "Tel"
            '4' -> "Kal"
            '5' -> "Pan"
            '6' -> "Soh"
            '7' -> "Set"
            '8' -> "Qok"
            _   -> "Nof"
        suffix = case (null zeros, null remaining) of
            (False, False) -> "om "
            (False, _    ) -> "eh "
            (_    , False) -> "at "
            _              -> "em "
        in digitSpell ++ suffix ++ spellNDos (genericLength zeros) ++ go remaining

```

# Answer
> 1 votes
# Jelly, 71 bytes

```
Dœṗ`ḊĖF€ṚµḢỊ;ȦḄị“ðỌÇƭḌ€h»s2¤ṭḢị“÷mƬ@wƇ75Ẉ⁸f0¦mḃ⁾æÑdṛƁ/.ⱮṾ»s3¤Ɗ,Lß$K⁸¡)K

```

A full program that accepts a positive integer and prints the result

**Try it online!** Or see the test-suite.

### How?

```
Dœṗ`ḊĖF€ṚµḢỊ;ȦḄị“...»s2¤ṭḢị“...»s3¤Ɗ,Lß$K⁸¡)K - Main Link: positive integer, N
D                                             - decimal digits of N
   `                                          - use as both arguments of:
 œṗ                                           -   partition before truthy indices
    Ḋ                                         - dequeue (remove leading empty list)
     Ė                                        - enumerate (e.g. [a,b,c]->[[1,a],[2,a],[3,c]])
      F€                                      - flatten each
        Ṛ                                     - reverse
         µ                                 )  - for each "Part":
          Ḣ                                   -   head (i.e. the original index) - Note: this removes it too
           Ị                                  -   is insignificant (i.e. are we dealing with the final d? = NOT B)
             Ȧ                                -   any and all? (0 if any zeros else 1 = NOT A)
            ;                                 -   concatenate -> [NOT B, NOT A]
              Ḅ                               -   from binary -> 2(NOT B)+(NOT A)
                       ¤                      -   nilad followed by link(s) as a nilad:
                “...»                         -     "atehemom"
                     s2                       -     split into twos -> ["at","eh","em","om"]
               ị                              -   index into -> appropriate suffix
                                   Ɗ          -   last three links as a monad - f(
                         Ḣ                    -     head -> d - Note: again, this removes it too
                                  ¤           -     nilad followed by link(s) as a nilad:
                           “...»              -       "QunPisTelKalPanSohSetQokNof"
                                s3            -       split into threes -> ["Qun","Pis","Tel","Kal","Pan","Soh","Set","Qok","Nof"]
                          ị                   -     index into -> appropriate prefix
                        ṭ                     -   tack -> [prefix,suffix]
                                       $      -   last two links as a monad - f(Part):
                                     L        -     length (number of trailing zeros, since we've removed the index and d)
                                      ß       -     call this Link (the whole Main Link)
                                    ,         -   pair -> [current, recursed]
                                          ¡   -   repeat...
                                         ⁸    -   ...times: chain's left argument - treated as True if we have zeros
                                        K     -   ...action: join with space characters
                                            K - join with space characters
                                              - implicit, smashing print

```

# Answer
> 6 votes
# Python 3.8 (pre-release), 172 bytes

```
f=lambda n:(d:=n.strip('0'))and' QPTKPSSQNuieaaoeoonsllnhtkf'[int(l:=d[-1])::9]+'eeaomhtm'[(t:=n!=d)+1%len(d)*2::4]+(' '+f(str(N:=n[::-1].find(l))).strip())*t+' '+f(n[:~N])

```

Try it online!

Straightforward implementation of the specification.

Input a string. Makes use of string indexing and various other tricks to simplify finding the least significant digit and removing digits. This makes the task much easier to accomplish because with numbers, one would have to perform messy tasks such as dividing by powers of 10 or using the `%` operator to "index into the number", and because of this difficulty it is golfier to convert the number to a string then perform some indexing. Then I thought, "Why not just use a string for the input?" and the code was thus shortened by 25 bytes, maybe more.

Thanks @ovs for -2 bytes.

# Answer
> 4 votes
# Charcoal, 86 bytes

```
⊞υＮＷυ«≔⊟υι¿ι«≔⌕⮌÷¹⊕↨ιχ⁰θ≧÷Ｘχθι§⪪”↶0ＯＰ⊘ηS℅ê*k⮌⁰nI¿'⊗ξ!»NV”³ι≧÷χι⊞υι⊞υθ¿θ¿ιom¦eh¿ιat¦em→

```

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

```
⊞υＮＷυ«

```

Start processing with the input value.

```
≔⊟υι¿ι«

```

If the current value to process is zero then ignore it and continue on to the next value.

```
≔⌕⮌÷¹⊕↨ιχ⁰θ≧÷Ｘχθι

```

Find the number of trailing zeros in the current value and remove them.

```
§⪪”↶0ＯＰ⊘ηS℅ê*k⮌⁰nI¿'⊗ξ!»NV”³ι

```

Output the prefix corresponding to the last nonzero digit.

```
≧÷χι

```

Divide the value by `10` again.

```
⊞υι⊞υθ

```

Push the final value and the number of trailing zeros to the list so that they get processed.

```
¿θ¿ιom¦eh¿ιat¦em→

```

Output the appropriate suffix and allow a space before any other output.

# Answer
> 2 votes
# 05AB1E, 72 bytes

```
"SDĀÅ¡¦ηRεDg≠UθćsgV.•¿Õ¾¸”mÚÄú±pE”¿м∍•3ôsè™.•DĀ€y‹•2ôYĀX«Cè«Y®.V‚"©.V˜ðý

```

Try it online or verify all test cases.

**Explanation:**

```
"..."           # Push the recursive string explained below
     ©          # Store it in variable `®` (without popping)
      .V        # Execute it as 05AB1E code
        ˜       # Flatten the resulting list
         ðý     # Join this list with space delimiter)
                # (after which the result is output implicitly)

S               # Convert the current value to a list of digits
                # (which will be the implicit input in the first iteration)
 D              # Duplicate this list of digits
  Ā             # Check for each digit if it's non-0
   Å¡           # Split the list of digits at the truthy (non-0) indices
     ¦          # Remove the leading empty list
                #  (e.g. "20230050" → [[2,0],[2],[3,0,0],[5,0]])
η               # Get the prefixes of this list
 R              # Reverse it
  ε             # Map over each prefix-list:
   D            #  Duplicate the current list of lists
    g           #  Pop the copy, and push its length
     ≠          #  Check that this length is NOT 1
      U         #  Pop and store this in variable `X`
    θ           #  Pop and push the final digit-list from the current prefix
     ć          #  Extract head; pop and push first item and remainder-list
                #  separately
      s         #  Swap so the remainder-list of 0s is at the top
       g        #  Pop and push its length (to get the amount of 0s)
        V       #  Pop and store this in variable `Y`
      .•¿Õ¾¸”mÚÄú±pE”¿м∍•
                #  Push compressed string "nofqunpistelkalpansohsetqok"
        3ô      #  Split it into parts of size 3
          s     #  Swap so the extracted head is at the top
           è    #  (Modular 0-based) index it into the list of triplets
            ™   #  Titlecase it
    .•DĀ€y‹•    #  Push compressed string "ematehom"
      2ô        #  Split it into parts of size 2
        YĀ      #  Push `Y` (amount of 0s), and check if it's NOT 0
          X«    #  Append `X` (prefix_length != 1)
            C   #  Convert it from binary to an integer
                #  (0 if X=0,Y=0; 1 if X=0,Y=1, 2 if X=1,Y=0, 3 if X=1,Y=1)
             è  #  Index that into the list of pairs
              « #  Append the two strings together
    Y           #  Push `Y` (amount of 0s) again
     ®.V        #  Do a recursive call with this as argument
        ‚       #  Pair the result together with the string

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•¿Õ¾¸”mÚÄú±pE”¿м∍•` is `"nofqunpistelkalpansohsetqok"` and `.•DĀ€y‹•` is `"ematehom"`.

# Answer
> 2 votes
# JavaScript (ES6),  ~~148 145~~  144 bytes

Expects the input integer as a string.

```
f=s=>x=s.replace(/[^0]0*/g,q=>s=b[+q[0]+3]+b[!s+2*!f(q.length-1+'')]+' '+x+s,s="",b="omehatemQunPisTelKalPanSohSetQokNof".match(/[A-Z]?../g))&&s

```

Try it online!

### How?

We first extract all suffixes and prefixes from the string `"omehatemQunPis...Nof"` into the array `b[]`, using the regular expression `/[A-Z]?../g`.

```
f =              // f is a recursive function taking
s =>             // a string s
x =              // the final result is saved in x
s.replace(       // look for all digit groups consisting of
  /[^0]0*/g,     // a non-zero digit followed by 0 to N zeros
  q =>           // for each such group q:
    s =          //   update s:
    b[           //     append the prefix according to
      +q[0] + 3  //     the leading non-zero digit
    ] +          //
    b[           //     append the suffix according to
      !s +       //     whether this is the leading group
      2 * !f(    //     and whether there's at least one zero,
        q.length //     which is deduced from the result of a
        - 1      //     recursive call with the number of 0's
        + ''     //     coerced to a string
      )          //
    ] +          //     append:
    ' ' +        //       - a space
    x +          //       - the result of the recursive call
    s,           //       - the previous value of s
    s = ""       //     start with an empty string
)                // end of replace()
&& s             // return s

```

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


title: Tips for golfing in BQN

text:
# Question
Title: Tips for golfing in BQN
What general tips do you have for golfing in BQN? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to BQN (e.g. "remove comments" is not an answer).

Please post one tip per answer.

At the moment of writing, the official BQN site is the most comprehensive resource for learning BQN. BQN is the Language of the Month for December 2021; you can find some more information and resources on the LotM page.

Additional resources:

# Answer
> 6 votes
# Use `⊒˜` instead of `↕∘≠`

Suggested by Marshall

(progressive index of) consumes indices given any array, providing a range of the array's size when applied with selfie. You can save a byte by using it in any place instead of `↕∘≠`.

Try it!

# Answer
> 5 votes
# BQN's combinators

BQN allows Lisp style functional programming and hence comes with its own set of combinator symbols. Some basic patterns can be simplified using combinators instead of trains:

| Lambda | Train | Combinator |
| --- | --- | --- |
| `{ F }` | `⊢ F ⊢` |  |
| `{F G }` | `F G` | `F∘G`, `F○G` |
| `{ F (G )}` | `⊢ F G` | `F⟜G` |
| `{(F ) G }` | `F G ⊢` | `F⊸G` |
| `{ F }` | `⊢ F ⊣` | (See: this APL tip, replace  with `˜`) |
| `{F G }` | `F G` | `F∘G` |
| `{(G ) F (G )}` | `G F G` | `F○G` |
| `{( F ) G ( H )}` | `F G H` | `F⊸G⟜H` |

You can use the shorter one between the train and the combinator versions wherever necessary, and sometimes in conjunction.

For a more visual explanation of the combinators, see here

# Answer
> 4 votes
# Don't forget about `¬`

BQN doesn't have increment and decrement primitives, which means you're often spending two bytes on `1+`, or potentially three on `¯1+`. Sometimes `¬` can help:

* Monadic `¬` ("not") is logical negation, but it's actually implemented as `1-`.
* Dyadic `¬` ("span") is even more interesting: it's `1+-`.

These can save bytes under some specific circumstances. For instance, if you need to decrement the result of an expression, `-¬aFb` is shorter than `¯1+aFb`. Similarly, `a¬-b` is shorter than `a+1+b`, and `a-¬b` is shorter than `a-1+b`. If you need to multiply a number by 2 and add 1, `¬⟜-` is equivalent to `1+2×⊢`.

This is similar to the use of `~` in C-like languages (although there, `~x` is `-x-1`, not `1-x`).

---
Tags: code-golf, tips
---


title: Shift a string gradually

text:
# Question
Title: Shift a string gradually
Given an input string and a wrapping string, find the location of the first input string char in the wrapping string and replace it with the wrapping string char 1 step to the right of that, find the second char in the wrapping string and replace it with the char 2 steps to the right, find the third and replace it with the char 3 steps to the right, and so on. If there are not enough chars in the wrapping string, wrap around.

The wrapping string does not have duplicates and the input string will always be made of chars in the wrapping string.

# Reference implementation

```
s, wrap = input(), input()
n = 1
res = ""
for char in s:
    res += wrap[(wrap.index(char) + n) % len(wrap)]
    n += 1

print(res)

```

# Test Cases

```
abc abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => bdf

xyz abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => yAC

ZZZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => abc

<empty string> <empty string> => <empty string>

abcdefg abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => bdfhjln

123 0123456789 => 246

121212 12 => 222222

```

# Scoring

This is code golf, so the shortest answer wins!

# Answer
> 5 votes
# Jelly,  ~~7~~  6 bytes

Thanks to @ovs for suggesting looking at swapping the argument order and hence saving a byte!

```
J+i@€ị

```

A dyadic Link that accepts the instruction on the left and the wrapping characters on the right and yields a list of characters.

**Try it online!**

### How?

```
J+i@€ị - Link: instruction, I; wrapping characters W
J      - range of length of I -> [1,2,3,...,length(I)]
    €  - for each c in I:
   @   -   with swapped arguments - f(W, c):
  i    -    first index of c in W
 +     - add together -> [index(i1 in W)+1,index(i2 in W)+2,...]
     ị - index into W (modular)

```

# Answer
> 5 votes
# , 14 bytes

```
[{~#@[|i.+#\@]

```

Try it online!

# Answer
> 5 votes
# Pip, 15 bytes

```
(b(b@?B)+U_MEa)

```

Takes the two strings as command-line arguments. Attempt This Online!

### Explanation

```
(b(b@?B)+U_MEa)
             a   First command-line arg
           ME    Enumerate and map this function to each index, character pair:
   b               Second command-line arg
    @?B            Find index of character
  (    )+          To that, add
         U_        One plus the index from map-enumerate
(b            )  Use each of the resulting numbers to index into 2nd cmdline arg
                 Autoprint, joined together (implicit)

```

# Answer
> 4 votes
# , ~~41~~ 40 bytes

```
\(s,w)rep(w,l<-sum(s|1))[match(s,w)+1:l]
```

Attempt This Online!

Takes input and outputs as vectors of char codes.

**Explanation outline:**

* `match` finds positions of the elements from `s` in the wrapping string `w`.
* We add a sequence from 1 to the length of `s` to account for "gradually" in the challenge.
* We need to index that to `w` with wrapping: using modular arithmetic or repeating `w` sufficiently many times - the latter turns out shorter.

# Answer
> 4 votes
# APL (dzaima/APL), 10 bytes

Tacit function taking the wrapping string on the left.

```
⍳⊃¨⌽⍨ᑈ∘⍳∘≢

```

Try it online!

`⍳∘≢` Indices from 1 to the length of the right argument.
`⌽⍨ᑈ` For each of those numbers, rotate the wrapping string by that amount. This gives a copy of the wrapping string for each character in the right argument, each rotated one further.

Indices of the right argument in the wrapping argument.
`⊃¨` Use each of these indices to pick a char from a rotated copy of the wrapping string.

Would be 12 bytes without dzaima/APL's each-right: `⍳⊃¨{⌽∘⍺¨⍳≢⍵}`.

# Answer
> 3 votes
# SNOBOL4 (CSNOBOL4), ~~120~~ 116 bytes

```
	W =DUPL(INPUT,SIZE(I =INPUT))
N	I POS(P) @Q LEN(1) . X @P	:F(O)
	W X LEN(Q) LEN(1) . R
	O =O R	:(N)
O	OUTPUT =O
END

```

Try it online!

Takes input as Wrapping String, then Input string, separated by a newline.

Slightly outdated explanation (algorithm is basically the same, though):

```
	I =INPUT			;* input string
	W =DUPL(INPUT,SIZE(I))		;* wrapping string: duplicated length(I) times
N	I POS(P) LEN(1) . X @P	:F(O)	;* match the next character in I as X (and its position as P), and on failure goto O
	W X LEN(P - 1) LEN(1) . R	;* In W, match X, then P - 1 characters, then 1 character as R
	O =O R	:(N)			;* append R to O and goto N
O	OUTPUT =O			;* print (with a newline)
END

```

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

Expects `(p)(q)`, where `p` is an array of characters and `q` is a string. Returns an array of characters.

```
p=>q=>p.map((c,i)=>(q+=q)[q.indexOf(c)-~i])

```

Try it online!

# Answer
> 3 votes
# Python 3.8 (pre-release), 60 bytes

```
f=lambda i,w,l=1:i and(w+w)[l+w.find(i[0])]+f(i[1:],w+w,l+1)

```

Try it online!

Improved recursive solution by @tsh

## 69 bytes

```
lambda i,w,o='':([(o:=o+(w:=2*w)[len(o)-~w.find(a)])for a in i],o)[1]

```

Try it online!

Takes 2 strings as input, outputs a string.

# Answer
> 3 votes
# BQN, ~~27~~ ~~23~~ ~~19~~ 16 bytes

```
(1+⊐+⊒˜∘⊢)⊏+○≢⥊⊣

```

Anonymous function; takes the wrapping string as left argument and the input string as right argument.

Try it at BQN online

# Answer
> 3 votes
# 05AB1E, 4 bytes

```
kā+è

```

I/O as a list of characters. (The wrapped string input can be either a string or list of characters, doesn't really matter.)

Try it online or verify all test cases.

**Explanation:**

```
      #  e.g. inputs: ["a","b","j"], "abcdefghij"
k     # Get the indices of the characters of the first implicit input-list in the
      # second implicit input
      #  STACK: [0,1,9]
 ā    # Push a list in the range [1,length] (without popping)
      #  STACK: [0,1,9], [1,2,3]
  +   # Add the values at the same positions in the lists together
      #  STACK: [1,3,12]
   è  # Use that to (modular) index into the second (implicit) input
      #  STACK: ["b","d","c"]
      # (after which the list of characters is output implicitly)

```

# Answer
> 2 votes
# APL (Dyalog Extended), 16 bytes

Anonymous tacit infix function, taking the wrapping string as left argument and the input string as right argument.

```
⊣⊇⍨≢⍤⊣|1+⍳⍤≢⍤⊢+⍳

```

Try it online! (last case also works in current version of the language)

index of each input string char in the wrapping string

`+` add to that:

the indices
of the
length
of the
right argument (the input string)

`1+` increment

`|` compute the division remainder when divided by:

the length
of the
left argument (the wrapping string)

select those elements
from:

the left argument (the wrapping string)

# Answer
> 2 votes
# Perl 5 \+ `-plF`, 45 bytes

I feel like this should be easier, so I must be missing a trick somewhere...

```
@l{@F}=0..@F;$_=<>;s/./$F[($l{$&}+"@+")%@F]/g
```

Try it online!

## Explanation

Creates a lookup hash `%l` using the keys from the "wrapping string" (implicitly stored in `@F` via `-F`) and the values as the numbers from `0` to `@F` (when a list is used in scalar context, the length of the list is used). Then each char in the input string (`$_=<>`) is `s///`ubstituted with the corresponding char at the required index in `@F`, using the current "end of match" list `@+` as a string, modulo the list length.

# Answer
> 2 votes
# TECO, ~~66~~ ~~60~~ 52 bytes

```
-1^XGa:Qb<JQiQbUmS^EUm^[.+QiUk^[Qk-(Z*(Qk/Z))J0A:^Ur^[%i^[>

```

Note that `^X` or `^[` are ASCII control codes, thus each counts at 1 byte. The two string arguments are fetched from Q-register a, b, and result is saved to Q-register r

## Explanation

```
^Ua12^[     ! register a !
^Ub121212^[ ! register b !
-1^X        ! Case sensitive search !
1Un         ! n = 1; i = 0 !
Ga          ! Load register a to buffer !
:Qb<        ! Do len(b) times !
J           ! Jump to zero !
QiQbUm      ! Set b[i] to register m !
S^EUm^[     ! Search to the b[i] in buffer !
.-1Uk       ! Save position to k !
(Qk+Qn)-(Z*((Qk+Qn)/Z))J  ! Locate wrapping !
0A:^Ur^[    ! Append to register r !
%n^[%i^[    ! n++; i++ !
>           ! Od !
:Gr         ! print register r !

```

# Answer
> 2 votes
# Ruby, 51 bytes

```
->s,w{k=0;s.chars.map{|c|(w*k+=1)[/#{c}.*/][k]}*''}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 7 bytes

```
vḟ:ż+$i

```

Try it Online!

Port of Jelly answer.

## How?

```
vḟ:ż+$i
vḟ      # For each element in the (implicit) second input, find its index in the (implicit) first input
  :ż    # Duplicate and push a length range [1, length]
    +   # Add top two things on stack together
     $  # Swap so (implicit) first input is pushed to the stack
      i # Index the list into the string

```

# Answer
> 1 votes
# Factor, 60 bytes

```
[ [ 1 + [ tuck index ] dip + rotate first ] with map-index ]

```

Attempt This Online!

Rotating the wrapping string and taking the first character is quite a bit shorter than modular arithmetic or `<circular>` indexing.

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

```
i;f(s,w)char*s,*w;{for(i=1;*s;)*s++=w[(index(w,*s)-w+i++)%strlen(w)];}

```

Try it online!

Inputs two strings.
Returns the answer in the first input string.

# Answer
> 1 votes
# Python, 62 bytes

```
lambda s,w:[w[(w.index(c)+i+1)%len(w)]for i,c in enumerate(s)]
```

Attempt This Online!

Outputs as a list of characters

# Answer
> 1 votes
# Charcoal, 10 bytes

```
⭆θ§η⁺⌕ηι⊕κ

```

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

```
 θ          Input string
⭆           Map over characters and join
   η        Wrapping string
  §         Cyclically indexed by
     ⌕      Index of
       ι    Current character in
      η     Wrapping string
    ⁺       Plus
         κ  Current index
        ⊕   Incremented
            Implicitly print

```

# Answer
> 1 votes
# MATL, 7 bytes

```
y&mtf+)

```

Try it online!

Takes input as `'wrapping string'` then `'input string'`, separated by a newline.

```
	% implicit input w,i
y	% dup from below. Stack: w,i,w
&m	% ismember: find the index of each element of i in w
t	% duplicate.
f	% find: return truthy index. Since all are truthy, this returns 1:length(i)
+)	% add and index modularly into w
	% implicit output

```

# Answer
> 1 votes
# Ruby, 73 bytes

```
s,w=gets.split;n=1;s.chars.each{|i|print w[(w.index(i)+n)%w.length];n+=1}
```

The method used is similar to the reference implementation.

Attempt This Online!

# Answer
> 1 votes
# BQN, 16 bytesSBCS

```
⊢⊏˜≠∘⊢|1+⊒˜∘⊣+⊐˜

```

Run online!

-5 from DLosc.

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


title: Diagram of the Utmost Extremes

text:
# Question
Title: Diagram of the Utmost Extremes
The Mathematica SE question Creating the Yin Yang symbol with minimal code seems to be an out-of-the-box ready-to-go Code Golf SE question!

> The following code creates the Yin Yang symbol

```
Graphics[{Black, Circle[{0, 0}, 1], White,
   DiskSegment[{0, 0}, 1, {1/2 \[Pi], 3/2 \[Pi]}],
   Black, DiskSegment[{0, 0}, 1, {3/2 \[Pi], 5/2 \[Pi]}], White,
   Disk[{0, 0.5}, 0.5],
   Black, Disk[{0, -0.5}, 0.5], Black, Disk[{0, 0.5}, 0.125],
   White, Disk[{0, -0.5}, 0.125]
   }] // Show

```

> Knowing that 'there is always someone who can do things with less code', I wondered what the optimal way is, in Mathematica, to create the Yin Yang symbol.
>
> Not really an urgent question to a real problem, but a challenge, a puzzle, if you like. I hope these kind of questions can still be asked here.

From my current understanding what's actually sought in this question is not the symbol for Yin and Yang which is just the complementary black and white halves of a circle, but the Taijitu or "Diagram of the Utmost Extremes" which is rotated by 90 degrees so that the circles halves are roughly left and right, and with two small circular spots are added along the vertical axis at half radius.

Answers to the meta question Default acceptable image I/O methods for image related challenges already show a high level of community acceptance; I wouldn't want to specify further.

Regular code golf; fewest bytes to generate Code Golf SE-acceptable graphics output per the meta link above.

In response to (and including recommendations from) helpful comments:

* border thickness must be between 1 pixel and 4% of the overall diameter
* spot diameter must be between 1/10 and 1/7 of the overall diameter
* overall diameter at least 200 pixels
* error 2 pixels / 1%.
* Should resemble black ink on white paper as the original symbol is defined. However since some anti-aliasing uses color, use of color is not excluded as long as the image looks monochrome.
* same orientation as the image specimen left side white, small dots along central vertical axis.

---

Source:

> This is the Taijitu (太極圖), with black representing yin and white representing yang. It is a symbol that reflects the inescapably intertwined duality of all things in nature, a common theme in Taoism. No quality is independent of its opposite, nor so pure that it does not contain its opposite in a diminished form: these concepts are depicted by the vague division between black and white, the flowing boundary between the two, and the smaller circles within the large regions.

# Answer
> 5 votes
# , ~~153~~ ~~152~~ ~~145~~ 144 bytes

*Edit: -8 bytes thanks to pajonk*

```
plot(NA,,,l<-c(-8,8),l,an=F,ax=F)
Map(function(r,c,y,h)polygon(r*1i^(1+1:(h*99)/99)+y*1i,b=c,c=c),c(8.2,8,4,4,1,1),1:0,c(0,0,l/2,4,-4),-.75:5*8)

```

Try it at rdrr.io

```
plot(NA,,,l<-c(-8,8),l,an=F,ax=F) # initializes a new plot area
                                  # from x,y = -8 to 8
                                  # without annotation, without axes

```

```
Map(                              # apply function...
 function(r,c,y,h)                # with arguments r=radius, c=colour, y=y position, h=half-circle?
  polygon(r*1i^(1+1:(h*99)/99)+y*1i,
                                  # draw polygon using complex coordinates
   b=c,c=c),                      # border=c, colour=c
                                  # ...to these values:
c(8.2,8,4,4,1,1),                 # radii for 6 circles
 1:0,                             # colours (recycled; 0=white, 1=black)
 c(0,0,-4,4,4,-4),                # y positions
 -.75:5*8                         # abs≥4:full circle, 2:half circle (only 2nd)
)

```

# Answer
> 4 votes
# JavaScript (ES6), ~~141~~ ~~110~~ 96 bytes

```
X=>Y=>(e=y=>((R=X-210)**2+(Y-y*100-10)**2)**.5/5)(2)<42&&e(2)>40|R>0^e(R>0?3:1)<20^e(3)<5^e(1)<5

```

A pixel-shader function taking x and y coordinates between 0 and 420 and returning a boolean value, as allowed by this consensus. The below snippet creates a 420x420 image.

-14 bytes thanks to tsh

```
f=

X=>Y=>(e=y=>((R=X-210)**2+(Y-y*100-10)**2)**.5/5)(2)<42&&e(2)>40|R>0^e(R>0?3:1)<20^e(3)<5^e(1)<5

let canvas = document.getElementById('x').getContext`2d`

for(let i = 0; i < 420; i++){
  for(let j = 0; j < 420; j++){
    canvas.fillStyle = f(i)(j) ? 'black' : 'white'
    canvas.fillRect(i,j,1,1);

  }
}
```

```
<canvas id=x width=420 height=420 ></canvas>
```

## Explanation (old)

```
X=>Y=>                 // Curry function taking x and y parameters
  (e = y => (          // Euclidean distance function named e
      (X-210)**2+      // To (x = 200,
      (Y-y*100-10)**2  // y = input * 100 + 10
    ) ** .5
  )(2) < 210           // Is the distance to the center less than 210?
  && e(2) > 200        // If not, shortcircuit, else is the distance to the center greater than 200 (border)?
  | (                  // Else...
    Y > 210            // Is Y > 210 (Bottom half)
    & e(3) < 100       // And distance to center of lower circle less than 100 (Black circle on bottom)
    | X > 210          // Or X > 210 (Area on left)
    & e(1) > 100       // And distance to center of upper circle > 100 (Excluding white top circle)
  ) & e(3) > 25        // And distance to center of lower circle > 25 (Excluding white bottom circle)
  | e(1) < 25          // Or distance to center of upper circle < 25 (Including black top circle)

```

# Answer
> 4 votes
# SVG (HTML 5) 172 bytes

This is just an optimization of Neil's post, but he was warry of path minification. I think that just a bit silly (I hope you can excuse the expression), as there are at least two libraries in millionfold use that do just that. One is a default part of Adobe Illustrator's SVG export, the other is part of the SVGO library. – Both would not fair well if used unaltered here, because they assume to work for standalone SVG files which need to be wellformed XML.

The pivotal part of path optimization is that the grammar expects a greedy parser and takes separation as optional: everything that can be legally interpreted as part of a token is read as a part of it, and the next token can start immediately.

So

```
M 0,-20 a 40,40 0 0 1 0,80

```

can be shortened to

```
M0-20a40,40,0,010,80

```
* because the `-` cannot be interpreted as part of a preceding number
* because command letters need no separation from numbers
* because the fourth and fifth parameters to an `A`/`a` command, commonly called `large_arc` and `sweep`, are actually flags that can only take the values `0` or `1`.

```
<svg viewBox=-41,-21,82,82><path d=M0-20a40,40,0,010,80a20,20,0,010-40a20,20,0,000-40a40,40,0,000,80a40,40,0,010-80 stroke=#000 /><circle r=5 /><circle cy=40 r=5 fill=#fff>
```

# Answer
> 3 votes
# PostScript, ~~139~~ 86 bytes

```
00000000: 5b28 5b29 7b92 967d 2f63 7b30 8768 0192  [([){..}/c{0.h..
00000010: 057d 285d 297b 6392 427d 3e3e 920d 2e30  .}(]){c.B}>>...0
00000020: 3492 9b88 4837 3292 8b39 7b34 7d92 8332  4...H72..9{4}..2
00000030: 2e30 3220 6392 a732 870e 0139 3092 0592  .02 c..2...90...
00000040: 4233 2031 5d5b 3520 315d 3320 2e32 5d30  B3 1][5 1]3 .2]0
00000050: 5b35 202e 325d                           [5 .2]

```

Before tokenization:

```
[([){setgray}/c{0 360 arc}(]){c fill}>>begin
.04 setlinewidth 72 72 scale
9{4}repeat 2.02 c stroke
2 270 90 arc fill
3 1][5 1]3 .2]0[5 .2]

```

As rendered by Preview in OS X:

Explanation:

```
% first some abbreviations
[([){setgray}/c{0 360 arc}(]){c fill}>>begin
.04 setlinewidth 72 72 scale
9{4}repeat            % push 4s onto stack
2.02 c stroke         % main stroked circle (r=2.02)
2 270 90 arc fill     % black semicircle (r=2)
3 1]                  % black semicircle (r=1)
[                     % choose white
5 1]                  % white semicircle (r=1)
3 .2]                 % white semicircle (r=.2)
0[                    % choose black
5 .2]                 % black semicircle (r=.2)

```

# Answer
> 2 votes
# SVG (HTML5), ~~199~~ 183 bytes

```
<svg viewBox=-41,0,82,82><path d=M0,1A40,40,0,0,1,0,81A20,20,0,0,1,0,41A20,20,0,0,0,0,1A40,40,0,0,0,0,81A40,40,0,0,1,0,1 stroke=#000 /><circle cy=21 r=5 /><circle cy=61 r=5 fill=#fff>
```

The path draws the main black body but also the outer border (it's golfier than a separate circle for some reason), but the two dots are separate circles. The border thickness is 1.25% of the overall diameter. The spot diameter is 12.5% of the overall diameter. The image scales to the viewing area. Edit: Saved 16 bytes thanks to @ccprog.

# Answer
> 2 votes
# HTML, 267 bytes

```
<c style="border:1vw solid;background:linear-gradient(90deg,#fff 50%,#000 50%)"><c w style=top:0%><c></c></c><c style=top:50%><c w><style>c{position:absolute;padding:25%;border-radius:50%;top:25%;left:25%;background:#000}c c c{transform:scale(.5)}[w]{background:#fff}
```

Size of large ball is 52vw (50vw + border). Width of border is 1vw (1.92%). Size of small ball is 6.25vw (12.0%).

---
Tags: code-golf, graphical-output
---


title: How many threes?

text:
# Question
Title: How many threes?
In this task your code will be given an integer \\$n\\$ as input. Your code should then output the greatest number of multiples of \\$3\\$ that can be concatenated (in base \\$10\\$) to form \\$3n\\$ (with no leading zeros). For example if you were given \\$26042\\$ as input,

\\$26042\times3=78126\\$

and \\$78126\\$ can be made by concatenating \\$78\\$, \\$12\\$ and \\$6\\$, so you output \\$3\\$.

Any standard forms of IO are permitted. Answers should aim to minimize the number of bytes in their code.

---

Here are the first \\$6562\\$ entries in this sequence starting with zero:

```
1,1,1,1,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1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,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2

```

# Answer
> 13 votes
# Retina, 11 bytes of Latin-1

```
v`.3*[012¶]

```

Try it online!

Retina works on strings rather than integers, so I'm taking the number as it'd appear in a file (digits followed by a newline).

(Note: as pointed out in the comments, `v`.3*[¶-2]` works for 10 bytes, but I didn't come up with it myself.)

## Algorithm

Almost all the solutions here have a multiplication by 3, but I thought it'd be interesting to try to solve the problem without it. We already know from the algorithm most people are using that we need to identify the number of suffixes of 3*n* that are divisible by 3. Now, given a suffix of *n* (say *s*), 3*s* will appear as a suffix of 3*n* if the multiplication *s*×3 does not carry into the digit before the suffix. Meanwhile, if the multiplication *s*×3 *does* carry, then the corresponding suffix of 3*n* will not be divisible by 3 (as the digital root of 3*s* is divisible by 3 – 3 divides (10-1) and we're working in base 10 – and the corresponding suffix of 3*n* will be equal to 3*s* but without a leading `1` or `2`, neither of which is divisible by 3).

We do need to adjust for the possibility that 3*n* has more digits than *n*, thus meaning that 3*n* has an extra suffix that doesn't correspond to any suffix of *n*. This suffix is trivially the whole number 3*n*, and will always be divisible by 3 (for obvious reasons). Thus, if the multiplication *n*×3 carries, we have to add 1 to the result. We can note that if *n*×3 doesn't carry, it will contribute 1 to the result using a naive algorithm, whereas if it does, it won't; and thus we can do this adjustment simply by counting the "suffix that represents the whole number *n*" unconditionally, rather than checking for a carry. Equivalently (and slightly more tersely), we can unconditionally *not* count this suffix, and count some other suffix instead (the empty suffix is convenient), as it'll come to the same total.

How do we determine if a multiplication by 3 would carry? Well, if the first digit of the number is greater than 3, it must; if it's less than 3, it can't. If it's 3, whether it carries or not will depend on the next digit of the number in the same way. If the number consists *entirely* of 3s, the multiplication won't carry (it'll stop just short at a number consisting entirely of 9s). Thus, the algorithm we want is "count the number of proper suffixes that start with 0 or more 3s, followed by 0, 1, 2, or the end of the string; plus one extra suffix".

## Explanation

This algorithm ends up longer than the consensus algorithm in most languages, so I'm submitting it in Retina, a language where it turns out to be shorter than the more usual method (and a similar length to golfing languages).

```
v`.3*[012¶]
v`            {Count the number of} points within the input from which you can
  .             ignore one character,
   3*           and skip past any number (including zero) of 3s,
     [012¶]     to find 0, 1, 2, or the newline at the end of the input.

```

The requirement to ignore one character before we start looking means that the improper suffix consisting of the whole number cannot be counted (as the suffixes that we actually look at will be the ones starting one character to the right of where Retina starts, and thus not at the first character). However, the improper suffix consisting only of the newline at the end of the number will always be counted, thus giving us the one extra suffix we need.

# Answer
> 11 votes
# Haskell, 51 bytes

```
f n=sum[1|x<-scanr(:)"0".show$3*n,read x`mod`3<1]-1

```

Try it online!

The key idea is the following: given a multiple of 3 (call it \\$3n\\$), the best way to write it as the juxtaposition of multiples of 3 is to start from the end (or the beginning) and select multiples of 3 greedily. For instance, if \\$3n=78126\\$, then we get (starting from the end) a \\$6\\$, then a \\$12\\$, and finally a \\$78\\$: \\$78|12|6\\$. Note that this is possible because a number is a multiple of 3 iff the sum of its digits is a multiple of 3. Also note that if we concatenate two multiples of 3, we get another multiple of 3, so \\$6,12|6,78|12|6\\$ are all multiples of 3.

Thus the answer can be found by considering the list of suffixes of \\$3n\\$ (e.g. \\$\[78126,8126,126,26,6\]\\$) and counting the multiples of 3.

# Answer
> 9 votes
# Husk, 9 bytes

```
#o¦3dṫd*3

```

Try it online or verify the first 2188 terms!

### Explanation

```
#(¦3d)ṫd*3  -- example: 42
        *3  -- times 3: 126
       d    -- digits: [1,2,6]
      ṫ     -- tails: [[1,2,6],[2,6],[6]]
#(   )      -- count values that are truthy when
    d       -- | undigits: [126,26,6]
  ¦3        -- | divisible by 3: [42,0,2]
            -- : 2

```

# Answer
> 5 votes
# ~~Perl 6~~ Raku, ~~54 28~~ 26 bytes

*-14 bytes thanks to nwellnhof!*

```
{sum [\+](.comb)X%%3}o*×3

```

Try it online!

This counts how many prefixes of the number times three are divisible by 3.

### Explanation:

```
{                   }o*×3  # Pass the input times 3 into the code block
     [\~](.comb)           # Get all the prefixes of the number
                X%%3       # Map each to whether they are divisible by 3
 sum                       # And get the sum

```

# Answer
> 5 votes
# 05AB1E, ~~14~~ ~~12~~ ~~7~~ 6 bytes

```
3*η3ÖO

```

-5 bytes creating a port of *@BMO*'s Husk answer.
-1 byte thanks to *@Nitrodon* by changing suffixes to prefixes.

Try it online or verify the first 1000 items.

**Explanation:**

```
3*        # Multiply the (implicit) input by 3
          #  i.e. 26042 → 78126
  η       # List of prefixes
          #  i.e. 78126 → ["7","78","781","7812","78126"]
   3Ö     # Check for each if its divisible by 3
          #  i.e. ["7","78","781","7812","78126"] → [0,1,0,1,1]
     O    # And take the sum (which is implicitly output)
          #  i.e. [0,1,0,1,1] → 3

```

---

**Old 12-bytes answer:**

```
3*.œʒ3ÖP}€gà

```

Or alternatively `€gà` can be `éθg`.

Try it online or verify the first 1000 items

**Explanation:**

```
3*             # Multiply the (implicit) input by 3
               #  i.e. 26042 → 78126
  .œ           # Take all possible partitions of this number
               #  i.e. 78126 → [["7","8","1","2","6"],["7","8","1","26"],["7","8","12","6"],
               #                ...,["781","26"],["7812","6"],["78126"]]
    ʒ   }      # Filter these partitions by:
     3ÖP       #  Only keep partitions where every number is divisible by 3
               #   i.e. ["7","8","1","2","6"] → [0,0,0,0,1] → 0
               #   i.e. ["78","12","6"] → [1,1,1] → 1

               #(option 1:)
         €g    # Take the length of each remaining partition
               #  i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]] → [3,2,2,1]
           à   # And take the max (which we output implicitly)
               #  i.e. [3,2,2,1] → 3

               #(option 2:)
         é     # Sort the remaining partitions by length
               #  i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]]
               #   → [["78126"],["78","126"],["7812","6"],["78","12","6"]]
          θ    # Take the last one (the longest)
               #  i.e. [["78126"],["78","126"],["7812","6"],["78","12","6"]]
               #   → ["78","12","6"]
           g   # And take its length (which we output implicitly)
               #  i.e. ["78","12","6"] → 3

```

# Answer
> 5 votes
# APL (Dyalog Unicode), 14 bytes

```
+/0=3|+\⍎¨⍕3×⎕

```

Try it online! or verify the first 1000

### Explanaition

```
+/0=3|+\⍎¨⍕3×⎕
             ⎕ ⍝ prompt for input
           3×  ⍝ multiply by 3
        ⍎¨⍕    ⍝ convert the number to a vector of digits
      +\       ⍝ take the cumulative sum
    3|         ⍝ find each term modulo 3
+/0=           ⍝ count those that equal 0

```

This works because a number is divisible by three if and only if the sum of its digits is divisible by three

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

```
f=(n,i=10)=>!(n*3%i%3)+(n*3>i&&f(n,i*10))

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~99~~ 88 bytes

```
lambda n:g(`3*n`)
g=lambda n:int(n)%3<1and 1+max([g(n[i:])for i in range(1,len(n))]+[0])

```

Try it online!

# Answer
> 3 votes
# MathGolf, ~~15~~ 14 bytes

```
3*▒0\Æ§_3÷\;]Σ

```

Try it online!

-1 byte thanks to JoKing

## Explanation

```
3*                Multiply the input by 3
  ▒               Convert to a list of digits
   0\             Push a zero and swap the top two elements
     Æ            Execute the next 5 characters for each block
      §           Concatenate
       _          Duplicate
        3÷        Check divisibility by 3 (returns 0 or 1)
          \       Swap top two elements
           ;      Discard TOS (the last swap
            ]Σ    Wrap the entire stack in an array and output its sum

```

I don't know if this is the correct solution to the problem but it mimics the JS solution by Arnauld. If I'm incorrect, I'll try to fix it.

# Answer
> 3 votes
# Haskell, 44 bytes

```
g.(*3).max 1
g 0=0
g n=0^mod n 3+g(div n 10)

```

Try it online!

Uses Delfad0r's observation that the output is the number of suffixes (equivalently, prefixes) of 3n that are multiples of 3. This method finds the prefixes arithmetically by repeatedly floor-dividing by 10 rather than using the string representation. The `0^` is a short arithmetic way to produce `1` if the exponent `mod n 3` is zero, and produce `0` otherwise.

The first line is the main function, which triples the input before passing it to the helper function `g` which is defined recursively. The `max 1` is a hack to make `f(0)` equal 1, since we're required to handle zero like the string `'0'` rather than the empty string.

# Answer
> 3 votes
# Jelly, 7 bytes

```
×3DÄ3ḍS

```

Try it online!

### How it works

```
×3DÄ3ḍS  Main link. Argument: n

×3       Compute 3n.
  D      Decimal; convert 3n to the array of its digits in base 10.
   Ä     Accumulate; take the cumulative sum.
         Note that an integer and its digit sum are congruent modulo 3.
    3ḍ   Test each partial digit sum for divisibility by 3.
      S  Take the sum of the Booleans, counting the multiples of 3.

```

# Answer
> 2 votes
# Pyth, ~~16~~ 15 bytes

```
lef!.E%vT3./`*3

```

Try it online here.

```
lef!.E%vT3./`*3Q   Implicit: Q=eval(input())
                   Trailing Q inferred
            `*3Q   Input * 3
            `      Convert to string
          ./       Take divisions into disjoint substrings
  f                Filter the above using:
       vT            Convert each back to integer
      %  3           Mod 3
    .E               Are any non-0?
   !                 Logical NOT
le                 Take the length of the last value
                   As the substring sets are generated in order of number of
                   substrings, the last value is guaranteed to be the longest

```

# Answer
> 2 votes
# Retina, ~~35~~ 32 bytes

```
.+
$.(*3*
Lv$`.+
<$&*->
<(---)*>

```

Try it online! Explanation:

```
.+
$.(*3*

```

Multiply the input by 3.

```
Lv$`.+
<$&*->

```

Convert each suffix to unary.

```
<(---)*>

```

Count the multiples of three.

# Answer
> 2 votes
# Shakespeare Programming Language, 376 bytes

```
T.Ajax,.Page,.Act I:x.Scene I:x[Enter Ajax and Page]Ajax:Listen tothy!You be the sum ofthe sum ofyou you you!Scene V:x.Page:You be the sum ofyou the quotient betweena cat the sum ofa cat the remainder of the quotient betweenI the sum ofa big cat a cat!Ajax:You be the quotient betweenyou twice the sum ofa big big cat a cat!Be you nicer zero?If solet usscene V.Page:Open heart

```

Try it online!

I wonder if the `1/(1+I/3)` trick is better than a control flow.

# Answer
> 2 votes
# Java 10, 66 bytes

```
n->{int m=1,r=n<1?1:0;for(n*=3;m<n;m*=10)r+=n%m%3<1?1:0;return r;}

```

Try it online.

**Explanation:**

Uses a combination of *@BMO*'s Husk answer (checking how many prefixex are divisible by 3) and *@Arnauld*'s JavaScript (ES6) answer (multiplying an integer by 10 every iteration, and get the prefixes with a modulo of this integer).

```
n->{             // Method with integer as both parameter and return-type
  int m=1,       //  Modulo-integer, starting at 1
      r=         //  Result-integer, starting at:
        n<1?     //   If the input is the edge-case 0:
         1       //    Start it at 1
        :        //   Else:
         0;      //    Start it at 0
  for(n*=3;      //  Multiply the input by 3
      m<n;       //  Loop as long as `m` is still smaller than `n`
      m*=10)     //    After every iteration: Multiply `m` by 10
    r+=n%m       //   If `n` modulo-`m` (to get a suffix),
          %3<1?  //   is divisible by 3:
        1        //    Increase the result-sum by 1
       :         //   Else:
        0;       //    Leave the result-sum the same by adding 0
  return r;}     //  Return the result-sum

```

# Answer
> 2 votes
# K (ngn/k), 16 bytes

```
{+/~3!+\.:'$3*x}

```

Try it online!

# Answer
> 2 votes
# Python 2, 48 bytes

```
n=input()*3;p=n<1
while n:p+=n%3<1;n/=10
print p

```

Try it online!

Similar to ovs's answer, but takes the whole prefix mod 3 without accumulating rather than the last digit. Outputs `True` as 1 on input of 0.

---

# Python 3, 42 bytes

```
f=lambda n:n>=1and(n%1<1/3)+f(n/10)or n==0

```

Try it online!

Uses ideas from ais523's very nice solution. Repeatedly floor-divides the input by 10 until it's zero, and counts how many times the fractional part is less than 1/3. On very large inputs float precision will eventually be a problem. The `n=0` case is handled with `or n==0` making it return True for 1. The code can work in Python 2 if the input is a float, if we rewrite `n%1<1/3` as `n%1*3<1` which is the same length.

# Answer
> 2 votes
# Husk, 7 bytes

```
#¦3∫d*3

```

Try it online!

Same as the other answer, except it uses cumulative sum.

# Answer
> 1 votes
# Japt `-x`, 12 bytes

```
*3 s å+ ®°v3

```

Try it or view results for`0-1000`

# Answer
> 1 votes
# Stax, 8 bytes

```
αNΘ╠╠1d}

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
3*      triple input
E       convert to array of decimal digits
:+      get all prefix sums
F       for each prefix sum
  3%!   is it a multiple of 3?
  +     add to running total

```

Run this one

# Answer
> 1 votes
# , 20 bytes

```
1#.0=[:(3|".)\3":@*]

```

Try it online!

# Answer
> 1 votes
# Python 2, 56 bytes

```
n=input()*3;k=p=0
while n:k+=n%10;n/=10;p+=k%3<1
print p

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-p`, 32 bytes

```
$_*=3;s/./$\+=!(($t+=$&)%3)/ge}{

```

Try it online!

# Answer
> 1 votes
# Vyxal, `s`, ~~6~~ ~~5~~ 4 bytes

```
3*¦₃

```

Try it Online!

;)

## Explained

```
3*¦₃
3*      # multiply the input by 3
  ¦     # take cumulative sums of that number, treating it as a list
   ₃    # get the divisibility of 3 of each number and then
        # the `-s` flag sums the top of the stack before outputting

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
T¦v₃∑

```

Try it Online!

## How?

```
T¦v₃∑
T     # Triple the (implicit) input
 ¦    # Cumulative sum
  v₃  # Is each element divisible by three?
    ∑ # Sum

```

# Answer
> 1 votes
# Desmos, 61 bytes

```
f(n)=total(0^{mod(floor(3n/10^{[0...floor(log(0^n+n))]}),3)})

```

Essentially does the prefix trick that some of the other answers are using. Pretty straightforward, though quite interesting to implement in Desmos.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Wolfram Language (Mathematica): (53) 43 Bytes

```
If[#<1,1-Sign@#,Boole[3#~Mod~1<1]+#0[.1#]]&

```

*-10 bytes from att*

Pretty long, but I figured it was worth posting anyways because it was difficult enough to golf.

Try It Online

---

## Explanation:

`If[#<1, 1-Sign@#`: If our input was 0, return 1.

`Boole[3#~Mod~1<1]`: Otherwise, check if the fractional part of 3n is less than 1, and return 1 if so.

`+#0`: Then, add this same expression to this total `[.1#]]&` but with a tenth of the input.

I also tried using the other algorithm, but I couldn't get anything below around 75 bytes with it. Probably possible to get much lower than 75 (I'm not great at golfing), but 43 certainly seems better.

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