title: Double Prime Words

text:
# Question
Title: Double Prime Words
Consider a word/string of length \\$n\\$, only including the letters A-Z, a-z. A word/string is a double prime word if and only if n is prime and the sum of the letters, s, is also prime, using their numeric position in the alphabet (`a=1, B=2, c=3`, etc.).

Input can be any combination of upper or lower case alphabetic characters, as there is no numeric difference between `a` or `A`.

Output is any appropriate logical format related to your language. i.e. True or False, T or F, 1 or 0, etc. Specifying what format your output will appear is highly appreciated, but not required. (Output need not include n, s, but I include them below as demonstration and example)

Winning condition is shortest code in bytes able to detect if a string is a double prime, fitting both conditions for n and s to be prime. (I've now included cases from all 4 possible situations of n, s.)

## Examples

```
Input -> Output (n, s)

Prime -> True (5, 61)
han -> True (3, 23)
ASK -> True (3, 31)
pOpCoRn -> True (7, 97)
DiningTable -> True (11, 97)
METER -> True (5, 61)

Hello -> False (5, 52)
SMILE -> False (5, 58)
frown -> False (5, 76)

HelpMe -> False (6, 59)
John -> False (4, 47)
TwEnTy -> False (6, 107)

HelloWorld -> False (10, 124)
Donald -> False (6, 50)
telePHONES -> False (10, 119)

A -> False (1, 1)
C -> False (1, 3) {1 is not prime}
d -> False (1, 4)

```

# Answer
# Jelly, 12 bytes

```
ŒuO_64µL,SẒP

```

Try it online!

## How it works

```
ŒuO_64µL,SẒP - Main link, takes string s as argument e.g. s = "Prime"
Œu           - Convert to upper case                          "PRIME"
  O          - Convert to ordinals                            [80, 82, 73, 77, 69]
   _64       - Subtract 65 (call this L)                      [16, 18, 9, 13, 5]
      µ      - Start a new link with L as the left argument
       L     - Take the length                                5
         S   - Take the sum                                   61
        ,    - Pair the two values                            [5, 61]
          Ẓ  - Take primality of each                         [1, 1]
           P - Take product                                   1

```
> 5 votes

# Answer
# Ruby, ~~27~~ 59 bytes

```
->a{[a.size,a.upcase.bytes.map{|i|i-64}.sum].all? &:prime?}

```

+33 bytes after correcting the solution, thanks to DrQuarius.

Try it online! or Verify all test cases
> 5 votes

# Answer
# , ~~68~~ 71 bytes

+3 bytes to correct a bug pointed out by Dominic van Essen

```
`?`=sum;s=?b<-utf8ToInt(scan(,""))%%32;l=?b^0;l-1&5>?c(!s%%1:s,!l%%1:l)

```

Try it online!

Notice that to convert both upper and lower case letters to the integers 1...26, we can take the ASCII codepoint modulo 32. `sum(!x%%1:x)` is a golfy way of counting the number of divisors of `x`, which will be equal to 2 iff `x` is prime.

Ungolfed:

```
`?` = sum                       # shorthand for sum
b = utf8ToInt(scan(, "")) %% 32 # take input and convert to ASCII, then take mod 32
s = sum(b)
l = sum(b^0)                    # l = length(b)
5 > sum(c(!s%%1:s,!l%%1:l))    # sum the number of divisors of s and l, and check whether you get <5.
       & l!=1                   # and that l is not 1

```
> 5 votes

# Answer
# perl -Mfeature=say -MList::Util=sum -pl, 95 bytes

```
s/[^a-z]//gi;$m=sum map-64+ord,split//,uc;$_=(1 x y===c)!~/^(11+)\1+$|^1$/&&(1x$m)!~/^(11+)\1$/

```

Try it online!

## How does it work?

```
s/[^a-z]//gi;   # Clean the input, remove anything which isn't an ASCII letter.

                          uc;     # Upper case the string
                  split//,        # Split it into individual characters
          -64+ord                 # Calculate its value:
                                  #           subtract 64 from its ASCII value
       map                        # Do this for each character, return a list
$m=sum                            # Sum the values, and store it in $m

     y===c                        # Returns the length of the input string
(1 x y===c)                       # Length of the input string in unary

/^(11+)\1+$|^1$/                  # Match a string consisting of a composite
                                  # number of 1's, or a single 1
!~                                # Negates the match, so
(1 x y===c)1~/^(11+)\1+$|^1$/     # this is true of the input string (after
                                  # cleaning) has prime length

(1x$m)!~/^(11+)\1+$/              # Similar for the sum of the values --
                                  # note that the value is at least 2, so
                                  # no check for 1.

```

Combining this, and the program will print 1 on lines which match the conditions, and an empty line for lines which do not match.
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
gAIlk>O‚pP

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
g           # Get the length of the (implicit) input-list
 A          # Push the lowercase alphabet
  I         # Push the input-list of characters
   l        # Convert the input to lowercase
    k       # Get the (0-based) index of each character in the alphabet-string
     >      # Increase each by 1 to make them 1-based indices
      O     # Take the sum of that
       ‚    # Pair the length together with this sum
        p   # Check for both whether they're a prime (1 if it's a prime; 0 if not)
         P  # And check if both are truthy by taking the product of the pair
            # (after which the result is output implicitly)

```
> 4 votes

# Answer
# , 70 bytes

```
function(s,S=sum,t=S(utf8ToInt(s)%%32))S(!nchar(s)%%1:t)^S(!t%%1:t)==4

```

Try it online!

I forced myself not to peek at Robin Ryder's answer before having a shot at this, and (satisfyingly) it turns out that we've used some rather different golfing tricks.

`t` is the total of all letter indices. This is certain to be greater-than-or-equal-to `nchar(s)` (it's only equal if the string `s` is "A" or "a"). So we can use modulo `1:t` to test for primality of the string length instead of modulo `1:nchar(s)`, and there's no need waste characters on a variable declaration to store `nchar(s)`.

Both primality tests `sum(!t%%1:t)` and `sum(!nchar(s)%%1:t)` must be equal to 2 if both the sum-of-letter-indices and the string length are prime.
We could check if they're both 2, but this requires `==2` twice (plus a `&` or equivalent), which seems wasteful. Is it ok to check that the total is 4? The edge-case we need to worry about is if one of them equals 1 and the other 3: this happens for the string "D" (length=1 and character-index=4 with divisors 1,2 and 4). So it's not Ok. Can we multiply them? Also no, because 1 and 4 will again give 4 (think about the string "F").
But - since we know that the string length must be less-than-or-equal to the sum-of-character-indices, we can use exponentiation: the only way to get 4 is 4^1 or 2^2, and since the sum-of-character-indices can't be 1 if the string-length is 4, 2^2 is the only possibility.

So the final, combined check for double-primality is `sum(!nchar(s)%%1:t)^sum(!t%%1:t)==4`, saving 3 characters compared to testing them separately.
> 4 votes

# Answer
# Rockstar, ~~327~~ ~~321~~ ~~319~~ 294 bytes

No built-in for testing primes!
No case conversion!
No way to get the codepoint of a character!

Why do I do these things to myself?! Spent so long just getting the damn thing to work, I'm sure it's far from optimally golfed but it'll do for now.

Outputs `0.25` for `true` and `0` for false.

```
F takes N
let D be N
let P be N-1
while P and D-2
let D be-1
let M be N/D
turn M up
let P be N/D-M

give P

G takes I
N's 27
while N
cast N+I in C
if C's S at X
give N

let N be-1

give G taking 64

listen to S
X's 0
T's 0
while S at X
let T be+G taking 96
let X be+1

say F taking T*F taking X

```

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

# Answer
# Wolfram Language (Mathematica), 34 bytes

```
PrimeQ@*Tr/@(LetterNumber@#&&1^#)&

```

Try it online!

-22 bytes from **@att**
> 3 votes

# Answer
# Retina 0.8.2, 77 bytes

```
\W|\d|_

$
¶$`
\G.
1
T`L`l
[t-z]
55$&
[j-z]
55$&
T`_l`ddd
.
$*
A`^(..+)\1+$
¶

```

Try it online! Link includes test cases. Explanation:

```
\W|\d|_

```

Delete anything that isn't a letter.

```
$
¶$`

```

Duplicate the letters.

```
\G.
1

```

Replace the letters on the first line with `1`s, thus taking the length in unary.

```
T`L`l

```

Convert the remaining letters to lower case.

```
[t-z]
55$&
[j-z]
55$&
T`_l`ddd

```

Convert them to digits that will sum to their numeric position.

```
.
$*

```

Convert the digits to unary, thus taking their sum.

```
A`^(..+)\1+$

```

Delete any composite values.

Check that both values are still present.
> 3 votes

# Answer
# Python 3, ~~86~~ ~~78~~ 87 bytes

Saved 8 bytes thanks to ovs!!!
Added 9 bytes to fix a bug kindly pointed out by Robin Ryder.

```
lambda s:~-len(s)*all(n%i for n in(len(s),sum(ord(c)&31for c in s))for i in range(2,n))

```

Try it online!

Returns a truthy or falsey value.
> 3 votes

# Answer
# Brachylog, 11 bytes

```
ḷạ-₉₆ᵐ+ṗ&lṗ

```

Try it online!

### How it works

```
ḷạ-₉₆ᵐ+ṗ&lṗ (is the implicit input)
ḷ           to lowercase
 ạ          to list of char codes
  -₉₆ᵐ      minus 96 (so 'a' -> 1)
      +     summed
       ṗ    prime?
        &l  and is the input's length
          ṗ prime?

```
> 3 votes

# Answer
# Japt, 16 bytes

```
Êj ©Uu ¬mc xaI j

```

Try it
> 2 votes

# Answer
# Scala, ~~75~~ ~~74~~ 69 bytes

```
| =>p(|size)&p(|map(_&95-64)sum)
def p(n:Int)=(2 to n/2)forall(n%_>0)

```

Try it online!
> 2 votes

# Answer
# C - ~~119~~ ~~108 99~~ 98 bytes (gcc)

@ceilingcat saved another byte!

```
b,t,e;p(c){for(;--e&&c%e;);c=e==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(e=t);}

```

try it online

previously

Many thanks to @DominicvanEssen and @ceilingcat for saving 20 bytes! - and particularly to Dominic for fixing error on n=1 (non-prime)

```
b,t,e;p(c){for(b=c;--b&&c%b;);c=b==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(t);}

```

first attempt below 119 bytes

```
a(char*a){int t=0,d=strlen(a),e=d;while(d)t+=a[--d]%32;return p(e)*p(t);}
p(int c){int b=c;while(--b&&c%b);return b<2;}

```

In fact can save 3 bytes by using `while(c%--b)` in the second routine, but this fails for the case of p(1) e.g. 'a'. or other single characters.

try it online
> 2 votes

# Answer
# , 27 22 18 bytes

```
1*/@p:#,1#.32|3&u:

```

Try it online!

*-5 bytes thanks to xash*

*-4 bytes thanks to Dominic van Essen*

* `32|3&u:` Turn each letter into its index by first converting to its ascii number, the modding by 32.
* `1#.` Sum.
* `#,` Prepend list length.
* `1...p:` Are each of those two numbers prime?
* `*/@` Multiply them together -- are they all prime?
> 2 votes

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

Returns **0** or **1**.

```
s=>(g=k=>n%--k?g(k):k==1)(Buffer(s).map(c=>x+=n<(n+=c>64&(c&=31)<27&&c),x=n=0)|n)&g(n=x)

```

Try it online!

### Commented

**Helper function**

```
g = k =>                   // g is a helper function testing if n is prime
  n % --k ?                //   decrement k; if it does not divide n:
    g(k)                   //     do recursive calls until it does
  :                        //   else:
    k == 1                 //     test whether k = 1

```

**Main function**

```
s =>                       // s = input string
  g(                       // test if the 'sum of the letters' is prime
    Buffer(s).map(c =>     //   for each ASCII code c in s:
      x +=                 //     increment x if ...
        n < (              //       ... n is less than ...
          n +=             //         ... the new value of n:
            c > 64 &       //           if c is greater than 64
            (c &= 31) < 27 //           and c mod 32 is less than 27:
            && c           //             add c mod 32 to n
        ),                 //
      x = n = 0            //     start with x = n = 0
    ) | n                  //   end of map(); yield n
  )                        // end of the first call to g
  & g(n = x)               // 2nd call to g with the 'length' x

```
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
uÇ64-Op¹gp&

```

Try it online!

Bytes removed due to lack of input restrictions
> 1 votes

# Answer
# Factor, 78 bytes

```
: d ( s -- ? ) dup [ length ] dip >lower [ 96 - ] map sum [ prime? ] bi@ and ;

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-pl`, 52 bytes

Uses the prime identification regex from @Abigail's answer

```
$_.=$".1x s/./1x(31&ord$&)/ge;$_=!/\b((11+)\2+|1)\b/

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~50~~ ~~55~~ 50 bytes

```
->s{[s.size,s.upcase.sum-64*s.size].all? &:prime?}

```

Try it online!

+5 bytes due to a misunderstanding of whether arrays could be considered truthy.

-5 bytes thanks to Razetime, using the nice trick of putting the " &:prime?" at the end instead of doing a ".map(&:prime?)" before the ".all?".

Posted separately because Razetime's solution actually didn't sum the alphabet index but simply the ascii ordinals. It fails for the double prime words "DiningTable" and "METER".
> 1 votes

# Answer
# Husk, 12 bytes

```
&ṗL¹ṗṁȯ-64ca

```

Try it online! Outputs a truthy number if the word is a double prime word, and 0 otherwise.
> 1 votes

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


title: Shortlex predecessor

text:
# Question
Title: Shortlex predecessor
*Please note the special scoring for this challenge.*

Given a non-empty string made of `a-z`, output the string immediately before it in the shortlex order.

**Shortlex order**

We enumerate strings in shortlex order by first listing the strings of length 0, then those of length 1, then length 2, and so on, putting them in alphabetical order for each length. This gives an infinite list of all strings. Said a bit differently, this sorts strings by length, tiebroken alphabetically.

For strings `a-z` as used in the challenge, this list goes (abridged):

```
(empty string)
a
b
c
...
z
aa
ab
...
az
ba
bb
...
zy
zz
aaa
aab
...

```

**Scoring**

Answers will be compared in shortlex order, with earlier being better.

Like in code golf, fewest bytes wins, but there's a tiebreak for same-length answers in favor of coming first alphabetically. This means that you'll want to further "golf" your answer to use characters with lower code points where this doesn't hurt its length. Characters nearer to the start are more important.

For non-ASCII languages, answers are treated as a sequence of bytes. Use the byte order of the code page to compare characters, not their UTF encoding.

For your answer's header, you can just put the code's length and say when you've outgolfed a same-length answer in the same language. You could also put the code's position in shortlex order if that number is not too long.

**Input and output**

The input string will be between 1 and 10 characters long, and consist only of letters `a-z`. As per site defaults, you may do I/O with strings as lists of characters or code points. The letters should be lowercase (code points 97-122).

**Test cases**

The first output is the empty string.

```
a ->
c -> b
z -> y
aa -> z
az -> ay
ba -> az
aaa -> zz
zaa -> yzz
golf -> gole
bzaaaaaaaa -> byzzzzzzzz
zzzzzzzzzz -> zzzzzzzzzy

```

**Related:** Smaller Strings in Printable ASCII base, Counting in bijective base 62

# Answer
# Haskell, ~~64~~, ~~63~~, ~~56~~, 55 bytes

* `c` is an infinite list of all strings composed of `97..122` in shortlex order.
* `\x y -> last$fst$span(/=x)y` gives the predecessor of `x` in `y`

```
a b=last$fst$span(/=b)c
c=[]:[d++[e]|d<-c,e<-[97..122]]

```

Try it online!

* 1 byte saved by using code points: `[97..122]` vs. `['a'..'z']`
* 9 bytes saved by ovs
* 1 bytes saved by Laikoni

## Shortlex optimality

To get the lowest-ordered version of this code:

* Each variable is chosen to be the smallest, front-to-back
* The two lines are sorted (`' ' < '='`)
> 7 votes

# Answer
# Python 3.8, ~~67~~ 65 bytes

*Thanks @xnor for helping me get my shortlex score down!*

```
A=lambda	B:(C:=B.pop())>97and	B+[C-1]or	A(B)+[122]if	B>[97]else[]

```

Try it online!

A recursive function that takes in a list of code points, and returns a list of code points.

Note that all spaces are replaced with tabs for smaller shortlex score.

Let `C` be the last character of the string, and `B` be the prefix. If `C == "a"`, then the result is `A(B) + "z"`. If `C != "a"`, then the result is `B + "{C-1}"`. The base case is when the string is `""` or \`"a", in which case the function returns the empty string.

---

Same idea, but this function takes in and returns proper strings.

# Python 3.8, ~~73~~ 72 bytes

```
A=lambda	B:B>"a"and[B[:-1]+chr(C:=ord(B[-1])-1),A(B[:-1])+"z"][97>C]or""

```

Try it online!
> 6 votes

# Answer
# Pyth, 8 bytes

```
ef!-TGrN

```

Try it online!

Throws an error for input `a`, but outputs nothing to STDOUT, which is technically the correct output.

**Explanation**

```
ef!-TGrN
      rN   Build a string range from the string '"' to the implicit input
 f         Filter for strings of this range satisfying:
  !         - the string becomes empty...
   -TG      - ...when all lowercase letters are removed
e          Take the last element

```

*Note*: `N` was used to start the range rather than `d` or `k` since it has a lower codepoint.
> 6 votes

# Answer
# Ruby `-pl`, ~~29~~ 13 bytes

```
*,$_=*?a...$_

```

Try it online!

Ironically, this task is essentially the opposite of Ruby's `next` (or alternatively `succ`) method on strings, however this potential `previous` method is not available out of the box. Therefore, to take advantage of existing functionality we have to loop through the range of strings (which is constructed using `succ`) from `"a"` all the way to the input (non-inclusive), and take the last position. Obviously, this will be too slow for the longer test cases.
> 6 votes

# Answer
# Retina 0.8.2, 22 bytes

```
(?=a+$)^a

T`l`zl`.a*$

```

Try it online! Link includes test cases. Explanation:

```
(?=a+$)^a

```

Remove one of the `a`s if all of the letters are `a`s. The lookahead is naturally placed before the anchor as it has a lower ASCII code.

```
T`l`zl`.a*$

```

Cyclically decrement any the trailing `a`s and the previous letter.
> 5 votes

# Answer
# JavaScript (ES6),  ~~65 64~~  62 bytes

I/O: array of code points

```
$=>$.reduceRight((A,B,C)=>!C&($=$&&--B<97)?A:[$*26+B,...A],[])

```

Try it online!

### Commented

```
$ =>                  // $[] = input array, reused for the carry
  $.reduceRight(      // for each
    (A, B, C) =>      // code point B at position C, using A[] as the accumulator:
    !C &              //   is it the leading 'digit'?
    ( $ = $ && --B    //   if the carry is set, decrement B
               < 97 ) //   and set it again if the result is 96 (just below 'a')
    ?                 //   if this is the leading 'digit' and the carry is set:
      A               //     leave A[] unchanged
    :                 //   else:
      [ $ * 26 + B,   //     prepend B if there's no carry or B + 26 otherwise
        ...A ],       //     (which gives 122, or 'z')
    []                //   initialize the accumulator to an empty array
  )                   // end of reduceRight()

```
> 4 votes

# Answer
# Jelly, ~~14~~ 13 bytes

```
LØaṗṪṖṭƊði’ị⁸

```

Try it online!

*-1 byte thanks to Jonathan Allan reminding me of the Cartesian power builtin.*

A ~~new~~ different approach using raw enumeration instead of math. `LØaṗṖL¦ði’ị⁸` is a byte shorter, but doesn't correctly produce the empty string for some reason. It's not quite so efficient as the first solution, so I've abridged the longer test cases...

```
 Øaṗ             Take the Cartesian product of the lowercase alphabet with itself
L                a number of times equal to the length of the input.
    Ṫ            Take the last element of the product (e.g. "zzzz"),
     Ṗ           remove its last element ("zzzz" -> "zzz"),
      ṭƊ         and re-append it to the product.
        ð        Given that product and the original input,
         i       find the input's index in the product,
          ’      subtract 1,
           ị⁸    and index back into the product.
                 Since Jelly uses modular 1-indexing, if the input is the least
                 string of its length, its index of 1 will decrement to 0, which
                 then maps it back to the end of the enumeration, which has been
                 truncated appropriately.

```

# Jelly, 21 bytes

```
O_96µJṚ’26*×µS’ḃ26ịØa

```

Try it online!

There's probably a shorter conversion from bijective base 26 out there, but I figured I may as well write my own before taking someone else's.
> 4 votes

# Answer
# Factor, 115 bytes

```
: а ( s -- s ) >array [ 96 - ] map reverse
dup length [0,b] [ 26 swap ^ ] map [ * ] 2map
sum 1 - bijective-base26 ;

```

A naive implementation using `bijective-base26` which does half the work. This solution doesn't work in TIO, because it apparently doesn't include the `html-help` dictionary.

Here's a screenshot from my desktop Factor Listener:
> 4 votes

# Answer
# Python 2, 81 bytes

```
A="";B=1
for C in input()[::-1]:A=chr((ord(C)-97-B)%26+97)+A;B*=C<"b"
print A[B:]

```

Try it online!

72 bytes with lists of code points as input and output:

```
A=[];B=1
for C in input()[::-1]:A=[(C-97-B)%26+97]+A;B*=C<98
print A[B:]

```

Try it online!
> 3 votes

# Answer
# , <sup>~~39~~ ~~36~~ ~~35~~ ~~31~~</sup> 26 bytes

*-5 when using codepoints*

```
*/@:=&97}.<:&.(26#.2,-&97)

```

Try it online!

### How it works

```
*/@:=&97}.<:&.(26#.2,-&97)
                     -&97  a->0,b->1,..
               26#.2,      append 2 and convert from base 26
          <:&.(          ) execute right side, then decrement,
                           then inverse of right side
               26#.2,      convert to base 26 and drop the 2
                     -&97  convert back to string
*/@:=&97                   does input string only contain a's?
        }.                 drop 0 or 1 letters

```
> 3 votes

# Answer
# Haskell, 56 bytes

```
a.b.a
a=reverse
b"a"=""
b('a':a)='z':b a
b(a:b)=pred a:b

```

Try it online! The identifier names are a bit confusing (i.e. `a` appears as the current character, the rest of the string, and as shorthand for `reverse`) in order to use low code points.

Currently beats the other Haskell answer, though I already submitted an one byte improvement there which will put it into the lead again.
> 3 votes

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

```
{`c$97+1_26\-1+26/2,{(~+/x)_x}x-97}

```

Try it online!

Strongly inspired by @xash's J solution \- don't forget to upvote it!
> 2 votes

# Answer
# PHP, 35 bytes

```
for($a=a;$a!=$argn;$b=$a++);echo$b;

```

Try it online!

who knew strings incrementing would serve one day? Too bad decrementing doesn't work..
> 2 votes

# Answer
# 05AB1E, 10 bytes

```
āAδã˜s¡нθJ

```

Try it online or verify all (short) test cases. (Times out for any test cases with a length above 5 due to the `ã` builtin.)

**Explanation:**

```
ā           # Push a list in the range [1, (implicit) input-length] (without popping)
 A          # Push the lowercase alphabet
  δ         # Apply double-vectorized:
   ã        #  Take the cartesian product
    ˜       # Flatten this list of lists
     s      # Swap so the input is at the top of the stack
      ¡     # Split this list of strings on the input
       н    # Only leave the first list
        θ   # And leave the last string of that first list
         J  # Join (for the edge case 'a', which will result in an empty list [])
            # (after which it is output implicitly as result)

```

NOTE: In this solution I'm alternatively able to change the `н` to `ć`/`¬`; `θ` to `¤`; and/or `J` to `»` without changing the functionality. However, all of those would only negatively effect the score, since `нθJ` are earlier in the 05AB1E encoding.
> 2 votes

# Answer
# SimpleTemplate, 25 bytes

I loved PHP's feature where incrementing `'a'` woud give `'b'`, and incrementing `'z'` would give `'aa'`.

So, since very early in the creating, I've decided to emulate that functionality, but PHP doesn't support *decrementing*.
That had to be implemented manually, a long time ago...

---

Anyway, this is the code for the task:

```
{@incby-1argv}{@echoargv}

```

The code is incredibly simple: Increment all values in `argv` by -1 (decrement) and output it (without a separator).

An ungolfed version of the code isn't much different:

```
{@inc by -1 argv}{@echo argv}

```

(Note: `argv` is the default variable that contains all arguments passed, both to the script as well as to a function. Converting to a function is trivial.)

---

You can try it on: http://sandbox.onlinephpfunctions.com/code/05d4f13a1d27480d119e516c446b9d001d1111d8
> 2 votes

# Answer
# perl -M5.010 -nl, 46 bytes

```
$"=a;say/^$"$/?"":do{{$,=$"++;/^$"$/||redo}$,}

```

Try it online!

Very slow. Starting with `a`, it iterates over all the strings consisting of lower case letters, in shortlex order. If it matches the input, it prints the previous string. Some bytes are wasted to deal with the input of `a`, which should return the empty string.
> 1 votes

# Answer
# Brachylog, 19 bytes

```
{{∧Ẓ∋}ᵐ|b↰}ᶠs[?,.]∧

```

Try it online!

I expect to be able to outgolf this.
> 1 votes

# Answer
# Perl 5 `-pl`, 42 bytes

-1 byte, thanks to @Abigail!

```
s/(.)(a*)$/$1=~y!b-za!a-y!dr.$2=~y!a!z!r/e

```

Try it online!

## Explanation

Mostly just using Regex here. First, match any character followed by a (greedy match of `0` or more) `a`s. In the replacement, return `$1`, `tr///`anslating (`y///`) chars to those directly preceding them (`/d`eleting any `a`s), followed by `$2`, translating `a`s to `z`s.

This should work for any length input.
> 1 votes

# Answer
# C (gcc), 85 bytes

Works backwards from the end, overwriting the string as it goes along. If the previous digit borrowed (which the first character processed always does), then decrement the current digit, wrapping if required. If the final digit processed wrapped, then return the next character in the string.

```
A,B,C;D(char*E){for(A=1,B=strlen(E);B--;E[B]=(A=C<97)?B?122:0:C)C=E[B]-A;return E+A;}

```

Try it online!
> 1 votes

# Answer
# Husk, 14 bytes

```
→←xṁOmπ…'a'zΘN

```

Try it online! Uses a strategy similar to the one in Kevin Cruijssen's answer.
> 1 votes

# Answer
# Charcoal, 33 bytes

```
≔⪪Ｓ¹θＷ›θ⟦a⟧«≔⊟θι←§β⊖⌕βι¿›ιa«↑θ≔υθ

```

Try it online! Link is to verbose version of code. Vaguely based on @SurculoseSputum's answer. Explanation:

```
≔⪪Ｓ¹θ

```

Split the input into characters.

```
Ｗ›θ⟦a⟧«

```

Repeat until we only have `a` or nothing left.

```
≔⊟θι

```

Get the last remaining letter.

```
←§β⊖⌕βι

```

Print its cyclic decrement leftwards.

```
¿›ιa«

```

If there is no borrow, ...

```
↑θ

```

... print the remaining list in reverse, ...

```
≔υθ

```

... and clear the list to exit the loop.
> 0 votes

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


title: Find the Inverse Neighbor Pairs

text:
# Question
Title: Find the Inverse Neighbor Pairs
### Definition

We say a pair of integers \\$(a,b)\\$, where \\$0\<a\<b\<N\\$ and \\$N\\$ is an integer larger than 4, is an inverse neighbor pair respect to \\$N\\$ if \\$ab\equiv1\text{ }(\text{mod }N)\\$ and \\$1\le b-a\le\log\_2{N}\\$. There may be no such pairs respect to some integers \\$N\\$.

To illustrate the definition, consider \\$N=14\\$. \\$(3,5)\\$ is an inverse neighbor pair respect to \\$N\\$ because \\$3\times 5=15\equiv1\text{ }(\text{mod }14)\\$ and \\$1\le 5-3=2\le\log\_2{14}\approx 3.807\\$. Another pair is \\$(9,11)\\$.

On the other hand, consider \\$N=50\\$. \\$(13,27)\\$ is not an inverse neighbor pair because although \\$13\times 27=351\equiv1\text{ }(\text{mod }50)\\$, their distance \\$27-13=14\\$ is too large to be "neighbors". In fact, there are no inverse neighbor pairs respect to this \\$N\\$, since there are no such pairs that both \\$ab\equiv1\text{ }(\text{mod }50)\\$ and \\$1\le b-a\le\log\_2{50}\approx 5.643\\$ can be fulfilled.

### Challenge

Write a program or function, that given an integer input \\$N\>4\\$, outputs or returns all inverse neighbor pairs respect to \\$N\\$ without duplicate. You may output them in any reasonable format that can be clearly interpreted as distinct pairs by a human, e.g. two numbers per line, or a list of lists, etc.

The algorithm you use must in theory vaild for all integers \\$N\>4\\$, although practically your program/function may fail or timeout for too large values.

### Sample I/O

For inputs without any inverse neighbor pairs, the word `empty` in the output column means empty output, not the word "empty" literally.

```
Input  -> Output
5      -> (2,3)
14     -> (3,5), (9,11)
50     -> empty
341    -> (18,19), (35,39), (80,81), (159,163), (178,182), (260,261), (302,306), (322,323)
999    -> (97,103), (118,127), (280,289), (356,362), (637,643), (710,719), (872,881), (896,902)
1729   -> empty
65536  -> (9957,9965), (15897,15913), (16855,16871), (22803,22811), (42725,42733), (48665,48681), (49623,49639), (55571,55579)
65537  -> (2880,2890), (4079,4081), (10398,10406), (11541,11556), (11974,11981), (13237,13249), (20393,20407), (26302,26305), (39232,39235), (45130,45144), (52288,52300), (53556,53563), (53981,53996), (55131,55139), (61456,61458), (62647,62657)
524287 -> (1023,1025), (5113,5127), (59702,59707), (82895,82898), (96951,96961), (105451,105458), (150800,150809), (187411,187423), (192609,192627), (331660,331678), (336864,336876), (373478,373487), (418829,418836), (427326,427336), (441389,441392), (464580,464585), (519160,519174), (523262,523264)

```

### Winning Condition

This is a code-golf challenge, so shortest valid submission of each language wins. Standard loopholes are forbidden by default.

# Answer
# 05AB1E, ~~17~~ ~~14~~ 13 bytes

*Thanks to @KevinCruijssen and @Grimmy for the fix and inspiration from Kevin's now deleted answer*

*-1 byte further thanks to @Grimmy*

```
L.ÆʒRÆo@}ʒPI%

```

Try it online!

---

# Explanation

```
L.Æ                    - Combinations of [1..N] with 2 elements
    ʒ     }            - Filter this when ...
     RÆo               - 2^(The difference of each pair) is...
        @              - <= the input
           ʒPI%        - Then filter this list further where the product modulo input is 1

```
> 5 votes

# Answer
# Jelly, 17 bytes

```
ŒcðIḢ2*>¬ȧ⁸P%⁼1ðƇ

```

A monadic Link accepting an integer which yields a list of pairs.

**Try it online!**

### How?

*not updated for less-than-or-equal...*

```
ŒcðIḢ2*<ȧ⁸P%⁼1ðƇ - Link: integer, n
Œc               - unordered pairs (of implicit range [1..n])
               Ƈ - filter keep those for which:
  ð           ð  - ...this dyadic chain, f(pair,n), is non-zero:
   I             -   deltas       [a,b] -> [b-a]
    Ḣ            -   head                   b-a
     2*          -   2 raised to         2^(b-a)
       <         -   is less than (n)    2^(b-a)<n  == b-a<log(n,2)
         ⁸       -   chain's left argument, the pair
        ȧ        -   logical AND           [a,b]    or  0
          P      -   product                a×b         0
           %     -   modulo (n)            (a×b)%n      0
            ⁼1   -   equals one?           (a×b)%n==1   0

```
> 3 votes

# Answer
# MATL, 20 bytes

```
:2XN!tpG\1=yd|WG>>Z)

```

The output is a 2-row matrix where each column is a pair.

Try it online!

### How it works

Consider input `5` as an example.

```
:     % Implicit input: N. Range [1 2 ... N]
      % STACK: [1 2 ... N]
2XN   % Combinations of 2 elements, as rows in a 2-column matrix
      % STACK: [1 2;
                1 3;
                ···;
                4 5]
!     % Transpose. Each combination is now a column in a 2-row matrix
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
tp    % Duplicate. Product of each column
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [2  3  4  5  6  8 10 12 15 20]
G\    % Modulo N
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [2 3 4 0 1 3 0 2 0 0]
1=    % Equal to 1?
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
y     % Push another copy of the 2-row matrix
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
d|    % Absolute difference between the two rows
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [1 2 3 4 1 2 3 1 2 1]
W     % 2 raised to that
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [2  4  8 16  2  4  8  2  4  2]
G>    % Greater than N? (**)
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [0 0 1 1 0 0 1 0 0 0]
>     % Greater than. This gives true for entries that are true in (*)
      % and false in (**)
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
Z)    % Use as a logical index into the columns of the 2-row matrix
      % STACK: [2;
                3]
      % Implicit display

```
> 2 votes

# Answer
## Fortran (GFortran), ~~86~~ 79 bytes

```
read*,n
print*,((pack([i,j],mod(i*j,n)==1.and.2.**(j-i)<=n),j=i+1,n),i=1,n)
end

```

*-7 bytes thanks to @DeathIncarnate*

Yes, I still write Fortran in 2020. Here I'm reading an implicit integer n and looping over i and j (a and b would be implicitly reals). An array (i, j) is masked using the intrinsic pack().

Try it online!
> 2 votes

# Answer
# JavaScript (V8),  ~~61 59~~  57 bytes

```
n=>{for(a=b=n;a=a||--b;)--a*b%n-1|2**(b-a)>n||print(a,b)}

```

Try it online!

The way the `for` loop is written, we have \\$b=N\\$ during the first \\$N\\$ iterations and we have \\$a=0\\$ before \\$b\\$ is decremented. But in both cases, it implies \\$ab\equiv 0\pmod N\\$, so the corresponding pairs are rejected anyway.
> 2 votes

# Answer
# JavaScript (V8), 56 bytes

```
x=>{for(y=x;i=--y;)for(z=x;z>>=1;)y*++i%x-1||print(y,i)}

```

Try it online!

This \\$O(n\log{n})\\$ algorithm works practically up to \\$N\approx2^{26.5}\approx9.49\times10^7\\$.

This was 67 bytes and was originally for my test case verifications only, and then I saw Arnauld's 57 bytes. Inspired by his solution, I checked whether I can golf the loops while keeping \\$O(n\log{n})\\$ complexity, and here it is.
> 2 votes

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

```
lambda N:[(a,b)for a in range(N)for b in range(a)if(1<<a-b)-N<a*b%N==1]

```

Thanks, Jitse, for saving me 5 bytes after some discussion.

You can try it online, where I'm not running the larger test cases because it times out
> 1 votes

# Answer
# Ruby, 64 bytes

```
->n{(r=*1...n).product(r).select{|a,b|b>a&&a*b%n==1&&n>=1<<b-a}}

```

Try it online!
> 1 votes

# Answer
# Charcoal, 27 bytes

```
ＮθＦθＦιＦ‹›Ｘ²⁻ικθ⁼¹﹪×ικθＩ⟦⟦κι

```

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

```
Ｎθ

```

Input `N`.

```
ＦθＦι

```

Loop `0 <= a < b < N`. (`a=0` can never be a solution, so it doesn't hurt to include it.)

```
Ｆ‹›Ｘ²⁻ικθ⁼¹﹪×ικθ

```

Check whether `2**(b-a)<=N` and `a*b%N==1`.

```
Ｉ⟦⟦κι

```

If so then output `a` and `b`, on separate lines, with each pair double-spaced.
> 1 votes

# Answer
# C (gcc) -lm, 76 bytes

A port of my JS answer.

```
a,b;f(n){for(a=b=n;a=a?a:--b;)--a*b%n-1|pow(2,b-a)>n||printf("%d,%d ",a,b);}

```

Try it online!
> 1 votes

# Answer
# bc, 140 94 90 bytes

```
define f(n){for(a=2;a<n;a=a+1){for(d=1;2^d<=n;d++){if(a*(a+d)%n==1){print" ",a,",",a+d}}}}

```

Try it online!

Function f() takes the number as input, writes its output to stdout, and returns 0, which should be ignored. The test wrapeper in the TIO needs a special marker for end-of-file, as it otherwise keeps trying to read

Having looked at another answer, I saw I could do \\$2^{d}\le{n}\\$ instead of \\$d\le\log\_2{n}\\$ -46, including the +2 for -l.

I was amazed to find it turned into a one-liner.

I then realized I had two unneeded pairs of parentheses. -4.

I have also realized that I allow b\>n, but it apparently doesn't hit in the test cases.

Edit: it turns out with \\$0\<a\<N\<b\\$, there can't be a hit unless \\${{b-a}\over2}\ge\sqrt{N-1}\\$ Combining with the neighbor requirement of \\$b-a\le\log\_2{N}\\$ we get \\$2\sqrt{N-1} \le \log\_2{N} \\$ This only happens at \\$N=1\\$, so I'm safe.

## ungolfed:

```
define f(n) {
    for (a=2; a<n; a=a+1) {
        for (d=1; 2^d<=n; d++) {
            if (a*(a+d)%n==1) {
                print " ", a, ",", a+d
            }
        }
    }
}

```

## originally: bc -l, 138 + 2 = 140 bytes

```
define f(n){
scale=9
m=l(n)/l(2)
scale=0
for(a=2;a<n;a=a+1){c=a+m
if(c>=n)c=n
for(b=a+1;b<c;b=b+1){if(((a*b)%n)==1){print " ",a,",",b
}}}}

```

Try it online!
> 1 votes

# Answer
# Burlesque, 46 bytes

```
riJs1ro2CBf{Jp^.-ab2j**g1.<jpdg1.%1==&&}:U_:so

```

Try it online!

```
ri     # Read as int
Js1    # Store a copy
ro     # Range [1,N]
2CB    # Combinations of length 2
f{     # Filter for
 J     # Duplicate
 p^.-  # i-j
 ab    # |i-j|
 2j**  # 2^|i-j|
 g1.<  # < N
 jpd   # i*j
 g1.%  # (i*j)%N
 1==   # Equal to 1
 &&    # Bitwise and
}
:U_    # Filter out i=j
:so    # Filter for sorted (removing duplicates)

```
> 1 votes

# Answer
# Haskell, 57 bytes

A port of my Python answer

```
f n=[(a,b)|a<-[0..n],b<-[0..a-1],2^(a-b)<=n,1==mod(a*b)n]

```

You can try it online
> 0 votes

# Answer
# Perl 6, 55 bytes

```
{grep {[*](@^a)%$_==1&&$_>=2**[R-](@a)>=2},(^$_ X ^$_)}

```

Try it online!
> 0 votes

# Answer
# , ~~77~~ 64 bytes

```
function(N)which((o=outer(x<-1:N,x,'-'))>0&2^o<=N&x%o%x%%N==1,T)

```

Try it online!

Returns a matrix with columns `b,a` of all inverse neighbor pairs. Since it creates several `NxN` matrices, this will run out of memory in a hurry.
> 0 votes

# Answer
# Husk, 24 bytes

```
fȯ≤¹`^2F-fȯ=1%¹F*fF>´×,ḣ

```

Try it online! Nothing too complicated, just the three filters applied to the list of ordered pairs.
> 0 votes

# Answer
# Japt, 18 bytes

```
õ à2 fÈrÍ§U«1nX×uU

```

Try it
> 0 votes

# Answer
# Wolfram Language (Mathematica), ~~73~~ ~~71~~ 69 bytes

```
n_:>Select[Range@n~Subsets~2,Mod[1##&@@#,n]==1&&2^#[[2]]<=2^#[[1]]n&]

```

Try it online!

Defined as a delayed rule that can be applied to any integer.
> 0 votes

---
Tags: code-golf, number, number-theory
---


title: Fibonacci distribution validator

text:
# Question
Title: Fibonacci distribution validator
> **Related:** Hello world!!! Fibonacci distribution

Create a program that returns True if a given input meets the following specifications, and False otherwise:

* The count of numeric characters (0-9) in the input matches a Fibonacci number.
* The count of non-numeric characters !(0-9) in the input matches the Fibonacci number immediately preceding the count of numeric characters.

Additional Rules:

* Your program must use the proper Fibonacci sequence, per OEIS - that is, the Fibonacci sequence must start with `0, 1, 1, 2, ...`
* If the numerics or non-numerics count is 1, the following must occur:
    + Numerics 1: Non-numeric count of 0 *or* 1 should be handled as True - all others False.
    + Non-Numerics 1: Numerics count of 1 *or* 2 should be handled as True - all others False.
* Input may be taken however you like, but the program must be capable of handling any arbitrary text.
* True/False are not case-sensitive, and can be substituted with 1/0 or T/F.
* You may only hard-code up to two Fibonacci numbers.
* Output may *only* be True/False or 1/0 or T/F. Any additional text or visible errors generated is unacceptable.

# Answer
> 4 votes
# Javascript, ~~92 88~~ 86 characters

```
t=prompt()
for(b=c=1;c<t[l='length'];c=a+b)a=b,b=c
alert(c==t[l]&b==t.match(/\d/g)[l])

```

I hope you don't mind I've hard-coded the the first three Fibonacci numbers.

# Answer
> 4 votes
# Golfscript, 36

```
:?1 2{.@+.?,<}do?,=@{.48<\58<^},,@=*

```

Explanation:

* `:?` stores the input into `?`.
* `1 2{.@+.?,<}do` computes the last two fibonacci numbers until it hits the input length. The block reads: "duplicate the top, rotate the third value to the top, add them, duplicate the top, get the input, get its length, compare".
* `?,=` compares the last computed fibonacci number to the input length.
* `@` brings the input to the top
* `{.48<\58<^},` filters out only digits. The block reads "is the ASCII value below 48 XOR below 58?"
* `,@=` compares the filtered string length to the lower fibonacci number (count of digits)
* `*` merges the two comparisons to provide a single boolean value.

Live demo: http://golfscript.apphb.com/?c=OyIvMDU5OiIKOj8xIDJ7LkArLj8sPH1kbz8sPUB7LjQ4PFw1ODxefSwsQD0q

# Answer
> 3 votes
# Python - ~~128~~ 125

```
import re
def v(s):
 l=len(re.sub("\d","",s));L=len(s)-l;a,b=1,2
 while a<L:
    if a==l and b==L:
     print 1;return
    b,a=a+b,b
 print 0

```

Really hope there is no problem with hardcoding the first few fibonacci numbers

# Answer
> 3 votes
# Python 3, 105 characters

Script file name is passed to the program through the command line

```
import sys
a=[0]*2
for b in open(sys.argv[1]).read():a['/'<b<':']+=1
a,b=a
while a>0:a,b=b-a,a
print(b==1)

```

## 87 characters

Script must be written in file with name `s`

```
a=[0]*2
for b in open('s').read():a['/'<b<':']+=1
a,b=a
while a>0:a,b=b-a,a
print(b==1)

```

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

```
ḟ,fɗØDẈẇ⁸LŻÆḞ¤

```

Try it online!

## How it works

```
ḟ,fɗØDẈẇ⁸LŻÆḞ¤ - Main link. Takes a string S on the left
    ØD         - Yield "0123456789"; D
   ɗ           - Group the previous three atoms together as a dyad, f(S, D):
ḟ              -   Remove digits from S
  f            -   Remove non-digits from S
 ,             -   Pair these two
      Ẉ        - Lengths of each in the pair; [a, b]
             ¤ - Create a nilad:
        ⁸      -   Yield S
         L     -   Take its length, L
          Ż    -   [0, 1, 2, ..., L]
           ÆḞ  -   nth Fibonacci number for each
       ẇ       - Sublist exists?
                 This returns 1 if the left argument ([a, b]) is a contiguous sublist
                 of the right argument (the list of Fib numbers), i.e.
                 a and b are both Fibonacci numbers, and a immediately precedes b

```

# Answer
> 2 votes
## Perl, 92

```
$_=join"",<>;@_=1;$d=s/\d//g;push@_,$t=$_[-1]+$_[-2]while$t<$d;print$t==$d&$_[-2]==y///c?1:0

```

Usage:

```
cat fib-test
print "Hello world%s"%("!"*int(3.141592653589793238462643383279502884197169399375105820))

perl -e '$_=join"",<>;@_=1;$d=s/\d//g;push@_,$t=$_[-1]+$_[-2]while$t<$d;print$t==$d&$_[-2]==y///c?1:0' fib-test
1

```

# Answer
> 2 votes
# Java - ~~147~~ 145

```
boolean v(String s){int l=s.replaceAll("\\d","").length(),L=s.length()-l,a=1,b=2,c;while(a<L){if(a==l&&b==L)return 0<1;c=b;b+=a;a=c;}return 0>1;}

```

I'd say this is not bad for Java.

**Edit**: Thanks to Chris Hayes for suggesting `0>1` for false and `0<1` for true.

# Answer
> 2 votes
# 05AB1E, ~~15~~ ~~12~~ 11 bytes

```
d1Ý¢¤ÅFs.kd

```

-3 bytes by taking inspiration from *@cairdCoinheringaahing*'s initial Jelly program
-1 byte thanks to *@ovs*

Input as a list of characters.

Try it online or verify a few more test cases.

**Explanation:**

```
d            # Check for each character in the (implicit) input-list if it's a
             # non-negative (>=0) integer (1 if truthy; 0 if falsey)
 1Ý          # Push the list [0,1]
   ¢         # Count them in the list of truthy/falsey results
    ¤        # Push the last count, without popping the pair itself
     ÅF      # Pop and push a list of Fibonacci numbers <= this count
       s     # Swap so the pair is at the top of the stack
        .k   # Get the index of the pair (as sublist) in the Fibonacci list
             # (or -1 if this pair isn't a sublist)
          d  # Check that this index is non-negative (>=0), thus that it was found
             # (after which the result is output implicitly)

```

Unfortunately the Fibonacci sequence contains two `1`s, otherwise we could have saved two bytes by changing `s.kd` to `sÅ¿` (check whether it ends with the pair), which fails for single-digit inputs.

# Answer
> 1 votes
# APL, 34 chars/bytes\*

```
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2

```

Expects the input string on standard input and prints either 0 or 1 as required. `⎕IO` must be set to 0 (the default is implementation-dependent.)

**Ungolfed**

```
s←⍞                ⍝ read input string
d←s∊⎕D             ⍝ vector with 1 for each digit, 0 for each non-digit in s
n←+/0 1∘.=d        ⍝ 2-vector with number of non-digits and number of digits in s
f←+\∘⌽             ⍝ a function that computes a fibonacci step (f 2 3 → 3 5)
t←f⍣{≥/+/⊃⍺n}0 1   ⍝ apply f repeatedly, starting with 0 1, until we get two fibonacci
                   ⍝   terms whose sum is ≥ the length of the input string (sum of n)
n≡t                ⍝ return 1 if the fibonacci terms match the no. of digits and non-digits

```

**Examples**

```
      {n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
%~n01234
1
      {n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
x'48656C6C6F20776F726C642121'||'!'
1
      {n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
[72 101 108 108 111 32 119 111 114 108 100 33 {.}2*]''+
1
      {n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
What?12345
0

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>

# Answer
> 1 votes
# Husk, ~~23~~ ~~21~~ ~~19~~ ~~18~~ 16 bytes

*Edit: -1 byte, then -2 more bytes, thanks to Razetime*

```
€↑→L¹İfe#€ṁsŀ9¹L

```

Try it online!

```
€↑→L¹İfe#€ṁsŀ9¹L
€                       # index of argument in list, if found, otherwise 0,
 ↑                      # list: the first n elements
  →L¹                   # n = length of input +1
     İf                 # of the list of fibonacci numbers
       e                # argument: 2-element list
        #               # 1. number of elements in input that are
         €    ¹         # present in list of
          ṁsŀ9          # string from 0 to 9
               L        # 2. length of input

```

# Answer
> 1 votes
# K (ngn/k), ~~46~~ ~~40~~ ~~38~~ 32 bytes

* -12 bytes from golfing, -2 from @ngn's improvements

```
{~^(|+\)\[#x;|!2]?+/'~:\~"0:"'x}

```

Try it online!

* `~"0:"'x` determine which characters in the input are digits
* `+/'~:\` count the number of digits and non-digits
* `~^(...)[...]?` determine if the above is in...
    + `(|+\)\[#x;|!2]` the pairs of fibonacci numbers

# Answer
> 0 votes
## Ruby, 85

```
d=-(n=(i=$<.read).gsub(/\d/,'').size)+i.size
a=b=1;while b<d;b=a+a=b end;p b==d&&a==n

```

Takes input either on `STDIN` or as a filename argument.

Output is either `"true"` or `"false"`.

# Answer
> 0 votes
# Japt v2.0a0, 20 bytes

```
Êô@MgXÃã de[\D\d]£èX

```

Try it (Test cases appropriated from caird)

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


# Question
Title: Randomly pick one number that is different than two other random numbers
Two random numbers `A` and `B` have been generated to be either 1, 2, or 3

your job is to randomly pick a third number `C` that can also be 1, 2 or 3. But, `C` cannot equal `A` or `B`.

* `A` can equal `B`.
* If `A = B`, then `C` has only two numbers left it can be.
* If `A ≠ B`, `C` has only one number it can be.
* Assume `A` and `B` have already been chosen for you

This is how `A` and `B` would be created in Python

```
A = random.randrange(1,4)
B = random.randrange(1,4)

```

Assume this is already in your code.

This is the shortest I've come up with in Python

```
while True:
    C = random.randrange(1,4)
    if C != A and C != B:
        break

```

Here are some acceptable values for `A`, `B` and `C`.

* `1,2,3`
* `1,1,2`
* `2,3,1`
* `3,3,2`

Here are some unacceptable values for `A`, `B` and `C`.

* `1,2,1`
* `2,3,3`
* `1,1,1`
* `3,2,3`

# Answer
## Ruby, 22 characters

```
([1,2,3]-[A,B]).sample

```

Still not sure if I understood the question correctly ...
> 18 votes

# Answer
# C,26

```
a-b?6-a-b:(rand()%2+a)%3+1

```

If I've understood the question correctly:

If `a` and `b` are different, there is no random. the answer must be the only one of 1,2,3 that is unused: `6-a-b`.

IF `a` and `b` are the same there are 2 choices:

```
a=b=           1 2 3
            return value
rand()%2=0     2 3 1
rand()%2=1     3 1 2

```
> 12 votes

# Answer
## Befunge (~~156~~ ~~89~~ ~~85~~ 74)

Okay, this is terrible, I know. But it's my first Befunge attempt ever, so I'm still pretty happy that it even works. I'm sure there's a much, much better solution.

```
<v1p90&p80&
<<@.g70_v#-g70_v#-g70g90g80p70
  v     <      <
^1?v
^3<2
^  <

```
> 5 votes

# Answer
# Python - 35

```
C=random.sample({1,2,3}-{A,B},1)[0]

```

Assumes random is imported, which seems to be specified in the question.

# PYG - 25

```
C=RSm({1,2,3}-{A,B},1)[0]

```
> 3 votes

# Answer
# GolfScript, 13 chars

```
~0]4,^.,rand=

```

This is a complete GolfScript program that reads two whitespace-separated numbers (each assumed to be either 1, 2, or 3) from standard input, and outputs a random number from the set {1, 2, 3} that does not equal any of the input numbers.

Try it online. (Note: the link is to the previous version; I'm on a mobile device and can't fix it.)

Here's a commented version of the program:

```
~         # eval the input, pushing the input numbers onto the stack
0         # push the number 0 onto the stack
]         # collect all the numbers on the stack into an array
4,        # create another array containing the numbers 0, 1, 2 and 3
^         # xor the arrays (i.e. take their symmetric set difference)
.,rand=   # choose a random element from the array

```

If you'd prefer a named function that takes the two numbers as arguments on the stack, that takes a few more chars:

```
{[\0]4,^.,rand=}:f;

```

The actual body of the function is only one char longer than the stand-alone code (because we need the `[` to make sure we consume only two arguments), but the overhead of wrapping the code in a block and assigning it to a symbol takes five more chars, for a total of 19.

Alternatively, if you literally have the two numbers assigned into the variables `A` and `B`, and want the third number assigned to `C`, that can also be done in 19 chars:

```
4,[0A B]^.,rand=:C;

```

(If leaving the third number on the stack instead is acceptable, you can leave the `:C;` off the end.)

Ps. Thanks for the suggestion to use `^`, Howard.
> 3 votes

# Answer
**Python, 14 characters**

I tried it for every 9 possible cases and it seems to work fine!

```
C=A^B or A^1|2

```

(edit): As edc65 pointed out, this isn't valid since it's not random... I missed that part of the question and I feel stupid right now.
> 3 votes

# Answer
# Befunge - 99 bytes

```
&:01p&:11p-!!#v_v
   @,g2+g11g10< "
   321 vv*2g<"v ^
 2v v v 5v*2^10<"
 v?v?v?vp5     ^<
 2 3 1 2<
 > > > >.@

```

Not very impressive.
> 2 votes

# Answer
## PowerShell, 21

```
1..3-ne$A-ne$B|random

```

*Very* straightforward. Abusing the fact that comparison operators act differently with an array as their left operand.
> 2 votes

# Answer
## Mathematica, 37 bytes

```
RandomChoice@DeleteCases[{1,2,3},a|b]

```

Basically the same as the Ruby answer, but considerably longer thanks to Mathematica's function names. I'm using lower-case variables, because upper-case names might clash with built-ins (they don't, in this case, but you simply don't do it in Mathematica).
> 1 votes

# Answer
## R, 42 chars

```
x=c(1,1,1);x[c(A,B)]=0;C=sample(1:3,1,p=x)

```

Vector `x` is the vector of probability weights for obtaining the elements of the vector being sampled. It is set to 1 for each at first, then elements corresponding to A and B are set to 0, hence they have no chance of being picked.
> 1 votes

# Answer
# Rebol - 40 chars

```
random/only difference[1 2 3]reduce[A B]

```
> 1 votes

# Answer
# CJam - 12

```
4,[AB0]-mr0=

```

This assumes the variables A and B have already been set, according to the question.

You can try it at http://cjam.aditsu.net/

To test it with random numbers, use:

```
"A="3mr):A", B="3mr):B", C="
4,[AB0]-mr0=

```

To test it with specific values, use (for example):

```
"A="1:A", B="1:B", C="
4,[AB0]-mr0=

```

**Explanation:**

`4,` creates the array \[0 1 2 3\]
`[AB0]-` removes the numbers A, B and 0 from the array
`mr` shuffles the remaining array
`0=` takes the first element

In a future CJam version this program will be 2 bytes shorter :)
> 1 votes

# Answer
## C 67

```
int C(int a,int b){int c=0;while(c!=a&&c!=b)c=rand()%3+1;return c;}

```
> 1 votes

# Answer
## JS, 35

inspired by Brandon Anzaldi's answer

```
A=1; // init
B=3; // init
do{C=1+new Date%3}while(C==A||C==B) // 35b

```
> 1 votes

# Answer
# Pyth, 5 bytes

```
O.-S3

```

Try it online!

```
O.-S3
O.-S3Q - Implicitly read input
   S3  - Create range [1, 2, 3]
 .-    - Subtract input elements from the range
O      - Select a random element.

```
> 1 votes

# Answer
# Arn, 9 bytes

```
╚<<ÙŒÔ“Âj

```

Try it!

# Explained

Unpacked: `?.$v{!&v}~3`

```
?.          Random entry in
  $           Filtered list
    v{          With block; entry named v
      !           Boolean NOT
          _           Variable ≡ STDIN; implied
        &           Contains (implicit casting to array)
          v           Variable `v`
    }            End block
    ~           On one-range to
      3           Literal three

```
> 1 votes

# Answer
# Julia, 32 or 56 depending on the rules

```
julia> r()=rand(1:3);f(x...)=(i=r();i in x?f(x...):i)
julia> f(r(),r())

```

32 if I don't need to generate a and b.
> 0 votes

# Answer
## JS, 43

```
for(C=0;~[0,A,B].indexOf(C);)C=1+new Date%3

```
> 0 votes

# Answer
# J (~~21~~ 19: too long for my liking)

```
({~?@#)(>:i.3)-.A,B

```

~~Are there any J wizards around to help remove that variable assignment?~~ It's only 2 chars shorter...

Or, if it doesn't have to be random, you could do with this:

```
{:(i.4)-.A,B

```

12 chars.
> 0 votes

# Answer
# Java - ~~126~~ ~~123~~ ~~83~~ 85 (using the clever `c=6-a-b`)

```
int c;if(a==b){int r=(int)(Math.random()*2);c=a==1?r+2:a==2?2*r+1:r+1;}else{c=6-a-b;}

```

Full version:

```
public void test(int a, int b) {
    int c;
    if (a == b) {
        // Random 0 or 1.
        int r = (int)Math.random()*2;
        c = // 1 -> 2 or 3
                a == 1 ? r + 2
                // 2 -> 1 or 3
                : a == 2 ? 2 * r + 1
                // 3 -> 1 or 2
                : r + 1;
    } else {
        // Whichever is not taken.
        //int[][] r = {{0, 3, 2}, {3, 0, 1}, {2, 1, 0}};
        //c = r[a - 1][b - 1];
        // Using @steveverrill's clever
        c = 6 - a - b;
    }
    System.out.println("a=" + a + " b=" + b + " c=" + c);
}

```
> 0 votes

# Answer
## R, 24 characters

Initialize with

```
a = sample(1:3,1)
b = sample(1:3,1)

```

Then

```
n=1:3;n[!n%in%c(a,b)][1]

```

Or just `n=1:3;n[!n%in%c(a,b)]` but then you return *both* numbers.
> 0 votes

# Answer
**R, 31 characters**

```
sample(rep((1:3)[-c(A,B)],2),1)

```

If you do `sample(x)` in R, then it is interpreted as a random sample from `1:x`. Repeating the vector `(1:3)[-c(A,B)]` twice is one way of stopping this from happening.
> 0 votes

# Answer
# Javascript - 76

```
r=(y,z)=>Math.floor(Math.random()*(z-y+1)+y);a=b=r(1,3);while(c==a)c=r(1,3);

```
> 0 votes

# Answer
# JavaScript - 41 (up to 46) 37 35 34 30

Updated:

Managed to get it down to 30 chars by modifying it, inspired by stevevarrill's answer in C.

`C=A-B?6-A-B:1+(A+new Date%2)%3`

---

Thank you nyuszika7h for getting me down to 34~:

`C=A;while(C==A|C==B)C=1+new Date%3`

Borrowing from xem's answer to at least fall on par with him:

`C=A;while(C==A||C==B)C=1+new Date%3`

Thanks for reminding me that `1+new Date%3 === (new Date%3)+1`!

Previous Solution:

`C=A;while(C==A||C==B)C=(new Date%3)+1`

Ensure conditions of `while()` are satisfied, and loop through until they're not.

---

Other solution:

`C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1;`

This assumes that `C` has already been declared OR that the JavaScript interpreter can handle undeclared variables.

However, if the JS interpreter can handle EOL without a semicolon, it could be bumped down to 41.

`C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1`

If `C` hasn't been declared, and there is no error correction for it, that will bring the tally up to 46 characters.

`var C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1;`

Test Program:

```
var iterations = 100;

for(var i = 0;i<iterations;i++) {
    var A = Math.floor(Math.random() * 3) + 1;
    var B = Math.floor(Math.random() * 3) + 1;
    C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1
    if (C === A || C === B || C > 3 || C < 1) {
        console.log('FAILURE!');
        console.log(A + ',' + B + ',' + C)
        return;
    }
    console.log(A+','+B+','+C);
}

```
> 0 votes

# Answer
# C - 38

```
main(c){for(;c==a|c==b;c=rand()%2+1);}

```
> 0 votes

# Answer
## Java, 264 bytes

```
Random r = new Random();ArrayList<Integer> s = new ArrayList<>();ArrayList<Integer> q = new ArrayList<>();for(int i=0; i<n; i++) s.add(r.nextInt(k));q.add(s.get(r.nextInt(n)));q.add(s.get(r.nextInt(n)));int x;do{x = s.get(r.nextInt()); }while(!q.contains(x));

```

This code generates `n` different random numbers from 0 to `k`.
> 0 votes

# Answer
# Golfscript, 13 Characters

```
~]4,^.,rand)=

```
> 0 votes

# Answer
## Befunge-98 (57 bytes)

This code assumes the numbers will be input on stdin. It will pick a random number if both of the first numbers are the same until it is different, otherwise it will choose the last available number.

```
6&::11p&:12pw>   ?1  >#<:11g-!_.@
     @.-g21-<>3;#[2#;^

```
> 0 votes

# Answer
# Jelly, 5 bytes

```
3Rḟ⁸X

```

Try it online!

This takes `[A, B]` as input, as Jelly doesn't have the concept of variables

## How it works

```
3Rḟ⁸X - Main link. Takes [A, B] on the left
3R    - Yield [1, 2, 3]
   ⁸  - Yield [A, B]
  ḟ   - Remove [A, B] from [1, 2, 3]
    X - Randomly select an element from the remaining list

```
> 0 votes

# Answer
# Japt, 7 bytes

```
3õ kU ö

```

Try it here
> 0 votes

# Answer
**Python, 54 41 105 characters**

Quite long answer in Python but I like list comprehension, so I decided to post this here

// \[0\] means it is the first element of

```
from random import random
C=[i for i in sorted([1,2,3], key=lambda x: random()) if not(i in(A,B))][0]

```

Fixed but it is really long now.
> -2 votes

---
Tags: code-golf, random
---


# Question
Title: Write a program that uses all printable non-alphanumeric ASCII symbols
In particular, use each of these symbols at least once in your source code:

```
! " # $ % & ' () * + , - .  / : ; < = > ? @ [ \ ] ^ _ ` { | } ~

```

Symbols inside comments, string literals, regexps (or any other kinds of literals etc.) don't count (but their delimiters such as `/**/` or `""` do count).

The program should not perform any action. It just has to compile and do nothing when run.

If for some reason some of the symbols cannot be used in the language of your choice, explain that rigorously (what and why must be excluded).

**Update:** A few answers used symbols withing regular expressions. I'd consider this a bit problematic, it's the same thing as putting them into string literals or comments (that's why I put *etc.* in that requirement). Please try without this. I also updated the requirement above.

**Update:** Shortest code wins (tagged as *code-golf*). As suggested, we'll most likely need some tie-breaker criteria. I suggest that if there is a tie, the winning one is the one in which the ASCII symbols appear as much ordered as possible. Formally: Filter out the first occurrence of each of the listed symbols from a program. This will result in a permutation on the listed symbols. The program with less inversion number of its permutation wins.

**Update:** I'd be happy to see some/more solutions in regular/mainstream languages, such as C(++), Java, Scala, Haskell, etc.

# Answer
> 18 votes
## Brainf\*ck, 32 characters

```
!"#$%&'()*+.-/:;>=<?@[\]^_`{|}~,

```

Prints a smiley face (if your console can output ASCII symbol 1)

Yay, a Branf\*ck solution that beats Golfscript! :P

If you insist on no output, just exchange the `+` and `.` :

```
!"#$%&'()*.+-/:;>=<?@[\]^_`{|}~,

```

# Answer
> 50 votes
## Perl, 32 chars

no hiding symbols in comments, string literals, or regular expressions. uses all symbols precisely once.

```
$`<@"^[(\{_},)]/+-~%'?&|:!*.=>;#

```

### Description

i have tried to indicate operator precedence with indentation: the right-most expressions are evaluated before those to their left

```
        $`            # scalar variable $ named `
      <               # numeric less-than inequality <
        @"            # array variable @ named "
                      #   (array evaluated in scalar context)
    ^                 # bitwise XOR ^
        [(\{_},)]     # array reference []
                      #   containing array ()
                      #     containing reference \
                      #       to anonymous hash reference {}
                      #         with one key "_"
                      #           and no value (nothing following comma ,)
                      #             (reference evaluated in scalar context)
      /               # numeric division /
        +-~%'         # unary addition +
                      #   and unary negation -
                      #     and bitwise complement ~
                      #       on hash variable % named '
                      #         (hash evaluated in scalar context)
  ?                   # ternary conditional operator ?:
    &|                # code reference variable & named |
  :                   # ternary conditional operator ?:
    ! *.              # logical negation !
                      #   on typeglob variable * named .
                      #     (typeglob evaluated in scalar context)
  =>                  # fat comma => for compound expression
                      #   (evaluates LHS as string, RHS is empty)
;                     # end of expression ;
#                     # start of comment #

```

# Answer
> 10 votes
## Whitespace, 32

```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

```

all non whitespace characters are ignored, so this is actually an empty program

# Answer
> 8 votes
## Python 65

```
a=lambda x:0.
@a#
def _():{[`'"$?'`,]};a<a!=a+a%a&a^a-a*a|~a>a/a\

```

I used the characters `?` and `$` inside a string literal. These characters are not legal outside string literals or comments.

# Answer
> 8 votes
# PHP, 32 chars

Probably a bit of a troll, this PHP program is also a **QUINE**, and uses all symbols in the exact order they are listed.

```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

```

Executed from the command line, the output will simply be the contents of the file, as there is no `<?php` to invoke the interpretor.

```
$ cat > a.php
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

$ php a.php
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

```

# Answer
> 7 votes
# Perl 6 (43 chars)

Let's define a infix operator with a rather unusual name:

```
sub infix:<!"#$%&'()*+,-./:;=?@[]^_´\|~>{}

```

It's not a literal nor a literal in a RE or anything hidden in a comment. You don't believe me? Running the following program will output "2":

```
sub infix:<!"#$%&'()*+,-./:;=?@[]^_´\|~>($a, $b){ $a + $b }
say 1 !"#$%&'()*+,-./:;=?@[]^_´\|~ 1;

```

But I'm quite sure you nitpickers will extend the rules further to exclude redefinition of the language itself to make us perl lubbers unhappy. :(

# Answer
> 7 votes
## Haskell, 53

```
a@""#%&*+/?^b|a'<-a!!0=(\_->a`b`[]);main=do{print$1}

```

We can make this a bit shorter

## 45

```
a'@""#%&*+/?!<|^b=(\_->1`b`[]);main=do{main}

```

however this program doesn't terminate, and uses more characters (`'!'`,`'<'`,`'|'`) in the newly-defined infix.

# Answer
> 5 votes
# k (33 chars)

Very easy in k. Unfortunately `"` must be paired.

```
(@:'!""#$%&*+-\./;<=>?^_{}[`]|,~)

```

# Answer
> 5 votes
## J, 33 characters

```
''&][?!"$>{}:<;,|^~*/\%+`-@.#(=_)

```

`'` needs to be doubled to avoid syntax errors.

My first answer was missing some symbols.

# Answer
> 5 votes
## GolfScript (33 chars)

```
{!""$%&()*+,-./<=>?@[\]^_`|~};:'#

```

`"` has to be paired. It took a bit of trial and error to get it to output nothing - most other positions of the `:'` result in some output.

# Answer
> 5 votes
## C, 48 chars

Kind of cheating.

```
#define _ ~''*+,-./:<=>?[]`|\
@%^$&!
main(){"";}

```

# Answer
> 5 votes
# Postscript - 32 chars

```
{!"#$&'()*+,-./:;=<>?@[\]^_`|~}%

```

Results in an object on the stack, but otherwise has no effects. Postscript allows almost any char in an identifier except for `<>()[]{}/` which are special syntax forms and `%` which introduces a comment. The program is tokenized as

```
{                  % start a procedure object
!"#$&'             % an identifier
()                 % an empty string
*+,-.              % an identifier
/:;=               % a symbol
<>                 % an empty hex string
?@                 % an identifier
[\]                % an array
^_`~|              % an identifier
}                  % close the procedure object
%                  % a comment

```

# Answer
> 3 votes
## **C# (91 characters)**

```
#define a
class a{static int @Main(){return(char)1.1*""[0]/1%1-1+1!=1?1:~1^1>>1<<1&1+'\0';}}

```

As far as I know, The **$** character is not a valid character outside string literals, so I didn't use it in my answer.

**EDIT** : Thanks to Peter Taylor, I shortened the code.

# Answer
> 3 votes
## PowerShell (52 characters)

```
$_+=(@(1.1,1)[0]-1)*1/1%'1'::ToInt|&{!"">~\1}<#^#>`;

```

I had to put the **^** character as a string literal because as far as I know, the **^** character is not a legal PowerShell character outside string literals. Correct me if I am wrong.

The only way I have found to fit in the **:** character is to use the **:: operator** to make a call to a static method.

# Answer
> 3 votes
### Scheme, 41 characters

```
(define !$%&*+,-./:<=>?@[\]^_`{|}~ "#'");

```

This takes advantage of Scheme's incredible tolerance for characters in variable names. In this program I create a variable with the name !$%&\*+,-./:\<=\>?@\[\]^\_\`{|}~ which Scheme happily accepts.

# Answer
> 3 votes
# Tcl 37 chars

```
set {!#$%&'()*+,-./:<=>?@[]^\_`|~} ""

```

Defines a variable `!#$%&'()*+,-./:<=>?@[]^\_`|~` with an empty string

# Answer
> 3 votes
# C: 83 56 characters

```
#undef a
_;main($){$/=-+~!0|0^0%1,1<.0>0?'`':*&"@"[0];}\

```

At-signs and backticks are not a part of the allowed C-syntax, so I have put them between quotation marks.

# Answer
> 2 votes
### Common Lisp, 33 characters

```
#+()'|!"$%&*,-./:;<=>?@[\]^_`{}~|

```

The main part of the above evaluates (or rather, would evaluate if not for the `#+()` in front of it) to the symbol named:

```
!#$%&()*+,-./:;<=>?@[\]^_`{}~

```

The `#+()` is to avoid output. I'm not sure if the `|foo|` syntax for symbols counts as a literal, but symbols are used as variable/function names in Common Lisp, and there are a few answers already using the necessary characters in those.

# Answer
> 2 votes
**Smalltalk** (Squeak 4.x dialect) **38** chars

Implement this method in Object, the syntax is valid if Preferences *Allow underscore assignment* (which is the default setting)

```
%&*+/<=>?@\!~y""^Z_([:z|{#'',$`;-y}]).

```

declare Z as global var in pop-up menu if interactive

Explanations:

* %&\*+/\<=\>?@!~ is a binary selector (an operator)
* y is the parameter (the operand)
* "" is an empty comment
* ^ means return
* Z is a global variable
* _ is an assignment
* () delimits a sub-expression
* \[:z|\] delimits a block of code with one parameter z
* {} delimits an Array
* #'' is a Symbol literal made of an empty String (first element of the Array)
* , is a binary message sent to above Symbol
* $\` is a Character literal used as argument of above message
* ; is for chaining a second message sent to the same Symbol receiver #''
* the second message is -
* y is used as the second message argument
* . is for separating next instruction (here it's a final period)

Damn, who said Smalltalk was readable?

Note that I didn't cheat, the only non valid character \` is put into a literal Character. **EDIT** see below, this was a false assertion (at least in Squeak)

---

But we can make it down to **34** chars with this trick

```
%&*+,-/<=>?@\!~|y""^[{#(:_;`$')}].

```

This time:

* #() delimits a literal Array
* which contains 4 literal Symbols : _ ; \` and 1 literal Character $'

Strictly speaking, we can consider this as cheating... It's not a literal String, but it is still a non empty literal...

I still have to double comment quote "" (unless I make a literal Character with it $", but then I need to double the String quote '')
I still have to use a letter for the parameter (\_ is not accepted even if we set Preferences *allow underscore in selector* to true).

What is nice is that we can even run the method, for example send the message to 1 with argument 2:

```
1%&*+,-/<=>?@\!~|2

```

---

**EDIT** Finally in **35** chars without cheating

```
!%&*+,-/<=>?@`y""^[:x_|#()~$';\{}].

```

Notes:

* Preferences *allow underscore in selector* enable using a block parameter named x\_
* \` is a valid character for binary selector contrarily to what I said
* I also use $' to avoid doubling a quote

# Answer
> 2 votes
## R: 108 characters

```
a=new(setClass("a",representation(b="list")));a@b=list(c_d=1:2);if(1!='\t'&.1%*%1^1>a@b$c[1]/1|F){`~`<-`?`}#

```

Clearly the longest submission, but to be able to use symbols `@` and `$` in R, we need to create an object that has slots (indexed using `@`) and named elements (indexed using `$`).
The shortest solution I could think of was to create a new class of object (`a=new(setClass("a",representation(b="list")))`), which takes its toll. Otherwise, appart from the classics that don't need explanations (such as `!=`, `#` or `1:2`),

```
`~`<-`?`

```

creates a new operator that does the same as operator `?` (i. e. it calls the help page of the element it precedes).

`%*%` computes the inner product of two matrices (here of `1^1` and `.1`).
Symbol `_` does nothing (AFAIK) in R but is routinely used in variable or function names, as it is the case here.

# Answer
> 2 votes
## TI-Basic, 36

```
:End:#$%&'()*+.-/;>=<?@[\]^_`{|}~,!"

```

# Answer
> 2 votes
# Jelly, 32 bytes

```
!"#$%&')*+,-./:;<=>?@[\]^_`{|}~(

```

Try it online!

This technically outputs `0`, but given that the empty program does that as well, I didn't see an issue with that (especially as there is no way to "output nothing" in Jelly, aside from outputting the empty string. In this case, ~~34~~ 33 bytes (-1 byte thanks to xigoi)).

## How it works

Jelly works by splitting its program into "links", which are compositions of "chains", which are collections of "atoms" and "quicks". 31 of the 32 characters used above are either atoms or quicks (or syntax characters), `(` is the only non-implemented character. When Jelly encounters an unimplemented character outside of a string literal, it breaks the chain, essentially ignoring everything before it. So the `(` breaks the program's chain, ignoring all the previous (erroring) characters. At this point, the new chain is made up of the characters after the breaking character, which in this case, is the "empty" program.

For the 33 byte version, the last byte -  \- is the new chain, and is an empty list, which is then implicitly output at the end of the program as nothing

# Answer
> 2 votes
# Rust, 45 bytes

```
macro_rules!a{[r"`\"#%&'_*+-./:<?@^|~]=>{()}}

```

Try it online!

Creates a macro that matches when you call it with the tokens r"\`\\"#%&'\_*+-./:\<?@^|~ and returns the unit type. Do note that the backtick and backslash are inside of a string literal because that is the only valid place they can go. Also, apparently whatever stack exchange uses for syntax highlighting can't handle rust's raw strings.

# Answer
> 1 votes
# CJam, 34 bytes

```
""`'5~*:+{i[}%-/#~|<=!$\?@,^>()_];

```

Try it online!

Explanation:

```
""`                 Push an empty string and get the string representation of that ("\"\"")
'5~*                Push a 5 character, convert it to a number, and multiply the previous string 5 times. We spend a alphanumeric char here because there's no way to use ' without wasting a char, as ' will simply accept the next character as a character and cannot be otherwise used (except in a string/char literal)
:+                  Over our string, try to do some concatenation. This doesn't really do much.
{i[}%               Convert all the characters in out string to their codepoints (34s for "). We now have a bunch of numbers on the stack. This is really nice, because CJam is strict with types but just about everything accepts numbers in some way. It's so nice that we spend a character on it.
-/#~|<=!$\?@,^>()_  Lots of meaningless operations. I just threw them in randomly and fiddled around with them so that everything would have enough operands, and we would be left with a small stack at the end
];                  Discard what we have left

```

---
Tags: code-golf, printable-ascii
---


title: Matrix in "slash" order

text:
# Question
Title: Matrix in "slash" order
Given two positive numbers `N >= 2` and `N <= 100` create a matrix which follows the following rules:

* First Number starts at position `[0,0]`
* Second Number starts at position `[0,1]`
* Third number goes below First Number (position `[1,0]`)
* Following numbers goes in "slash" direction
* Range of numbers used is `[1, N1 * N2]`. So, numbers goes from starting 1 to the result of the multiplication of both inputs.

**Input**

* Two numbers `N >= 2` and `N <= 100`. First number is the amount of rows, Second number the amount of columns.

**Output**

* Matrix. (Can be outputted as a multidimensional array or a string with line breaks)

**Example:**

Given numbers `3 and 5` output:

```
1   2   4   7   10
3   5   8   11  13
6   9   12  14  15

```

Given numbers `2 and 2`

```
1   2
3   4

```

Given Numbers `5 and 5`

```
1   2   4   7   11
3   5   8   12  16
6   9   13  17  20
10  14  18  21  23
15  19  22  24  25

```

The shortest code in bytes wins.

# Answer
# Jelly, ~~6~~ 5 bytes

```
pSÞỤs

```

Try it online!

### How it works

```
pSÞỤs  Main link. Left argument: n. Right argument: k

p      Take the Cartesian product of [1, ..., n] and [1, ..., k], yielding
       [[1, 1], [1, 2], ..., [n, k-1], [n, k]].
 SÞ    Sort the pairs by their sums.
       Note that index sums are constant on antidiagonals.
   Ụ   Grade up, sorting the indices of the sorted array of pairs by their values.
    s  Split the result into chunks of length k.

```
> 21 votes

# Answer
# Python 3, 91 bytes

```
def f(n,k):M=[(t//k+t%k,t)for t in range(n*k)];return zip(*k*[map([M,*sorted(M)].index,M)])

```

Try it online!
> 8 votes

# Answer
# , ~~101~~ ~~60~~ 54 bytes

```
function(M,N)matrix(rank(outer(1:M,1:N,"+"),,"l"),M,N)

```

Try it online!

*Thanks to @nwellnhof for the suggestion of `rank`*

Ports Dennis' Jelly answer.

Old answer, 101 bytes:

```
function(M,N)matrix(unsplit(lapply(split(1:(M*N),unlist(split(x,x))),rev),x<-outer(1:M,1:N,"+")),M,N)

```

Try it online!

`split` is doing most of the work here; possibly there's a golfier algorithm but this definitely works.

Explanation:

```
function(M,N){
x <- outer(1:M,1:N,"+")			# create matrix with distinct indices for the antidiagonals
idx <- split(x,x)			# split into factor groups
items <- split(1:(M*N),unlist(idx))	# now split 1:(M*N) into factor groups using the groupings from idx
items <- lapply(items,rev)		# except that the factor groups are
					# $`2`:1, $`3`:2,3, (etc.) but we need
                                        # $`2`:1, $`3`:3,2, so we reverse each sublist
matrix(unsplit(items,x),M,N)		# now unsplit to rearrange the vector to the right order
					# and construct a matrix, returning the value
}

```

Try it online! -- you can use wrap a `print` around any of the right-hand sides of the assignments `<-` to see the intermediate results without changing the final outcome, as `print` returns its input.
> 7 votes

# Answer
# Java 10, ~~121~~ ~~120~~ ~~109~~ 105 bytes

```
m->n->{var R=new int[m][n];for(int i=0,j,v=0;i<m+n;)for(j=++i<n?0:i-n;j<i&j<m;)R[j][i-++j]=++v;return R;}

```

-11 bytes thanks to *@OlivierGrégoire*.
-4 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
m->n->{                // Method with two integer parameters and integer-matrix return-type
  var R=new int[m][n]; //  Result-matrix of size `m` by `n`
  for(int i=0,j,       //  Index integers, starting at 0
          v=0;         //  Count integer, starting at 0
      i<m+n;)          //  Loop as long as `i` is smaller than `m+n`
    for(j=++i<n?0      //   Set `j` to 0 if `i+1` is smaller than `n`
               :i-n;   //   or to the difference between `i` and `n` otherwise
        j<i&j<m;)      //   Inner loop `j` until it's equal to either `i` or `m`,
                       //   so basically check if it's still within bounds:
      R[j][i-++j]=++v; //    Add the current number to cell `j, i-(j+1)`
  return R;}           //  Return the result-matrix

```
> 6 votes

# Answer
# , 15 bytes

```
$1(+/:@;)</.@i.

```

-4 more bytes for this solution by miles. Thanks!

Try it online!

# , 22 19 bytes

-3 bytes thanks to FrownyFrog!

```
,$[:>:@/:@/:@,+/&i.

```

Try it online!

An implementation of Dennis' fantastic Jelly solution in J.

## Explanation:

Dyadic verb, takes left and right argument (m f n)

`+/&i.` creates lists 0..m-1 and 0..n-1 and makes an addition table for them:

```
   3 +/&i. 5
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6

```

`[:>:@/:@/:@,` flattens the table and grades the list twice and adds 1 to it:

```
   3 ([:>:@/:@/:@,+/&i.) 5
1 2 4 7 10 3 5 8 11 13 6 9 12 14 15

```

`,$` reshapes the list back into mxn table:

```
   3 (-@],\[:>:@/:@/:@,+/&i.) 5
1 2  4  7 10
3 5  8 11 13
6 9 12 14 15

```
> 5 votes

# Answer
# APL+WIN, 38 or 22 bytes

Prompts for integer input column then row:

```
m[⍋+⌿1+(r,c)⊤m-1]←m←⍳(c←⎕)×r←⎕⋄(r,c)⍴m

```

or:

```
(r,c)⍴⍋⍋,(⍳r←⎕)∘.+⍳c←⎕

```

based on Dennis's double application of grade up. Missed that :(
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~14~~ 12 bytes

```
{⍵⍴⍋⍋∊+/↑⍳⍵}

```

Try it online!

-2 thanks to ngn, due to his clever usage of `↑⍳`.

Based off of Dennis's 5-byte Jelly solution.
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~73~~ 67 bytes

Count elements in rows above: `Min[j+k,#2]~Sum~{k,i-1}`

Count elements on the current row and below: `Max[j-k+i-1,0]~Sum~{k,i,#}`

Put into a table and add 1. Voila:

```
1+Table[Min[j+k,#2]~Sum~{k,i-1}+Max[j-k+i-1,0]~Sum~{k,i,#},{i,#},{j,#2}]&

```

Update: I realized there is a shorter way to count all the positions ahead of a normally specified position in the matrix with just one sum over two dimensions:

```
Table[1+Sum[Boole[s-i<j-t||s-i==j-t<0],{s,#},{t,#2}],{i,#},{j,#2}]&

```

Try it online!

Try it online!
> 4 votes

# Answer
# 05AB1E, 23 bytes

```
*L<DΣ¹LILâOsè}UΣXsè}Á>ô

```

Try it online!
> 3 votes

# Answer
# Python 3, 164 bytes

```
from numpy import*
r=range
def h(x,y):
 a,i,k,j=-array([i//y+i%y for i in r(x*y)]),1,2,0
 while j<x+y:a[a==-j],i,k,j=r(i,k),k,k+sum(a==~j),j+1
 a.shape=x,y;return a

```

Try it online!

This is definitely not the shortest solution, but I thought it was a fun one.
> 2 votes

# Answer
# TI-Basic, 76 bytes

```
Prompt A,B
{A,Bdim([A]
1X
For(E,1,B+A
For(D,1,E
If D≤A and E-D<B
Then
X[A](D,E-D+1
X+1X
End
End
End
[A]

```

Prompts for user input and returns the matrix in `Ans` and prints it.

TI-Basic is a tokenized language; all tokens used here are one byte, other than `[A]` which is 2 bytes.

Note: TI-Basic (at least on the TI-84 Plus CE) only supports matrices up to 99x99, and so does this program.

Explanation:

```
Prompt A,B        # 5 bytes, prompt for user input
{A,Bdim([A]      # 9 bytes, make the matrix the right size
1X               # 4 bytes, counter variable starts at 1
For(E,1,B+A       # 9 bytes, Diagonal counter, 1 to A+B-1, but we can over-estimate since we have to check later anyway.
For(D,1,E         # 7 bytes, Row counter, 1 to diagonal count
If D≤A and E-D<B  # 10 bytes, Check if we are currently on a valid point in the matrix
Then              # 2 bytes, If so,
X[A](D,E-D+1     # 13 bytes, Store the current number in the current point in the matrix
X+1X             # 6 bytes, Increment counter
End               # 2 bytes, End dimension check if statement
End               # 2 bytes, End row for loop
End               # 2 bytes, End dimension for loop
[A]               # 2 bytes, Implicitly return the matrix in Ans and print it

```
> 2 votes

# Answer
# Python 2, 93 bytes

```
def f(b,a):i=1;o=[];exec"if b:o+=[],;b-=1\nfor l in o:k=len(l)<a;l+=[i]*k;i+=k\n"*a*b;print o

```

Try it online!

Semi-Ungolfed version:

```
def f(b,a):
    i=1
    o=[]
    for _ in range(a*b)
        if b:
            o+=[[]]
            b-=1

        for l in o:
            if len(l)<a:
                l+=[i]
                i+=1
    print o

```
> 2 votes

# Answer
# Japt, ~~25~~ 24 bytes

Hardly elegant, but gets the job done. Working with 2D data in Japt is tricky.

```
;N×Ç<U©Ap[] A®Ê<V©Zp°T
A

;                      // Set alternative default vars where A is an empty array.
 N×Ç                   // Multiply the inputs and map the range [0..U*V).
    <U                 // If the current item is less than the second input,
      ©Ap[]            // add a new empty subarray into A.
            A®         // Then, for each item in A,
              Ê<V      // if its length is less than the first input,
                 ©Zp°T // Add the next number in the sequence to it.
A                      // Output the results, stored in A.

```

I added the `-Q` flag in TIO for easier visualization of the results, it doesn't affect the solution.
Bit off one byte thanks to Oliver.

Try it online!
> 2 votes

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

```
(a,b,e=[...Array(b)].map(_=>[]))=>f=(x=0,y=i=0)=>(x<a&y<b&&(e[y][x]=++i),x?f(--x,++y):y>a+b?e:f(++y,0))

```

Try it online!
> 2 votes

# Answer
# Perl 6, ~~61~~ 59 bytes

```
{($!={sort($_ Z=>1..*)>>.{*}})($!([X+] ^<<$_)).rotor(.[1])}

```

Try it online!

Another port of Dennis' Jelly solution.
> 2 votes

# Answer
# Java (JDK 10), ~~142~~ 131 bytes

```
X->Y->{var A=new int[X][Y];int E=1;for(int y=0;y<Y+X-1;y++)for(int x=0;x<X;x++){if(y-x<0|y-x>Y-1)continue;A[x][y-x]=E++;}return A;}

```

Try it online!

**Explanation:**

```
X->Y->{                            // Method with two integer parameters and integer-matrix return-type
    var A=new int[X][Y];           // The Matrix with the size of X and Y
    int E=1;                       // It's a counter
        for(int y=0;y<Y+X-1;y++)   // For each column plus the number of rows minus one so it will run as long as the bottom right corner will be reached
            for(int x=0;x<X;x++){  // For each row
                if(y-x<0|y-x>Y-1)  // If the cell does not exist becouse it's out of range
                    continue;      // Skip this loop cycle
                A[x][y-x]=E++;     // Set the cell to the counter plus 1
            }
    return A;                      // Return the filled Array
}

```

*Big thank to Kevin Cruijssen because I didn't know how to run my code on tio.<br>Some code like the header and footer are stolen from him. -\> His answer*
> 2 votes

# Answer
# Husk, 9 bytes

```
ṠCoηÖ¤×,ḣ

```

Try it online! Most of the heavy lifting is done by `×`, which creates pairs in the desired order so that it can support infinite lists.

### Explanation

```
CηÖ×,ḣ²ḣ⁰⁰  (Expanded; let N and K denote the arguments.)
 ηÖ          Take the list of indices of the sorted values of
   ×,         the list of all pairs taken from
     ḣ²        the range from 1 to N and
       ḣ⁰      the range from 1 to K, and
C        ⁰  cut it into lengths of K.

```
> 2 votes

# Answer
# PHP, 115 bytes

a pretty lazy approach; probably not the shortest possible.

```
function($w,$h){for(;$i++<$h*$w;$r[+$y][+$x]=$i,$x--&&++$y<$h||$x=++$d+$y=0)while($x>=$w|$y<0)$y+=!!$x--;return$r;}

```

anonymous function, takes width and height as parameters, returns 2d matrix

try it online
> 1 votes

# Answer
# JavaScript (Node.js), 108 105 101 100 bytes

```
n=>(l=>{for(r=[];i<n*n;n*~-n/2+2>i?l++:l--*y++)for(T=y,t=l;t--;)r[T]=[...r[T++]||[],++i]})(y=i=0)||r

```

Try it online!
> 1 votes

# Answer
# Attache, 45 bytes

```
{Chop[Grade//2<|Flat!Table[`+,1:_2,1:_],_]+1}

```

Try it online!

Anonymous lambda, where paramaters are switched. This can be fixed for +1 byte, by prepending `~` to the program. The test suite does this already.

## Explanation

This approach is similar to the J answer and the Jelly answer.

The first idea is to generate a table of values:

```
Table[`+,1:_2,1:_]

```

This generates an addition table using ranges of both input parameters. For input `[5, 3]`, this gives:

```
A> Table[`+,1:3,1:5]
 2 3 4 5 6
 3 4 5 6 7
 4 5 6 7 8

```

Then, we flatten this with `Flat!`:

```
A> Flat!Table[`+,1:3,1:5]
[2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]

```

Using the approach in the J answer, we can grade the array (that is, return indices of sorted values) twice, with `Grade//2`:

```
A> Grade//2<|Flat!Table[`+,1:3,1:5]
[0, 1, 3, 6, 9, 2, 4, 7, 10, 12, 5, 8, 11, 13, 14]

```

Then, we need to chop the values up correctly, as in the Jelly answer. We can cut every `_` elements to do this:

```
A> Chop[Grade//2<|Flat!Table[`+,1:3,1:5],5]
 0 1  3  6  9
 2 4  7 10 12
 5 8 11 13 14

```

Then, we just need to compensate for the 0-indexing of Attache with `+1`:

```
A> Chop[Grade//2<|Flat!Table[`+,1:3,1:5],5]+1
 1 2  4  7 10
 3 5  8 11 13
 6 9 12 14 15

```

And thus we have the result.
> 1 votes

# Answer
# Python 3, 259 bytes

So I did this a weird way. I noticed that there were two patterns in the way the array forms.

**The first** is how the top rows pattern has the difference between each term increasing from 1 -\> h where h is the height and l is the length. So I construct the top row based on that pattern

For a matrix of dim(3,4) giving a `max RoC = 3` We will see the top row of the form

```
1, (1+1), (2+2), (4+3) = 1, 2, 4, 7

```

Suppose instead that the dim(3,9) giving a `max RoC = 3` we will instead see a top row of

```
`1, (1+1), (2+2), (4+3), (7+3), (10+3), (13+3), (16+3), (19+3) = 1, 2, 4, 7, 10, 13, 16, 19, 22

```

**The second** pattern is how the rows change from one another. If we consider the matrix:

```
1   2   4   7   11
3   5   8   12  16
6   9   13  17  20
10  14  18  21  23
15  19  22  24  25

```

and subtract each row from the row below (ignoring the extra row) we get

```
2 3 4 5 5
3 4 5 5 4
4 5 5 4 3
5 5 4 3 2

```

Upon seeing this matrix we can notice this matrix is the sequence `2 3 4 5 5 4 3 2` where by each row is 5 terms of this pattern shifted by 1 for each row. See below for visual.

```
         |2 3 4 5 5| 4 3 2
       2 |3 4 5 5 4| 3 2
     2 3 |4 5 5 4 3| 2
   2 3 4 |5 5 4 3 2|

```

So to get the final matrix we take our first row we created and output that row added with the 5 needed terms of this pattern.

This pattern will always have the characteristics of beginning `2-> max value` and ending `max value -> 2` where the `max value = min(h+1, l)` and the number of times that the max value will appear is `appearances of max = h + l -2*c -2` where `c = min(h+1, l) - 2`

So in whole my method of creating new rows looks like

```
1  2  3  7  11 +      |2 3 4 5 5|4 3 2  = 3  5  8  12 16

3  5  8  12 16 +     2|3 4 5 5 4|3 4 2  = 6  9  13 17 20

6  9  13 17 20 +   2 3|4 5 5 4 3|4 2    = 10 14 18 21 23

10 14 18 21 23 + 2 3 4|5 5 4 3 2|       = 15 19 22 24 25

```

Relevant code below. It didn't end up being short but I still like the method.

```
o,r=len,range
def m(l,h):
 a,t=[1+sum(([0]+[x for x in r(1,h)]+[h]*(l-h))[:x+1]) for x in r(l)],min(l,h+1);s,c=[x for x in r(2,t)],[a[:]]
 for i in r(h-1):
  for j in r(o(a)):
   a[j]+=(s+[t]*(l+h-2*(t-2)-2)+s[::-1])[0+i:l+i][j]
  c+=[a[:]]
 for l in c:print(l)

```

Try it online!
> 1 votes

# Answer
# Japt, 20 bytes

```
õ ïVõ)ñx
£bYgUñ¹ÄÃòV

```

Try it
> 0 votes

# Answer
# Haskell, 92 bytes

```
r=[1..]
(#)=take
n!k=[[sum$lookup(i,j)$zip[(i,j)|s<-r,i<-n#r,j<-k#r,i+j==s]r|j<-k#r]|i<-n#r]

```

Try it online!
> 0 votes

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