# Question
Title: Reverse two sections of a string around a pivot
# Background

I am currently in an AP Comp Sci A: Java class, and I want to start some of my friends on code golfing. I have a challenge from the course, and I would like to see how many bytes the community can do this challenge in.

# Challenge details:

Given two input strings, the main string and the pivot string, do the following:

If the pivot string is exactly once as a substring of the main string, the part of the main string that comes before the pivot string shall be swapped with the part that comes after, while *preserving the order within said subtrings being swapped*.

For example:

If the pivot string is empty or the pivot string is *not* found within the main string, the program does not have to have defined behavior.

If there is more than one instance of the pivot string, the split should occur at the first and *only* the first instance of the pivot.

Examples: Given the main string `OneTwoThreeTwoOne` and the pivot string `Two`, the output should be `ThreeTwoOneTwoOne`.

Given the main string `1Two2Two3Two4` and pivot `Two`, the output should be `2Two3Two4Two1`.

Given the main string `OneTwoThree` and the pivot string "Two", the output should be `ThreeTwoOne`. Given the main string `the rabbit is faster than the turtle` and the pivot string

```
 is faster than

```

(note the single space trailing and preceding), the output should be `the turtle is faster than the rabbit`.

Given the main string `1-2-3-4-5-6` and the pivot `-`, the output should be `2-3-4-5-6-1`.

## Afterword:

This is my first ever question on code golf, so if you have suggestions or constructive criticism, then feel free to say so.

Additionally, my code for this project (written in Java because the course focuses on that) can be found below. If you have any tips, I'd love to see them. Its currently 363 bytes, but I bet you guys can come up with much better and smaller solutions.

```
import java.util.Scanner;interface Main{static<T>void D(T f){System.out.println(f);}static void main(String[]A){Scanner s=new Scanner(System.in);D("Enter the first String:");String a=s.nextLine();D("Enter the pivot String:");String p=s.nextLine();if(p.isEmpty()|!a.contains(p)){D("Error: Pivot String not found.");return;}String w[]=a.split(p,2);D(w[1]+p+w[0]);}}

```

Note: The text for the inputs and for the case that the pivot string is not found is mandatory for the original assignment, but not for this challenge.

# Answer
# Mathematica, 42 bytes

```
Reverse@StringSplit[##,2]~StringRiffle~#2&

```

Try it online!
> 7 votes

# Answer
# Jelly, 6 bytes

```
œṣṙ1j⁴

```

Try it online!

# Explanation

```
œṣṙ1j⁴  Main Link
œṣ      Split around sublists equal to the pivot
  ṙ1    Rotate left by one
    j⁴  Rejoin on the pivot

```
> 6 votes

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

```
lambda a,b:b.join(a.split(b,1)[::-1])

```

Where `a` is the main string and `b` is the pivot string.

Try it online!
> 6 votes

# Answer
## Wolfram Language (Mathematica), 34 bytes

```
p#2<>p<>#&@@StringSplit[#,p,2]&

```

Try it online!

An unnamed, curried function which should be called with the pivot first and the main string second. E.g., if you assigned the function to a name `f`:

```
f["-"]["1-2-3-4-5-6"]

```
> 6 votes

# Answer
# Ohm v2, 4 bytes

```
ïλ⁴j

```

Try it online!
> 5 votes

# Answer
# SOGL V0.12, ~~9~~ 5 bytes

```
ΘK+,∑

```

Try it Here!

Explanation:

```
Θ      split the 2nd input on the 1st one
 K     get the 1st element
  +    and add it to the end
   ,∑  join on the 1st input

```
> 4 votes

# Answer
# Perl 5, 20 + 2 (`-pl`) = 22 bytes

```
<>=~/$_/;$_="$'$_$`"

```

Try it online!

Takes the pivot string on the first line, then the full string on the second.
> 4 votes

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

thanks to ThePlasmaRailgun for some bytes

```
p,m=input()
k=m.split(p,1)
print k[1]+p+k[0]

```

Try it online!
> 4 votes

# Answer
# Python 2, 37 bytes

```
lambda a,b:b.join(a.split(b,1)[::-1])

```

Try it online!
> 4 votes

# Answer
# C# (Visual C# Compiler), 56 bytes

```
(m,p)=>(m+p+m).Substring(m.IndexOf(p)+p.Length,m.Length)

```

Try it online!
> 4 votes

# Answer
## Alice, 18 bytes

```
/?.?.Qz
\IoI%!oo@/

```

Try it online!

### Explanation

```
/...
\...@/

```

This is just a framework for linear Ordinal mode (string-processing) code. Unfolding the zigzag control flow, we get:

```
I.I.!zo?o?%Qo

I.  Read the first string, duplicate it.
I   Read the second string (the pivot).
.!  Store a copy of the pivot on the tape.
z   Drop. Removes everything up to and including the pivot from the first string,
    so we get only the stuff after the pivot.
o   Output that.
?o  Retrieve the pivot from the tape and output it.
?%  Retrieve the pivot again and split the input around (all occurrences of)
    the pivot.
Q   Reverse the stack.
o   Output the top of the stack (i.e. the chunk in front of the first pivot).

```
> 4 votes

# Answer
# Retina, ~~24~~ 23 bytes

tanks to Martin Ender for -1 byte

```
(.*)¶(.*?)\1(.*)
$3$1$2

```

Try it online!
> 3 votes

# Answer
# , ~~63~~ ~~58~~ 57 bytes

```
function(M,P)sub(sub("_",P,"(.+?)(_)(.+)"),"\\3\\2\\1",M)

```

Try it online!

`M` is the main string, `P` is the pivot.

ovs' Retina answer indicated that I could repair my earlier attempt at a regex approach

```
(.+)(Pivot string)(.+)

```

by adding `?` to the first capture group.
> 2 votes

# Answer
# Python 2, 48 bytes

```
lambda s,p:p.join(s.split(p)[1:]+s.split(p)[:1])

```

Try it online!
> 2 votes

# Answer
# Pyth, 8 bytes

```
jQ.<cEQ1

```

**Try it here!**

### Explanation

```
jQ.<cEQ1 - Full program.

    cEQ  - Split the second input by the first input.
  .<   1 - Cyclically rotate by 1 place to the left.
jQ       - Join on the first input.

```
> 2 votes

# Answer
# Java 8, 47 bytes

```
x->y->x.replaceAll("(.*?)("+y+")(.*)","$3$2$1")

```

Try it online
> 2 votes

# Answer
# Charcoal, 13 bytes

```
≔⪪θηθ⪫Ｅθ§θ⊕κη

```

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

```
  θ             First input
   η            Second input
 ⪪              Split
≔   θ           Assign result
      Ｅθ        Map over result
           κ    Current index
          ⊕     Incremented
        §θ      Circularly index into result
     ⪫      η   Join
                Implicitly print

```
> 2 votes

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

```
(s,p,[a,...r]=s.split(p))=>r.join(p)+p+a

```

### Test cases

```
let f =

(s,p,[a,...r]=s.split(p))=>r.join(p)+p+a

console.log(f('the rabbit is faster than the turtle', ' is faster than '))
console.log(f('1-2-3-4-5-6', '-'))
```
> 2 votes

# Answer
# C,  ~~106~~  100 bytes

```
i,l;f(s,p)char*s,*p;{l=strlen(p);for(i=0;strncmp(s+i,p,l);++i);printf("%s%s",s+i+l,p);write(1,s,i);}

```

Try it online!
> 2 votes

# Answer
# , 14 bytes

```
#@[}.{.@ss|.,~

```

# How it works:

The left argument is the pivot, the right one - the string to be reversed

```
            ,~   appends the pivot to the string
     {.@ss       finds the positions of the pivot in the string and takes the first one
          |.     rotates the appended string to the left, so that the pivot is at the start
#@[              finds the length of the pivot string (n)
   }.            drops n characters from the begining of the rotated string

```

Try it online!
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), 53 bytes

```
	P =INPUT
	INPUT ARB . R P REM . L
	OUTPUT =L P R
END

```

Try it online!

Takes input as Pivot, then Main, separated by a newline.

This is basically the SNOBOL equivalent of my R answer.
> 2 votes

# Answer
# Japt, ~~8~~ 7 bytes

```
£Zg°Y}V

```

Try it here
> 0 votes

# Answer
# Perl 6, 31 bytes

```
->$_,$b {S/(.*?)$b(.*)/$1$b$0/}

```

Test it
> 0 votes

# Answer
# PHP, 62 bytes

```
<?=![,$s,$p]=$argv,preg_filter("(^(.*)$p(.*)$)U","$2$p$1",$s);

```

requires PHP 7.1; may fail if the pivot contains regex special chars (`\+*?[^]$(){}=!<>|:-`).
no changes if Pivot is empty, empty output if Pivot is not in input.
Run with `-n`.

**safe version, 77 bytes:**

```
<?=preg_filter("(^(.*)".preg_quote($p=$argv[1])."(.*)$)U","$2$p$1",$argv[2]);

```

no changes if Pivot is empty, empty output if Pivot is not in input.
Run with `-n`.

**non-regex version, 71 bytes:**

```
$a=explode($p=$argv[2],$argv[1]);$a[]=array_shift($a);echo join($p,$a);

```

yields warnings if the Pivot is empty; no change if Pivot is not in input.

Run with `-nr`.

Try them online.
> 0 votes

# Answer
# Red, 63 bytes

```
f: func[p s][rejoin[copy find/tail s p p copy/part s find s p]]

```

Try it online!
> 0 votes

# Answer
# Swift, 131 bytes

```
import Foundation
func f(s:String,d:String){var c=s.components(separatedBy:d);print((c+[c[0]]).suffix(from:1).joined(separator:d))}

```

## Explanation (ungolfed)

```
import Foundation                     // Import String.components
func f(s:String,d:String){
    var c=s.components(separatedBy:d) // Split the input string by the separator
    print((c+[c[0]])                  // Add the last element of c ([A,B,C] -> [A,B,C,A])
        .suffix(from:1)               // Remove the first element  ([A,B,C,A] -> [B,C,A])
        .joined(separator:d))         // Join with the separator
}

```
> 0 votes

# Answer
# C (gcc), 76 bytes

```
f(s,t)char*s,*t;{char*p=strstr(s,t);printf("%s%s%.*s",p+strlen(t),t,p-s,s);}

```

Try it online!
> 0 votes

# Answer
**C++11, 64 bytes**

```
[s,p,&a]{int f=s.find(p);a=s.substr(f+p.size())+p+s.substr(0,f);}

```

A lambda, which captures the strings s, p and a, with a as a reference (in-out).

Test code

```
#include <iostream>
#include <string>

std::string Test(std::string s, std::string p) {
    std::string a;
[s,p,&a]{int f=s.find(p);a=s.substr(f+p.size())+p+s.substr(0,f);}();
    return a;
}

int main() {
    std::string
        s = "OneTwoThreeTwoOne",
        p = "Two",
        r = "ThreeTwoOneTwoOne";
    auto a = Test(s,p);
    std::cout << ((a==r)?"OK":"Failed") << ": " << a << std::endl;

    return 0;
}

```
> 0 votes

# Answer
# Clean, 83 bytes

```
import StdEnv;f s c=(\p=p takeWhile++[hd s,c:p dropWhile])\g=reverse(tl(g((<>)c)s))

```

A `String` in Clean is normally `{#Char}` \- an unboxed (`#`) `Char` array (`{}`). This function takes `[Char]` instead of `String`, which is a second, valid version of `String`.

The full function signature is `f :: [.t] .t -> [.t] | [.t <= Char]`.

Try it online!
> 0 votes

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


title: Binary Sequences

text:
# Question
Title: Binary Sequences
Given a binary number A as input with d \> 1 digits, output a binary number B with d digits according to the following rules for finding the nth digit of B:

* The first digit of B is zero if the first and second digits of A are equal; otherwise, it is one.
* If 1 \< n \< d, then if the (n-1)th, nth and (n+1)th digits of A are equal, then the nth digit of B is zero; otherwise, it is one.
* The dth digit of B is zero if the (d-1)th and dth digits of A are equal; otherwise, it is one.

## Rules

String/list input/output format is fine. Another allowed way of input/output is an integer followed by the number of preceding zeros (or following the number of preceding zeros).

Make your code as short as possible.

## Test Cases

```
00 -> 00
01 -> 11
11 -> 00
010111100111 -> 111100111100
1000 -> 1100
11111111 -> 00000000
01010101 -> 11111111
1100 -> 0110

```

# Answer
# Jelly, 9 bytes

```
.ịṚjṡ3E€¬

```

Try it online!

I/O as list of digits.

Explanation:

```
.ịṚjṡ3E€¬
.ịṚ       Get first and last element
   j      Join the pair with the input list, thus making a list [first, first, second, ..., last, last]
    ṡ3    Take sublists of length 3
      E€  Check if each has all its elements equal
        ¬ Logical NOT each

```
> 7 votes

# Answer
## Haskell, ~~59~~ ~~58~~ 54 bytes

```
f s=[1-0^(a-b+a-c)^2|a:b:c:_<-scanr(:)[last s]$s!!0:s]

```

Try it online!

```
f s=                        -- input is a list of 0 and 1
          s!!0:s            -- prepend the first and append the last number of s to s
      scanr(:)[last s]      --   make a list of all inits of this list
     a:b:c:_<-              -- and keep those with at least 3 elements, called a, b and c
    1-0^(a-b+a-c)^2         -- some math to get 0 if they are equal or 1 otherwise

```

Edit: @Ørjan Johansen saved 4 bytes. Thanks!
> 7 votes

# Answer
# 05AB1E, 6 bytes

```
¥0.ø¥Ā

```

I/O is in form of bit arrays.

Try it online!

### How it works

```
¥       Compute the forward differences of the input, yielding -1, 0, or 1 for each
        pair. Note that there cannot be two consecutive 1's or -1's.
 0.ø    Surround the resulting array with 0‘s.
    ¥   Take the forward differences again. [0, 0] (three consecutive equal
        elements in the input) gets mapped to 0, all other pairs get mapped to a
        non-zero value.
     Ā  Map non-zero values to 1.

```
> 6 votes

# Answer
# 05AB1E, 11 bytes

```
¬s¤)˜Œ3ù€Ë_

```

Try it online! or as a Test suite

**Explanation**

```
¬             # get head of input
 s            # move it to the bottom of the stack
  ¤           # get the tail of the input
   )˜         # wrap in list ([head,input,tail])
     Œ3ù      # get sublists of length 3
        €Ë    # check each sublists for equality within the list
          _   # logical negation

```
> 5 votes

# Answer
# Haskell, ~~66~~ ~~61~~ 59 bytes

```
g t@(x:s)=map("0110"!!)$z(x:t)$z t$s++[last s]
z=zipWith(+)

```

Try it online! Input is a list of zeros and ones, output is a string. Usage example: `g [0,1,0,1,1,1,1,0,0,1,1,1]` yields `"111100111100"`.

---

### Previous 61 byte solution:

```
g s=["0110"!!(a+b+c)|(a,b,c)<-zip3(s!!0:s)s$tail s++[last s]]

```

Try it online!
> 5 votes

# Answer
# , ~~26~~ 14 bytes

Credit to Emigna's 05AB1E solution

```
2=3#@=\{.,],{:

```

Try it online!

### Original attempt

```
2|2#@="1@|:@,,.@i:@1|.!.2]

```

Try it online!

```
             ,.@i:@1              -1, 0, 1
                    |.!.2]         shift filling with 2
  2         ,                      add a row of 2s on top
         |:                        transpose
   #@="1                           count unique elements in each row
2|                                 modulo 2

```
> 4 votes

# Answer
# Husk, ~~15~~ 11 bytes

```
Ẋȯ¬EėSJ§e←→

```

Takes input as a list, try it online! Or try this one that uses strings for I/O.

### Explanation

```
Ẋ(¬Eė)SJ§e←→ -- implicit input, for example [1,0,0,0]
      SJ     -- join self with the following
        §e   --   listify the
                  first and
                  last element: [1,0]
             -- [1,1,0,0,0,0]
Ẋ(   )       -- with each triple (eg. 1 0 0) do the following:
    ė        --   listify: [1,1,0]
   E         --   are all equal: 0
  ¬          --   logical not: 1
             -- [1,1,0,0]

```
> 2 votes

# Answer
# Python 3, 58 bytes

```
lambda a:[len({*a[i and~-i:i+2]})-1for i in range(len(a))]

```

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

```
I0;;0In0

```

I/O is in form of bit arrays.

Try it online!

### How it works

```
I0;;0In0  Main link. Argument: A (bit array of length d)

I         Increments; compute the forward differences of all consecutive elements
          of A, yielding -1, 0, or 1 for each pair. Note that there cannot be
          two consecutive 1's or -1's.
 0;       Prepend a 0 to the differences.
   ;0     Append a 0 to the differences.
     I    Take the increments again. [0, 0] (three consecutive equal elements in A)
          gets mapped to 0, all other pairs get mapped to a non-zero value.
      n0  Perform not-equal comparison with 0, mapping non-zero values to 1.

```
> 2 votes

# Answer
# JavaScript (ES6), 45 bytes

Takes input as an array of characters. Returns an array of integers.

```
a=>a.map((v,i)=>(i&&v^p)|((p=v)^(a[i+1]||v)))

```

### Test cases

```
let f =

a=>a.map((v,i)=>(i&&v^p)|((p=v)^(a[i+1]||v)))

console.log(JSON.stringify(f([..."00"])))           // -> 00
console.log(JSON.stringify(f([..."01"])))           // -> 11
console.log(JSON.stringify(f([..."11"])))           // -> 00
console.log(JSON.stringify(f([..."010111100111"]))) // -> 111100111100
console.log(JSON.stringify(f([..."1000"])))         // -> 1100
console.log(JSON.stringify(f([..."11111111"])))     // -> 00000000
console.log(JSON.stringify(f([..."01010101"])))     // -> 11111111
console.log(JSON.stringify(f([..."1100"])))         // -> 0110
```

### Commented

```
a =>                  // given the input array a
  a.map((v, i) =>     // for each digit v at position i in a:
    (                 //   1st expression:
      i &&            //     if this is not the 1st digit:
           v ^ p      //       compute v XOR p (where p is the previous digit)
    ) | (             //   end of 1st expression; bitwise OR with the 2nd expression:
      (p = v) ^       //     update p and compute v XOR:
      (a[i + 1] ||    //       the next digit if it is defined
                   v) //       v otherwise (which has no effect, because v XOR v = 0)
    )                 //   end of 2nd expression
  )                   // end of map()

```
> 2 votes

# Answer
# Jelly, 16 bytes

```
ḣ2W;ṡ3$;ṫ-$W$E€¬

```

Try it online!

I was going to golf this but Erik has a shorter solution already and golfing mine would just bring mine closer to his. I'm still golfing but I won't update unless I can beat him or find a unique idea.

# Explanation

```
ḣ2W;ṡ3$;ṫ-$W$E€¬  Main Link
ḣ2                First 2 elements
  W               Wrapped into a list (depth 2)
   ;              Append
    ṡ3$           All overlapping blocks of 3 elements
       ;          Append
        ṫ-$W$     Last two elements wrapped into a list
             E€   Are they all equal? For each
               ¬  Vectorizing Logical NOT

```
> 1 votes

# Answer
# Mathematica, 56 bytes

```
Boole[!Equal@@#&/@Partition[ArrayPad[#,1,"Fixed"],3,1]]&

```

Try it online!
> 1 votes

# Answer
# Japt, ~~14~~ ~~13~~ 12 bytes

Partly ported from Dennis' Jelly solution. Input & output are arrays of digits.

```
ä- pT äaT mg

```

Saved a byte thanks to ETHproductions.

Try it

---

## Explanation

Implicit input of array `U`. `ä-` gets the deltas of the array. `pT` pushes 0 to the end of the array. `äaT` first adds another 0 to the start of the array before getting the absolute deltas. `mg` maps over the elements of the array returning the sign of each element as -1 for negative numbers, 0 for 0 or 1 for positive numbers.
> 1 votes

# Answer
# Perl 5, 62 + 1 (`-n`) = 63 bytes

```
s/^.|.$/$&$&/g;for$t(0..y///c-3){/.{$t}(...)/;print$1%111?1:0}

```

Try it online!
> 1 votes

# Answer
# Husk, 10 bytes

```
Ẋo±≠↔Θ↔ΘẊ-

```

Try it online!

Thanks to Zgarb for -1 byte.
> 1 votes

# Answer
# Python 3, 54 bytes

```
lambda x:[n^1in x[i-(i>0):i+2]for i,n in enumerate(x)]

```

I/O is in form of Boolean arrays.

Try it online!
> 1 votes

# Answer
# J, 32 Bytes

```
B=:2&(+./\)@({.,],{:)@(2&(~:/\))

```

### How it works:

```
B=:                              | Define the verb B
                       2&(~:/\)  | Put not-equals (~:) between adjacent elements of the array, making a new one
            ({.,],{:)            | Duplicate the first and last elements
   2&(+./\)                      | Put or (+.) between adjacent elements of the array

```

I left out some @s and parenthesis, which just make sure it goes together nicely.

A step by step example:

```
    2&(~:/\) 0 1 0 1 1 1 1 0 0 1 1 1
1 1 1 0 0 0 1 0 1 0 0

    ({.,],{:) 1 1 1 0 0 0 1 0 1 0 0
1 1 1 1 0 0 0 1 0 1 0 0 0

    2&(+./\) 1 1 1 1 0 0 0 1 0 1 0 0 0
1 1 1 1 0 0 1 1 1 1 0 0

    B 0 1 0 1 1 1 1 0 0 1 1 1
1 1 1 1 0 0 1 1 1 1 0 0

```
> 1 votes

# Answer
# Pyth, 15 bytes

```
mtl{d.:++hQQeQ3

```

**Try it here!**

Alternatively:

* `mtl{d.:s+hQeBQ3`.
* `.aM._M.+++Z.+QZ`.

This prepends the first element and appends the last element, then gets all overlapping substrings of length 3, and finally takes the number of distinct elements in each sublist and decrements it. This mess has been done on mobile at midnight so I wouldn’t be surprised if there are some easy golfs.
> 0 votes

# Answer
# Retina, 35 bytes

```
(.)((?<=(?!\1)..)|(?=(?!\1).))?
$#2

```

Try it online! Link includes test cases. Explanation: The regex starts by matching each input digit in turn. A capture group tries to match a different digit before or after the digit under consideration. The `?` suffix then allows the capture to match 0 or 1 times; `$#2` turns this into the output digit.
> 0 votes

# Answer
# Gaia, 9 bytes

```
ọ0+0¤+ọ‼¦

```

Try it online!

### Explanation

```
ọ0+0¤+ọ‼¦ ~ A program accepting one argument, a list of binary digits.

ọ         ~ Deltas.
 0+       ~ Append a 0.
   0      ~ Push a zero to the stack.
    ¤     ~ Swap the top two arguments on the stack.
     +    ~ Concatenate (the last three bytes basically prepend a 0).
      ọ   ~ Deltas.
        ¦ ~ And for each element N:
       ‼  ~ Yield 1 if N ≠ 0, else 0.

```

### Gaia, 9 bytes

```
ọ0¤;]_ọ‼¦

```

Try it online!
> 0 votes

# Answer
# , **309 bytes**

```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char** argv){int d=strlen(argv[1]);char b[d + 1];char a[d + 1];strcpy(a, argv[1]);b[d]='\0';b[0]=a[0]==a[1]?'0':'1';for(int i=1;i<d-1;i++){b[i]=a[i]==a[i+1]&&a[i]==a[i - 1]?'0':'1';}b[d-1]=a[d-1]==a[d-2]?'0':'1';printf("%s\n",b);}

```

Not exactly a language fit for golfing, but worth an answer none-the-less. Try it out here!

**Explanation**

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {
    /* Find the number of digits in number (taken in as a command line argument) */
    int d = strlen(argv[1]);

    /* d + 1 to account for d digits plus the null character */
    char b[d + 1];
    char a[d + 1];

    /* Saves having to type argv[1] every time we access it. */
    strcpy(a, argv[1]);

    /* Set the null character, so printf knows where our string ends. */
    b[d] = '\0';

    /* First condition */
    /* For those not familiar with ternary operators, this means b[0] is equal to '0' if a[0] equals a[1] and '1' if they aren't equal. */
    b[0] = a[0] == a[1] ? '0' : '1';

    /* Second condition */
    for(int i = 1; i < d - 1; i++) {
        b[i] = a[i] == a[i+1] && a[i] == a[i - 1] ? '0' : '1';
    }

    /* Third condition */
    b[d - 1] = a[d - 1] == a[d - 2] ? '0' : '1';

    /* Print the answer */
    printf("%s\n", b);
}

```
> 0 votes

# Answer
# APL+WIN, 29 bytes

```
(↑b),(×3|3+/v),¯1↑b←×2|2+/v←⎕

```

Prompts for screen input as a vector of digits and outputs a vector of digits.

Explanation

```
b←×2|2+/v signum of 2 mod sum of successive pairs of elements

×3|3+/v signum of 3 mod sum of successive triples of elements

(↑b),...., ¯1↑b concatenate first and last elements of b for end conditions

```
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 273 bytes

```
	I =INPUT
	D =SIZE(I)
N	P =P + 1
	EQ(P,1)	:S(S)
	EQ(P,D)	:S(E)
	I POS(P - 2) LEN(2) . L
	I POS(P - 1) LEN(2) . R
T	Y =IDENT(L,R) Y 0	:S(C)
	Y =Y 1
C	EQ(P,D) :S(O)F(N)
S	I LEN(1) . L
	I POS(1) LEN(1) . R :(T)
E	I RPOS(2) LEN(1) . L
	I RPOS(1) LEN(1) . R :(T)
O	OUTPUT =Y
END

```

Try it online!

```
	I =INPUT			;* read input
	D =SIZE(I)			;* get the string length
N	P =P + 1			;* iNcrement step; all variables initialize to 0/null string
	EQ(P,1)	:S(S)			;* if P == 1 goto S (for Start of string)
	EQ(P,D)	:S(E)			;* if P == D goto E (for End of string)
	I POS(P - 2) LEN(2) . L		;* otherwise get the first two characters starting at n-1
	I POS(P - 1) LEN(2) . R		;* and the first two starting at n
T	Y =IDENT(L,R) Y 0	:S(C)	;* Test if L and R are equal; if so, append 0 to Y and goto C
	Y =Y 1				;* otherwise, append 1
C	EQ(P,D) :S(O)F(N)		;* test if P==D, if so, goto O (for output), otherwise, goto N
S	I LEN(1) . L			;* if at start of string, L = first character
	I POS(1) LEN(1) . R :(T)	;* R = second character; goto T
E	I RPOS(2) LEN(1) . L		;* if at end of string, L = second to last character
	I RPOS(1) LEN(1) . R :(T)	;* R = last character; goto T
O	OUTPUT =Y			;* output
END

```
> 0 votes

# Answer
# C (tcc), ~~64~~ ~~62~~ 56 bytes

```
c,p;f(char*s){for(p=*s;c=*s;p=c)*s=p-c==c-(*++s?:c)^49;}

```

I/O is in form of strings. The function **f** modifies its argument **s** in place.

Try it online!
> 0 votes

# Answer
# Common Lisp, 134 bytes

```
(lambda(a &aux(x(car a))(y(cadr a)))`(,#1=(if(= x y)0 1),@(loop for(x y z)on a while y if z collect(if(= x y z)0 1)else collect #1#)))

```

Try it online!
> 0 votes

---
Tags: code-golf, binary
---


title: String Permutations - case and order

text:
# Question
Title: String Permutations - case and order
# Challenge

For any string that is composed of alphabetical characters of any case, make a function that returns a list of all of it's variations, order and case-wise empty strings returns empty list.

# Test Cases

```
"" -> []
"a" -> ['a', 'A']
"ab" -> ['ab', 'Ab', 'aB', 'AB', 'ba', 'Ba', 'bA', 'BA']
"abc" -> ['abc', 'Abc', 'aBc', 'ABc', 'abC', 'AbC', 'aBC', 'ABC', 'bac', 'baC', 'bAc', 'bAC', 'Bac', 'BaC', 'BAc', 'BAC', 'CBa', 'CBA', 'cba', 'cbA', 'cBa', 'cBA', 'Cba', 'CbA', 'caB', 'cAb', 'cAB', 'cab', 'CaB', 'CAb', 'CAB', 'Cab', 'Acb', 'AcB', 'acb', 'acB', 'aCb', 'aCB', 'ACb', 'ACB', 'Bca', 'BcA', 'bca', 'bcA', 'bCa', 'bCA', 'BCa', 'BCA']
'aa' -> ['aa', 'Aa', 'aA', 'AA']  (for duplicate letters extra, duplicate permutations are allowed if necessary)
```

As the permutations rack up quickly **you only need to handle up to 4 ASCII letter chars.**

This is , so the shortest code in bytes wins!

# Answer
> 3 votes
# Python 2, 89 bytes

```
lambda s:map(list,map(permutations,product(*zip(s.swapcase(),s))))
from itertools import*

```

Try it online!

Doesn't work in Python 3. Swap case idea from HyperNeutrino.

# Answer
> 2 votes
# Jelly, 9 bytes

```
żŒsp/Œ!€Ẏ

```

Try it online!

# Explanation

```
żŒsp/Œ!€Ẏ  Main Link
ż          zip each character with
 Œs        its case swapped
   p/      reduce over cartesian product
       €   for each sublist
     Œ!    find all permutations
        Ẏ  flatten by one layer

```

# Answer
> 1 votes
# Jelly, 11 bytes

```
Œu,ŒlZŒpŒ!€

```

Try it online!

**16** **bytes** if we need formatting and no repeated permutations.

```
Œu,ŒlZŒpŒ!€;/QŒṘ

```

Try it online!

This is assuming (a) we need delimiters between the permutations (achieved by `ŒṘ` at the end) and (b) the input `'aa'`--\>`['AA','Aa','aA','aa']` and doesn't count the two 'a's as unique, which would give the same answer but each permutation would appear twice.

**Explanation**

```
Œu,ŒlZŒpŒ!€;/QŒṘ   Main link
Œu                 Upper case. 'aB'->'AB'
   Œl              Lower case. 'aB'->'ab'
  ,                Pair dyad. -> [['A','B'],['a','b']]
     Z             Zip the columns. -> [['A','a'],['B','b']]
      Œp           Cartesian product of the elements in the outermost list. -> [['A','B'],['A','b'],['a','B'],['a','b']]
        Œ!€        The permutations applied at €ach element in the list. -> [[['A','B'],['B','A']],[['A','b'],...
                   The rest is deleting duplicates and formatting.
           ;/      Concatenates the lists of permutations. In Essentially flattens the list by one level.
             Q     Remove repeated elements
              ŒṘ   Print in Python's string format

```

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

I/O format: arrays of characters.

```
a=>(r=[],P=(a,m=[])=>a.map((_,i)=>P(b=[...a],[...m,...b.splice(i,1)]))>[]||(g=i=>i>>m.length||g(-~i,r.push(m.map((c,j)=>c[`to${i>>j&1?'Upp':'Low'}erCase`]()))))())(a)&&r

```

Not the right tool for the job... Still, there's probably a golfier way.

### Demo

```
let f =

a=>(r=[],P=(a,m=[])=>a.map((_,i)=>P(b=[...a],[...m,...b.splice(i,1)]))>[]||(g=i=>i>>m.length||g(-~i,r.push(m.map((c,j)=>c[`to${i>>j&1?'Upp':'Low'}erCase`]()))))())(a)&&r

f([...'abc']).forEach(a => console.log(a.join('')))
```

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


title: Count of relatively prime partitions

text:
# Question
Title: Count of relatively prime partitions
The partitions of an integer **N** are all the combinations of integers smaller than or equal to **N** and higher than **0** which sum up to **N**.

A relatively prime partition is an integer partition, but whose elements are *(overall)* coprime; or in other words, there is no integer greater than 1 which divides all of the parts.

# Task

Given an integer as input, your task is to output the count of relatively prime partitions it has. Rather not surprised that there is an OEIS sequence for this. The aim is to shorten your code as much as possible, with usual code golf rules.

Also, you don't have to worry about memory errors. Your algorithm must only theoretically work for an arbitrarily big values of **N**, but it is fine if your language has certain limitations. You can assume that **N** will always be at least 1.

# Test cases and Example

Let's take `5` as an example. Its integer partitions are:

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

```

From this, the first 6 only are relatively prime partitions. Note that the last one (formed by the integer in question only) must not be taken into account as a relatively prime partition (except for **N**=1) because its GCD is **N**.

```
N -> Output

1  -> 1
2  -> 1
3  -> 2
4  -> 3
5  -> 6
6  -> 7
7  -> 14
8  -> 17
9  -> 27
10 -> 34

```

# Answer
> 7 votes
# JavaScript (ES6), ~~130~~ 120 bytes

```
f=(n,d=n)=>d&&(n%d?0:(M=n=>n%++k?k>n||M(n):n/k%k&&-M(n/k))(n/d,k=1)*(P=n=>!k|n<0?0:n?P(n,k--)+P(n-++k):1)(k=d))+f(n,d-1)

```

### Demo

```
f=(n,d=n)=>d&&(n%d?0:(M=n=>n%++k?k>n||M(n):n/k%k&&-M(n/k))(n/d,k=1)*(P=n=>!k|n<0?0:n?P(n,k--)+P(n-++k):1)(k=d))+f(n,d-1)

for(n = 1; n <= 30; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```

### How?

This is recursively computing:

```
     /                  \     /                   \
    |  (M = n =>         |   |  (P = n =>          |
    |    n % ++k ?       |   |    !k | n < 0 ?     |
    |      k > n ||      |   |      0              |
    |      M(n)          |   |    :                |
sum |    :               | * |      n ?            | for d in divisors(n)
    |      n / k % k &&  |   |        P(n, k--) +  |
    |      - M(n / k)    |   |        P(n - ++k)   |
    |  )(n / d, k = 1)   |   |      :              |
    |                    |   |        1            |
    |                    |   |  )(k = d)           |
     \                  /     \                   /
        Möbius(n / d)            npartitions(d)

```

# Answer
> 4 votes
# Pyth, 7 bytes

```
/iM./Q1

```

**Test suite.**

### Explanation

```
/iM./Q1  | Full program.
         |
   ./Q   | The integer partitions (./) of the evaluated input (Q).
 iM      | Get the GCD (i) of each (M).
/     1  | Count (/) the 1's (1).

```

Pyth's behaviour comes in handy, since mapping with a 2-argument function automatically folds the command on the list, and the GCD of a one-element list is the element itself, so we don't have to handle that separately.

# Answer
> 4 votes
# Pari/GP, 39 bytes

This sequence (A000837) is the Möbius transform of the partition numbers (A000041).

```
n->sumdiv(n,d,moebius(n/d)*numbpart(d))

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 35 bytes

```
Count[GCD@@@IntegerPartitions@#,1]&

```

Try it online!

This is my first Mathematica submission. *Thanks to alephalpha for -4 bytes!*

# Answer
> 2 votes
# Jelly, 7 bytes

```
Œṗg/€ċ1

```

Try it online!

# Answer
> 1 votes
# Swift, ~~202~~ 185 bytes

*Saved 17 bytes thanks to @Mr.Xcoder*

```
func p(_ n:Int,_ m:[Int]=[])->[[Int]]{return 0<n ?(1...min(m.last ?? n,n)).flatMap{p(n-$0,m+[$0])}:[m]}
{n in n>1 ?p(n).filter{a in !(2...n).contains{m in !a.contains{$0%m>0}}}.count:1}

```

Try it online!

## Explanation

```
func p(_ n:Int,_ m:[Int]=[])->[[Int]]{// Recursive helper function p where p(n, prefix) is
                                      // a list of all possiblie partitions of n
  return n > 0 ?                      // If n > 0:
    (1 ... min(m.last ?? n, n))       //   For i in range from 1 to min(n, last value in prefix):
      .flatMap{p(n - $0, m + [$0])}   //     Add p(n - i, prefix + i) to the return list
  :                                   // Else:
    [m]                               //   Return just the prefix
}
{n in                                 // Main function:
  n > 1 ?                             // If n > 1:
    p(n).filter {a in                 //   Take the list of possible partitions of n where
      !(2...n).contains{m in          //   there is no integer m in the range from 2 to n where
        !a.contains{$0%m>0}           //   all elements in the partitioning divide m
      }
    }.count                           //   and return the length of the list
  :                                   // Else (if n == 1):
    1}                                //   Return 1

```

---
Tags: code-golf, math, sequence, number-theory, integer-partitions
---


# Question
Title: Frequency Distribution of Multiple Dice Rolls
Given two positive integers `a` and `b`, output the frequency distribution of rolling a `b`-sided die `a` times and summing the results.

A frequency distribution lists the frequency of each possible sum if each possible sequence of dice rolls occurs once. Thus, the frequencies are integers whose sum equals `b**a`.

## Rules

* The frequencies must be listed in increasing order of the sum to which the frequency corresponds.
* Labeling the frequencies with the corresponding sums is allowed, but not required (since the sums can be inferred from the required order).
* You do not have to handle inputs where the output exceeds the representable range of integers for your language.
* Leading or trailing zeroes are not permitted. Only positive frequencies should appear in the output.

## Test Cases

Format: `a b: output`

```
1 6: [1, 1, 1, 1, 1, 1]
2 6: [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
3 6: [1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1]
5 2: [1, 5, 10, 10, 5, 1]
6 4: [1, 6, 21, 56, 120, 216, 336, 456, 546, 580, 546, 456, 336, 216, 120, 56, 21, 6, 1]
10 10: [1, 10, 55, 220, 715, 2002, 5005, 11440, 24310, 48620, 92368, 167860, 293380, 495220, 810040, 1287484, 1992925, 3010150, 4443725, 6420700, 9091270, 12628000, 17223250, 23084500, 30427375, 39466306, 50402935, 63412580, 78629320, 96130540, 115921972, 137924380, 161963065, 187761310, 214938745, 243015388, 271421810, 299515480, 326602870, 351966340, 374894389, 394713550, 410820025, 422709100, 430000450, 432457640, 430000450, 422709100, 410820025, 394713550, 374894389, 351966340, 326602870, 299515480, 271421810, 243015388, 214938745, 187761310, 161963065, 137924380, 115921972, 96130540, 78629320, 63412580, 50402935, 39466306, 30427375, 23084500, 17223250, 12628000, 9091270, 6420700, 4443725, 3010150, 1992925, 1287484, 810040, 495220, 293380, 167860, 92368, 48620, 24310, 11440, 5005, 2002, 715, 220, 55, 10, 1]
5 50: [1, 5, 15, 35, 70, 126, 210, 330, 495, 715, 1001, 1365, 1820, 2380, 3060, 3876, 4845, 5985, 7315, 8855, 10626, 12650, 14950, 17550, 20475, 23751, 27405, 31465, 35960, 40920, 46376, 52360, 58905, 66045, 73815, 82251, 91390, 101270, 111930, 123410, 135751, 148995, 163185, 178365, 194580, 211876, 230300, 249900, 270725, 292825, 316246, 341030, 367215, 394835, 423920, 454496, 486585, 520205, 555370, 592090, 630371, 670215, 711620, 754580, 799085, 845121, 892670, 941710, 992215, 1044155, 1097496, 1152200, 1208225, 1265525, 1324050, 1383746, 1444555, 1506415, 1569260, 1633020, 1697621, 1762985, 1829030, 1895670, 1962815, 2030371, 2098240, 2166320, 2234505, 2302685, 2370746, 2438570, 2506035, 2573015, 2639380, 2704996, 2769725, 2833425, 2895950, 2957150, 3016881, 3075005, 3131390, 3185910, 3238445, 3288881, 3337110, 3383030, 3426545, 3467565, 3506006, 3541790, 3574845, 3605105, 3632510, 3657006, 3678545, 3697085, 3712590, 3725030, 3734381, 3740625, 3743750, 3743750, 3740625, 3734381, 3725030, 3712590, 3697085, 3678545, 3657006, 3632510, 3605105, 3574845, 3541790, 3506006, 3467565, 3426545, 3383030, 3337110, 3288881, 3238445, 3185910, 3131390, 3075005, 3016881, 2957150, 2895950, 2833425, 2769725, 2704996, 2639380, 2573015, 2506035, 2438570, 2370746, 2302685, 2234505, 2166320, 2098240, 2030371, 1962815, 1895670, 1829030, 1762985, 1697621, 1633020, 1569260, 1506415, 1444555, 1383746, 1324050, 1265525, 1208225, 1152200, 1097496, 1044155, 992215, 941710, 892670, 845121, 799085, 754580, 711620, 670215, 630371, 592090, 555370, 520205, 486585, 454496, 423920, 394835, 367215, 341030, 316246, 292825, 270725, 249900, 230300, 211876, 194580, 178365, 163185, 148995, 135751, 123410, 111930, 101270, 91390, 82251, 73815, 66045, 58905, 52360, 46376, 40920, 35960, 31465, 27405, 23751, 20475, 17550, 14950, 12650, 10626, 8855, 7315, 5985, 4845, 3876, 3060, 2380, 1820, 1365, 1001, 715, 495, 330, 210, 126, 70, 35, 15, 5, 1]

```

# Answer
> 10 votes
# Octave, 38 bytes

```
@(a,b)round(ifft(fft((a:a*b<a+b)).^a))

```

Try it online!

### Explanation

Adding independent random variables corresponds to convolving their probability mass functions (PMF), or multiplying their characteristic functions (CF). Thus the CF of the sum of `a` independent, identically distributed variables is given by that of a single variable raised to the power of `a`.

The CF is essentially the Fourier transform of the PMF, and can thus be computed via a FFT. The PMF of a single `b`-sided die is uniform on `1`, `2`, ..., `b`. However, two modifications are required:

* `1` is used instead of the actual probability values (`1/b`). This way the result will be de-normalized and will contain integers as required.
* Padding with zeros is needed so that the FFT output has the appropriate size (`a*b-a+1`) and the implicit periodic behaviour assumed by the FFT doesn't affect the results.

Once the characteristic function of the sum has been obtained, an inverse FFT is used to compute the final result, and rounding is applied to correct for floating-point inaccuracies.

### Example

Consider inputs `a=2`, `b=6`. The code `a:a*b<a+b` builds a vector with `b=6` ones, zero-padded to size `a*b-a+1`:

```
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

```

Then `fft(...)` gives

```
[36, -11.8-3.48i, 0.228+0.147i, -0.949-1.09i, 0.147+0.321i, -0.083-0.577i, -0.083+0.577i, 0.147-0.321i, -0.949+1.09i, 0.228-0.147i, -11.8+3.48i]

```

One can almost recognize the sinc function here (Fourier transform of a rectangular pulse).

`(...).^a` raises each entry to `a` and then `ifft(...)` takes the inverse FFT, which gives

```
[1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]

```

Although the results in this case are exactly integers, in general there may be relative errors of the order of `1e-16`, which is why `round(...)` is needed.

# Answer
> 8 votes
# Mathematica, 29 bytes

```
Tally[Tr/@Range@#2~Tuples~#]&

```

Just generates all possible dice rolls, takes their totals, then counts. Each frequency comes labeled with its value.

# Mathematica, 38 bytes

```
CoefficientList[((x^#2-1)/(x-1))^#,x]&

```

Expands `(1+x+x^2+...+x^(a-1))^b` and takes the coefficients of `x`. Since `1+x+x^2+...+x^(a-1)` is the generating function for a single die roll and products correspond to convolutions - adding values of dice - the result gives the frequency distribution.

# Answer
> 6 votes
# Haskell, ~~90~~ ~~79~~ ~~77~~ 75 bytes

Thanks to Lynn for the Cartesian product trick. -11 bytes thanks to many Haskell tricks from Funky Computer Man, -2 bytes from naming, -2 bytes thanks to Laikoni. Golfing suggestions are welcome! Try it online!

```
import Data.List
g x=[1..x]
a!b=map length$group$sort$map sum$mapM g$b<$g a

```

**Ungolfed**

```
import Data.List
rangeX x = [1..x]
-- sums of all the rolls of b a-sided dice
diceRolls a b = [sum y | y <- mapM rangeX $ fmap (const b) [1..a]]
-- our dice distribution
distrib a b = [length x | x <- group(sort(diceRolls a b))]

```

# Answer
> 4 votes
# Pyth - 10 bytes

Just takes all possible dice combinations by taking the cartesian product of `[1, b]`, `a` times, summing, and getting the length of each sum group.

```
lM.gksM^SE

```

Test Suite.

# Answer
> 4 votes
# 05AB1E, 8 bytes

```
LIãO{γ€g

```

Try it online!

## How?

```
LIãO{γ€g  - Full program.

L         - Range [1 ... input #1]
 I        - Input #2.
  ã       - Cartesian Power.
   O      - Map with sum.
    {     - Sort.
     γ    - Group consecutive equal elements.
      €g  - Get the length of each

```

# Answer
> 4 votes
# , 58 bytes

```
function(a,b)table(rowSums(expand.grid(rep(list(1:b),a))))

```

Try it online!

# Answer
> 4 votes
# , 52 bytes

```
function(a,b)Re(fft(fft(a:(a*b)<a+b)^a,T)/(a*b-a+1))

```

Try it online!

A port of @Luis Mendo's Octave solution, `fft(z, inverse=T)` unfortunately returns the unnormalized inverse FFT, so we have to divide by the length, and it returns a `complex` vector, so we take only the real part.

# Answer
> 3 votes
# Jelly, 5 bytes

```
ṗS€ĠẈ

```

**Try it online!**

Note that this takes the arguments in reverse order.

## How?

```
ṗS€ĠL€   - Full program (dyadic) | Example: 6, 2

ṗ        - Cartesian Power (with implicit range) | [[1, 1], [1, 2], ... , [6, 6]]
 S€      - Sum each | [2, 3, 4, ... , 12]
   Ġ     - Group indices by values | [[1], [2, 7], [3, 8, 13], ... , [36]]
    L€   - Length of each group | [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]

```

---

Alternative solutions:

```
ṗZSĠL€
ṗZSµLƙ
ṗS€µLƙ

```

# Answer
> 3 votes
## SageMath, 40 bytes

```
lambda a,b:reduce(convolution,[[1]*b]*a)

```

Try it online

`convolution` computes the discrete convolution of two lists. `reduce` does what it says on the tin. `[1]*b` is a list of `b` `1`s, the frequency distribution of `1db`. `[[1]*b]*a` makes a nested list of `a` copies of `b` `1`s.

---

# Python 2 \+ NumPy, 56 bytes

```
lambda a,b:reduce(numpy.convolve,[[1]*b]*a)
import numpy

```

Try it online!

I've included this solution with the above one, since they're essentially equivalent. Note that this function returns a NumPy array and not a Python list, so the output looks a bit different if you `print` it.

`numpy.ones((a,b))` is the "correct" way to make an array for use with NumPy, and thus it could be used in place of `[[1]*b]*a`, but it's unfortunately longer.

# Answer
> 2 votes
# Python 2, ~~102~~ 91 bytes

```
lambda b,a:map(map(sum,product(*[range(a)]*b)).count,range(b*~-a+1))
from itertools import*

```

Try it online!

# Answer
> 2 votes
# Pari/GP, 26 bytes

```
a->b->Vec((1/(1-x)%x^b)^a)

```

Try it online!

# Answer
> 2 votes
# Haskell, 61 bytes

```
g x=[1..x]
a#b=[sum[1|m<-mapM g$b<$g a,sum m==n]|n<-[a..a*b]]

```

Try it online! Use as `a#b`.

Partly based on Sherlock9's Haskell answer.

# Answer
> 2 votes
# MATL, 9 bytes

```
:Z^!Xs8#u

```

Same approach as Maltysen's Pyth answer.

Inputs are in reverse order. Try it online!

# Answer
> 1 votes
# Perl 5, 53 bytes

```
$g=join',',1..<>;map$r[eval]++,glob"+{$g}"x<>;say"@r"

```

Try it online!

Input format:

```
b
a

```

# Answer
> 1 votes
# , ~~25 24 21~~ 20 bytes

```
3 :'#/.~,+//y$i.{:y'

```

Try it online!

Initially I incremented the \[0..n-1\] list to get \[1..n\] but apparently it’s not necessary.

# Answer
> 1 votes
# Actually, ~~13~~ 12 bytes

-1 byte thanks to Mr. Xcoder. Try it online!

```
R∙♂Σ;╗╔⌠╜c⌡M

```

**Ungolfed**

```
                Implicit input: b, a
R∙              ath Cartesian power of [1..b]
  ♂Σ            Get all the sums of the rolls, call them dice_rolls
    ;╗          Duplicate dice_rolls and save to register 0
      ╔         Push uniquify(dice_rolls)
       ⌠  ⌡M    Map over uniquify(dice_rolls), call the variable i
        ╜         Push dice_rolls from register 0
         c        dice_rolls.count(i)
                Implict return

```

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

```
f=(n,m,a=[1],b=[])=>n?[...Array(m)].map((_,i)=>a.map((e,j)=>b[j+=i]=(b[j]|0)+e))&&f(n-1,m,b):a
```

```
<div oninput=o.textContent=f(+n.value,+m.value).join`\n`><input id=n type=number min=0 value=0><input id=m type=number min=1 value=1><pre id=o>1
```

Limited by 32-bit integer overflow, but floats could be used instead at a cost of 1 byte.

# Answer
> 1 votes
# Javascript (ES6), 89 bytes

```
b=>g=a=>a?(l=[..."0".repeat(b-1),...g(a-1)]).map((_,i)=>eval(l.slice(i,i+b).join`+`)):[1]

```

Takes input in currying syntax in reverse order `f(b)(a)`

```
f=b=>g=a=>a>0?(l=[..."0".repeat(b-1),...g(a-1)]).map((_,i)=>eval(l.slice(i,i+b).join`+`)):[1]
r=_=>{o.innerText=f(+inb.value)(+ina.value)}
```

```
<input id=ina type=number min=0 onchange="r()" value=0>
<input id=inb type=number min=1 onchange="r()" value=1>
<pre id=o></pre>
```

# Answer
> 1 votes
# AWK, 191 bytes

Outputs frequencies as a vertical column.

```
func p(z){for(m in z)S[z[m]]++
for(i=$1;i<=$1*$2;i++)print S[i]}func t(a,b,z,s){if(a){if(R++)for(n in z)for(i=0;i++<b;)s[n,i]=z[n]+i
else for(i=0;i++<b;)s[i]=i
t(--a,b,s)}else p(z)}{t($1,$2)}

```

Try it online!

Adding 6 more bytes allows for multiple sets of inputs.

```
func p(z,S){for(m in z)S[z[m]]++
for(i=$1;i<=$1*$2;i++)print S[i]}func t(a,b,z,s){if(a){if(R++)for(n in z)for(i=0;i++<b;)s[n,i]=z[n]+i
else for(i=0;i++<b;)s[i]=i
t(--a,b,s)}else p(z)}{R=0;t($1,$2)}

```

Try it online!

# Answer
> 1 votes
## Clojure, 86 bytes

```
#(sort-by key(frequencies(reduce(fn[r i](for[y(range %2)x r](+ x y 1)))[0](range %))))

```

An example:

```
(def f #(...))
(f 5 4)

([5 1] [6 5] [7 15] [8 35] [9 65] [10 101] [11 135] [12 155] [13 155] [14 135] [15 101] [16 65] [17 35] [18 15] [19 5] [20 1])

```

# Answer
> 0 votes
# C (gcc), 142 bytes

```
i,j,k;int*f(a,b){int*r=malloc(sizeof(int)*(1+a*~-b));r[0]=1;for(i=1;i<=a;i++)for(j=i*~-b;j>=0;j--)for(k=1;k<b&k<=j;k++)r[j]+=r[j-k];return r;}

```

Try it online!

# Answer
> 0 votes
# Julia, 43 bytes

```
f(n,d)=reduce(conv,repmat([ones(Int,d)],n))

```

Try it online!

---
Tags: code-golf, integer, probability-theory, statistics
---


title: Delete the first periodic digit

text:
# Question
Title: Delete the first periodic digit
We all know that whenever a rational number is written in decimal, the result is either terminating or (eventually) periodic. For example, when 41/42 is written in decimal, the result is

```
0.9 761904 761904 761904 761904 761904 761904 761904 ...

```

with an initial sequence of digits `0.9` followed by the sequence `761904` repeated over and over again. (A convenient notation for this is `0.9(761904)` where the parentheses surround the block of repeating digits.)

Your goal in this challenge is to take a positive rational number, delete the first digit that's part of the repeating sequence, and return the resulting rational number. For example, if we do this to 41/42, we get

```
0.9  61904 761904 761904 761904 761904 761904 761904 ...

```

or `0.9(619047)` for short, which is 101/105.

If the rational number has a terminating decimal expansion, like 1/4 = `0.25` does, nothing should happen. You can think of 1/4 either as `0.250000000...` or as `0.249999999...` but in either case, deleting the first digit of the repeating part leaves the number unchanged.

## Details

* The input is a positive rational number, either as a pair of positive integers representing the numerator and denominator, or (if your language of choice allows it and you want to) as some sort of rational-number object.
* The output is also a rational number, also in either form. If the result is an integer, you may return the integer instead of a rational number.
* If taking a pair of numbers as input, you may assume they're relatively prime; if producing a pair of numbers as output, you must make them be relatively prime.
* Be careful that you find the *first* digit that starts a repeating block. For example, one could write 41/42 as `0.97(619047)` but that doesn't make 2041/2100 (with the decimal expansion `0.97(190476)`) a valid answer.
* You may assume that in the input you get, the first periodic digit is *after* the decimal point, making `120/11` = `10.909090909...` invalid input: (its first periodic digit could be considered the `0` in `10`). You may do anything you like on such input.
* This is : the shortest solution wins.

## Test cases

```
41/42 => 101/105
101/105 => 193/210
193/210 => 104/105
104/105 => 19/21
1/3 => 1/3
1/4 => 1/4
2017/1 => 2017/1
1/7 => 3/7
1/26 => 11/130
1234/9999 => 2341/9999

```

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
FromDigits@MapAt[RotateLeft@*List@@#&,RealDigits@#,{1,-1}]&

```

Try it online!

### Explanation

```
RealDigits@#

```

Find the decimal digits of the input.

```
MapAt[RotateLeft@*List@@#&, ..., {1,-1}]

```

If there are repeating digits, `RotateLeft` them. (`List@@#` prevents the code from attempting to rotate the last decimal digit if the rational number is terminating).

```
FromDigits@

```

Convert to rational.
> 12 votes

# Answer
# Jelly, ~~36~~ ~~32~~ ~~31~~ 30 bytes

-1 byte thanks to *Erik the Outgolfer*!

```
ọ2,5Ṁ⁵*©×Ɠ÷µ×⁵_Ḟ$+Ḟ,®×³+.Ḟ÷g/$

```

Try it online!

Should be correct. Floating point imprecision add 3 bytes for `+.Ḟ`.

Relies on the input being irreducible.

---

## Explanation

This relies on:

* Let the numerator be `n/d` in its simplest form. Then the link `ọ2,5Ṁ` applied to `d` will give the number of non-periodic digit after the radix point.

```

ọ2,5Ṁ⁵*©×Ɠ÷µ×⁵_Ḟ$+Ḟ,®×³+.Ḟ÷g/$     Main link (monad take d as input)

    Ṁ                              Maximum
ọ                                  order of
 2,5                               2 or 5 on d
     ⁵*                            10 power
       ©                           Store value to register ®.
        ×Ɠ                         Multiply by eval(input()) (n)
          ÷                        Divide by first argument (d).
                                   Now the current value is n÷d×®.
           µ                       With that value,
            ×⁵                     Multiply by ⁵ = 10
              _Ḟ$                  subtract floor of self
                 +Ḟ                add floor or value (above)
                                   Given 123.45678, will get 123.5678
                                   (this remove first digit after `.`)
                   ,®              Pair with ®.
                     ×³            Scale
                       +.Ḟ         Round to integer
                          ÷g/$     Simplify fraction

```
> 5 votes

# Answer
# Python 2, ~~237~~ ~~235~~ 214 bytes

<sup>-21 bytes thanks to Mr. Xcoder</sup>

```
from fractions import*
F=Fraction
n,d=input()
i=n/d
n%=d
R=[]
D=[]
while~-(n in R):R+=n,;n*=10;g=n/d;n%=d;D+=g,
x=R.index(n)
r=D[x+1:]+[D[x]]
print i+F(`r`[1::3])/F('9'*len(r))/10**x+F("0."+"".join(map(str,D[:x])))

```

Try it online!

Input is done as a tuple `(numerator, denominator)`; output is a `fractions.Fraction` object.

This uses a long-division-style method to get the starting and repeating digits of the answer, then moves the first repeating digit to the end and uses string manipulation and `fraction.Fraction` to convert it back to a ratio.

Ungolfed version:

```
import fractions

num, denom = input()
integer_part, num = divmod(num, denom)

remainders = []
digits = []
current_remainder = num
while current_remainder not in remainders:
    remainders.append(current_remainder)
    current_remainder *= 10
    digit, current_remainder = divmod(current_remainder, denom)
    digits.append(digit)

remainder_index = remainders.index(current_remainder)
start_digits = digits[:remainder_index]
repeated_digits = digits[remainder_index:]

repeated_digits.append(repeated_digits.pop(0))

start_digits_str = "".join(map(str, start_digits))
repeated_digits_str = "".join(map(str, repeated_digits))

print(integer_part+int(repeated_digits_str)/fractions.Fraction('9'*(len(repeated_digits_str)))/10**len(start_digits_str)+fractions.Fraction("0."+start_digits_str))

```
> 4 votes

# Answer
# Python 3, ~~177~~ ~~173~~ 169 bytes

```
from fractions import*
def f(n,d):
 i=1;r=[]
 while~-(i%d in r):r+=[i%d];i*=10
 r=10**r.index(i%d);u=i-r;v=i//r-1;t=u//d*n
 return Fraction(t-t%v+t%v*10//v+t%v*10%-~v,u)

```

Try it online!
> 4 votes

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

Thanks to this tip (now deleted) for -3 byte!

```
(x=10^Max@IntegerExponent[#,{2,5}];(Floor@#+Mod[10#,1])/x&[x#2/#])&

```

Try it online!

A port of my Jelly answer. Longer than the existing Mathematica answer by 8 bytes...

The function take 2 input `[denominator, numerator]`, such that `GCD[denominator, numerator] == 1`.
> 1 votes

# Answer
# Perl 6, 102 bytes

```
{$/=.base-repeating;(+$0//$0~0)+([~]([$1.comb].rotate)/(9 x$1.chars)*.1**(($0~~/\.<(.*/).chars)if $1)}

```

Try it

Takes a Rational number and returns a Rational or Int number.

## Expanded:

```
{  # bare block lambda with implicit Rational parameter ｢$_｣

  $/ = .base-repeating; # store in ｢$/｣ the two strings '0.9' '761904'

    # handle the non-repeating part
    (
      +$0        # turn into a number
      // $0 ~ 0  # if that fails append 0 (handle cases like '0.')
    )

  +

    # handle the repeating part
    (
          [~]( [$1.comb].rotate ) # rotate the repeating part
        /
          ( 9 x $1.chars )        # use a divisor that will result in a repeating number

        *

         # offset it an appropriate amount

         .1 ** (
           ( $0 ~~ / \. <( .* / ).chars # count the characters after '.'
         )

      if $1  # only do the repeating part if there was a repeating part
    )
}

```

Note will handle denominators upto `uint64.Range.max` to handle larger denominators use `FatRat(9 x$1.chars)` Try it.
> 1 votes

---
Tags: code-golf, math, rational-numbers
---


title: Generate a Texting Dictionary

text:
# Question
Title: Generate a Texting Dictionary
*this challenge was based on a sandboxed post by @dmckee*

Old fashioned cell phones were and are used heavily as texting platforms, unfortunately the keyboard has only 12 + a few buttons, and is therefor ill-suited to naive text entry.

Common solutions make use of the traditional telephone coding (generally with a modest extension for 'q' and 'z'):

```
2: a,b,c
3: d,e,f
4: g,h,i
5: j,k,l
6: m,n,o
7: p(,q),r,s
8: t,u,v
9: w,x,y(,z)

```

In this case we are interested in the one-press-per-letter schemes that offer up words matching words on a frequency basis. That is if the user type "4663" the phone will offer up words like "good", "home", "gone", "hood", "hoof", etc that code to 4663 in order of their frequency.

Your task is to read one or more input files and generate a frequency sorted dictionary that could be used to implement this scheme.

## Inputs

* All input will be plain ASCII text.
* You may accept input from named files, the standard input, or other conventional source supported by your implementation language, but there *must* be some mechanism to process several files in a single run.
* Non-letter, non-whitespace characters should be stripped from the input, this means that contractions will be coded *without* their apostrophe: `"don't" --> "dont" --> 3668`
* Words are a sequence of letters separated surrounded by whitespace
* All whitespace (space, tab, newline, beginning-of-file, end-of-file) is equivalent.
* Input will be all lowercase or caps your preference.

## Output

* The output consists of a ASCII text stream
* You may direct this to a file, the standard output, or any other conventional destination supported by your implementation language
* The output should consist of one line for each string of digits corresponding to at least one word in the input.
* Each line should consist of the digit string and a list of all corresponding words sorted by frequency with the most frequent coming first. A sample line of output would be

```
4663 good home gone hood hoof

```
* Tokens (digit strings and corresponding words) should be separated by a single space.
* Equally frequent words may be sorted in any order.

The winner is the shortest code.

## Test Cases

```
potato, potato, damd, fjefje, djfaejri

Top 1000 words used.

The potato was a down goat goat down game gill pont pint point.

```

More actual test cases will be given in about a week to prevent any sort of hard-coding action.

# Answer
# Jelly, ~~42~~ 41 bytes

```
>”q+91N+O:3«9µ€Ḍ’0x
ċ@Þ³ṚQµÇ€⁸ṭ"Zḟ€0Ėṛ/Ðf

```

Try it online!

Monadic link take a list of strings as argument.

The footer is for formatting the output to a form suitable for outputting. Without it, the monadic link returns:

```
[[3, ["d", "f", "e"]], [4628, ["goav", "goat"]], [6346, ["mego", "mdim"]]]

```

(that is, a list, each has the format `[number, list of words]`).

The `"Zḟ€0` idea was taken from this answer.

---

Explanation:

The first link, which given a string and output its telephone number, is mostly a port from my Python answer.

```
>”q+91N+O:3«9µ€Ḍ’0x     Link.
                        Implicit input, call it (st).
             µ€         Monadic link map for each character (ch):
>”q                     Larger than character 'q'? If yes, get 1, else get 0.
   +91N                 add 91, and then negate. Current value = -((ch>'q')+91)
       +O               Add the ord (ASCII value) of ch. Get ch-(ch>'q')-91.
         :3             Integer division by 3.
           «9           If the result is larger than 9, set it to 9. (« : min)
                        With the list of digits obtained by
                        mapping the previous chain to characters:
               Ḍ        Convert from decimal digits to number.
                ’       Decrement.
                 0x     Repeat that many digits of zero.

```

Then, the second link:

```
  Þ                         Sort by...
ċ@                            count. (frequency)
   ³                        I have no idea what is this used for.
    Ṛ                       Reverse. (so that words with max count appear first)
     Q                      Unique.
      µ                     With that value,
       Ç                    Map the previous link over this word list.
         ṭ"                 Vectorize tack with...
        ⁸                     the word list.
           Z                Zip (transpose).
            ḟ€0             Filter out 0 from each element.
               Ė            Enumerate.
                  Ðf        Filter, keep elements with truthy...
                ṛ/            last element.

```
> 2 votes

# Answer
## Mathematica, 202 bytes

```
{g[#],##}~r~" "&@@@GatherBy[#&@@@SortBy[Tally@StringReplace[StringSplit@#,x_/;!LetterQ@x->""],-Last@#&],g=""<>ToString/@(\[LeftFloor]If[#<113,(#-91)/3,(#-88.2)/3.4]\[RightFloor]&/@ToCharacterCode@#)&]~(r=Riffle)~"
"<>""&

```

Note that `\[LeftFloor]` and `\[RightFloor]` are 3 bytes each.
> 5 votes

# Answer
## C++, ~~566~~ 533 bytes

-33 bytes thanks to Zacharý ( about 20 bytes ) and user202729 ( about 12 bytes )

```
#include<map>
#include<string>
#include<fstream>
#include<regex>
#include<set>
using namespace std;using s=string;struct z{s d;int f;int operator<(z a)const{return f<=a.f&&d<a.d;}};regex r("[^a-z]");void g(){fstream e("a"),o("d",ios::out);map<s,int>m;while(!e.eof()){s t;e>>t;t=regex_replace(t,r,"");++m[t];}map<s,set<z>>t;for(auto a:m){s k;for(auto c:a.first)k+="22233344455566677778889999"[c-97];t[k].insert({a.first,a.second});}for(auto&a:t){o<<'\n'<<a.first<<' ';for(auto m=a.second.rbegin();m!=a.second.rend();++m)o<<m->d<<' ';}}

```

Uses a set to ensure that the words in the `z` struct are ordered, so a reverse iterator loop can be done.
> 4 votes

# Answer
# Perl 5, 123 bytes + 1 (`-a`) = 124 bytes

```
y/A-Z//dc&$k{y/A-Z/22233344455566677778889999/r}{$_}++for@F}{$,=$";say$_,sort{$k{$_}{$b}-$k{$_}{$a}}keys%{$k{$_}}for keys%k

```

Try it online!

Takes input as uppercase.
> 3 votes

# Answer
# Clean, ~~245~~ ... ~~214~~ 210 bytes

```
import StdEnv
r=removeDup
$s=toString[48+min((toInt c-91-toInt c/113)/3)9\\c<-:s]
?f=foldr(\s-> \l=[(a+if(s==b)1 0,b)\\(a,b)<-l])(zip([0,0..],r f))f
@f=r[(s,reverse(map snd(sort(?[l\\l<-f| $l==s]))))\\s<-map$f]

```

Try it online!
> 3 votes

# Answer
# Röda, 218 bytes

```
{g={|n|chars n|[("2223334445556667777888999"/"")[ord(_)-97]]|concat}m=new map
replace`[^\w\s]|_`,""|(_/`\s+`)|sort|count|m[g(_)]+=[-_,_1]if m[g(_1)]=[]unless[m[g(_1)]?]
keys m|sort|{|k|[k];m[k]|sort|_|[` $_2`];[`
`]}_}

```

Try it online!
> 1 votes

# Answer
# Java 8, 480 + 19 = 499 bytes

A `Runnable` lambda. Byte count includes lambda and required import. Input and output are as specified through standard in/out. Input is in all lowercase. Dictionary items are not printed in any particular order.

```
import java.util.*;

```

```
()->{Map<String,Integer>f=new HashMap();new Scanner(System.in).useDelimiter("\\s+").forEachRemaining(n->f.put(n=n.replaceAll("[^a-z]",""),f.getOrDefault(n,0)+1));Map<String,Set>n=new HashMap();f.forEach((k,v)->{String c=k;for(int i=0;i<8;)c=c.replaceAll("["+"abc def ghi jkl mno pqrs tuv wxyz".split(" ")[i]+"]",++i+1+"");n.putIfAbsent(c,new HashSet());n.get(c).add(k);});n.forEach((k,v)->System.out.println(v.stream().sorted((y,z)->f.get(z)-f.get(y)).reduce(k,(y,z)->y+" "+z)));}

```

Try It Online

## Ungolfed lambda

```
() -> {
    Map<String, Integer> f = new HashMap();
    new Scanner(System.in)
        .useDelimiter("\\s+")
        .forEachRemaining(
            n -> f.put(
                n = n.replaceAll("[^a-z]", ""),
                f.getOrDefault(n, 0) + 1
            )
        )
    ;

    Map<String, Set> n = new HashMap();
    f.forEach((k, v) -> {
        String c = k;
        for (int i = 0; i < 8;)
            c = c.replaceAll(
                "[" + "abc def ghi jkl mno pqrs tuv wxyz".split(" ")[i] + "]",
                ++i + 1 + ""
            );
        n.putIfAbsent(c, new HashSet());
        n.get(c).add(k);
    });

    n.forEach((k, v) ->
        System.out.println(
            v.stream()
                .sorted((y, z) -> f.get(z) - f.get(y))
                .reduce(k, (y, z) -> y + " " + z)
        )
    );
}

```

`f` is my frequency map, and `n` collects words based on their numeric encoding. As usual with programs this long, this is probably far from optimal. Improvements are welcome.

I could have replaced `++i+1+""` in the number encoding step with `""+-~++i` for the same number of bytes. But I respect you all too much to do that.
> 1 votes

# Answer
# PHP, 273 bytes

```
<?$f=str_split;$w=explode(" ",preg_replace(['/\s+/','/[^a-z ]/is'],[' ',''],$argv[1]));$l=$f('22233344455566677778889999');foreach($w as$x){$z='';foreach($f($x)as$y){$z.=$l[ord($y)-97];}$a[$z][$x]++;}foreach($a as$n=>$b){arsort($b);echo$n." ".join(" ",array_keys($b))."
";}

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~179~~ ~~156~~ 155 bytes

Thanks *Rod* for -23 bytes!
Thanks anonymous user suggestion for -1 byte!

```
def f(l):
	d={}
	for w in l:k=(*[min(27,ord(x)-91-(x>'q'))//3for x in w],);d[k]=k in d and{w}|d[k]or{w}
	for k in d:print(k,sorted(d[k],key=l.count)[::-1])

```

Try it online!
> 1 votes

---
Tags: code-golf, text-processing
---


title: Unicode Fractions

text:
# Question
Title: Unicode Fractions
Given a fraction in the format `m/n` (where m and n are coprime integers), output the corresponding Unicode fraction. Your program/function will not be expected to take in any input that does not correspond to a Unicode character. Arrays, e.g. `[2, 3]` as opposed to `2/3`, are accepted. `m / n` as opposed to `m/n` is also fine. Two separate inputs `m` and `n` are also valid.

The Unicode fractions that must be handled are as follows:

```
½, ⅓, ⅔, ¼, ¾, ⅕, ⅖, ⅗, ⅘, ⅙, ⅚, ⅐, ⅛, ⅜, ⅝, ⅞, ⅑, ⅒

```

Thus, the possible inputs are as follows:

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

```

The Unicode codepoints of the characters are as follows:

```
188 ¼
189 ½
190 ¾
8528 ⅐
8529 ⅑
8530 ⅒
8531 ⅓
8532 ⅔
8533 ⅕
8534 ⅖
8535 ⅗
8536 ⅘
8537 ⅙
8538 ⅚
8539 ⅛
8540 ⅜
8541 ⅝
8542 ⅞

```

## Test Cases

```
1/2 -> ½
1/3 -> ⅓
2/3 -> ⅔
1/4 -> ¼
3/4 -> ¾
3/8 -> ⅜
1/10 -> ⅒

```

Make your code as short as possible; this is code golf.

# Answer
# JavaScript (Node.js), ~~78~~ 77 bytes

*Saved 1 byte thanks to @HermanLauenstein*

Takes input in currying syntax `(m)(n)`.

```
m=>n=>'¾⅗  ⅜    ⅞⅘½⅓¼⅕⅙⅐⅛⅑⅒⅚⅔⅝⅖'[(m*9+n)%31]

```

Try it online!
> 14 votes

# Answer
# Perl 6,  ~~48~~  43 bytes

```
{chr first *.unival==$^m/$^n,(|^191,|(8528..*))}

```

Try it

```
{chr first *.unival==$_,(|^191,|(8528..*))}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣
  chr

    first               # find the first value

      *.unival ==       # which has a unicode value that matches
          $_,           # the input fraction (as a Rational)

      (
        |^191,     # ¼(189) ½(188) ¾(190)
        |(8528..*) # all of the rest
      )
}

```

Note that the search has to be split up so that it doesn't return other Unicode characters that have the same unival. (otherwise it would be `(1..*)`)
> 12 votes

# Answer
# APL (Dyalog), ~~88~~ 64 bytes

```
{⎕UCS(⌊(⍺-1)÷(1+⍵≡8)⌈4×⍵≡6)-(291194049⊤⍨10⌿12)[⍵]-189⌈8539××⍵|4}

```

Try it online!

-3 thanks to dzaima.

Using ETHproductions's 84-byte approach.

The `f←` included on TIO isn't counted, since it's put there just to be able to test the function.
> 7 votes

# Answer
## JavaScript (ES6), ~~88~~ ~~86~~ ~~84~~ ~~81~~ 79 bytes

*Saved 2 bytes thanks to @Arnauld*

```
m=>n=>String.fromCharCode((4%n?8528:188)|"  130470912"[n]*1.3+~-m/-~"3 1"[n-6])

```

Not quite as short as the other JS answer, but it was fun to calculate the code-point of each fraction mathematically.

### Test snippet

```
let f =
m=>n=>String.fromCharCode((4%n?8528:188)|"  130470912"[n]*1.3+~-m/-~(n-6?n==8:3))

document.body.innerText = [
  [1,2],
  [1,3], [2,3],
  [1,4], [3,4],
  [1,5], [2,5], [3,5], [4,5],
  [1,6], [5,6],
  [1,7],
  [1,8], [3,8], [5,8], [7,8],
  [1,9],
  [1,10]
].map(([m,n])=>m+"/"+n+": "+f(m)(n)).join('\n')
```

Old method (82 bytes):

```
m=>n=>String.fromCharCode((4%n?8539:189)-("0x"+"  08162b0a9"[n])+~-m/-~"3 1"[n-6])

```

Saved 4 bytes on this one thanks to @Arnauld.
> 7 votes

# Answer
# SOGL V0.12, 51 bytes

```
5*+'æ%'⁵%"∫}ΣS“LI─{"#!“+ζ}¹"¾ŗŗŗŗŗŗ⅛ŗ⅜½⅝ŗ⅞ ⅓⅔ŗ  ¼”W

```

Try it Here!

uses the mapping `(m + n*5)%33%22`

Explanation:

```
5*                        multiply the 1st input by 5
  +                       add to the 2nd input
   'æ%                    modulo 33
      '⁵%                 module 22

"∫}ΣS“                    push 2153527158
      LI─                 base 11 decode that - [10 0 5 6 7 8 9 1 2]
         {     }          for each of that
          "#!“+             add 8528
               ζ            and convert to a character
                "...”     push "¾ŗŗŗŗŗŗ⅛ŗ⅜½⅝ŗ⅞ ⅓⅔ŗ  ¼", replacing ŗ with each character of the above array
                     W    and get the (m + n*5)%33%22th item from that

```
> 2 votes

# Answer
# Clojure, 127 bytes

```
(comp{2/3\⅔ 4/5\⅘ 1/3\⅓ 1/2\½ 5/6\⅚ 1/5\⅕ 1/4\¼ 3/5\⅗ 1/7\⅐ 3/4\¾ 2/5\⅖ 1/6\⅙ 1/9\⅑ 1/8\⅛ 3/8\⅜ 1/10\⅒ 5/8\⅝ 7/8\⅞}read-string)

```

An anonymous function that takes input as `"1/2"`, and returns the corresponding character.

A straight mapping from a Clojure `Ratio` to a fraction character. `comp`, and the fact that Clojure maps are functions really helped here. I needed to pass the string input through `read-string` to evaluate it as a ratio type, since that allows me to discard all the bloating quotes in the map. `comp` let me do that point-free, which was nice. The "full" code would be:

```
(defn to-unicode-fraction [frac]
  (get {2/3\⅔ 4/5\⅘ 1/3\⅓ 1/2\½ 5/6\⅚ 1/5\⅕ 1/4\¼ 3/5\⅗ 1/7\⅐,
        3/4\¾ 2/5\⅖ 1/6\⅙ 1/9\⅑ 1/8\⅛ 3/8\⅜ 1/10\⅒ 5/8\⅝ 7/8\⅞}
       (read-string frac)))

```

After looking over the other answers, I realized that this approach is pretty naïve. I'm looking for ways of improving it.
> 2 votes

# Answer
# Swift, ~~106~~ 82 bytes

*Port of @Arnaulds JavaScript answer*

*Saved 24 bytes thanks to @Mr.Xcoder*

```
{Array("¾⅗  ⅜    ⅞⅘½⅓¼⅕⅙⅐⅛⅑⅒⅚⅔⅝⅖")[($0*9+$1)%31]}

```

Try it online!
> 1 votes

# Answer
# Charcoal, ~~77~~ ~~48~~ 46 bytes

```
Ｆ§§⪪“YW³⦄Ｅν~vγ@⊖Ｘμ～?Iw⸿Ｍ➙b℅¦⦃”,ＮＮ℅⁺℅ι×⁹⁰∨№βι⁹⁴

```

Try it online! Link is to verbose version of code. Edit: Saved ~~29~~ 31 bytes by mapping from ASCII chars to multibyte chars. Explanation:

```
    “....”                  Compressed string `R,EFcGbIMDO,H J,K  Pd,L,N Q,`
   ⪪      ,                 Split on commas
           Ｎ                First input
  §                         Circularly index
            Ｎ               Second input
 §                          Circularly index
Ｆ                           "Loop over" character (loop variable `i`)
                     №βι    Count of `i`s in lowercase letters
                    ∨   ⁹⁴  Replace zero result with 94
                 ×⁹⁰        Multiply by 90
               ℅ι           Take ordinal of `i`
              ⁺             Sum
             ℅              Convert back to character
                            Implicitly print

```
> 1 votes

# Answer
# Python 3, 97 bytes

```
lambda m,n:'½ ⅓⅔ ¼_¾ ⅕⅖⅗⅘ ⅙___⅚ ⅐ ⅛_⅜_⅝_⅞ ⅑ ⅒'.split()[n-2][m-1]

```
> 0 votes

# Answer
# Python 3, 87 bytes

```
lambda n:'⅛⅑⅜¾⅗⅔⅚⅖⅝⅘⅞⅒½⅓¼⅕⅙⅐'[int(n[::2])%50%36%31%18]

```

Try it online!

or

```
lambda n:'⅝⅔⅜⅖__⅞¾⅗⅘_⅒½⅓¼⅕⅙⅐⅛⅑⅚'[int(n[::2])%36%27%22]

```

Try it online!
> 0 votes

# Answer
# Vim Script, 67 bytes

```
fu!F(m,n)
if a:n==10|norm a⅒
else|exe'norm a'.a:m.a:n
endif
endfu

```

The function works with Vim's *digraphs* which are entered after starting them iwth `ctrl-k.` Apparently, the relevant `ctrl-k` character after the `exe'norm` is not rendered in the code block above.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, unicode
---


# Question
Title: First and last prime numbers with prime digits of range
# Challenge

For a given positive integers range, find the first and last prime number entirely composed of prime number digits, exceptionally including 0 (for the **digits**, a range of 0-2 should output 2-2). The range is inclusive. If no number is found, the expected output is 0. If there is only one such number, the expected output is that number twice.

# Examples

* For the range 1–100, the first prime number is 2 and the last is 73 (7 and 3 are prime numbers).
* For the range 70–80, the first prime number is 73 and the last is also 73 (Since there is only one correct number in the given range, we return it twice).
* For the range 190–200, there is no correct answer, so you return 0.
* For the range 2000-2100, the first prime number is 2003 and the last is 2053 (we omit the digit 0, but all the other digits are prime)

This is , so the shortest code in bytes win!

All standard loopholes apply.

# Input

* You are free to accept two integers as input however you may see fit, stack, function argument(s), CLI argument, stdin.
* You **must** only receive two integers.

# Output

* You **must** either return the result (a tuple, an array, multi-return if your language supports it), leave it on the stack, or print it (in this case, they must be separated somehow).
* The order of the outputs is irrelevant.
* You are allowed leading/trailing brackets and newlines.
* You must return two numbers, if there is an answer, even if they are the same.
* You must return 0 if there is no answer.

# Answer
> 6 votes
# Python 2, 123 bytes

```
def f(a,b):r=[i for i in range(a,b+1)if(set(`i`)<=set('02357'))>any(i%k<1for k in range(3,i))];return len(r)and(r[0],r[-1])

```

Try it online!

# Answer
> 5 votes
# Perl 6, ~~105~~ ~~94~~ ~~90~~ 86 bytes

```
{my @b=grep {is-prime all($_,|.comb>>.Int Xor 2)},$^a..$^b;say @b??"@b[0] @b[*-1]"!!0}

```

# Answer
> 4 votes
# JavaScript (ES6), 83 bytes

Takes the range **\[a-b\]** in currying syntax `(a)(b)`. Returns either a 2-element array or **0**.

```
n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])

```

### Test cases

```
let f =

n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])

console.log(f(1)(100))
console.log(f(70)(80))
console.log(f(190)(200))
```

# Answer
> 4 votes
# Mathematica, 91 bytes

```
If[(s=Select[Range@##,(p=PrimeQ)@#&&And@@((p@#||#<1)&/@IntegerDigits@#)&])!={},MinMax@s,0]&

```

Try it online!

# Answer
> 3 votes
# Jelly, 14 bytes

```
æRµDo2ÆPẠµÐf.ị

```

Try it online!

### How it works

```
æRµDo2ÆPẠµÐf.ị ~ Full program.

æR             ~ Inclusive prime range.
  µ      µÐf   ~ Only keep those which satisfy a condition.
   Do2ÆPẠ      ~ The filter condition:
   D             ~ The decimal digits of the current number.
    o2           ~ Logical or with 2 (maps 0 to 2 and any other digit to itself).
      ÆP         ~ Is prime (element-wise)?
        Ạ        ~ Check whether all the digits satisfy the condition.
            .ị ~ Get the element at modular index 0.5. Some details:
                 ~ Jelly is 1-indexed, so 1 gives us the first element, whilst 0
                   gives us the last element.
                 ~ If the ceil and the floor of the given number N don't match,
                   then Jelly returns the items at indexes floor(N) **and** ceil(N).
                 ~ If the list is empty, this yields 0, hence it is very convenient.

```

---

If taking the whole range would be allowed (although I think it should not be), then 12 bytes:

```
Do2,ÆPȦµÐf.ị

```

Try it online!

# Answer
> 3 votes
# Pyth, 24 bytes

Using my initial approach turns out to be shorter.

```
.x,eKfP#I_M-+TjT;0}EQhKZ

```

**Try it here!**

(I was just updating to 23 but Steven beat me to it)

```
?KfP#I_M-+TjT;0}FQhM_BK0

```

**Try it here!**

Natually, `hM_BK` can be replaced by `,hKeK`.

### 25 bytes

```
.x,eKf.AmP_|d2+TjT;}EQhKZ

```

**Try it here!**

### 26 bytes

```
|>2.<f.AmP_|d2+TjT;*2}EQ1Z

```

**Try it here!**

```
|>2.<fP#I_M|R2+TjT;*2}EQ1Z

```

**Try it here!**

---

### How they work

```
.x,eKfP#I_M-+TjT;0}EQhKZ ~ Full program. Q, E = first, second inputs

.x                     Z ~ Try-catch block. If the code errors, output 0.
     f            }EQ    ~ Filter the range [E ... Q] for (uses a variable T):
            +TjT;          ~ Append T to the list of its digits.
           -     0         ~ Remove the zeros.
         _M                ~ Multiply each by -1 (for primality testing).
        I                  ~ Check if the result is invariant over...
      P#                   ~ Removing non-prime items.
    K                    ~ Assigned the filtered range to a variable K.
  ,e                     ~ Pair the last element of K with...
                     hK  ~ Its first element.

```

---

```
|>2.<f.AmP_|d2+TjT;*2}EQ1Z ~ Full program.

                   *2}EQ   ~ Inclusive range, repeated twice..
     f                     ~ Filter, using T as the current number.
                jT;        ~ Base-10 digits of T.
              +T           ~ Concatenated with T.
        mP_|d2             ~ Prime check after performing OR 2 (makes 0 be treated as prime)
      .A                   ~ Do all satisfy this condition?
   .<                   1  ~ Rotate by one place cyclically to the left.
 >2                        ~ Last two elements (ignored if there aren't enough)
|                        Z ~ Logical or with 0.

```

# Answer
> 3 votes
# Brachylog, 16 bytes

```
⟦₂{ṗṗᵐ}ˢ⟨⌋≡⌉⟩|∧0

```

Try it online!

The completely non-sensical "return 0 if there's no prime" makes us lose 3 bytes (`|∧0`) for no reason (it would return `false.` if we didnt add them)

### Explanation

```
⟦₂                Range from the smallest element of the input to the biggest
  {   }ˢ          Select on that range:
   ṗ                Numbers that are primes
    ṗᵐ              And whose digits are primes
        ⟨   ⟩     Fork on this new list:
         ⌋          Minimum
           ⌉        maximum
          ≡         Do nothing and return [Minimum, Maximum]
             |∧0  If all of this fails (i.e. the list after selection is empty), return 0

```

# Answer
> 2 votes
# Jelly, 14 bytes

```
Do2ÆPẠ
æRÇÐf.ị

```

Try it online!

```
æRÇÐf.ị            Main link
æR                 Prime range
   Ðf              Filter the range with...
  Ç                The helper link
      ị            At index (decimal, returns [xs[floor], xs[ceil]], otherwise 0)
     .             0.5

Do2ÆPẠ             Helper link
D                  For each decimal
 o2                Replace 0s with 2s, an actual prime prime (could be 3, 5, or 7).
   ÆP              Filter primes (1 if true, 0 if false)
     Ạ             Check if all are true

```

Thanks to Erik the Outgolfer for the help fixing a bug. Thanks to Mr. Xcoder for the `.ị` trick.

# Answer
> 2 votes
## Mathematica 85 Bytes

I know there is already a similar answer, but the approach here is quite different.

```
MinMax@Cases[Range@##,x_/;PrimeQ@x&&DisjointQ@@IntegerDigits/@{x,14689}]/.{_,∞}->0&

```

This 83 character answer will paste and run in Mathematica. The TIO site doesn't know how to interpret ∞.

# Answer
> 1 votes
# Ruby, 87 bytes

```
->a,b{(z=(a..b).select{|x|(2...x).none?{|r|x%r<1}&&/[14689]/!~"%d"%x})[0]?(z.minmax):0}

```

Try it online!

# Answer
> 1 votes
# CJam, 36 bytes

```
),>{mp},{s{_!\~mp|}%1-!},_{_0=\W=}0?

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~68 66 65 61~~  58 bytes

```
{($_=($^a..$^b).grep({.is-prime&&/^<[02357]>+$/})[0,*-1])[1]??$_!!0}

```

Try it

```
{($_=($^a..$^b).grep({.is-prime&&!/<[14689]>/})[0,*-1])[1]??$_!!0}

```

Try it

```
{($_=($^a..$^b).grep({.is-prime*!/<[14689]>/})[0,*-1])[1]??$_!!0}

```

Try it

```
{($_=($^a..$^b).grep({.is-prime*!/<[14689]>/}))??.[0,*-1]!!0}

```

Try it

```
{($_=grep {.is-prime*!/<[14689]>/},$^a..$^b)??.[0,*-1]!!0}

```

Try it

## Expanded:

```
{  # bare block lambda with two placeholder parameters ｢$a｣ and ｢$b｣

  (
    $_ =  # store the list in ｢$_｣ for later use

      grep {
          .is-prime

        *              # True * True == 1 (all others equal 0)

          !/<[14689]>/ # doesn't contain a non-prime other than 0
      },

      $^a .. $^b       # inclusive Range

  )            # is the list Truish (not empty)
  ?? .[0,*-1]  # if so output the first and last values (from ｢$_｣)
  !! 0         # otherwise return 0
}

```

# Answer
> 1 votes
# Perl 5, 79 + 2 (`-ap`) = 81 bytes

```
map{$f=0|sqrt;1while$_%$f--;$s||=$_,$\=-$_ if!$f&&!/[14689]/}$F[0]..$F[1];$_=$s

```

Try it online!

# Answer
> 1 votes
# Java 8, ~~165~~ ~~164~~ ~~163~~ 152 bytes

```
(a,b)->{for(;a<=b&p(a);a++);for(;b>a&p(b);b--);return a>b?"0":a+" "+b;}boolean p(int n){int i=1;for(;n%++i%n>0;);return!(n+"").matches("[02357]+")|i<n;}

```

-1 byte thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
(a,b)->{           // Method with two integer parameters and String return-type
                   //  (Input `a` is the lowest input, input `b` is the highest input)
  for(;a<=b        //  Increase `a` as long as it's smaller than or equal to `b`,
       &p(a);a++); //  and it's not a prime, and not all of its digits are prime-digits
  for(;b>a         //  Decrease `b` as long as it's larger than `a`,
       &p(b);b--); //  and it's not a prime, and not all of its digits are prime-digits
  return a>b?      //  If `a` is now larger than `b`:
    "0"            //   Return 0, because nothing is found
   :               //  Else:
    a+" "+b;}      //   Return the resulting `a` and `b`

// Separated method that'll result in true if the integer is NOT a prime number,
// or any of its digits are NOT prime numbers (excluding 0)
boolean p(int n){int i=1;for(;n%++i%n>0;);return!(n+"").matches("[02357]+")|i<n;}

```

# Answer
> 1 votes
# Clean, ~~142~~ ~~131~~ 125 bytes

```
import StdEnv
@a b#l=[n\\n<-[a..b]|and[gcd p n<2&&or[c==k\\k<-:"02357"]\\p<-[1..n-1],c<-:toString n]]
|l>[]=[hd l,last l]=[0]

```

Ungolfed:

```
import StdEnv
fn start finish
    # primes
        = [ n
            \\
            n <- [start..finish]
            | and [ gcd p n == 1 && isMember c ['0','2','3','5','7']
                \\
                p <- [1..n-1],
                c <-: toString n
            ]
        ]
    | isEmpty primes
        = [0]
    = [hd primes, last primes]

```

Try it online!

# Answer
> 1 votes
# Pyth, ~~28~~ ~~25~~ 23 bytes

```
.xhM_BfP#I_M #+TjT;}FQ0

```

Test suite. Returns \[2003,2053\] for the last test case, since 2053 is prime.

---
Tags: code-golf, number, primes
---


# Question
Title: Create a regex to match a given range of integers in a given radix
# Task

Write a program/function that, given three integers **n**,**a**,**b** prints a regular expression which matches all of the base-`n` integers from `a` to `b` (and no integers outside of that range).

Your algorithm should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type. (don't abuse native data type, that's a standard loophole)

# Input

Three integers, `n, a, b` where `n` is in the range 1-32. `a` and `b` may be taken as base-`n` string/character list/digit list.

# Output

A single string, represent the regex.

# Rules

* Base-n integers use the first `n` digits of `0123456789ABCDEFGHIJKLMNOPQRSTUV`, you can choose to use upper-case or lower-case.
* `a` and `b` may be negative, denoted by a `-` in front of the integer
* You may assume `a ≤ b`.
* Any regex flavor is allowed.
* The behavior of the regex on strings not a base-n integer is undefined.

# Winning criteria

Answers will be scored by the length of the code in bytes. (so rules apply)

# Answer
# 05AB1E, 17 bytes

```
ŸεD0‹'-×sÄIB«}'|ý

```

Try it online!

For some reason I don't seem to be able to replace `I` with `³`.
> 4 votes

# Answer
# Jelly, 24 bytes

```
ƓØBḣḊ;0
rµṠṾṖ$€ż⁸Aṃ¢¤j”|

```

Try it online!

Take 2 input from command line argument as decimal number, and base from stdin.
> 2 votes

# Answer
# Python 2, 157 bytes

```
n,a,b=input();s=o=''
for i in range(a,b+1):
 if i<0:i=abs(i);s='-'
 if i==0:o='0'+o
 while i:i,r=i/n,i%n;o=[`r`,chr(55+r)][r>9]+o
 o='|'+s+o;s=''
print o[1:]

```

Try it online!
> 1 votes

---
Tags: code-golf, regular-expression
---