title: Spelling Bee Acceptable

text:
# Question
Title: Spelling Bee Acceptable
This is similar to this question. However, I have a different goal in mind: Reduce the wordlist to words that could appear. The easy part is to delete hyphens and similar.

The hard part, however: Remove words containing more than seven letters.

So, the problem:
Given a set of words containing only lowercase (or uppercase) ASCII letters, remove the words containing eight or more different letters.

Any input and output format is acceptable.

Standard loophole rules apply.

Shortest byte count wins.

Clever solutions are better, and faster is better as well.

My solution (implementing a quite clever O(n) algorithm, noncompetitive ref implementation):

```
#include <stdio.h>
#include <stdint.h>

int main(void) {
  char str[1024];
  while(scanf("%s\n", str) == 1) {
    uint32_t st = 0;
    int s = 0;
    for(char *p = str; *p && s <= 7; p++) {
      s += ~st >> (*p - 'a') & 1;
      st |= 1 << (*p - 'a');
    }
    if(s <= 7)
      printf("%s\n", str);
  }
}

```

# Answer
> 4 votes
# APL (Dyalog Unicode), 11 bytes

```
{⍵/⍨8>≢∪⍵}¨

```

Takes input as a list of strings.

**Explanation:**

```
{⍵/⍨8>≢∪⍵}¨
{       ⍵}¨ for each word
       ∪    take unique letters
    8>≢     length less than 8 as a boolean (0 or 1)
 ⍵/⍨        repeat word that many times

```

Try it online!

# Answer
> 3 votes
# Perl 6, 20 bytes

```
*.grep(8>*.comb.Set)

```

Try it online!

Filters by words that have a set of letters with size less than 8.

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
ʒÙg8‹

```

Try it online.

**Explanation:**

```
ʒ        # Filter the (implicit) input-list by:
 Ù       #  Only leave distinct letters of the word
  g      #  Take its length
   8‹    #  And only leave those with a length smaller than 8
         # (And output implicitly after we're done filtering)

```

# Answer
> 2 votes
# Jelly, 6 bytes

```
Qṫ¥Ðḟ8

```

Try it online!

### How it works

```
Qṫ¥Ðḟ8  Main link. Argument: A (array or words)

   Ðḟ   Filterfalse; only keep the words W of A for which the chain to the left
        returns a falsy value.
  ¥         Combine the two links to the left into a dyadic chain.
Q               Unique; remove duplicate letters from W.
 ṫ   8          Tail 8; remove the first 7 letters of the result.

```

# Answer
> 2 votes
# J, 10 bytes

```
#~8>#@~.@>

```

# explanation

```
#~ 8 > #@~.@>
#~                 NB. filter the input based on...
   8 >             NB. is 8 greater than...
       #@          NB. the length of...
         ~.@       NB. the unique characters of...
            >      NB. the unboxed input.

```

Try it online!

# Answer
> 2 votes
# Java 8, 46 bytes

```
s->s.filter(w->w.chars().distinct().count()<8)

```

Try it online.

**Explanation:**

```
s->               // Method with String-Stream as both parameter and return-type
  s.filter(w->    //  Filter the words in the input-Stream by:
    w.chars()     //  Convert the String to characters
     .distinct()  //  Only leave distinct characters
     .count()<8)  //  Only leave words with less than 8 distinct characters

```

# Answer
> 2 votes
# MathGolf, 6 bytes

```
Ç{▀£7>

```

Try it online!

## Explanation

Really similar to the 05AB1E solution, but I lose one byte thanks to explicitly having to define the code block for filtering.

```
Ç       Implicit faulty filter by block
 {      Start block
  ▀     Get unique characters of string
   £    Get length
    7>  Is greater than 7

```

# Answer
> 1 votes
# Python 2, 40 bytes

```
lambda i:[x for x in i if len(set(x))<8]

```

Try it online!

Test cases borrowed from @Dennis. Input and output are both lists.

# Answer
> 1 votes
# Red, 54 bytes

```
func[b][foreach a b[if 8 > length? unique a[print a]]]

```

Try it online!

The first test set was taken from Dennis'

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

Dennis's word set was also used here.

Thanks to nwellnhof for the suggestions.

```
char*s,*t;f(i,j,k){for(;~scanf("%ms",&s);i<8&&puts(s))for(i=j=0,t=s;*t;j=k)k=j|1<<*t++,i+=j<k;}

```

Try it online!

# Answer
> 1 votes
# JavaScript, 33 bytes

```
a=>a.filter(s=>new Set(s).size<8)

```

Try it online, using Dennis' test cases

# Answer
> 1 votes
# C# (.NET Core), 58 bytes

```
 a=>a.Where(x=>x.GroupBy(y=>y).Count()<8)

```

Try It Online!

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

```
#import<bits/stdc++.h>
f(){for(char*n;~scanf("%ms",&n);)std::set<int>(n,n+strlen(n)).size()<8&&puts(n);}

```

Try it online!

-1 byte thanks to @ceilingcat

# Answer
> 1 votes
# perl -nlE, 32 bytes

```
my%h;@h{/./g}=();say if keys%h<8

```

This reads words from `STDIN`, printing out those with less than 7 different characters.

# Answer
> 0 votes
# Racket, 95 bytes

```
(require racket/set)(define(f l)(filter(lambda(x)(<(set-count(list->set(string->list x)))8))l))

```

Try it online!

The test set was taken from Dennis'

# Answer
> 0 votes
# Charcoal, 12 bytes

```
ΦＡ›⁸ＬΦι⁼μ⌕ιλ

```

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

```
 Ａ              Input array
Φ               Filter strings where
   ⁸            Literal 8
  ›             Is greater than
    Ｌ           Length of
      ι         Current string
     Φ          Filtered on characters where
        μ       Inner index
       ⁼        Equals
           λ    Current character's
         ⌕      First index in
          ι     Current string
                Implicitly print matching strings

```

# Answer
> 0 votes
# JavaScript (ES6), 53 bytes

Without using a set:

```
a=>a.filter(w=>[...w].every(o=c=>o[c]=o[c]||--k,k=8))

```

Try it online! (using Dennis' test set)

# Answer
> 0 votes
# Japt `-f`, 6 bytes

```
¬â Ê<8

```

Try it, using Dennis' test cases

# Answer
> 0 votes
# Snap! 4, scratchblocks2 syntax

(pretending that Snap! exclusive blocks are valid in scratchblocks2 but functions use the Scratch `define`)

# 69 bytes

`b` takes a list of strings.

```
define((b)
report((#)keep items such that(<(length of [])<[7]>)from(b

```

---
Tags: code-golf
---


# Question
Title: Convert to uppercase and lowercase without branching and comparisons
Write two functions/programs which take an ASCII code of character (8-bit unsigned integer) and one of them converts char to uppercase and other to lowercase.

That is, they must be equivalent to following functions:

```
unsigned char toUpper(unsigned char c){
    if (c >= 97 && c <= 122) return c - 32;
    return c;
}
unsigned char toLower(unsigned char c){
    if (c >= 65 && c <= 90) return c + 32;
    return c;
}

```

However you are not allowed to use branching (`if`s, `goto`s), loops and comparison and logical operators. Recursion, language built-in functions, regular expressions, arrays and objects also not allowed. You may use **only** arithmetic and bitwise operations on 8-bit unsigned integers.

**Score:**

1 - for `| & ^ ~ >> <<` operators
1.11 - for `+ -` operators
1.28 - for `*` operator
1.411 - for `/ %` operators

Answer with lowest total score (for two functions added) wins. If answers with equal score than first (oldest) answer wins.

# Answer
## C, C++ and related languages, 6.22

```
unsigned char toggle(unsigned char c, unsigned char lo, unsigned char hi)
{
    unsigned char m = (unsigned char)((lo - c) ^ (hi - c)) >> 7;
    return c ^ (m << 5);
}

unsigned char toUpper(unsigned char c)
{
    return toggle(c, 96, 122);
}

unsigned char toLower(unsigned char c)
{
    return toggle(c, 64, 90);
}

```
> 3 votes

# Answer
## C and other languages with integer division, ~~15.204~~ ~~14.644~~ ~~14.084~~ 11.864

```
unsigned char toUpper(unsigned char c){
    return c - ((c/97) ^ (c/123)) << 5;
}

unsigned char toLower(unsigned char c){
    return c + ((c/65) ^ (c/91)) << 5;
}

```
> 8 votes

# Answer
# C, 11.482

My functions I have found before posting question, I hope there will better ones.

```
unsigned char toUpper(unsigned char c){
    unsigned char a = c - 97;
    return c - ((32 - a / 26) & 32);
}
unsigned char toLower(unsigned char c){
    unsigned char a = c - 65;
    return c + ((32 - a / 26) & 32);
}

```
> 2 votes

# Answer
# C (gcc), 9.042 step score

```
uchar toUpper(uchar c){
    return c^(((uchar)(c+133)/230)<<5);
}
uchar toLower(uchar c){
    return c^(((uchar)(c+165)/230)<<5);
} // 9.042 step score

```

Try it online!

# C (gcc), 2.11 existance score

```
uchar sub(uchar a, uchar b) {return a-b;}
uchar shr(uchar a, uchar b) {return a>>b;}
uchar add(uchar a, uchar b) {return sub(a, sub(0, b));}
uchar isneg(uchar a) {return shr(a, 7);}
uchar reach230(uchar a) {return shr(add(isneg(a),isneg(sub(229,a))),1);}
uchar dif(uchar a) {uchar t=reach230(a); t=add(t,t); t=add(t,t); t=add(t,t); t=add(t,t); t=add(t,t); return t;}
uchar toUpper(uchar c){ return sub(c,dif(add(c,133))); }
uchar toLower(uchar c){ return add(c,dif(add(c,165))); }

```

Try it online!
> 0 votes

---
Tags: math, restricted-source, atomic-code-golf
---


title: Dina's Paintings

text:
# Question
Title: Dina's Paintings
Dina loves most numbers. In fact, she loves every number that is not a multiple of n (she really hates the number n). For her friends’ birthdays this year, Dina has decided to draw each of them a sequence of n−1 flowers. Each of the flowers will contain between 1 and n−1 flower petals (inclusive). Because of her hatred of multiples of n, the total number of petals in any non-empty contiguous subsequence of flowers cannot be a multiple of n. For example, if n=5, then the top two paintings are valid, while the bottom painting is not valid since the second, third and fourth flowers have a total of 10 petals. (The top two images are Sample Input 3 and 4.)

Dina wants her paintings to be unique, so no two paintings will have the same sequence of flowers. To keep track of this, Dina recorded each painting as a sequence of n−1 numbers specifying the number of petals in each flower from left to right. She has written down all valid sequences of length n−1 in lexicographical order. A sequence a1,a2,…,a(n−1) is lexicographically smaller than b1,b2,…,bn−1 if there exists an index k such that ai=bi for i \< k and ak \< bk.

***What is the kth sequence on Dina’s list?***

**Input** The input consists of a single line containing two integers n (2≤n≤1000), which is Dina’s hated number, and k (1≤k≤1018), which is the index of the valid sequence in question if all valid sequences were ordered lexicographically. It is guaranteed that there exist at least k valid sequences for this value of n.

***Output*** Display the *k*th sequence on Dina’s list.

```
Sample Input 1
4 3
Sample Output 1
2 1 2

```

---

```
Sample Input 2
2 1
Sample Output 2
1

```

---

```
Sample Input 3
5 22
Sample Output 3
4 3 4 2

```

---

```
Sample Input 4
5 16
Sample Output 4
3 3 3 3

```

# Answer
## Haskell, 87 bytes

```
n#k=[d|d<-mapM id$[1..n]<$[2..n],all(\x->mod x n>0)$p d]!!k
p(x:y)=scanl(+)x<>p$y
p x=x

```

Uses 0-based indexing. Needs the latest version of `Prelude` which is not installed on TIO, hence an additional `import`.

Try it online!

```
   d|d<-mapM id$[1..n]<$[2..n]    -- keep all 'd' from the lists of numbers [1..n] of
                                  -- length n-1
     , all(\x->      )            -- where all elements 'x' from
                       p d        -- the sums of the subsequences of 'd'
               mod x n>0          -- are not a multiple of n
 [                           ]!!k -- pick the 'k'th element

p(x:y)=scanl(+)x<>p$y             -- the sums of subsequences are calculated by
                                  -- prepending the cumulative sums of the list to
                                  -- a recursive call with the tail of the list
p x=x                             -- base case for recursion: empty list

```
> 1 votes

# Answer
# Jelly, 12 bytes

```
’ṗ`Ẇ§%ẠʋƇ⁸ị@

```

A dyadic Link accepting `n` on the left and `k` on the right.

**Try it online!** (no way this will work for large n, but would in theory)

### How?

```
’ṗ`Ẇ§%ẠʋƇ⁸ị@ - Link: integer n, integer k
’            - decrement n -> n-1
  `          - use for both arguments of:
 ṗ           -   Cartesian power (all (n-1)^2 flower sequences - lex order)
         ⁸   - chain's left argument, n (as right argument for...)
        Ƈ    - filter keep those (sequences) which are truthy under:
       ʋ     -   last four links as a dyad (f(sequence, n)):
   Ẇ         -     all ((n-1)n/2) contiguous sublists (of the sequence)
    §        -     sum each
     %       -     modulo (n)
      Ạ      -     all? (all non-zero?)
           @ - with swapped arguments (i.e. f(k, listOfValidSequences)
          ị  -   index into (1-based)

```
> 0 votes

# Answer
# Perl 6, ~~74~~ 68 bytes

```
{([X] (1..^$^a)xx$a-1).grep(!*[^*X.. ^*].grep:{$_&.sum%%$a})[$^b-1]}

```

Try it online!

Anonymous code block that returns a list of numbers, or an integer in the case of \\$n=2\\$.

### Explanation:

```
{([X] (1..^$^a)xx$a-1).grep(!*[^*X.. ^*].grep:{$_&.sum%%$a})[$^b-1]}
{                                                                  }  # Anonymous code block
 ([X] (1..^$^a)xx$a-1)  # From all n length sequences of 1 to n-1
                      .grep(                               )   # Filter by
                            !           .grep:{          }  # None of
                             *[^*X.. ^*]    # All partitions (including empty lists)
                                               $_    # Are non-empty
                                                 &.sum%%$a  # And the sum is divisible by n
                                                            [$^b-1]  # Get the kth index of the list

```
> 0 votes

# Answer
# Charcoal, 35 bytes

```
ＮθＩ↨§Φ…Ｘθ⁻θ²Ｘθ⊖θ¬ΦθΦλ¬﹪Σ✂↨ιθνλ¹θ⊖ηθ

```

Try it online! Link is to verbose version of code. Works by taking the range \\$ n^{n-2} \ldots n^{n-1}-1 \\$ in base \\$ n \\$ and filtering out illegal sequences (including ones with zero digits). Explanation:

```
Ｎ                                   Input `n` as a number
 θ                                  Save in variable
        θ                           `n`
       Ｘ                            To the power
          θ                         `n`
         ⁻                          Minus
           ²                        2
      …                             Ranged up to
             θ                      `n`
            Ｘ                       To the power
               θ                    `n`
              ⊖                     Decremented
     Φ                              Filtered `i` by
                ¬                   Not
                  θ                 Implicit range `0` .. `n-1`
                 Φ                  Filtered `l` by
                    λ               Implicit range `0` .. `l`
                   Φ                Filtered `m` by
                     ¬              Not
                       Σ            Sum
                          ι         `i`
                         ↨          Converted to base
                           θ        `q`
                        ✂           Sliced
                            ν       From `m`
                             λ      To `l`
                              ¹     Step 1
                      ﹪             Modulo
                               θ    `n`
    §                               Indexed by
                                 η  Second input `k`
                                ⊖   Decremented
   ↨                                Converted to base
                                  θ `n`
  Ｉ                                 Cast to string
                                    Implicitly printed

```
> 0 votes

---
Tags: code-golf
---


title: How fast am I vrooooming?

text:
# Question
Title: How fast am I vrooooming?
# Introduction

My car speedometer was hacked! Instead of showing me how fast i'm driving, it just shows: "Vroooom!" Please help me know how fast i'm going.

# Challenge

Take a string as input, and check if it matches the regex `/^[Vv]ro*m!$/m`. In English that means any line of the string must start with a capital or lowercase `v`, then a lowercase `r`, then any amount (including zero) of the lowercase letter `o`, then the exact string `m!`. There may be other lines, but the Vroom string must be on it's own line.

If you find a match, then you must count the amount of `o`'s in the Vroom string and output it. If you don't find a match however, you should output any default value that can't be outputted otherwise (like `-1` or an empty string)

# Reminders

# Scoring

This is , so the shortest code in bytes wins. **However**, I will not mark any answer as accepted.

# Test cases

**Input**

```
Vrom!

```

**Output** `1`

**Input**

```
vrooooooom!

```

**Output** `7`

**Input**

```
Hello, Vroom!

```

**Output** `(none)`

**Input**

```
Foo bar boo baz
Vrooom!
hi

```

**Output** `3`

**Input**

```
Vrm!ooo

```

**Output** `(none)`

**Input**

```
PPCG puzzlers pie

```

**Output** `(none)`

**Input**

```
hallo
vROOOm!

```

**Output** `(none)`

# Answer
# sed 4.2.2, 20 bytes

`-nr` options required at the command-line.

```
s/^[Vv]r(o*)m!$/\1/p

```

This outputs the speed in unary as the number of `o`s.

Try it online!
> 8 votes

# Answer
# Python 2, ~~56~~ 53 bytes

```
lambda x:len(re.search('^[Vv]r(o*)m!$',x,8).group(1))

```

Try it online!

Basic regex and grouping, uses re.MULTILINE flag (which has a value of 8) and re.search to ensure it works for multiline inputs. Raises an exception when no match is found. Thanks to @ovs for the -3 bytes from `(re.M == 8)` tip.
> 4 votes

# Answer
# , ~~62 60 58~~ 44 bytes

```
nchar(grep("^[Vv]ro*m!$",readLines(),v=T))-4

```

Try it online!

@Giuseppe with 14 bytes golfed.

Original approach with explanation:

```
function(x)attr(el(regexec("(?m)[Vv]r(o*)m!$",x,,T)),"m")[2]

```

Try it online!

R has seven pattern matching functions. The more commonly used ones are `grep`, `grepl`, and `sub`, but here's a nice use for `regexec`.

`regexec` gives you a bunch of things, one of which is the length of any captured substring, in this case the `(o*)` part of the multiline regex.

The `attr(el .... "m")[2]` stuff is a golfy way to get the desired number.

Returns `NA` if there is no match.
> 4 votes

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

```
a=>(l=/[Vv]r(o*)m!/.exec(a))&&l[1].length

```

Try it online!
> 3 votes

# Answer
# Powershell, ~~62~~ ~~58~~ ~~53~~ 48 bytes bytes

```
"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4

```

returns numbers of `o` in a first `Vroom!`, or -4 if `Vroom!` not found.

Notes:

* `sls` is alias for Select-String;
* `(?m-i)` inside regexp means:
    + Use multiline mode. `^` and `$` match the beginning and end of a line, instead of the beginning and end of a string.
    + Use case-sensitive matching
* `|% M*` is shortcut for the property `Matches`, which gives a first match because we don't use `-AllMatches` parameter.

Test script:

```
$f = {

"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4

}

@(
,('Vrom!',1)
,('vrooooooom!',7)
,('Hello, Vroom!',-4)
,('Foo bar boo baz
Vrooom!
hi',3)
,('Vrm!ooo',-4)
,('PPCG puzzlers pie',-4)
,('hallo
vROOOm!',-4)
,('
Vrooom!
Vrooooom!
',3)        # undefined behavior.
,('vrm!',0) # :)
) | % {
    $n,$expected = $_
    $result = &$f $n
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 1
True: 7
True: -4
True: 3
True: -4
True: -4
True: -4
True: 3
True: 0

```
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~99~~ 82 bytes

```
I	INPUT POS(0) ('V' | 'v') 'r' ARBNO('o') @X 'm!' RPOS(0)	:F(I)
	OUTPUT =X - 2
END

```

Try it online!

Pretty direct SNOBOL translation of the spec, reads each line until it finds one that matches `^[Vv]ro*m!$`, then outputs the length of the `o*` bit.

Enters an infinite loop if no `Vroom!` can be found.
> 2 votes

# Answer
# PowerShell, 83 bytes

```
($args-split"`n"|%{if(($x=[regex]::Match($_,"^[Vv]ro*m!$")).success){$x}}).length-4

```

Try it online!

`-split`s the input `$args` on ``n`ewlines, pipes those into a for loop. Each iteration, we check whether our `[regex]::Match` is a `.success` or not. If so, we leave `$x` (the regex results object) on the pipeline. Outside the loop, we take the `.length` property -- if it's the regex results object, this is the length of the match (e.g., "Vroom!" would be 6); if it's not a regex results object, the length is zero. We then subtract `4` to remove the counts for the `Vrm!` and leave that on the pipeline. Output is implicit. Outputs a `-4` if no match is found.
> 2 votes

# Answer
# Retina, 21 bytes

```
L$m`^[Vv]r(o*)m!$
$.1

```

Try it online! Explanation: `L` lists matches, so if the regex fails to match then output is empty. `$` causes the result to be the substitution rather than the match. `m` makes it a multiline match (the equivalent to the trailing `m` in the question). The `.` in the substitution makes it output the length of the capture in decimal.
> 2 votes

# Answer
# Perl 6, 26 bytes

```
{-!/^^[V|v]r(o)*m\!$$/+$0}

```

Try it online!
> 2 votes

# Answer
# C (gcc), 188 183 bytes

Why use regexes when you can use a state machine instead? :-)

```
a,b;f(char*s){for(a=b=0;a<5;s++){!a&*s==86|*s=='v'?a++:a==1&*s=='r'?a++:a==2?*s-'o'?*s-'m'?0:a++:b++:a==3&*s==33?a++:!*s&a==4?a++:*s-10?(a=-1):a-4?(a=0):a++;if(!*s)break;}s=a<5?-1:b;}

```

Try it online!
> 2 votes

# Answer
# Stax, 16 bytes

```
∞╠mQ╛3mQ->n▀÷↕┐ò

```

Run and debug it
> 1 votes

# Answer
# Japt, 18 bytes

```
fè`^[Vv]*m!$` ®èo

```

Try it online!

Saved a byte by taking input as an array of lines.

Includes an unprintable character between `]` and `*`.

Explanation:

```
fè                   Get the line(s) that match
  `^[Vv]*m!$`          The provided RegEx with a little compression
              ®èo    Count the number of "o" in that line if it exists

```
> 1 votes

# Answer
# Haskell, ~~75~~ ~~71~~ 69 bytes

```
f s=[length n-2|r<-lines s,n<-scanr(:)"m!"$'o'<$r,v<-"Vv",r==v:'r':n]

```

Try it online!

No regex. Instead builds all valid `Vrooom!`-strings up to a sufficient length and compares the lines of the input against them, collecting the number of `o`s in a list. Thus for invalid inputs an empty list is returned.
> 1 votes

# Answer
# C (gcc), 138 124 bytes

Here's the boring regex way.

```
#include<regex.h>
f(char*s){regmatch_t m[9];regcomp(m+2,"^[Vv]r(o*)m!$",5);s=regexec(m+2,s,2,m,0)?-1:m[1].rm_eo-m[1].rm_so;}

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~104~~ 100 bytes

```
s;main(c,n){for(;gets(&s);sscanf(&s,"v%*[o]%nm%c%c",&n,&c,&c)-1||c-33?:printf("%d",n-2))s=s-768|32;}

```

Try it online!

Output the `n` for each valid line, exactly in the requirement(nothing if no valid line, the `n` if exactly one)

```
int s; // Use as a char[]
main(c){
  while(gets(&s)) {
    s=s-768|32; // byte 0: 'V'=>'v'; byte 1: 'r'=>'o', 'o'=>'l'
    if (sscanf(&s,"v%[o]m%c%c",&s,&c,&c)==2 && c=='!') {
    // The last '%c' get nothing if it's EndOfLine
      printf("%d",strlen(&s)-1))
    }
  }
}

```
> 1 votes

# Answer
# Pyth, 28 bytes

```
IJjb.nm:rd0"^vro*m!$"1.z/J\o

```

Try it online!
> 0 votes

# Answer
# Pyth, 20 bytes

```
/R\o:#"^Vro*m!$"1cQb

```

Outputs as a list containing only the number of 'o's, or an empty list if there's no Vroom.
Try it here

### Explanation

```
/R\o:#"^Vro*m!$"1cQb
                 cQb  Split on newlines.
    :#"^Vro*m!$"1     Filter the ones that match the regex.
/R\o                  Count the `o`s in each remaining element.

```
> 0 votes

# Answer
# C# (.NET Core), 134 122 bytes

```
for(var a="";a!=null;a=Console.ReadLine())if(new Regex(@"^[Vv]ro*m!$").Match(a).Success)Console.Write(a.Count(x=>x=='o'));

```

Try it online!

*-12 bytes: moved* `null` *check into* `for` *loop and removed brackets*

Ungolfed:

```
for(var a = ""; a != null; a = Console.ReadLine())  // initialize a, and while a isn't null, set to new line from console
    if(new Regex(@"^[Vv]ro*m!$")                        // set regex
                        .Match(a).Success)              // check if the line from the console matches
        Console.Write(a.Count(x => x == 'o'));              // write the number of 'o's to the console

```
> 0 votes

# Answer
# Pip, 21 bytes

```
a~,`^[Vv]r(o*)m!$`#$1

```

Try it online!

Match regex `^[Vv]r(o*)m!$` in multiline mode; output length of capture group.
> 0 votes

# Answer
## C++, MSVC, ~~164~~ 159 bytes

-5 bytes thanks to Zacharý

It compiles even with the `regex` header only

```
#include<regex>
using namespace std;int f(vector<string>i){smatch m;for(auto&e:i)if(regex_match(e,m,regex("^[Vv]ro*m!$")))return m[0].str().size()-4;return-1;}

```

Tests :

```
std::cout << "Vrom!" << " -> " << f({ "Vrom!" }) << '\n';
std::cout << "vrooooooom!" << " -> " << f({ "vrooooooom!" }) << '\n';
std::cout << "Hello, Vroom!" << " -> " << f({ "Hello, Vroom!" }) << '\n';
std::cout << "Foo bar boo baz \\n Vrooom! \\n hi" << " -> " << f({ "Foo bar boo baz", "Vrooom!", "hi" }) << '\n';
std::cout << "Vrm!ooo" << " -> " << f({ "Vrm!ooo" }) << '\n';
std::cout << "PPCG puzzlers pie" << " -> " << f({ "PPCG puzzlers pie" }) << '\n';
std::cout << "hallo \\n vROOOm!" << " -> " << f({ "hallo", "vROOOm!" }) << '\n';

```
> 0 votes

# Answer
# sfk, 94 bytes

```
xex -i -case "_[lstart][char of Vv]r[chars of o]m![lend]_[part 4]o_" +linelen +calc "#text-1"

```

Try it online!

Gives `-1` when you're not vrooming.
> 0 votes

# Answer
## JavaScript, 90 73 61 bytes

```
_=>_.replace(/^[Vv]r(o*)m!$|[^\1]/mg,(m,a)=>a||'').length||-1

```

Try it online!

Replace characters that are not captured at `(o*)` with empty string, return `length` of string containing only `"o"` or `-1` if resulting string is empty.
> 0 votes

# Answer
# Ruby, ~~28~~ 29 bytes

```
p$_[/^[vV]r(o*)m!$/].count ?o

```

Try it online!

Multi-line strings require three more bytes. I'm not sure if that's a hard requirement. If so, I'll update this.

```
->l{l[/^[Vv]r(o*)m!$/].count ?o}

```
> 0 votes

# Answer
# Red, 104 bytes

```
func[s][n:""if parse/case s[opt[thru"^/"]["V"|"v"]"r"copy n any"o""m!"opt["^/"to end]][print length? n]]

```

Try it online!

A straightforward solution. Red's `parse` is cool and readable, but too long compared to regex

```
Red []
f: func [ s ] [
    n: ""
    if parse/case s [
             opt [ thru newline ]
             [ "V" | "v" ]
             "r"
             copy n any "o"
             "m!"
             opt [ newline to end ]
    ] [ print length? n ]
]

```
> 0 votes

# Answer
# J, 35 bytes

```
(]{~0<{.)(1{'^[Vv]r(o*)m!'rxmatch])

```

Returns negative 1 if the pattern doesn't match.
> 0 votes

# Answer
# Ruby, 32 bytes

```
->n{n=~/^[Vv]r(o*)m!$/m;$1.size}

```

Matches the string to the regex, then uses Ruby's magic regex group variables to get the first group's size.

Call it like so:

```
x=->n{n=~/^[Vv]r(o*)m!$/m;$1.size}
x["Vrooooooooooooooooooooom!"] # returns 21

```
> 0 votes

# Answer
# Clojure, 90 bytes

```
#(do(def a(clojure.string/replace % #"(?ms).*^[Vv]r(o*)m!$.*""$1"))(if(= a %)-1(count a)))

```

Try it online!

This anonymous function returns the number of "o"s in the vroom string, or -1 if there is no valid vroom string.

### Readable version

```
(fn [s]
  (def a (clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1"))
  (if (= a s) -1 (count a)))

```

### Explanation

```
#"(?ms).*^[Vv]r(o*)m!$.*" ; This regex matches any string that contains a valid vroom string. The first capturing group contains only the "o"s in the vroom string
(clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1") ; Replaces a match of the above regex with its first capturing group. The resulting string is stored in the variable a
(if (= a s) -1 (count a))) ; a equals s if and only if there is no valid vroom string, so if a equal s we return -1. If there is a valid vroom string, a contains only the "o"s from the vroom string, so we return the length of a

```
> 0 votes

# Answer
# perl -nE, 35 bytes

```
$s=length$1if/^[Vv]r(o*)m!$/}{say$s

```

This uses the *Eskimo greeting* (`}{`) which abuses the a quick on how the `-n` option is dealt with by perl.
> 0 votes

# Answer
# Java 8, 109 bytes

```
s->{int r=-1;for(var l:s.split("\n"))r=l.matches("[Vv]ro*m\\!")?l.replaceAll("[^o]","").length():r;return r;}

```

Try it online.

**Explanation:**

```
s->{                             // Method with String parameter and integer return-type
  int r=-1;                      //  Result-integer, starting at -1
  for(var l:s.split("\n"))       //  Loop over the lines:
    r=l.matches("[Vv]ro*m\\!")?  //   If the current line matches the regex:
       l.replaceAll("[^o]","").length()
                                 //    Change `r` to the amount of "o"'s in it
      :                          //   Else:
       r;                        //    Leave the result `r` unchanged
  return r;}                     //  Return the result

```
> 0 votes

# Answer
# 05AB1E, ~~39~~ 37 bytes

```
|ʒć„VvsåsÁÁD…m!rÅ?s¦¦¦Ù'oså)P}Dgi`'o¢

```

Although 05AB1E is a golfing languages, regex-based challenges are definitely not its strong suite, since it has no regex-builtins.

Outputs `[]` if no match was found.

Try it online or verify all test cases.

**Explanation:**

```
|              # Get the input split by newlines
 ʒ             # Filter it by:
  ć            #  Head extracted: Pop and push the remainder and head-character
               #   i.e. "vrm!" → "rm!" and "v"
               #   i.e. "Vroaom!" → "roaom!" and "V"
   „Vvså       #  Is this head character in the string "Vv"?
               #   i.e. "v" → 1 (truthy)
               #   i.e. "V" → 1 (truthy)
  s            #  Swap so the remainder is at the top of the stack again
   ÁÁ          #  Rotate it twice to the right
               #   i.e. "rm!" → "m!r"
               #   i.e. "roaom!" → "m!roao"
     D         #  Duplicate it
      …m!rÅ?   #  Does the rotated remainder start with "m!r"?
               #   i.e. "m!r" → 1 (truthy)
               #   i.e. "m!roao" → 1 (truthy)
  s¦¦¦         #  Remove the first three characters from the duplicated rotated remainder
               #   i.e. "m!r" → ""
               #   i.e. "m!roao" → "oao"
      Ù        #  Uniquify, leaving only distinct characters
               #   i.e. "" → ""
               #   i.e. "oao" → "oa"
       'oså   '#  Is this uniquified string in the string "o"?
               #   i.e. "" → 1 (truthy)
               #   i.e. "oa" → 0 (falsey)
  )P           #  Check if all three checks above are truthy
               #   i.e. [1,1,1] → 1 (truthy)
               #   i.e. [1,1,0] → 0 (falsey)
 }             # Close the filter
  D            # After the filter, duplicate the list
   gi          # If its length is 1:
               #   i.e. ["vrm!"] → 1 (truthy)
               #   i.e. [] → 0 (falsey)
     `         #  Push the value in this list to the stack
               #   i.e. ["vrm!"] → "vrm!"
      'o¢     '#  And count the amount of "o" in it (and output implicitly)
               #   i.e. "vrm!" → 0
               # (Implicit else:)
               #  (Implicitly output the duplicated empty list)
               #   i.e. []

```
> 0 votes

# Answer
## 16-bit x86 assembly code, 35 bytes

```

l1: lodsb          ;fetch a byte
    cbw            ;zero AH to allow returning 0
    cwd            ;zero counter
l2: and   al, 0dfh ;lower- to upper-case
    je    l4       ;exit if end of string
    cmp   al, 'V'
    jne   l1
    lodsb          ;fetch a byte
    cmp   al, 'r'
    jne   l2       ;if not 'r', branch to try 'v' or 'V' instead
l3: lodsb          ;fetch a byte
    test  al, al
    je    l4       ;exit if end of string
    inc   dx       ;speculatively count 'o's
    cmp   al, 'o'
    je    l3       ;loop while 'o'
    lodsw          ;fetch two bytes
    dec   si       ;align pointer as though only one byte fetched
                   ;in case of mismatch at the end
    cmp   ax, '!m' ;Intel backwards ordering
    jne   l2       ;loop while not matching complete string
    xchg  dx, ax   ;return count only if match
l4: ret
```

Accepts a pointer to the string in si, returns the count (or 0) in ax.
> 0 votes

# Answer
# Kotlin, 55 bytes

```
{Regex("^[Vv]ro*m!\$").find(it)?.value?.count{it=='o'}}

```

Try it online!
> 0 votes

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


title: Doce logf a string swapper

text:
# Question
Title: Doce logf a string swapper
# Challenge

Take an input string \\$s\\$, and split it into words \\$w\_1, w\_2, ..., w\_n\\$. If the amount of words is odd, then return \\$s\\$. Otherwise, for each word: Take the *second last* letter, and swap it with the first letter keeping capitalization positions. So `GolF` becomes `LogF`.

Now check if the amount of words is a multiple of 2, if they are, then take the new words and make another set of words \\$q\_1, q\_2, ..., q\_{n/2}\\$, where \\$q\_n\\$ is a concatenation of \\$w\_n\\$ and \\$w\_{2n}\\$ before applying the whole thing again to the \\$q\\$ words.

If the amount of words isn't a multiple of 2, then return \\$w\\$ separated by spaces.

---

# Example

String: `Hello bye hey world woo doo`.

* Split it: `[Hello, bye, hey, world, woo, doo]`
* Is the length an even number? Yes, proceed
* Swap the first and second-last letters: `[Lelho, ybe, ehy, lorwd, owo, odo]`
* Is the length an even number? Yes, make new groups of 2: `[Lelho ybe, ehy lorwd, owo odo]`
* Swap again: `[Belho yle, why lored, dwo ooo]`
* Is the length an even number? No, return `Belho yle why lored dwo ooo`

---

# Notes

* Input words will always have more than 2 characters
* Input will always be letters from a-z, capital or lowercase, and separated by a single space
* Standard loopholes and Default I/O rules apply
* You may not take input in the form of a word list/array
* You don't need to handle edge cases

---

# Test Cases

```
Hello bye hey world woo doo   --> Belho yle why lored dwo ooo
Code golf awesome stuff       --> Goce lodf swesoae ftumf
Very hard code golf challenge --> Very hard code golf challenge (odd length)
Very hard coding stuff        --> Hevy rard sodicg ftunf

```

---

# Scoring

This is , so the shortest code (in bytes) wins.

# Answer
> 1 votes
# Node.js v10.9.0, 171 bytes

```
s=>(h=a=>a.map(w=>Buffer(w).map((c,i,a)=>(i?i-p?c:x:a[x=c,p=w.length-2])&31|c&96)+''),g=n=>n&1?a.join` `:g(n/2,a=h(h(a).join` `.match(/\S+ \S+/g))))((a=s.split` `).length)

```

Try it online!

### Commented

The helper function \\$h\\$ takes an array of words \\$a\\$ and apply the letter transformation to each of them.

```
h = a =>                     // a[] = input array
  a.map(w =>                 // for each word w in a[]:
    Buffer(w)                //   convert w to a Buffer
    .map((c, i, a) =>        //   for each ASCII code c at position i in this array a[]:
      ( i ?                  //     if this is not the first letter:
          i - p ?            //       if this is not the second last letter:
            c                //         just use c
          :                  //       else:
            x                //         use the backup x of the first letter
        :                    //     else:
          a[                 //       use the second last letter
            x = c,           //       save the first letter in x
            p = w.length - 2 //       p = index of the second last letter
          ]                  //
      ) & 31                 //     use the lower bits of the above character
      | c & 96               //     use the upper bits of the current character (case)
    ) + ''                   //   end of inner map(); coerce the Buffer back to a string
  )                          // end of outer map()

```

Main part:

```
s => (                       // s = input string
  g = n =>                   // g = recursive function taking the number of words n
    n & 1 ?                  // if n is odd:
      a.join` `              //   stop recursion and return a[] joined with spaces
    :                        // else:
      g(                     //   do a recursive call to g:
        n / 2,               //     with n / 2
        a = h(               //     update a[]:
          h(a)               //       apply the letter transformation
          .join` `           //       join with spaces
          .match(/\S+ \S+/g) //       make groups of 2 words
        )                    //     apply the letter transformation again on the result
      )                      //   end of recursive call
)((a = s.split` `).length)   // initial call to g with a[] = list of words, n = length

```

# Answer
> 0 votes
# Python 3, 189 bytes

```
J=' '.join
s=input().split()
f=lambda w,i:(w[~i].lower(),w[~i].upper())[w[i-1].isupper()]
while~len(s)&1:s=[f(w,1)+w[1:-2]+f(w,-1)+w[-1]for w in s];s=[*map(J,zip(s,s[1:]))][::2]
print(J(s))

```

Try it online!

# Answer
> 0 votes
# Charcoal, 68 bytes

```
≔⪪Ｓ θＦ¬﹪Ｌθ²«≔¹ηＷ¬﹪Ｌθη«≔ＥＥ⪪θη⪫λ ⭆⭆Ｅλ⁻⁻Ｌλξ²§λ⎇∧νξξν⎇№α§λξ↥ν↧νθ≔²η»»⪫θ

```

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

```
≔⪪Ｓ θ

```

Split the input on spaces.

```
Ｆ¬﹪Ｌθ²«

```

Do nothing if the number of words is odd.

```
≔¹η

```

Don't pair the words up on the first pass.

```
Ｗ¬﹪Ｌθη«

```

Repeat while the number of words is even.

```
≔ＥＥ⪪θη⪫λ ...θ

```

Pair the words up, map over the paired words, and save the result.

```
Ｅλ⁻⁻Ｌλξ²

```

Map each character index to the length of the word minus the index minus 2.

```
⭆...§λ⎇∧νξξν

```

Map each character to itself unless its index or the above calulation is zero in which case use the character at the index given by the above calculation.

```
⭆...⎇№α§λξ↥ν↧ν

```

Map each character to upper or lower case depending on whether the original character of that word was upper or lower case.

```
≔²η»»

```

Pair the words up on successive passes.

```
⪫θ

```

Join the (remaining) words on spaces and implicitly print.

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


title: Magic: The Gathering, Paying for Spells

text:
# Question
Title: Magic: The Gathering, Paying for Spells
For more MtG-goodness: Magic: The Gathering Combat with Abilities

# Premise:

In Magic: the Gathering, you cast spells by paying their mana cost by tapping lands for the required amount. These lands can produce one of the five colors which are:

* White (W)
* Blue (U)
* Black (B)
* Red (R)
* Green (G)

The cost is made up of two parts: a number which is the generic mana requirement, and a series of symbols representing the colored mana requirement. The number is the generic mana cost and can use any color of mana to satisfy it, e.g. `(3)` can be paid with `WGG`. The symbols are a 1:1 requirement of a specific color. e.g. `WWUBR` would require 2 white mana, 1 blue, 1 black and 1 red. **The Generic part will always come before the Colored part.** As a reminder, `(0)` is a valid cost and must be handled.

You can have costs that are entirely generic, or entirely colored, or both. For example, the following card has a cost of 4BB and is be paid with 4 of whatever colored mana and 2 black mana:

Lands in this challenge will each produce one mana. However, we will consider lands that can produce multiple colors but still only yield 1 mana. E.g. `G` will produce a green mana, `WG` can produce either 1 white or 1 green.

# Input:

You will be given two inputs, a card's cost and a list of lands.

The card's cost can either be a string, or a tuple containing a number and a string for the colored part. If there's no generic part, you can pad the string/tuple with a 0.

The land list will be a list of strings where each one is what a given land can produce. This list can be empty (you have no lands). You can also take this as a list of ints using bit-mask logic but post your scheme if you do. Order is also up to you if it matters, otherwise it'll be assumed in `WUBRG` order.

```
#Example input formats
"4BB", ("WG","B","B") #
(4,"BB"), (7,3,3)     #Both should return falsy

```

# Output:

A `truthy` value if you can successfully pay the cost given your lands and a `falsey` value if you cannot.

# Rules:

* You'll be guaranteed valid input
* Mana will be assumed to always be in "WUBRG" order. If you want a different order, state so in your answer.
* Colors will always be grouped in the cost, e.g. "WWUBBRG"
* Input will use either all Uppercase or all lowercase, your choice.
* You should be able to handle regex `127[WUBRG]{127}` and 254 lands.
* Standard loopholes forbidden
* This is , shortest answer per language wins

# Examples:

```
"0", ("")                => 1
"1BB", ("WG","B","B")    => 1
"BB", ("WG","B","B")     => 1
"WB", ("WG","B","B")     => 1
"1UB", ("W","U","B")     => 1
"1BB", ("WB","WB","WG")  => 1
"1", ("WG","B","B")      => 1
"1BB", ("WGR","WB","WB") => 1
"WUBRG", ("W","U","B","R","G")  => 1
"1WWUBB", ("W","WG","U","B","B","R")  => 1
"10BB", ("WGR","WB","WB","B","B","B","B","B","B","B","B","B") => 1

"R", ("")                => 0
"4", ("WG","B","B")      => 0
"1BB", ("WG","WB")       => 0
"1UB", ("WG","W","UB")   => 0
"1UBR", ("W","WG","UBR") => 0
"WUBRG", ("WUBRG")       => 0
"1WWUBB", ("W","WG","U","B","B")  => 0
"10UU", ("WGR","WB","WB","B","B","B","B","B","B","B","B","B") => 0

```

# Answer
# JavaScript (ES6), 91 bytes

Takes input as `(cost)(lands)`:

* \\$cost\\$ is a list of characters in `BGRUW` order, prefixed with the generic part, even when it's \\$0\\$
* \\$lands\\$ is a list of strings.

```
a=>g=([c,...r],n=0,s=e='')=>[...n+s].sort()+e==a|(c&&[e,e,...c].some((c,i)=>g(r,n+!i,s+c)))

```

Try it online!

### Commented

```
a =>                        // main function taking the array a[] describing the cost
  g = (                     // g = recursive function taking:
    [c, ...r],              //   c = next land string; r[] = remaining land strings
    n = 0,                  //   n = generic mana, initialized to 0
    s = e = ''              //   s = generated cost string, initialized to e = empty string
  ) =>                      //
    [...n + s].sort() + e   // prepend n to s, split, sort and force coercion to a string
    == a | (                // if this is matching a[], the test is successful
      c &&                  // if c is defined:
      [                     //   try the following recursive calls:
        e,                  //     - increment n and append nothing to s
        e,                  //     - do nothing
        ...c                //     - leave n unchanged and append a character to s
      ].some((c, i) =>      //   for each c at position i in the above array:
        g(r, n + !i, s + c) //     process the recursive call
      )                     //   end of some()
    )                       // end of the recursive part

```
> 3 votes

# Answer
# Python 2, ~~131~~ 129 bytes

```
lambda (g,c),m:any(all(c[i]in p[i]for i in range(l(c)))for p in permutations(m,l(c)))*(g<=l(m)-l(c))
l=len
from itertools import*

```

Try it online!
> 2 votes

# Answer
# Retina, 60 bytes

```
\d+
*
~["^("|'|]")*\n"1,L$`(?<=(^|.*¶)+).*
(?($#1)^|([_$&]))

```

Try it online! Link includes test cases. Explanation:

```
\d+
*

```

Convert the generic mana to unary. This uses repeated `_`s.

```
1,L`.*

```

Match all lines after the first, i.e. the list of lands. (This would normally match again at the very end of the input, but the lookbehind prevents that.)

```
(?<=(^|.*¶)+)

```

Capture the 1-indexed line number in `$#1`.

```
$
(?($#1)^|([_$&]))

```

Replace each land with a regex that captures costs matching that land or generic costs, but only once.

```
|'|

```

Join the resulting regexes with `|`s.

```
["^("]")*\n"

```

Wrap the regex in `^(` and `)*\n` (I can't seem to insert a  here).

```
~

```

Count the number of matches of that regex on the current value.

Example: For the case of `1BB¶WB¶WB¶WG` the generated regex is:

```
^((?(2)^|([_WB]))|(?(3)^|([_WB]))|(?(4)^|([_WG])))*\n

```

which `_BB¶WB¶WB¶WG` matches as required.
> 2 votes

# Answer
# Perl 6, ~~56~~ 46 bytes

```
{(1 x*~*).comb.Bag⊆any [X] $(1 X~$_)>>.comb}

```

Try it online!

Curried function. Takes input as `(@lands)($generic_cost, $colored_costs)` with an explicit 0 for generic cost. The basic idea is to introduce a new symbol `1` representing generic mana and use Perl 6 Bags (multisets) to check whether it's possible to obtain the required mana from lands.

### Explanation

```
{ ... }  # Anonymous block returning WhateverCode
  # Preprocess cost
  1 x*    # '1' for generic mana repeated times generic cost
      ~*  # Concat with colored costs
 (      ).comb  # Split into characters
              .Bag  # Convert to a Bag (multiset)
                             # Preprocess lands
                             1 X~$_   # Prepend '1' to each land
                           $(      )  # Itemize to make 1-element lists work
                                    >>.comb  # Split each into chars
                       [X]  # Cartesian product, yields all possible ways
                            # to select colors from lands
                  # Finally check if the cost Bag is a subset of any possible
                  # color selection (which are implicitly converted to Bags)
                  ⊆any

```
> 1 votes

# Answer
# Jelly, 21 bytes

```
Œpµ®œ-)Ạ
L<⁴Ṫ©L+Ḣ¤ȯçṆ

```

Try it online!

Outputs

The input format is what really makes this hard for Jelly. Because  and  modify the array, we need to use `©` and `®` in addition. With 3 separate inputs this would be 18 bytes. (Although I'm sure there's 14 or so byte solution waiting to be posted by one of the Jelly masterminds.)
> 1 votes

# Answer
# Pyth, 25 bytes

```
&glQ+hAElH}k.-LHusM*GHQ]k

```

Try it online!

If Pyth had a "Cartesian product of array" function like Jelly's `Œp`, this would easily beat my Jelly solution. Currently that is done by `usM*GHQ]k`.
> 1 votes

# Answer
# Haskell, 94 bytes

```
x#[]=[]
x#(s:t)|x`elem`s=t|0<1=s:x#t
(e,[])?s=length s>=e
(e,x:y)?s|x#s==s=0>1|0<1=(e,y)?(x#s)

```

Try it online!

We rely on the fact that all colors will be given in the same order in the cost and in the land list. First we tap the lands giving the required colored mana and after that just check that we still have enough lands to pay the colorless cost.
> 1 votes

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


title: Gold nugget storage

text:
# Question
Title: Gold nugget storage
Given a positive integer, write it as the sum of numbers, where each of them is in \\$\\{kt|k\in{1,9,81},t\in{1,2,3,...,64}\\}\\$. How many numbers at least are used? Shortest code win.

Samples:

```
Input  Output Method
1      1      1
2      1      2
64     1      64
65     2      64+1
72     1      72
343    2      342+1
576    1      576
577    2      576+1
5184   1      5184
46656  9      5184+5184+5184+5184+5184+5184+5184+5184+5184
5274   2      5184+90

```

# Answer
# Jelly, 17 bytes

```
64R×9;Ɗ⁺ff€¥@ŒṗẈṂ

```

Try it online!

-1 thanks to Jonathan Allan.

Explanation (you can't test for inputs larger than `58` over TIO):

```
64R×9;Ɗ⁺ff€¥@ŒṗẈṂ Arguments: x
64R               [1..64]
   ×9;Ɗ           Multiply by 9, prepend to original list
       ⁺          Do the above once more
             Œṗ   Positive integer partitions of x
           ¥@     Call with reversed arguments (x = partitions, y = flattened outer product)
         f€         For each partition in x, keep the elements that are in y
        f           Keep the elements of x that have remained intact after the above
               Ẉ  Lengths of the remaining partitions
                Ṃ Minimum

```
> 3 votes

# Answer
# JavaScript (ES6), ~~72~~ ~~66~~ ~~57~~ 56 bytes

*Saved 1 byte thanks to @nwellnhof*

```
f=n=>n&&1+f(n<5184?n>64&&n%(n<576?9:n>719?81:72):n-5184)

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~30~~ 27 bytes

```
ŽK≠‰`91vDy64*›i1sy9*%]64/îO

```

Try it online! or verify all test cases

*-3 bytes thanks to Kevin Cruijssen*

This is my first 05AB1E submission, so I am sure that this can be optimized.
> 2 votes

# Answer
# Perl 6, 47 bytes

```
{+($_,(*X-(1,9,81 X*^65)).grep(*>=0).min...^0)}

```

Try it online!

A greedy algorithm seems to work.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 66 bytes

```
Min[Length/@IntegerPartitions[#,All,Union[#,9#,81#]&@Range@64,#]]&

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Should this identifier be suggested?

text:
# Question
Title: Should this identifier be suggested?
## Introduction

In Android Studio and other IDEs there are code completions to assist efficient code insertion (especially when the names of the classes or methods are so verbose), like the one in the image below.

There are slightly different logics used between IDEs to determine what classes, methods and variables to suggest, but otherwise are common: typing the initial letters of each word, and the identifier matching those initial letters will be suggested.

## Challenge

In this challenge, write a program or function which receives two strings, namely `input` and `identifier`, determine whether the `identifier` matches the `input`.

We split `identifier` into words where:

* a lowercase letter is followed by an uppercase letter (`"SplitHere" -> "Split", "Here"`),
* an uppercase letter is followed by an uppercase letter and a lowercase letter (`"SPLITHere" -> "SPLIT", "Here"`), or
* there is a number or an underscore `_` (`"SPLIT_HERE" -> "SPLIT", "HERE"`).

If this is still not clear enough, here is the regex representing the condition to split: `(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|[_0-9]`. Here are a few samples:

* `theWord_Example`, in which 3 words (`the`, `Word`, `Example`) can be found.
* `THEWORD2EXAMPLE`, in which only 2 words (`THEWORD`, `EXAMPLE`) can be found (because `THEWORD` is a run of uppercase letters and so does `EXAMPLE`).
* `THEWordEXAMPLE3`, in which 3 words (`THE`, `Word`, `Example`) can be found (`Word` is considered to be a separate word here).
* `THEWORDEXAMPLEFOUR`, in which only 1 words (`THEWORDEXAMPLEFOUR`) can be found (the whole run of uppercase letters).

For this purpose here we use a simplified version. In reality the logic is far more complex. In this version there are only two rules:

1. If `input` consists of only lowercase letters, then an `identifier` matches the `input` only if there is a splitting of `input` into substrings, that for each substring there is a word within the `identifier` starting with that substring, in that exact order.

> Example input: `sbo`
>
> Truthy cases: `**S**QLite**B**ind**O**rColumnIndexOutOfRangeException`, `**S**parse**Bo**oleanArray`, **(UPDATE)** `**S**tringIndexOutOf**Bo**undException`
>
> Falsy cases: `SeekBar` (missing `o`), `**S**tatus**B**arN**o**tification` (the `o` is not at the beginning of a word)
2. If `input` contains uppercase letters, then a split on the `input` must be made before each uppercase letter when applying Rule 1.

> Example input: `sbO`
>
> Truthy cases: `**S**QLite**B**ind**O**rColumnIndexOutOfRangeException`
>
> Falsy cases: `**S**parse**Bo**oleanArray` (the `O` must appear at the beginning of a word), `**S**tringIndex**O**utOf**B**oundException` (wrong order)

## I/O

**Input**: two strings, one for `input` and one for `identifier`. You can assume that the regex `[A-Za-z]+` matches `input` and the regex `[A-Za-z0-9_]` matches `identifier`.

**Output**: one of the truthy or falsy values. You can choose what value to return as truthy and what as falsy, but your choice must be consistent across all cases. For example you can return `1/0`, `true/false`, `π/e` or whatever, but they must stay the same across all cases.

## Test cases

Each line consists of two strings, namely `input` and `identifier` respectively.

Truthy cases:

```
"sbo" "SparseBooleanArray"
"sbo" "StringIndexOutOfBoundException"
"sbo" "SQLiteBindOrColumnIndexOutOfRangeException"
"sbO" "SQLiteBindOrColumnIndexOutOfRangeException"
"Al" "ArrayList"
"AL" "ArrayList"
"Al" "ALARM_SERVICE"
"As" "ALARM_SERVICE"
"AS" "ALARM_SERVICE"
"SD" "SQLData"
"SqD" "SQLData"
"SqlD" "SQLData"
"SqDa" "SQLData"
"the" "theWord_Example"
"the" "THEWORD2EXAMPLE"
"the" "THEWordEXAMPLE3"
"the" "THEWORDEXAMPLEFOUR"
"thw" "theWord_Example"
"thw" "THEWordEXAMPLE3"
"te" "theWord_Example"
"te" "THEWORD2EXAMPLE"
"te" "THEWordEXAMPLE3"

```

Falsy cases:

```
"sbo" "SeekBar"
"sbo" "StatusBarNotification"
"sbO" "StringIndexOutOfBoundException"
"sbO" "SparseBooleanArray"
"AL" "ALARM_SERVICE"
"ASE" "ALARM_SERVICE"
"SQD" "SQLData"
"SqLD" "SQLData"
"SLD" "SQLData"
"SQDt" "SQLData"
"SQDA" "SQLData"
"thw" "THEWORD2EXAMPLE"
"thw" "THEWORDEXAMPLEFOUR"
"te" "THEWORDEXAMPLEFOUR"

```

## Winning Criteria

This is a , so shortest code of each language wins. Default loopholes are not allowed.

# Answer
> 1 votes
# Python 2, ~~239~~ 227 bytes

```
lambda a,b:any(re.match(w,''.join(map(str.title,re.sub('(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])|(\d)','_',b).split('_'))))for w in g(a))
import re
g=lambda s:s and{c+w for w in g(s[1:])for c in[s[0],'.*'+s[0].upper()][s<'[':]}or{''}

```

Try it online!

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

Expects `(identifier)(input)`.

```
S=>g=([c,...s],l=[],o='')=>c?g(s,o?[...l,o]:l,c)|c>{}&g(s,l,o+c):eval(`/~${[...l,o].join`.*~`}/i`).test(S.replace(/./g,(c,i)=>!i|(!/[A-Z]/.test(l)|S[i+1]>'_')&(l=c)<{}?'~'+c:c))

```

Try it online!

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


title: Through Space and Time

text:
# Question
Title: Through Space and Time
## Introduction:

In general we usually speak of four dimensions: three space dimensions for `x`, `y`, and `z`; and one time dimension. For the sake of this challenge however, we'll split the time dimension into three as well: `past`, `present`, and `future`.

## Input:

Two input-lists. One containing integer `x,y,z` coordinates, and one containing integer years.

## Output:

One of any four distinct and constant outputs of your own choice. One to indicate the output `space`; one to indicate the output `time`; one to indicate the output `both space and time`; and one to indicate the output `neither space nor time`.

We'll indicate we went to all three space dimensions if the differences of the integer-tuples is not 0 for all three dimensions.
We'll indicate we went to all three time dimensions if there is at least one year in the past, at least one year in the future, and at least one year equal to the current year (so in the present).

## Example:

**Input:**
Coordinates-list: `[{5,7,2}, {5,3,8}, {-6,3,8}, {5,7,2}]`
Year-list: `[2039, 2019, 2018, 2039, 2222]`

**Output:**
Constant for `space`

**Why?**
The `x` coordinates are `[5,5,-6,5]`. Since they are not all the same, we've went through the `x` space dimension.
The `y` coordinates are `[7,3,3,7]`. Since they are not all the same, we've also went through the `y` space dimension.
The `z` coordinates are `[2,8,8,2]`. Since they are not all the same, we've also went through the `z` space dimension.
The current year is `2018`. There are no years before this, so we did not visit the `past` time dimension.
There is a `2018` present in the year-list, so we did visit the `present` time dimension.
There are multiple years above `2018` (`[2039, 2019, 2039, 2222]`), so we also visited the `future` time dimension.

Since we've visited all three `space` dimensions, but only two of the three `time` dimensions, the output will only be (the constant for) `space`.

## Challenge rules:

* You can use any four distinct and constant outputs for the four possible states.
* Input can be in any reasonable format. Coordinates list can be tuples, inner lists/arrays of size 3, strings, objects, etc. List of years may be a list of date-objects instead of integers as well if it would benefit your byte-count.
* You can assume the `x,y,z` coordinates will be integers, so no need to handle floating point decimals. Any of the `x`, `y`, and/or `z` coordinates can be negative values, though.
* You cannot take the input-lists pre-ordered. The input-lists should be in the order displayed in the test cases.
* You can assume all year values will be in the range `[0,9999]`; and you can assume all coordinates are in the range `[-9999,9999]`.
* If your language doesn't have ANY way to retrieve the current year, but you'd still like to do this challenge, you may take it as additional input and mark your answer as ***(non-competing)***.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Coordinates-input: [{5,7,2}, {5,3,8}, {-6,3,8}, {5,7,2}]
Years-input:       [2039, 2019, 2018, 2039, 2222]
Output:            space

Coordinates-input: [{0,0,0}, {-4,-4,0}, {-4,2,0}]
Years-input:       [2016, 2019, 2018, 2000]
Output:            time

Coordinates-input: [{-2,-2,-2}, {-3,-3,-3}]
Years-input:       [2020, 1991, 2014, 2018]
Output:            both

Coordinates-input: [{5,4,2}, {3,4,0}, {1,4,2}, {9,4,4}]
Years-input:       [2020, 1991, 2014, 2017, 2019, 1850]
Output:            neither

```

# Answer
> 2 votes
# 05AB1E, 15 bytes

Output is a list `[space, time]` where **1** stands for `x` and **0** stands for `no x`

```
ø€Ë_Psžg.SÙg3Q)

```

Try it online!

**Explanation**

```
    ø                 # zip space coordinates
     €Ë               # for each axis, check that all values are equal
       _              # logical negation
        P             # product (1 for space, 0 for no space)
         s            # put the time list on top of the stack
          žg.S        # compare each with the current year
              Ù       # remove duplicates
               g3Q    # check if the length is 3
                  )   # wrap the space and time values in a list

```

# Answer
> 6 votes
# Perl 6, ~~47~~ 46 bytes

*-1 byte thanks to nwellnhof*

```
{Set(@^b X<=>Date.today.year)>2,max [Z==] @^a}

```

Try it online!

Anonymous code block that takes two lists and returns a tuple of booleans, with the first element being whether you traveled in time, and the second being whether you didn't traveled in space.

### Explanation

```
{                                            }  # Anonymous code block
     @^b X         # Map each element of the year list to:
          <=>      # Whether it is smaller, equal or larger than
             Date.today.year  # The current year
 Set(                       )    # Get the unique values
                             >2  # Is the length larger than 2?
                               ,
                                    [Z  ] @^a   # Reduce by zipping the lists together
                                max       # And return if any of them are
                                      ==  # All equal

```

# Answer
> 6 votes
# Python 2, ~~111~~ 109 bytes

```
lambda S,T:(min(map(len,map(set,zip(*S))))>1,date.today().year in sorted(set(T))[1:-1])
from datetime import*

```

Try it online!

# Answer
> 3 votes
# Japt, 22 bytes

Takes input as a 2D-array of integers for the space dimensions and a 1D-array of integers for the years. Outputs `2` for space only, `1` for time only, `3` for both and `0` for neither.

```
yâ mÊeÉ Ñ+!Jõ kVmgKi¹Ê

```

Try it

```
                           :Implicit input of 2D-array U=space and array V=time
y                          :Transpose U
 â                         :Deduplicate columns
   m                       :Map
    Ê                      :  Lengths
     e                     :All truthy (not 0) when
      É                    :  1 is subtracted
        Ñ                  :Multiply by 2
           J               :-1
            õ              :Range [-1,1]
              k            :Remove all the elements present in
               Vm          :  Map V
                 g         :    Signs of difference with
                  Ki       :    The current year
                    ¹      :End removal
                     Ê     :Length
         +!                :Negate and add first result

```

# Answer
> 2 votes
# Japt, 25 bytes

*I'm 100% sure this is not the best approach, still looking for some shorter way to do this :c*

Returns a tuple of booleans. The first is if you traveled in space and the second if you traveled in time

```
[Uyâ e_Ê¦1ÃV®-Ki)gÃâ Ê¥3]

```

---

```
[Uyâ e_Ê¦1ÃV®-Ki)gÃâ Ê¥3]   Full Program, U = Space, V = Time
                            -- U = [[-2,-2,-2], [-3,-3,-3]]
                            -- V = [2020, 1991, 2014, 2018]
[                       ]   Return array containing....
 Uyâ                        Transpose Space coords
                            -- U = [[-2,-3], [-2,-3], [-2,-3]]
                            and map Z
      _Ê¦1                  Z length greater than 1?
                            -- U = [true, true, true]
     e                      return true if all Z are true
                            -- U = true
          V®                Map each time
            -Ki)            Subtract current year
                            -- V = [2,-27,-4,0]
                gÃ          get sign (-1,0,1)
                            -- V = [1,-1,-1,0]
                   â        unique elements
                            -- V = [1,-1,0]
                     Ê¥3    return true if length == 3
                            -- V = true

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), ~~104~~ 100 bytes

Takes input as `(space)(time)`. Returns \\$1\\$ for *time*, \\$2\\$ for *space*, \\$3\\$ for *both* or \\$0\\$ for *neither*.

24% of the code is spent figuring out in which year we are ... \o/

```
s=>t=>2*s[0].every((x,i)=>s.some(b=>x-b[i]))|t.some(y=>(s|=(y/=(new Date).getFullYear())>1?4:y+1)>6)

```

Try it online!

### Commented

```
s => t =>              // s[] = space array; t[] = time array
  2 *                  // the space flag will be doubled
  s[0].every((x, i) => // for each coordinate x at position i in the first entry of s[]:
    s.some(b =>        //   for each entry b in s[]:
      x - b[i]         //     if we've found b such that b[i] != x, the coordinate is valid
    )                  //   end of some()
  )                    // end of every()
  |                    // bitwise OR with the time flag
  t.some(y =>          // for each year y in t[]:
    (s |=              //   update the bitmask s (initially an array, coerced to 0)
      ( y /=           //     divide y
        (new Date)     //     by the current year (this is safe as long as no time-travel
        .getFullYear() //     machine is available to run this it at year 0)
      ) > 1 ?          //   if the result is greater than 1:
        4              //     do s |= 4 (future)
      :                //   else:
        y + 1          //     do s |= y + 1; y + 1 = 2 if both years were equal (present)
                       //     otherwise: y + 1 is in [1, 2), which is rounded to 1 (past)
    ) > 6              //   set the time flag if s = 7
  )                    // end of some()

```

# Answer
> 1 votes
# , ~~106~~, 105 bytes

```
function(s,t)all((x<-apply(s,1,range))[1,]-x[2,])-2*all((-1:1)%in%sign(as.POSIXlt(Sys.Date())$ye+1900-t))

```

Try it online!

Input :

```
s : matrix of space coordinates (3 x N)
t : vector time years

```

Output an integer value equal to :

```
 1 : if traveled through space only
-2 : if traveled through time only
-1 : if traveled through space and time
 0 : if traveled neither through space nor time

```

# Answer
> 1 votes
## Batch, 353 bytes

```
@echo off
set/as=t=0,y=%date:~-4%
for %%a in (%*) do call:c %~1 %%~a
if %s%==7 (if %t%==7 (echo both)else echo space)else if %t%==7 (echo time)else echo neither
exit/b
:c
if "%6"=="" goto g
if %1 neq %4 set/as^|=1
if %2 neq %5 set/as^|=2
if %3 neq %6 set/as^|=4
exit/b
:g
if %4 lss %y% (set/at^|=1)else if %4==%y% (set/at^|=2)else set/at^|=4

```

Note: Since commas are argument separators in Batch, in order to input the space coordinates you need to quote then e.g.

```
spacetime "5,7,2" "5,3,8" "-6,3,8" "5,7,2" 2000 2002

```

Explantion:

```
@echo off

```

Turn off unwanted output.

```
set/as=t=0,y=%date:~-4%

```

Set up two bitmasks and also extract the current year. (In YYYY-MM-DD locales use `%date:~,4%` for the same byte count.)

```
for %%a in (%*) do call:c %~1 %%~a

```

Loop over all the arguments. The `~` causes coordinate values to be split into separate parameters.

```
if %s%==7 (if %t%==7 (echo both)else echo space)else if %t%==7 (echo time)else echo neither
exit/b

```

Check whether the bitmasks are fully set and output the appropriate result.

```
:c
if "%6"=="" goto g

```

See whether this is a pair of coordinates or a coordinate and a year.

```
if %1 neq %4 set/as^|=1
if %2 neq %5 set/as^|=2
if %3 neq %6 set/as^|=4
exit/b

```

If it's a coordinate then update the space bitmask according to whether the relevant spacial dimension was visited.

```
:g
if %4 lss %y% (set/at^|=1)else if %4==%y% (set/at^|=2)else set/at^|=4

```

If it's a year then update the time bitmask according to whether the relevant time dimension was visited.

# Answer
> 1 votes
# Java 10, 154 bytes

```
s->t->{int y=java.time.Year.now().getValue(),c=0,d=1,i=3;for(;i-->0;d*=c,c=0)for(var l:s)c=l[i]!=s[0][i]?1:c;for(int a:t)c|=a>y?4:a<y?1:2;return c/7*2+d;}

```

Returns `1` for *space*, `2` for *time*, `3` for *both*, `0` for *neither*. Try it online here.

Ungolfed:

```
s -> t -> { // lambda taking two parameters in currying syntax
            // s is int[][], t is int[]; return type is int

    int y = java.time.Year.now().getValue(), // the current year
        c = 0, // auxiliary variable used for determining both space and time
        d = 1, // initally, assume we have moved in all three space dimensions
        i = 3; // for iterating over the three space dimensions

    for(; i -- > 0; d *= c, c = 0) // check all coordinates for each dimension, if we have not moved in one of them, d will be 0
        for(var l : s) // check the whole list:
            c = l[i] != s[0][i] ? 1 : c; // if one coordinate differs from the first, we have moved

    for(int a : t) // look at all the years; c is 0 again after the last loop
        c |= a > y ? 4 : a < y ? 1 : 2; // compare to the current year, setting a different bit respectively for past, present and future

    return c / 7 // if we have been to past, the present and the future ...
           * 2   // ... return 2 ...
           + d;  // ... combined with the space result, otherwise return just the space result
}

```

---
Tags: code-golf, number, integer, date
---


title: Encode the column cipher

text:
# Question
Title: Encode the column cipher
Given a string to encode, and a number of columns (the key), encode the string as follows:

I will be using the example `Hello, world!` and the key `3`

First, write out the number of columns:

```
1 2 3

```

Next, write the text starting from the upper left, one character per column, and when you run out of columns, go to the next line.

```
1 2 3
H e l
l o ,
  w o
r l d
!

```

Now, to get your encoded text, read the text starting from the top left corner, but this time, first read one column, and then the next, and so on. If there is not a character in the slot, put a space.

```
Hl r!eowl l,od

```

Note that here, there is a trailing space.

This is your encoded text.

Another test case is `Programming Puzzles and Code Golf SE` with key `5`:

```
1 2 3 4 5
P r o g r
a m m i n
g   P u z
z l e s
a n d   C
o d e   G
o l f   S
E

```

The encoded text is `PagzaooErm lndl omPedef gius rnz CGS`.

**More test cases**

```
"abcdefghijklmnopqrstuvwxyz", 2 -> "acegikmoqsuwybdfhjlnprtvxz"
"codegolf.stackexchange.com", 4 -> "cg.ccgoooskhemdltea. efaxnc "
"Pen Pineapple Apple Pen!!!", 7 -> "PeAeeapnnpp! pl!Ple!ie  n P "
"1,1,2,3,5,8,13,21,34,55,89", 10 -> "18,,,5115,3,2,8,2931 ,, 53 ,4 "

```

Remember, this is , so the code with the fewest bytes wins.

# Answer
> 5 votes
# MATL, 4 bytes

```
e!1e

```

Try it online!

This is about as straightforward as possible. `e` is a builtin that reshapes a matrix into *n* rows. So we read in *input1* as a string, and shape into a matrix with *input2* rows:

```
Hl r!
eowl
l,od

```

Then, we transpose it to get this:

```
Hel
lo,
 wo
rld
!

```

After that, we just call `1e` to reshape it into a single row, and display it as a string.

As you can see in this sample program, the "reshape" function conveniently adds as many zeroes as necessary for the matrix to be a perfect rectangle. When displaying as a string, MATL treats '0's as spaces, so this automatically fills in the necessary number of spaces for no extra work.

# Answer
> 5 votes
# Jelly, 3 bytes

```
sz⁶

```

**TryItOnline!**

### How?

```
sz⁶ - Main link: string, columns
s   - split string (a list of characters) into chunks of length column
 z  - transpose the resulting list of lists with filler
  ⁶ - literal ' '
    - implicit print

```

# Answer
> 2 votes
# PHP, 85 Bytes

```
for(;$i<$x=$argv[2];$i++)for($j=0;$j<strlen($t=$argv[1])/$x;)echo$t[$i+$j++*$x]??" ";

```

PHP, 90 Bytes

```
for(;$i<$x=$argv[2];$i++)foreach(array_chunk(str_split($argv[1]),$x)as$a)echo$a[+$i]??" ";

```

# Answer
> 2 votes
# Ruby, ~~78~~ ~~67~~ 65 bytes

```
->s,k{s.gsub!(/(.)(.{,#{k-=1}})/){$><<$1
$2.ljust k}while s=~/./}

```

See it on eval.in: https://eval.in/668412

# Ungolfed

```
->s,k{
  s.gsub!(/(.)(.{,#{ k -= 1 }})/) {
    $> << $1
    $2.ljust k
  } while s =~ /./
}

```

# Answer
> 2 votes
# Pyth - 5 bytes

```
s.tcF

```

Try it online here.

# Answer
> 2 votes
## Python 2, 46 bytes

```
lambda s,n:(s[0]+(s[1:]+-len(s)%n*' ')*n)[::n]

```

The idea is to take the input string, copy it `n` times with the first character from removed, then takes every `n`'th character.

Let's look for example at `s="abcdef", n=3`, where the length is a multiple of `n`:

```
abcdefbcdefbcdef
^  ^  ^  ^  ^  ^
a  d  b  e  c  f

```

The first cycle through the string takes every `n`th character from the first one. Then, each subsequent cycle shifts one index to the right because the first character is skipped. To ensure that the length is a multiple of `n`, the initial string is padded with spaces.

# Answer
> 1 votes
# Japt, 15 bytes

```
U+SpV f'.pV)y q

```

**Test it online!**

Japt has an "all subsections of length N" built-in, but neither a "all non-overlapping subsections" nor "every Nth char". Suddenly, there is a gaping hole in my life...

## Explanation

```
U+SpV            // Take U concatenated with V spaces.
      f'.pV)     // Take every substring of 3 chars.
            y    // Transpose the resulting array.
              q  // Join on the empty string.
                 // Implicit: output last expression

```

# Answer
> 1 votes
## Perl, 61 bytes

54 bytes of codes and `-F -pi` flags.

```
for$l(1..$^I){$\.=$F[$^I*$_+~-$l]//$"for 0..$#F/$^I}}{

```

Takes the input string without final newline, and the key should be placed after `-i` flag :

```
$ echo -n "Hello, World!" | perl -F -pi3 -E 'for$l(1..$^I){$\.=$F[$^I*$_+~-$l]//$"for 0..$#F/$^I}}{'
Hl r!eoWl l,od

```

# Answer
> 1 votes
# Python 2, 58 bytes

```
lambda s,n:`sum(zip(*zip(*n*[iter(s+' '*~-n)])),())`[2::5]

```

Test it on Ideone.

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

It's a recursive solution.

```
f=(s,k,i=0,r=Math.ceil(s.length/k),c=s[i%r*k+i/r|0])=>k*r==i?'':(c?c:' ')+f(s,k,++i)

```

# Answer
> 1 votes
# R, 92 81 bytes

```
function(x,n)cat(t(matrix(c(el(strsplit(x,"")),rep(" ",-nchar(x)%%n)),n)),sep="")

```

Try it on R-fiddle

This turned out to be a bit of a headache because R automatically recycles the input vector when the rows or column specified in the matrix creation is not a multiple of the length of the input. Therefore we have to pad the vector with `-nchar(x)%%n` spaces before passing it to the matrix function.

The last step is just transposing the matrix and printing it.

# Answer
> 1 votes
# Mathematica, ~~43~~ 40 bytes

*Thanks to miles for saving three bytes!*

```
Join@@Thread@Partition[##,#2,{1,1}," "]&

```

Unnamed function taking two arguments, an array of characters and an integer; returns an array of characters. Most of the heavy lifting is done by the `Thread` function, which (in this context) exchanges rows and columns. `Partition` needs to be called with a couple of useless arguments so that it will pad with the fifth argument `" "`.

# Answer
> 0 votes
# Perl, 87 bytes

```
($a,$b)=@ARGV;for$c(1..$a){for(0..(length$a)/$b){$e.=substr($a,$b*$_+$f,1)}$f++;}say$e;

```

Accepts two arguments as parameters and Usage:

```
perl -M5.010 encol.pl "Hello, World!" 3
Hl r!eoWll,od

```

# Answer
> 0 votes
## Ruby, 89 bytes

```
->s,i{t="";i.times{|n|s.ljust(i*(s.size*1.0/i).ceil).scan(/#{?.*i}/).each{|j|t<<j[n]}};t}

```

Terrible score, tips appreciated.

# Answer
> 0 votes
# Pyth, 40 bytes

```
=Zw=+Z*d+Q-*Q/lZQlZV*QlZIq%%NlZQ/NlZp@ZN

```

Test it here

Probably the ugliest Pyth code ever, but this is my first attempt at Pyth.

```
=Zw=+Z*d+Q-*Q/lZQlZV*QlZIq%%NlZQ/NlZp@ZN
         Q                               Set Q to eval(input())
=Zw                                      Initialises Z to next input string
              lZ                         Gets the length of Z
             /lZQ                        Integer divides lZ by Q
           *Q/lZQ                        Multiplies that result by Q
          -*Q/lZQlZ                      Subtracts the length of Z from that
        +Q-*Q/lZQlZ                      Adds Q to that
                                         (This is how many spaces to pad)
      *d+Q-*Q/lZQlZ                      Gets that many spaces (d is set to ' ')
   =+Z*d+Q-*Q/lZQlZ                      Appends that to Z
                    *QlZ                 Multiplies Q by lZ
                   V*QlZ                 Does a for loop for integers in that range, on N
                           %NlZ          Gets N modulo lZ
                          %%NlZQ         Gets that modulo Q
                                         This is the column of the letter at index N mod Q
                                /NlZ     Gets the column that is being printed
                        Iq%%NlZQ/NlZ     If they are equal...
                                    p@ZN Print the index of N into Z without a newline
                                         (This is implicitly modulo the length of Z)

```

If anyone has tips to improve my golfing, please leave a comment!

# Answer
> 0 votes
# Actually, 12 bytes

Golfing suggestions welcome, especially if you can figure out a golfier way to pad spaces. Try it online!

```
;' *(q╪dX┬ΣΣ

```

**Ungolfing**

```
      Implicit input s, then n.
;     Duplicate n. Stack: n, n, s
' *   Push n spaces.
(q    Rotate s to TOS and append the spaces to the end of s.
╪     Split s into n-length substrings.
dX    Dequeue and discard any extra spaces that remain after chunking.
      This works even when we didn't need to add spaces in the first place.
┬     Transpose the remaining substrings. This returns a list of lists of chars.
Σ     Sum the transposed substrings into one list of chars.
Σ     Sum the list of chars into one string.
      Implicit return.

```

**Another 12-byte version**

In this version, the order of the inputs is reversed, but this can be changed if that isn't allowed. Golfing suggestions welcome. Try it online!

```
│l±%' *o╪┬ΣΣ

```

**Ungolfing**

```
      Implicit input n first, then s.
│     Duplicate stack. Stack: s, n, s, n
l±    Push -len(s).
%     Push -len(s)%n, which gets the number of spaces we need to pad with. Call this m.
' *   Push m spaces to the stack.
o     Append the spaces to the end of s.
╪     Split s into n-length substrings.
┬     Transpose these substrings. This returns a list of lists of chars.
Σ     Sum the transposed substrings into one list of chars.
Σ     Sum the list of chars into one string.
      Implicit return.

```

# Answer
> 0 votes
## Pyke, 10 bytes

```
k=.,Rc.,ss

```

Try it here!

# Answer
> 0 votes
## C#, 161 bytes

I am so sorry.

```
(s,i)=>String.Join("",Enumerable.Range(0,i).SelectMany(x=>Enumerable.Range(0,s.Length/i+1).Select(n=>(n*3+x)).Where(m=>m<s.Length).Select(o=>s.Substring(o,1))));

```

# Answer
> 0 votes
## GolfSharp, 82 bytes

```
(s,i)=>r(0,i).m(x=>r(0,s.L()/i+1).s(n=>(n*3+x)).w(m=>m<s.L()).s(o=>s.R(o,1))).j();

```

# Answer
> 0 votes
# Groovy, 90 Bytes

```
{s,n->(s.padRight((int)(s.size()/n+1)*n) as List).collate(n).transpose().flatten().join()}

```

Pad the input by the ceiling of the size divided into `n` chunks.

Get the padded string as a list of characters.

Collate into n chunks and transpose.

```
({s,n->(s.padRight((int)(s.size()/n+1)*n) as List).collate(n).transpose().flatten().join()})("Programming Puzzles and Code Golf SE",5)

```

Results in:

```
PagzaooErm lndl omPedef gius    rnz CGS

```

# Answer
> 0 votes
# Python 3, 48 bytes

```
lambda c,k:''.join([c[i:-1:k]for i in range(k)])

```

# Answer
> 0 votes
# Powershell, 57 bytes

```
param($s,$n)$r=,''*$n
$s|% t*y|%{$r[$i++%$n]+=$_}
-join$r

```

Test script:

```
$f = {

param($s,$n)$r=,''*$n
$s|% t*y|%{$r[$i++%$n]+=$_}
-join$r

}

@(
    ,("abcdefghijklmnopqrstuvwxyz", 2  , "acegikmoqsuwybdfhjlnprtvxz")
    ,("codegolf.stackexchange.com", 4  , "cg.ccgoooskhemdltea.efaxnc")
    ,("Pen Pineapple Apple Pen!!!", 7  , "PeAeeapnnpp! pl!Ple!ie n P")
    ,("1,1,2,3,5,8,13,21,34,55,89", 10 , "18,,,5115,3,2,8,2931,,53,4")
) | % {
    $s,$n,$expected = $_
    $result = &$f $s $n
    "$($result-eq$expected): $result"
}

```

Output:

```
True: acegikmoqsuwybdfhjlnprtvxz
True: cg.ccgoooskhemdltea.efaxnc
True: PeAeeapnnpp! pl!Ple!ie n P
True: 18,,,5115,3,2,8,2931,,53,4

```

# Answer
> 0 votes
# SINCLAIR ZX81/TIMEX TS-1000/1500 BASIC, 134 tokenized BASIC bytes

```
 1 INPUT A$
 2 INPUT A
 3 LET C=-SGN PI
 4 FOR I=SGN PI TO A
 5 PRINT I;
 6 NEXT I
 7 PRINT
 8 FOR I=SGN PI TO LEN A$
 9 LET C=C+SGN PI
10 IF C=A THEN LET C=NOT PI
11 IF NOT C AND I>SGN PI THEN PRINT
12 PRINT A$(I);
13 NEXT I

```

The first parameter `A$` is the string value that you want to cipher, and the second `A` is the number of columns that you want to cipher to. The variable `C` is used to add in a new line after `A` characters.

Lines 4 to 6 inclusive print out the column numbers at the top of the screen area.

Line 7 adds a new line (`"\r\n"` equivalent).

Lines 8 - 13 will then print out each character of `A$`.

This programme does not require a RAM expansion to work.

# Answer
> 0 votes
# K (oK), 27 bytes

**Solution:**

```
{,/+(0N;y)#(y*-_-(#x)%y)$x}

```

Try it online!

**Explanation:**

```
{,/+(0N;y)#(y*-_-(#x)%y)$x} / the solution
{                         } / lambda taking implicit x and y
                        $x  / pad x
           (           )    / do this together
                     %y     / divide by y
                 (  )       / do this together
                  #x        / count (#) length of x
                -           / negate \
               _            / floor   | ceiling
              -             / negate /
            y*              / multiply by y
          #                 / reshape
    (0N;y)                  / null by y grid
   +                        / transpose
 ,/                         / flatten

```

# Answer
> 0 votes
# 05AB1E (legacy), 3 bytes

```
ôζJ

```

The Python legacy version is used instead of the Elixir rewrite, because the new version doesn't implicitly convert strings to characters when using `zip`, which the old version did.

Try it online or verify all test cases.

**Explanation:**

```
ô      # Split the (implicit) input-String into chunks of size (implicit) input-integer
       #  i.e. "Hello, world!" and 3 → ['Hel','lo,',' wo','rld','!']
 ζ     # Zip, swapping rows and columns (with space filler by default)
       #  i.e. ['Hel','lo,',' wo','rld','!'] → ['Hl r!','eowl ','l,od ']
  J    # Join the list of strings together (and output implicitly)
       #  i.e. ['Hl r!','eowl ','l,od '] → 'Hl r!eowl l,od '

```

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


# Question
Title: Convert to and from the factorial number system
The Factorial Number System, also called factoradic, is a mixed radix numeral system. The factorials determine the place value of a number.

In this system, the right most digit can be either 0 or 1, the second rightmost digit can be 0, 1 or 2, and so on. This means that an `n` digit factoradic number can have a maximum value of `(n + 1)!`.

For example, to convert the factoradic number `24201` to decimal you would do this:

```
2 * 5! = 240
4 * 4! = 96
2 * 3! = 12
0 * 2! = 0
1 * 1! = 1
240 + 96 + 12 + 0 + 1 = 349

```

Hence the factoradic number `24201` is `349` base `10`.

To convert a decimal number (with `349` as an example) into a factoradic number, you would do this:

Take the largest factorial less than the number. In this case it is `120`, or `5!`.

```
349 / 5! = 2 r 109
109 / 4! = 4 r 13
13 / 3! = 2 r 1
1 / 2! = 0 r 1
1 / 1! = 1 r 0

```

Hence `349` base `10` is the factoradic number `24201`.

Your challenge is to create the shortest program or function that converts an input number to the other base.

The input will be a string representation of a non-negative integer. A factoradic number will be preceded by a `!` (eg. `!24201`), while a decimal number will not be preceded by anything. You may assume that the maximum input will be `10! - 1` \- `3628799` in decimal and `987654321` in factoradic. This means that letters will not appear in a factoradic input/output.

The program doesn't need to prepend a `!` to a factoradic output, and may output a string or an integer. The input may be in any reasonable format.

---

Test cases:

```
Input: 1234
Output: 141120

Input: 746
Output: 101010

Input: !54321
Output: 719

Input: !30311
Output: 381

```

# Answer
> 11 votes
### APL, 39 37 characters

```
{A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}

```

Examples:

```
      {A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'1234'
141120
      {A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'!54321'
719

```

# Answer
> 10 votes
## Python 2.7 (~~163~~ ~~157~~ 152)

```
i=raw_input()
exec("b='';a=362880;j=int(i);x=9;"+'b+=`j//a`;j%=a;a/=x;x-=1;'*9,"a=x=1;b=0;"+'b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i))['!'in i]
print int(b)

```

More readable version:

```
i=raw_input()
if'!'in i:a=x=1;b=0;c='b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i)
else:b='';a=362880;j=int(i);x=9;c='b+=`j//a`;j%=a;a/=x;x-=1;'*9
exec c;print int(b)

```

Breakdown:

```
Factoradic -> Decimal, when i is in the form !(number)
a=1   #Factorial value (multiplied every iteration)
x=1   #Index value
b=0   #Output
iterate ~-len(i) times:    #PSEUDOCODE! bitwisenot(a) = ~a = -a-1
    b+=a*int(i[-x])        #add the value of the xth last character in the factoradic #
    x+=1                   #Increment x
    a*=x                   #Set a to x!, (x-1)! * x = x!

Decimal -> Factoradic
b=''                       #Output
a=362880                   #Factorial value, set to 9! here
j=int(i)                   #Integer value of the input
x=9                        #Index value
iterate 9 times:           #PSEUDOCODE! This block is in an exec() loop
    b+=`j/a`               #Add floor(j/a) to b
    j%=a                   #Take out all multiples of a in j
    a/=x                   #Set a to (x-1)!, x! / x = (x-1)!
    x-=1                   #Decrement x

```

# Answer
> 9 votes
## GolfScript (48 44 43 chars)

```
.~\{1{):?\.?%\?/@}9*{*+}+9*}:^{:N,{^N=}?}if

```

This is a self-contained program. The factoriadic =\> decimal conversion is quite slow, because it does a search using the decimal =\> factoriadic conversion rather than a direct base conversion.

The input format allows for a very short mode switch: `.~` copies the input string and evaluates it, so if the input is just a number we end up with e.g. `"1234" 1234` on the stack, and if it starts with `!` (logical not, with any non-empty string being truthy) we end up with e.g. `0 30311` on the stack. Then the value at the bottom of the stack is truthy for decimal =\> factoriadic and falsy for factoriadic =\> decimal.

# Answer
> 4 votes
# PHP \<7.1 ~~178 171 170 168 164 155 147 144 138 126~~ 123 bytes

```
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)$r+=$x[$i]*$b;if(+$x)for(;$j>1;$x%=$b)$r.=$x/($b/=$j--)|0;echo+$r;

```

Run as pipe with `-r` or test it online.

* no extension required
* no ~~sub~~ function needed: the factorial base is being reused (incresed/decreased in the loops)
* pure integer and string arithmetics, should even work in php 3 (and still works in php 7):
* ~~decimal 0 returns empty string instead of `0`.~~ (both other PHP answers do too.) ~~If that is unacceptable, add +5 for the extra case.~~

**ungolfed:**

```
// two loops in one: compute the decimal number from a factorial
// or find the first factorial larger than a decimal $x
// the latter inits $r with '0': $i=strlen -> $x[$i]=='' -> (int)$x[$i]==$x[$i]*$b==0
// $b is the current digit´s base; $j is the bases´ latest factor
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)
    $r+=$x[$i]*$b;
// and now for dec->fact ...
if(+$x)
    for(;$j>1;$x%=$b)
        // both $b and $j are one step too far in the first iteration;
        // -> decrement must precede the actual loop body
        // -> can be merged into the digit calculation -> all braces golfed
        $r.=$x/($b/=$j--)|0;
        // now: go on with the remainder (see loop head)
echo+$r; // final type cast removes leading zeros (from the first loop)
    // and fixes the '0' result (no operations at all on that input!)

```

**abandoned golfing ideas:**

* `$b<=$x` --\> `$b<$x` (-1)
would break pure decimal factorials (i.e. those that result in a factorial number with only one non-zero digit). JMPC´s solution suffers from that; HamZa´s does not.
* ~~`floor($x/$b)` -\> `(int)($x/$b)`<br>could be a bit faster, but type casting precedes division, so I need the parentheses and don´t gain a byte.~~ `$x/$b|0` does the trick
* ~~The loop in fact-\>dec is similar to the factorial-find in dec-\>fact. Same increment, body does not matter, but unfortunately different preset and different post condition. Dang; could have golfed -21 there.~~
YAY I found a solution. Took quite a bit of golfing, but chopped off another -4 (no: -9) *and* closed all bugs/loopholes.

Any more potential ... or am I done golfing?

# Answer
> 3 votes
# JavaScript (ES 6) ~~139 137 122 113~~ 111

tried a different approach using some array magic; but I ended up at ~~174~~ 172 bytes with that:

```
f=x=>{if('!'==x[0]){a=x.split``.reverse();i=b=1;r=0;a.pop();a.map(d=>{r+=d*b;b*=++i})}else{t=[];for(i=b=1;b<=x;b*=++i){t.unshift(b)}r='';t.map(b=>{r+=x/b|0;x%=b})}return r}

```

So I just took my PHP code and translated it. Could remove all the `$`s and a few `;`, but the necessity to initialize vars ate up some of that benefit. Managed to golf both answers down a bit further, though.

**golfed**

```
f=x=>{for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)r+=x[i]*b;if(x|0)for(r='';j>1;x%=b)r+=x/(b/=j--)|0;return r}

```
* first version returns '' for decimal 0; add +2 to fix
* second version requires string input
* both tested in Firefox, Edge and Opera

**ungolfed**

```
f=x=>
{
    for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)
        r+=x[i]*b;
    if(x|0)
        for(r='';j>1;x%=b)
            r+=x/(b/=j--)|0;
    return r
}

```

**test suite**

```
<table id=out border=1><tr><th>dec</th><th>result<th>expected</th><th>ok?</th></tr></table>
<script>
    addR=(r,s)=>{var d=document.createElement('td');d.appendChild(document.createTextNode(s));r.appendChild(d)}
    test=(x,e)=>{var y=f(x),r=document.createElement('tr');addR(r,x);addR(r,y);addR(r,e);addR(r,e==y?'Y':'N');document.getElementById('out').appendChild(r)}
    samples={'349':'24201','1234':'141120','746':'101010','719':'54321','381':'30311','24':'1000','0':'0'};
    for(d in samples){test(d,samples[d]);test('!'+samples[d],d)}
</script>

```

# Answer
> 2 votes
## Python, 128 chars

This takes about half an hour to run, but it's small:

```
A=[`x`for x in xrange(10**9)if all(x/10**d%10<d+2 for d in range(9))]
i=raw_input()
print A.index(i[1:])if'!'in i else A[int(i)]

```

It builds a list of all \<= 9 digit factoradic numbers in numeric order, then does a lookup or index to convert.

If you want to test, just replace `10**9` with `10**6` and restrict yourself to 6-digit variadic numbers.

I could technically save a character by using `range(10**9)` instead of `xrange(10**9)`. Don't try this at home.

# Answer
> 2 votes
# Perl 6, ~~66~~ ~~65~~ 60 bytes

*-1 byte thanks to Jo King*

```
{/\!/??:1[.flip.chop.comb Z*[\*] 1..*]!![R~] .polymod(2..*)}

```

Try it online!

# Answer
> 2 votes
# Jelly, 15 bytes

```
ḊV€;0Æ¡µÆ!ṖḌƊ¬?

```

Try it online!

### How it works

```
ḊV€;0Æ¡µÆ!ṖḌƊ¬?     Main link (monad). Input: integer or string
             ¬?  *) If the given input is a string, run 1); otherwise run 2)

ḊV€;0Æ¡  1) Factorial base -> integer
ḊV€         Remove "!" and map each char to number
   ;0       Append zero (this is needed to run the built-in correctly)
     Æ¡     Built-in conversion

Æ!ṖḌ  2) Integer -> factorial base
Æ!       Built-in conversion
  ṖḌ     Remove a zero at the end, and convert to decimal

```

### Why `*)` works

`¬` is element-wise logical NOT. When given a single integer, it becomes a single zero, which is false. However, when given a string, each element (character) is turned to a zero, and the whole result is an array of zeroes which is true.

Zero as an integer is a special case. It goes through the "factorial -\> integer" route, but it still gives zero which is correct.

# Without factorial base built-in, 25 bytes

```
⁵R!µ³%Ḋ:ṖUḌ
⁵R!ḋḊUV€ƊµÇ¬?

```

Try it online!

### How it works

```
⁵R!µ³%Ḋ:ṖUḌ  Aux. link (monad). Integer -> factorial base
⁵R!µ         Set (1..10)! as left argument
    ³%Ḋ:Ṗ    Compute each digit: (input % (2..10)!) // (1..9)!
         UḌ  Reverse and convert the digit array to decimal

⁵R!ḋḊUV€ƊµÇ¬?  Main link (monad).
         µÇ¬?  If the input is a string, apply the left chain;
               otherwise, apply the aux. link above
⁵R!            (1..10)!
   ḋ           Dot product with...
    ḊUV€Ɗ      Remove "!", reverse, map each character to digit

```

# Answer
> 1 votes
# Mathematica 213 177 175

A factorial number is wrapped in `f[]`, whether it is input or output.

```
g@{n_,j_,r_}:=If[j==0,FromDigits@r,g@{q=QuotientRemainder[n,j!];q[[2]],j-1,Append[r,q[[1]]]}]
z@n_:=If[!IntegerQ@n, g[{n[[1]],9,{}}], f@Tr@(p=1;# (p++)!&/@Reverse@IntegerDigits@n)]

```

**Usage**

```
z[24201]

```

> f\[349\]

```
z[f[349]]

```

> 24201

*Conversion of factorial to decimal number*. `QuotientRemainder[n,j!]` recursively acts on the digits of the factorial number from left to right, decrementing `j` at each step. `QuotientRemainder[349, 5!]`, for instance, returns `{2, 109}` and so on.

*Conversion of decimal to factorial number*. Moving right to left, the pure function, `# (p++)! &`, multiplies each digit,`#`, by the appropriate factorial.

# Answer
> 1 votes
### GolfScript, 69 characters

```
10,1>{1$*}*](.0=33={1>01/-1%0\{~@(@*@+}/\}{~\-1%{1$<},{1$1$/@@%}/}if;

```

Takes input from STDIN as usual and prints the result. Online test.

# Answer
> 1 votes
## Haskell, 221 chars

### Code Golf

```
m v@(a:b)|a=='!'=(sum.zipWith(*)g.map(read.(:[])).reverse) b|True=(fst.until((<0).fst.snd)(\(s,(i,b))->(s*10+b`quot`f i,(i-1,b`rem`f i))).(\n->(0,((1+).last.takeWhile((n>=).f)$[1..], n))).read) v;g=scanl1(*)[1..];f=(g!!)

```

### Usage

```
$ ghci factorial.hs
ghci> m "1234"
 141120
ghci> m "!54321"
 719

```

### Ungolfed code

```
parse v@(a:b) | a == '!' = to b
              | otherwise = from v

to = sum . zipWith (*) factorials . map (read . (:[])) . reverse

from = fst . until finished next . boostrap . read
    where finished = ((<0) . fst . snd)
          next (s,(i,r)) = (s * 10 + r `quot` factorial i, (i-1 ,r `rem` factorial i))
          bootstrap n = (0, (lastFact n, n))
          lastFact n = (1+) . last . takeWhile ((n>=) . factorial) $ [1..]

factorials = scanl1 (*) [1..]

factorial = (factorials!!)

```

# Answer
> 1 votes
# PHP ~~231~~ ~~214~~ 204

Newest Answer

```
function g($x){return $x?$x*g($x-1):1;}function f($x,$e){if($x[0]=="!"){for($t=1;$t<$c=strlen($x);$t++){$e+=$x[$t]*g($c-$t);}}else{while(g(++$p)<=$x);while(--$p){$e.=floor($x/g($p));$x%=g($p);}}return$e;}

```

Old Answer

```
 function f($n){if($n[0]=="!"){$n=str_split($n);$c=count($n);$f=$y=1;while($c-->1){$e+=($f*$n[$c]);$f*=++$y;}return$e;}else{for($i=$c=1;$i<$n;$i*=$c){$r[$c++]=$i;}foreach(array_reverse($r)as$t){$e.=floor($n/$t);$n=$n%$t;}return$e;}}

```

### Example

```
echo f('349')."\n"
    .f('!24201')."\n"
    .f('1234')."\n"
    .f('746')."\n"
    .f('!54321')."\n"
    .f('!30311');

```

### Output

```
24201
349
141120
101010
719
381

```

# Answer
> 0 votes
# K, 102

```
"I"$,/$*:'|:'{{(x-y*g),g:_(x:*x)%y:*/1+!y}\[x,0n;|1+!{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]]}

```

Could definitely be improved.

```
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 349
24201
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 746
101010
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 1234
141120

```

# Answer
> 0 votes
## VBA 225

Thanks to Titus for the help! Still looking to golf some more.

```
Sub a(b)
Set w=WorksheetFunction
e=Len(b)
If IsNumeric(b) Then
i=0
For d=0To 8
h=w.Fact(9-d)
g=b Mod h
If g<b+i Then
i=1
f=f &Int(b/h)
b=g
End If
Next
Else
For d=2To e
f=f+w.Fact(e-d-1)*Mid(b,d,1)
Next
End If
MsgBox f
End Sub

```

# Answer
> 0 votes
# D (159 chars)

```
int x(string n){import std.conv;int r,i=9,f=9*'鶀',d;if(n[0]<48){while(r.text.x<n[1..$].to!int)r++;}else{d=n.to!int;while(i){r=r*10+d/f;d%=f;f/=i--;}}return r;}

```

## Ungolfed and with program entry point

All command line arguments are printed as `<original> -> <converted>`. Only decimal to factoradic is actually implemented in `x`. The other way round just calls `x` with all decimal numbers (0..\*) until the result equals the input. This takes ~3 seconds for the largest input (!987654321).

Executable online version: http://dpaste.dzfl.pl/46e425f9

```
void main(string[] args) {
    import std.stdio;
    foreach (arg; args[1 .. $]) {
        writefln("%s -> %s", arg, x(arg));
    }
}

int x(string n) {
    import std.conv;
    int r, i=9, f=9*'鶀', d;  // 鶀's Unicode index equals 8*7*6*5*4*3*2*1

    // If the first character value is less than 48 ('0') it should be a '!'.
    if (n[0] < 48) {
        // Call x with different input (0..*) until it matches our n.
        // r.text.x is rewritten as x(text(r)).
        while (r.text.x < n[1..$].to!int) r++;
    } else {
        d = n.to!int;
        // Try d / 9!, d / 8!, etc. just as in the problem description.
        while (i) {
            r = r*10 + d/f;
            d %= f;
            f /= i--;
        }
    }
    return r;
}

```

# Answer
> 0 votes
# PHP, 124 bytes

```
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];)$r+=$c*$f*=++$n;for(;$a>=$f*=++$i;);for(;~-$i;$a%=$f)$r.=0|$a/$f/=$i--;echo+$r;

```

Try it online!

Extended

```
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];) # runs in case of "!" at the beginning
  $r+=$c*$f*=++$n; #reverse string multiply with the next factorial "!"*$f=0
for(;$a>=$f*=++$i;); # runs not in case of "!" at the beginning string comparing. search the factorial that is higher as input value
for(;~-$i;$a%=$f) # runs only when the second loop had runs
  $r.=0|$a/$f/=$i--; # concat the value of the division with the highest factorial used
echo+$r; # Output result

```

# Answer
> 0 votes
# Perl 6, 150 bytes

```
{/^\!/??([+] [Z*] .comb.skip.reverse,[\*] 1..*)!!(reduce
->\a,\b{a[0]~a[1] div b,a[1]%b},("",+$_),|(first
*[*-1]>$_,[\,] [\*] 1..*).reverse[1..*])[0]}

```

# Answer
> 0 votes
# APL(NARS), 36 chars, 72 bytes

```
{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}

```

it seems that 10⊥(9..2)⊤ is better than the recursive function, thanks to Howard for the other APL solution that show that... (even if i not understand 100%). Input for numbers without '!' \<10!. Test:

```
  u←{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}
  u¨'1234' '746' '!54321' '!30311' '!24201'
141120 101010 719 381 349
  u '0'
0
  u '!0'
0
  u '9'
111
  u '!111'
9
  u '!9'
9

```

---
Tags: code-golf, number, base-conversion
---