title: That's a lot of monkeys

text:
# Question
Title: That's a lot of monkeys
The infinite monkey theorem states that, given infinite time, a machine sending an endless stream of random characters will always type any given text.

That sounds to me like a great idea for a challenge.

## Process

In order to monkey-ize a string A, the following steps should be taken:

1. Take an empty string. We will call this string B.
2. Pick a uniformly random printable ASCII character (characters in the range `0x20` to `0x7E`) and add that character to B.
3. If A is a substring of B, B is our monkey-ized string. Otherwise, repeat step 2 until A is a substring of B.

This process is only an example, easier methods may exist depending on your language. You do not need to follow this method exactly, as long as the same distribution of outputs is achieved.

## The challenge

Write a program or function that, given a non-empty string in any reasonable format, returns a monkey-ized version of that string.

Your program only has to practically work for inputs of length 3 or less. For longer inputs, it is allowed to terminate early with or without outputting anything.

## Example

Unfortunately, it's kind of hard to create examples for this question due to the random nature of it and the large outputs.

However, I can supply a single example for the input `hi`, on Hastebin.

## Scoring

Since this is , the submission with the fewest bytes wins.

# Answer
> 12 votes
# C, 192 bytes

```
i;g(s,b,i,n,j)char*s,*b;{for(b[i+1]=0;b[n+j];++n)s[n]-b[n+j]&&(n=-1,++j);return n;}f(char*s){char*b=calloc(strlen(s),1);for(i=0;s[i];)i=(b[i]=putchar(rand()%95+32))-s[i]?i?g(s,b,i,0,0):0:i+1;}

```

Try it online!

It's a mess now, but at least it works even for the corner cases...

---

# ~~C,  ~~63~~   ~~62~~  61 bytes~~

~~*Thanks to @Jonathan Frech for saving a byte!*<br>```
i;f(char*s){for(i=0;s[i=putchar(rand()%95+32)-s[i]?0:i+1];);}

```~~

~~Try it online!~~

# Answer
> 9 votes
# Python, 79 bytes

```
f=lambda x,s='':x in s and s or f(x,s+chr(randint(32,126)))
from random import*

```

Try it online!

This is theoretically sound, but will crash early due to python's recursion limits (you can set them further to get longer results)

# Python, 84 bytes

```
from random import*
x,s=input(),''
while x not in s:s+=chr(randint(32,126))
print(s)

```

Try it online!

This one is ought to work for relatively longer strings, since it doesn't rely on recursion, at the cost of 5 bytes.

# Answer
> 8 votes
# Ohm v2, 10 bytes

```
Ý£D³ε‽α@§↔

```

Try it online!

Explanation:

```
Ý£D³ε‽α@§↔  Main wire, arguments: a (string)

Ý           Push empty string to top of stack
 £          Start infinite loop
  D³ε‽        If a is a substring of the ToS, break out of the loop
      α@§     If not, select a random printable ASCII character...
         ↔    ...and concatenate it with the ToS

```

# Answer
> 7 votes
# Funky, 64 bytes

```
s=>{S=""whileS::sub((#S)-#s)!=s S+=S.char(math.random(32,126))S}

```

This uses a few tricks I've been wanting to use in Funky, like a variable name after a keyword as in `whileS`, and using the fact that strings implicitly parent to the `string` library.

## Ungolfed

```
function monkey(target){
    monkeyCode = ""
    while (monkeyCode::sub((#monkeyCode)-#target)!=target){
        monkeyCode += string.char(math.random(32,126))
    }
    monkeyCode
}

```

Try it online!

# Answer
> 7 votes
## GNU sed \+ coreutils, 75 + 1(r flag) = 76 bytes

```
h
:
s:.*:shuf -i32-126|dc -e?P:e
H;g
s:\n::2g
/^(.+)\n(.*)\1/{s::\2\1:;q}
b

```

Try it online! (It takes a lot of runs to get an answer for a length 2 input, because most of the time you run out of allowed TIO computation time.)

**Explanation:**

```
h                                # copy input string 'A' to hold space
:                                # start loop
    s:.*:shuf -i32-126|dc -e?P:e # run shell script: shuf outputs a rnd permutation
                                 #of the set of numbers from 32 to 126, and '?P' in
                                 #dc converts the 1st read decimal to an ASCII char
    H;g                          # append char to hold space ('A\n.'), then copy
                                 #result back to pattern space
    s:\n::2g                     # remove all '\n's from pattern space, but first
    /^(.+)\n(.*)\1/{             # if pattern is 'A\n.*A' (A substring of B), then
        s::\2\1:;q               # search previous regex used and leave only '.*A',
                                 #then quit (implicit printing before exit)
    }
b                                # repeat loop

```

**Benchmark:** approximate, for scaling purposes only

* input length: 1, 10 random inputs (runs), average time: \< 1 s
* input length: 2, 10 random inputs (runs), average time: 90 s
* input length: 3, 10 random inputs (runs), average time: lots of hours!

# Answer
> 7 votes
# Haskell, 100 bytes

```
import System.Random
s#(a:b)|and$zipWith(==)s$a:b=s|1>0=a:s#b
m a=(a#).randomRs(' ','~')<$>newStdGen

```

Try it online!

Basic idea is to generate an infinite list of characters with `randomRs` and stop it once we find the string.

# Answer
> 7 votes
# C# (.NET Core), 86 bytes

```
a=>{var b="";for(var r=new Random();!b.Contains(a);b+=(char)r.Next(32,127));return b;}

```

I don't really like how much creating the `Random` instance takes, but I don't think there's a way around it.

Try it online!

# Answer
> 6 votes
## Charcoal, ~~15~~ ~~14~~ 12 bytes

```
Ｗ¬№ωθ≔⁺ω‽γωω

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes due to a subsequent bug fix in Charcoal. Explanation:

```
    θ           Input string
   ω            Predefined variable `w`
  №             Count number of occurrences
 ¬              Logical not
Ｗ               Loop while true
       ω        Predefined variable `w`
      ⁺         Concatenated with
         γ      Predefined printable characters
        ‽       Random element
     ≔    ω     Assign to predefined variable `w`
           ω    Predefined variable `w`
                Implicitly print

```

# Answer
> 6 votes
# Perl 5, 31 +2 (-pa) bytes

```
}{$_.=chr 32+rand 95until/\Q@F/

```

Try it online

# Answer
> 6 votes
# , ~~79~~ ~~76~~ 75 bytes

*-3 bytes thanks to MickyT for changing the random sampler*

*-1 byte thanks to Robin Ryder for tweaking the random sampler again*

```
function(S){G=""
while(!grepl(S,G))G=paste0(G,intToUtf8(32+95*runif(1)))
G}

```

Try it online!

# Answer
> 6 votes
# Japt, 26 bytes

```
@(PbU >-1}a@P+=(Mq95 +32 d

```

Try it online!

# Answer
> 5 votes
# Ruby, 42 bytes

```
->w,s=""{s+=[*" "..?~].sample;s[w]?s:redo}

```

Try it online!

# Answer
> 4 votes
# Pyth - 14 bytes

```
.W!}zH+ZOrd\k

```

Try it online here.

# Answer
> 4 votes
# Mathematica, 65 bytes

```
""//.x_/;x~StringFreeQ~#:>x<>RandomChoice@CharacterRange[32,126]&

```

Try it online!

*-3 bytes from Jonathan Frech*

# Answer
> 4 votes
# Lua, ~~99~~ 102 bytes

* Saved a bug thanks to ATaco, which added three bytes.

```
function f(B)s=string S=""while not(s.find(S,B,1,1))do S=S..s.char(math.random(32,126))end print(S)end

```

Try it online!

# Answer
> 4 votes
# MATL, ~~17~~ 16 bytes

```
''`6Y2TZrhtGXfn~

```

Try it online!

-1 byte thanks to Giuseppe

# Answer
> 4 votes
# Octave, 62 bytes

```
t=input(o="");while(~nnz(regexp(o,t)))o=[o,randi(95)+31];end;o

```

Try it online!

Explanation:

```
t=input(o="");               % get stdin and define output
while(~nnz(regexp(o,t)))     % while no matches
    o=[o,randi(95)+31];      % concatenate string with ascii char
end;
o                            % output result

```

Many thanks to Luis Mendo for the edits!

# Answer
> 4 votes
# Japt, ~~16~~ ~~14~~ 11 bytes

```
;_øU}a@P±Eö

```

Try it

```
;_øU}a@P±Eö     :Implicit input of string U
 _              :Function taking a string as argument
  øU            :  Contains U
    }           :End function
     a@         :Get the first result of the following function that returns true
       P±       :  Append to P (initially the empty string)
;        E      :  ASCII
          ö     :  Random character

```

# Answer
> 3 votes
## Alice, 21 bytes

```
/U!?"$~dr@
\idwz K"o/

```

Try it online!

### Explanation

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

```

This is framework for mostly linear programs that operate entirely in Ordinal (string-processing) mode. The IP bounces diagonally up and down through the program twice, which means that the actual code is a bit weirdly interleaved. The commands in the order they're actually executed are:

```
i!w" ~"rUd?z$Kdo

```

Let's go through this:

```
i       Read all input.
!       Store the input on the tape for later.
w       Push the current IP address onto the return address stack.
        This marks the beginning of the main loop.

  " ~"    Push this string.
  r       Range expansion. Turns the string into " !...}~", i.e. a string
          with all printable ASCII characters.
  U       Random choice. Picks a uniformly random character from this
          string. This will remain on the stack throughout the rest of
          the program and will form part of the resulting string.
  d       Join stack. This takes all strings on the stack and joins them
          into a single string and pushes that (it does this without actually
          removing any elements from the stack).
  ?       Retrieve the input from the tape.
  z       Drop. If the joined string contains the input, everything up to
          and including the input will be discarded. Otherwise, nothing
          happens to the joined string. This means that the result will be
          an empty string iff the joined string ends with the input.
$K      If the top of the stack is not empty, jump back to the w to continue
        with another iteration of the main loop.
d       Join the stack into a single string once more.
o       Print it.

```

# Answer
> 3 votes
# Perl 6, 39 bytes

```
{("",*~(" ".."~").pick...*~~/$_/)[*-1]}

```

Try it online!

`(...)[*-1]` returns the last element of the sequence defined by `...`, of which:

* `""` is the first element;
* `* ~ (" " .. "~").pick` generates the next element by appending a random character in the appropriate range to the previous element; and
* `* ~~ /$_/` is the ending condition, which is that the current element matches the main function's input argument `$_` as a literal substring.

# Answer
> 3 votes
# Java 8, ~~81~~ ~~79~~ 78 bytes

```
a->{String b="";for(;!b.contains(a);b+=(char)(32+Math.random()*95));return b;}

```

-1 byte thanks to *@OlivierGrégoire* for pointing me to a (big \>.\<) mistake I've made..

**Explanation:**

Try it here.

```
a->{                    // Method with String as both parameter and return-type
  String b="";          //  Result-String, starting empty
  for(;!b.contains(a);  //  Loop as long as the result does not contain the input
    b+=(char)(32+Math.random()*95)
                        //   Append a random character to `b`
  );                    //  End of loop
  return b;             //  Return the result-String
}                       // End of method

```

# Answer
> 3 votes
# 05AB1E, ~~10~~ 9 bytes (-1 @ Emigna)

```
[žQΩJD¹å#

```

Try it online!

---

Do the monkey with me.

---

```
[              | Loop forever.
 žQ            | Push 0x20-0x7E as a single string.
   .R          | Pick from it randomly.
     J         | Join stack (B) with new char.
      D        | Duplicate (B).
       ¹å      | Push input (A) and check if input (A) is in (B).
         #     | If the previous statement is true, break loop.

```

# Answer
> 2 votes
# QBIC, 33 bytes

```
≈instr(Z,;)<1|Z=Z+chr$(_r32,126|)

```

## Explanation

```
≈instr( , )<1|   WHILE InStr() can't find
         ;        the input (cmd line string argument) as part of
       Z          the output (Z$, which is printed automatically on exit)
Z=Z+             add to the output
chr$(         )  an ASCII character
     _r32,126|   with a random codepoint between 32 and 126 (incl)

```

## Sample run:

```
Command line: hi

`;7L3f$qy )H99tZ@>(-Z1efL|Q-5'BE=P8BdX?Lem/fp|G#~WY[ Q4s9r~Af*T})P4`4d$#ud3AiuTwQPFS@8c7_59C$ GlJ%iJ[FA(rNt<y>Hl=r,wSbBB%q!8&#*CixW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g)+WZLLN9[ue073Q!F"J;X^49*$R'W%C.r~Fj&B`)tq[01a4En%H,kvyZG|,)%$44rJg[tq<wG9FjN<m@larki#;Bns%D}v_efPRH(OeRq0{=>Uc[~xcTcV_9|k54Q2*N.3]LlmFasY3"p =$$onbg$M+ReRsnH|9gV~#2?c1-V$35."DZH-O$~,c.gs]%,]p4\OFIW%l:,E,YT8FCeU8hy#lNq1lCpS 0I&q_*q>|=,(-dHuzi~6$GW22*A\w*&R< W`$HPRr,2A}3w\"Y?d%{2^xP:GqI\26A|.e'H2Z[M4=P.H87O~{)9|B*tHAC\j^S,StW!*snsz82R!:eD@uB4x+x&zSIN(3V|.^N_$=i=p}iK4h'v"$:I<t e:Y/XrSOF83=lkVNa0^k@jB@{ARE@r=Bja`(Bw>@?+`Wo,= u5HhXPeRMXS4@H#$-Jwg2"2-]%7p.o2Ar9J6Y1Ra?"3<oee&bpO^O{nw9=%\0brVNXrelWGoJyb/5W%MB0UBaPsc*29K<N~``NriWM$"eY0@xh^<$b:E/J~S%{#ry~6d?4Vv@^&9'=iBA#2U]bj9>UoJ#wQDN~6cB&/_Pu-XF?_hu3><(M7RW\%Ly@rTC9^b`?kVL~w%[{!&{#aS7<mc@J>ZaN7s}Y.c0:Y.\d&_[L{m|>|>%J^@!i9y0_lwejChi

```

# Answer
> 2 votes
# PHP, 55+1 bytes

```
while(!strpos(_.$argn,_.$s.=chr(rand(32,126))));echo$s;

```

Run as pipe with `-nR`. Not suitable for TIO cause of probable timeout.

Insert a space between the quotation marks for PHP older than 7.1.

This **51+1 bytes** version will fail if input is `0`:

```
while(!strstr($argn,$s.=chr(rand(32,126))));echo$s;

```

# Answer
> 2 votes
# Javascript 74 bytes

```
s=(a,b='')=>~b.search(a)?b:s(a,b+String.fromCharCode(32+Math.random()*95))

```

call like this:

```
s('hi')

```

# Answer
> 2 votes
# Pushy, ~~20~~ 18 bytes

```
LFZ^tCN[,` ~`U'x?i

```

**Try it online!**

The program keeps a stack `len(input)` characters long, and constantly removes the first and appends a new random char, until the initial input string is reached. Each character is printed as it is added, creating the desired effect.

Explanation:

```
                      \ == SETUP ==
 F                    \ Put input on second stack
L Z^tC                \ On the main stack, make length(input) copies of 0
      N               \ Remove printing delimiter (newline by default)

                      \ == MAIN LOOP ==

       [              \ Infinitely:
        ,             \    Pop the first item on stack
         ` ~`U        \    Add a new random character (between 32 and 126)
              '       \    Print this new character
               x?     \    If the stacks are now equal:
                 i    \        Exit program

```

# Answer
> 2 votes
# Julia 0.6, 53 bytes

```
a->(s="";while !contains(s,a) s*=randstring(1) end;s)

```

Try it online!

# Answer
> 2 votes
# Brachylog, 17 bytes

```
I⁰∧Ẹ{sI⁰&|;Ṭṛᵗc↰}

```

Try it online!

```
I⁰                   The global variable I⁰
                     is the input,
  ∧                  and
   Ẹ                 starting with the empty string
    {          ↰}    call this sub-predicate again
            ṛ        with a random
           Ṭ         printable ASCII character
          ;  ᵗc      appended to the string we're building
         |           unless
      I⁰             I⁰ (which is the input)
     s               is a substring of the string we've been building
        &            in which case the string is output.

```

Can randomly stack overflow. This makes use of two recently added features in Brachylog: global variables, and the apply-to-tail metapredicate .

# Answer
> 1 votes
# Pyth, 13 bytes

```
W!}z=akpOrd\

```

where the unprintable character is 0x7F.

Test

# Answer
> 1 votes
# Bash 94 bytes

```
p=printf\ -v;until [[ $s = *"$1" ]];do $p x %x $[32+RANDOM%95];$p c \\x$x;s+=$c;done;echo "$s"

```

Try it online

# Answer
> 1 votes
# Excel VBA, 84 bytes

```
Dim b
Sub m(a)
b=b &Chr(Int(113*Rnd+14))
If InStr(1,b,a)Then [A1]=b Else m a
End Sub

```

It's a straightforward implementation. Output is to cell `A1` in the active sheet

# Answer
> 1 votes
# Jelly, 17 bytes

```
³ẇ®¬
ḟµ;©ØṖX¤ø¢¿Ḋ

```

Try it online!

**Explanation**

```
³ẇ®¬            First link
³               Program input...
 ẇ              ...is a contiguous sublist of...
  ®             ...the register?
   ¬            Logical NOT

ḟµ;©ØṖX¤ø¢¿Ḋ    Main link
ḟ               Filter: With only one input this returns the empty list. Note ⁸ doesn't work here.
 µ              New monadic chain
    ØṖX¤        Random (X) element from printable ASCII (ØṖ).
  ;             Concatenate with the above
   ©            Copy the result of the concatenation with the above to check if program input is a sublist.
        ø       New niladic chain.
         ¢      Calls first link.
          ¿     Repeat the monadic chain until the first link returns false.
           Ḋ    Removes the first element of the result.
                For some reason (???) the integer 0 is always at the beginning of the result which needs to be removed.

```

Tested with one and two character inputs (two character sometimes takes a long time or seems to stall) but should work in theory for any length input.

The recursive solution I came up with below is slightly longer.

**Jelly, 19 bytes**

```
³ẇ®¬
;©ØṖX¤ßµ¢¡
ḟ`Ç

```

Try it online!

# Answer
> 1 votes
# , ~~38~~ ~~33~~ ~~30~~ 29 bytes

*-9 bytes thanks to FrownyFrog*

```
(],a.{~32+?@95}.~1#.E.)^:_&''

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~55~~ 73 bytes

<sup>+18 thanks to mazzy bringing it up to spec</sup>

```
for(;$args-cne-join($b+=[char](32..126|random))[-"$args".Length..-1]){}$b

```

Try it online!

First, it picks randomly an int from the printable range, casts that to a character, and appends it to our accumulator string. The monkeys will always form the word with the last character so keeps going until the ending of our generated string is the target word. So with that fact, it then compares the last `n` characters joined into a string (via reserve indexing) to the target.

# Answer
> 1 votes
# Thunno 2, 11 bytes

```
""($Ƈ~;kcɼ+

```

Attempt This Online!

#### Explanation

```
""($Ƈ~;kcɼ+  # Implicit input
""           # Starting with an empty string,
  ($Ƈ~       #  while the input is not in the top of stack:
      ;kcɼ+  #   add a random printable ASCII character
             # Implicit output

```

# Answer
> 1 votes
# Vyxal, ~~14~~ ~~13~~ 11 bytes (Test it)

```
¤{:?c¬|kQ℅+

```

Thanks to lyxal for -2 bytes!

# Answer
> 0 votes
# JavaScript 91 bytes

```
for(b="",a=prompt();b.search(a)<1;b+=String.fromCharCode(~~(Math.random()*95+32)));alert(b)

```

# Answer
> 0 votes
# Noether, 24 bytes

```
I~a""~b1(b94R32+BP+~ba/)

```

Try it online!

# Answer
> 0 votes
# Perl 6, 52 bytes

```
{("",*~(' '..'~').roll...*).grep(*.contains($_))[0]}

```

Try it online!

# Answer
> 0 votes
# Emacs Lisp, 113 bytes

```
(lambda(a)(let((case-fold-search)(b""))(while(not(string-match a b))(setq b(concat b(string(+(random 95)32)))))))

```

Try it online!

Try-it-online version has an additional byte for printing purposes.

`(case-fold-search)` assures `string-match` proper casing, it can be omitted depending on your Emacs configurations (18 bytes).

Better readable version:

```
((lambda (a)
    (let ((case-fold-search) (b ""))
      (while (not (string-match a b))
    (setq b (concat b (string (+ (random 95) 32)))))
      )))

```

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


title: Lengthen letter runs

text:
# Question
Title: Lengthen letter runs
Given a non-empty string of lowercase ASCII letters `a-z`, output that string with each consecutive “run” of the same letter lengthened by one more copy of that letter.

For example, `dddogg` (**3** `d`’s, **1** `o`, **2** `g`’s) turns into `ddddooggg` (**4** `d`’s, **2** `o`’s, **3** `g`’s).

This is : the shortest answer in bytes wins.

## Test cases

```
aabbcccc -> aaabbbccccc
doorbell -> ddooorrbbeelll
uuuuuuuuuz -> uuuuuuuuuuzz
q -> qq
xyxyxy -> xxyyxxyyxxyy
xxxyyy -> xxxxyyyy

```

# Answer
> 11 votes
# 05AB1E, 5 bytes

```
.¡€ĆJ

```

Explanation:

```
Example input: "dddogg"
.¡       Split into chunks of consecutive equal elements
         stack: [['ddd', 'o', 'gg']]
  €      For each...
   Ć       Enclose; append the first character to the end of the string
         stack: [['dddd', 'oo', 'ggg']]
    J    Join array elements into one string
         stack: ['ddddooggg']
Implicitly output top element in stack: "ddddooggg"

```

Try it online or as a test suite.

Enclose is a pretty new builtin; it's the first time I've used it. Very convenient ;)

# 05AB1E, 4 bytes

```
γ€ĆJ

```

has been replaced by `γ` in the latest update.

# Answer
> 15 votes
# Python 3, 44 bytes

```
for c in input():print(c,end=c[id==c:]);id=c

```

Try it online!

# Answer
> 10 votes
# Retina, 11 bytes

```
(.)\1*
$1$&

```

Try it online!

Replaces each run of characters with one of the run's characters followed by the run itself.

# Answer
> 8 votes
# Pyth, 7 bytes

```
r9hMMr8

```

Test suite.

## How it works

```
r9hMMr8  example input: "xxyx"
     r8  run-length encoding
         [[2, "x"], [1, "y"], [1, "x"]]
  hMM    apply h to each item
         this takes advantage of the overloading
         of h, which adds 1 to numbers and
         takes the first element of arrays;
         since string is array of characters in
         Python, h is invariant on them
         [[3, "x"], [2, "y"], [2, "x"]]
r9       run-length decoding
         xxxyyxx

```

# Answer
> 7 votes
# MATL, 5 bytes

```
Y'QY"

```

Try it online!

### Explanation

Consider input `'doorbell'`.

```
Y'    % Implicit input. Run-length encoding
      % STACK: 'dorbel', [1 2 1 1 1 2]
Q     % Increase by 1, element-wise
      % STACK: 'dorbel', [2 3 2 2 2 3]
Y"    % Run-length decoding. Implicit display
      % STACK: 'ddooorrbbeelll'

```

# Answer
> 6 votes
## Alice, 17 bytes

```
/kf.>o./
@i$QowD\

```

Try it online!

### Explanation

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

```

This is a framework for programs which operate entirely in Ordinal mode and are essentially linear (simple loops can be written, and one is used in this program, but it's trickier to work with otherwise branching control flow here). The instruction pointer bounces diagonally up and down through the code from left to right, then gets shifted by one cell by the two mirrors at the end, and the moves back from right to left, executing the cells it skipped on the first iteration. The linearised form (ignoring the mirrors) then basically looks like this:

```
ifQ>w.Doo.$k@

```

Let's go through this:

```
i     Read all input as a string and push it to the stack.
f     Split the string into runs of equal characters and push those
      onto the stack.
Q     Reverse the stack, so that the first run is on top.
>     Ensure that the horizontal component of the IP's movement is east.
      This doesn't do anything now, but we'll need it after each loop
      iteration.
w     Push the current IP address to the return address stack. This marks
      the beginning of the main loop.

  .     Duplicate the current run.
  D     Deduplicate the characters in that run so we just get the character
        the run is made up of.
  o     Output the character.
  o     Output the run.
  .     Duplicate the next run. When we've processed all runs, this will
        duplicate an implicit empty string at the bottom of the stack instead.
  $     If the string is non-empty (i.e. there's another run to process),
        execute the next command otherwise skip it.

k     Pop an address from the return address stack and jump there. Note that
      the return address stack stores no information about the IP's direction,
      so after this, the IP will move northwest from the w. That's the wrong
      direction though, but the > sets the horizontal component of the IP's
      direction to east now, so that the IP passes over the w again and can
      now execute the next iteration in the correct direction.
@     Terminate the program.

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
Œg;Q$€

```

Try it online!

Only works as a full program (i.e. stringified output).

# Answer
> 4 votes
# Brachylog, 8 bytes

```
ḅ{t,?}ᵐc

```

Try it online!

### Explanation

```
             Example input: "doorbell"
ḅ            Blocks: ["d","oo","r","b","e","ll"]
 {   }ᵐ      Map: ["dd","ooo","rr","bb","ee","lll"]
  t            Tail: "d" | "o" | "r" | "b" | "e" | "l"
   ,?          Prepend to input: "dd" | "ooo" | "rr" | "bb" | "ee" | "lll"
       c     Concatenate: "ddooorrbbeelll"

```

# Answer
> 4 votes
## C, 49 bytes

```
i;f(char*s){for(;putchar(*s);)i=s[i]^s[1]||!s++;}

```

See it work online.

# Answer
> 3 votes
# Python 2, 47 bytes

```
f=lambda s:s and-~(s[0]*2!=s[:2])*s[0]+f(s[1:])

```

Try it online!

# Answer
> 3 votes
# PHP, 40 Bytes

```
<?=preg_filter('#(.)\1*#',"$1$0",$argn);

```

Online Version

## PHP\<7.1, 44 Bytes

Version without Regex

```
for(;a&$c=$argn[$i++];)echo$c[$c==$l].$l=$c;

```

Online Version

# Answer
> 3 votes
# C, 53 bytes

```
i;f(char*s){for(;i=*s++;)putchar(i^*s?putchar(i):i);}

```

Try it online!

# Answer
> 3 votes
# Japt, 8 bytes

7 bytes of code, +1 for the `-P` flag.

```
ó¥ ®+Zg

```

Test it online!

### Explanation

This uses the `ó` (partition on falsy) built-in that I just added yesterday:

```
ó¥  ®   +Zg
ó== mZ{Z+Zg}

ó==           // Split the input into runs of equal chars.
    mZ{    }  // Replace each item Z in this array with
       Z+Zg   //   Z, concatenated with the first char of Z.
-P            // Join the resulting array back into a string.
              // Implicit: output result of last expression

```

# Answer
> 3 votes
# Hexagony, 33 bytes

```
\~..,}/',\<.-/.<@;$>.${;/${/"$.>$

```

### Expanded:

```
   \ ~ . .
  , } / ' ,
 \ < . - / .
< @ ; $ > . $
 { ; / $ { /
  " $ . > $
   . . . .

```

Try it online!

The pseudo-code is more or less:

```
char = readchar()
while (char > 0)
    print(char)
    run_char = char
    do
        print(char)
        char = readchar()
    while (run_char == char)

```

# Answer
> 3 votes
# Jelly, 5 bytes

```
n2\×ż

```

Try it online!

### How it works

```
n2\×ż  Main link. Argument: s (string)

n2\    Reduce all overlapping slices of length two by non-equal.
       For input "doorbell", this returns [1, 0, 1, 1, 1, 1, 0].
   ×   Multiply the characters of s by the Booleans in the resulting array. This is
       essentially a bug, but integer-by-string multiplication works as in Python.
       For input "doorbell", this returns ['d', '', 'o', 'r', 'b', 'e', '', 'l'].
       Note that the last character is always left unchanged, as the Boolean array
       has one fewer element than s.
    ż  Zip the result with s, yielding an array of pairs.
       For input "doorbell", this returns [['d', 'd'], [[], 'o'], ['o', 'o'],
           ['r', 'r'], ['b', 'b'], ['e', 'e'], [[], 'l'], ['l', 'l']].
       (implicit) Print the flattened result.

```

# Answer
> 3 votes
# JavaScript (ES6), ~~33~~ 30 bytes

```
s=>s.replace(/(.)\1*/g,"$1$&")

```

---

## Try It

```
f=
s=>s.replace(/(.)\1*/g,"$1$&")
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("aabbcccc")) // aaabbbccccc
console.log(f("doorbell")) // ddooorrbbeelll
console.log(f("uuuuuuuuuz")) // uuuuuuuuuuzz
console.log(f("q")) // qq
console.log(f("xyxyxy")) // xxyyxxyyxxyy
console.log(f("xxxyyy")) // xxxxyyyy
```

```
<input id=i><pre id=o>
```

# Answer
> 3 votes
# brainfuck, 23 bytes

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

```

Try it online!

### Explanation

```
,            read the first input character
 [           main loop to be run for each input character
 .           output the character once
 [->->+<<]   subtract from previous character (initially 0), and create a copy of this character
 >[          if different from previous character:
   [-]       zero out cell used for difference (so this doesn't loop)
   >.<       output character again from copy
 ]
 ,           read another input character
]

```

# Answer
> 3 votes
# Thunno 2 `J`, 3 bytes

```
ġ€ẹ

```

Try it online!

#### Explanation

```
ġ€ẹ  # Implicit input
ġ    # Group consecutive
 €   # Single function map:
  ẹ  #  Enclose (append
     #  first character)
     # Join into a string
     # Implicit output

```

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
.¡DÔ‚ø˜J

```

Try it online!

Explanation:

```
.¡DÔ‚ø˜J
.¡       Split equal runs of input
  D      Duplicate
   Ô     Take connected-uniquified
    ‚    Pair connected-uniquified equal runs with original equal runs
     ø   Zip
      ˜  Deep-flatten (i.e. normal flattening)
       J Join elements together

```

# Answer
> 2 votes
# Perl 6, 18 bytes

```
{S:g/)>(.)$0*/$0/}

```

Try it

## Expanded:

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

  S        # replace and return
  :global  # all occurrences
  /

    )>     # don't actually remove anything after this

    (.)    # match a character

    $0*    # followed by any number of the same character

  /$0/     # replace with the character (before the match)
}

```

# Answer
> 2 votes
## Haskell, 36 bytes

```
f(a:b:c)=a:[a|a/=b]++f(b:c)
f x=x++x

```

Usage example: `f "aab"` -\> `"aaabb"`. Try it online!

When the string has at least two chars, bind `a` to the first char, `b` to he second and `c` to the rest of the string. The output is `a` followed by `a` if `a` is not equal to `b` followed by a recursive call with `b:c`. If there's only one char, the result is two times this char.

# Answer
> 2 votes
## CJam, 10 bytes

```
le`1af.+e~

```

Try it online!

Explanation:

```
e# Input: doorbell
l   e# Read line:              | "doorbell"
e`  e# Run-length encode:      | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]]
1a  e# Push [1]:               | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]] [1]
f.+ e# Vectorized add to each: | [[2 'd] [3 'o] [2 'r] [2 'b] [2 'e] [3 'l]]
e~  e# Run-length decode:      | "ddooorrbbeelll"
e# Implicit output: ddooorrbbeelll

```

# Answer
> 2 votes
# Ruby, 30 bytes

```
->s{s.gsub(/((.)\2*)/){$1+$2}}

```

# Answer
> 2 votes
# APL (Dyalog) with AGL, 11 bytes

```
⊢é⍨2-0,2=/,

```

Try it online!

`,` ravel\*

`2=/` pair-wise comparison (shows which characters to leave as-is)

`0,` prepend a zero (indicating that the initial character should be duplicated)

`2-` subtract that from two (gives 2 for the letters which need to be duplicated, and 1 for the rest)

`⊢é⍨` replicate the argument using that (`é` is just the function `/`)

---

<sup>* This is a no-op on strings, but makes scalar characters into strings. Not required, as argument should be a string, but it makes the tests look neater, and we need a no-op function here anyway. To remove this feature, use  instead of `,`.</sup>

# Answer
> 1 votes
# Mathematica, ~~34~~ 21 bytes

*Thanks to Martin Ender for finding the* right *way to do this in Mathematica, saving 13 bytes!*

```
##&[#,##]&@@@Split@#&

```

Pure function using an array of characters as both input and output formats. `Split` separates a list into its runs of equal characters. `##&[#,##]&` is a function that returns a sequence of arguments: the first argument it's fed, then all of the arguments (so repeating the first one in particular); this is applied (`@@@`) to every sublist of the `Split` list.

# Answer
> 1 votes
## Batch, 140 bytes

```
@set/ps=
@set r=
:g
@if not "%s:~,1%"=="%s:~1,1%" set r=%r%%s:~,1%
@set r=%r%%s:~,1%
@set s=%s:~1%
@if not "%s%"=="" goto g
@echo %r%

```

Takes input on STDIN.

# Answer
> 1 votes
## sed, ~~18~~ 15 bytes (+1 for -r)

```
s/(.)\1*/\1&/g

```

## Original solution

```
s/((.)\2*)/\1\2/g

```

# Answer
> 1 votes
## R, 36 bytes

```
gsub("((.)\\1*)","\\2\\1",scan(,""))

```

# Answer
> 1 votes
# Java, ~~151~~ ~~146~~ 60 bytes

```
String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}

```
* -5 bytes, thanks to @FryAmTheEggman
* -86 bytes, thanks to @KevinCruijssen

**Regex**

```
(         )     group

 (.)            a character

     \\2*       optional repetition

```

**Detailed**

```
import java.util.*;
import java.lang.*;
import java.io.*;

class H
{
    public static String f(String s)
    {
        return s.replaceAll("((.)\\2*)","$1$2");
    }

    public static void main(String[] args)
    {
        f("dddogg");
    }
}

```

# Answer
> 1 votes
## PowerShell, 50 bytes

```
{-join([char[]]$_|%{if($_-ne$p){($p=$_)}$_});rv p}

```

Try it online!

# Answer
> 1 votes
# brainfuck, 38 bytes

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

```

Try it online!

```
,.               print the "doubling" of the first char of input
[                this main loop runs on every char
  .              print it "normally" (the not-doubling)
  >,             read the next char
  [              judiciously placed "loop" to prevent printing NULs
    [->+>+<<]    copy new char at position p to p+1 and p+2
    <[->>-<<]>>  subtract old char from p+1 - zero if same, nonzero otherwise
    [            if it *is* different (nonzero)...
      [-]        clear it
      >.<        print the char (at p+2 now) again
    ]
  ]
  >              the new char is now the old char
]

```

# Answer
> 1 votes
# Alice, 12 bytes

*Two bytes were golfed thanks to Martin Ender even before this answer was posted. He's more powerful than you could ever imagine.*

```
I4&.h%?-$OO!

```

Try it online!

### Explanation

```
I                 Input a character and push its unicode value
 4&.              Push 4 more copies of this value to the stack
                  (they will be needed for the following operations)
    h%            Try to compute n%(n+1), exits with an error if n==-1
                  which happens on EOF
      ?           Push a copy of what's currently on the tape.
                  In the first iteration this will push -1, in following
                  iterations it will push the previous character.
       -$O        If the two topmost values on the stack are different
                  output the third one. This will output one more copy of
                  any new character encountered.
          O       Output this character.
           !      Store this character on the tape.

                  Execution loops back to the beginning of the line.

```

# Answer
> 1 votes
# Vyxal `d`, 3 bytes

```
ĠvǏ

```

Try it Online!

# Answer
> 1 votes
# Vyxal, 9 bytes (Try it)

```
øeƛ÷›";ød

```

# Answer
> 0 votes
# , 9 bytes

```
Í¨.©±*/&±

```

Try it online!

# Answer
> 0 votes
# Javascript ES6, ~~56~~ 46 bytes

```
b=>[...b].map((c,i,a)=>a[i+1]!=c?c+c:c).join``

```

Saved 10 bytes thanks to @Shaggy using spread operator and `c+c`

---

# Try it

```
f=

b=>[...b].map((c,i,a)=>a[i+1]!=c?c+c:c).join``

console.log(f("aabbcccc")); //aaabbbccccc
console.log(f("uuuuuuuuuz")); //uuuuuuuuuuzz
console.log(f("q")); //qq
console.log(f("xyxyxy")); //xxyyxxyyxxyy
console.log(f("xxxyyy")); //xxxxyyyy
```

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

---

### Data

* **Input** The string to be *stretched*
* **Output** The *stretched* string

---

### Golfed

```
(string i)=>{var t=' ';for(int x=0;x<i.Length;x++)if(i[x]!=t){i=i.Insert(x,t+"");t=i[x+1];}i=i.Trim()+t;return i;};

```

---

### Ungolfed

```
( string i ) => {
   var t = ' ';

   for( int x = 0; x < i.Length; x++ )
      if( i[ x ] != t ) {
         i = i.Insert( x, t + "" );
         t = i[ x + 1 ];
      }

   i = i.Trim() + t;

   return i;
};

```

---

### Ungolfed readable

```
// Takes a string to be stretched
( string i ) => {

   // Creates a temp var to hold the chars
   var t = ' ';

   // Cycles through every char in the string
   for( int x = 0; x < i.Length; x++ )

      // Checks if the temp var is different to the current one
      if( i[ x ] != t ) {

         // If so, insert a new char in the middle
         i = i.Insert( x, t + "" );

         // Stores the new char
         t = i[ x + 1 ];
      }

   // Removes the trailling space added due to the temp var
   i = i.Trim() + t;

   // Return the stretched string
   return i;
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String> f = ( int[] i ) => {
            var t = ' ';

            for( int x = 0; x < i.Length; x++ )
               if( i[ x ] != t ) {
                  i = i.Insert( x, t + "" );
                  t = i[ x + 1 ];
               }

            i = i.Trim() + t;

            return i;
         };

         List<String>
            testCases = new List<String>() {
               "a",
               "ab",
               "aab",
               "abcdvaabb",
               "aasd231",
               "",
            };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" );
         }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.0** \- `115 bytes` \- Initial solution.

---

### Notes

* None

# Answer
> 0 votes
# Cubix, 19 ~~23~~ bytes

```
A.?@WW>o-!wu;W>1$o;

```

Try it online!

```
    A .
    ? @
W W > o - ! w u
; W > 1 $ o ; .
    . .
    . .

```

~~I think I can take a couple of this yet, but running out of steam and will probably come back to this later~~. General algorithm hasn't changed much, just the program flow.

* `W` redirect to top face heading down
* `A` put all input onto stack
* `?@` test for end of input and exit if
* `W>o` if positive (should be) W changes lane which put the IP on the \> redirecting to the output
* `-!wu` check against next char using subtraction, if truthy (different) jump the lane change on the u-turn
* from the u-turn in execution order `;o$1>1$o`. This drops the difference; outputs the char; skips the 1; redirects back; push sacrificial 1; skips the output
* from the end of the u-turn and the beginning of the lane change `;.;WW`. Drops the top 2 items from the stack; Change lane; Change lane. This puts the IP back on the `?` in the third step. Rinse and repeat.

# Answer
> 0 votes
# Swift, 61 bytes

```
var b="ab".characters.map {"\($0)"},c="";for a in b{c=c+a+a;}

```

# Answer
> 0 votes
# Prolog (SWI), 51 bytes

```
\A:-get(C),C>0,(C=A;A<1;put(A)),put(C),\C;!.
:- \0.

```

Try it online!

# Answer
> 0 votes
# Arturo, 30 bytes

```
$=>[replace&{/((.)\2*)}"$1$2"]

```

Try it!

Non-regex answer:

# Arturo, 38 bytes

```
$=>[chunk&=>[&]|map'x->x++x\0|flatten]

```

Try it!

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


title: Is it a Sphenic Number?

text:
# Question
Title: Is it a Sphenic Number?
A Sphenic Number is a number that is the product of exactly three distinct primes. The first few Sphenic numbers are `30, 42, 66, 70, 78, 102, 105, 110, 114`. This is sequence A007304 in the OEIS.

## Your Task:

Write a program or function to determine whether an inputted integer is a Sphenic number.

## Input:

An integer between 0 and 10^9, which may or may not be a Sphenic Number.

## Output:

A truthy/falsy value indicating whether the input is a Sphenic Number.

## Examples:

```
30  -> true
121 -> false
231 -> true
154 -> true
4   -> false
402 -> true
79  -> false
0   -> false
60  -> false
64  -> false
8   -> false
210 -> false

```

## Scoring:

This is , shortest code in bytes wins.

# Answer
# Brachylog, ~~6~~ 3 bytes

```
ḋ≠Ṫ

```

Try it online!

### Explanation

```
ḋ        The prime factorization of the Input…
 ≠       …is a list of distinct elements…
  Ṫ      …and there are 3 elements

```
> 8 votes

# Answer
## bash, 43 bytes

```
factor $1|awk '{print $2-$3&&$3-$4&&NF==4}'

```

Try it online!

Input via command line argument, outputs `0` or `1` to stdout.

Fairly self-explanatory; parses the output of `factor` to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors).
> 12 votes

# Answer
# MATL, 7 bytes

```
_YF7BX=

```

Try it online! Or verify all test cases.

### Explanation

```
_YF   % Implicit input. Nonzero exponents of prime-factor decomposition
7     % Push 7
B     % Convert to binary: gives [1 1 1]
X=    % Is equal? Implicit display

```
> 11 votes

# Answer
# C, ~~88~~ ~~78~~ ~~126~~ ~~58~~ ~~77~~ 73 + 4 (`lm`) = 77 bytes

```
l,j;a(i){for(l=1,j=0;l++<i;fmod(1.*i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}

```

Ungolfed commented explanation:

```
look, div; //K&R style variable declaration. Useful. Mmm.

a ( num ) { // K&R style function and argument definitions.

  for (
    look = 1, div = 0; // initiate the loop variables.
    look++ < num;) // do this for every number less than the argument:

      if (fmod(1.0 * num / look, look))
      // if num/look can't be divided by look:

        if( !(num % look) ) // if num can divide look
          num /= look, div++; // divide num by look, increment dividers
      else div = 9;
      // if num/look can still divide look
      // then the number's dividers aren't unique.
      // increment dividers number by a lot to return false.

  // l=j==3;
  // if the function has no return statement, most CPUs return the value
  // in the register that holds the last assignment. This is equivalent to this:
  return (div == 3);
  // this function return true if the unique divider count is 3
}

```

Try it online!
> 9 votes

# Answer
# Jelly, 8 bytes

```
ÆEḟ0⁼7B¤

```

Try it online!

Uses Luis Mendo's algorithm.

Explanation:

```
ÆEḟ0⁼7B¤
ÆE       Prime factor exponents
  ḟ0     Remove every 0
    ⁼7B¤ Equal to 7 in base 2?

```
> 5 votes

# Answer
# CJam, 11 bytes

```
rimFz1=7Yb=

```

Try it online! Or verify all test cases.

### Explanation

Based on my MATL answer.

```
ri    e# Read integer
mF    e# Factorization with exponents. Gives a list of [factor exponent] lists
z     e# Zip into a list of factors and a list of exponents
1=    e# Get second element: list of exponents
7     e# Push 7
Yb    e# Convert to binary: gives list [1 1 1]
=     e# Are the two lists equal? Implicitly display

```
> 5 votes

# Answer
# Jelly, 6 bytes

```
ÆE²S=3

```

Try it online!

### How it works

```
ÆE²S=3  Main link. Argument: n

ÆE      Compute the exponents of n's prime factorization.
  ²     Take their squares.
   S    Take the sum.
    =3  Test the result for equality with 3.

```
> 5 votes

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

```
ÓnO3Q

```

Try it online!

Uses Dennis's algorithm.
> 4 votes

# Answer
# Ruby, ~~81~~ ~~49~~ 46 bytes

Includes 6 bytes for command line options `-rprime`.

```
->n{n.prime_division.map(&:last)==[1]*3}

```

Try it online!
> 4 votes

# Answer
# Husk, 6 bytes

```
≡ḋ3Ẋ≠p

```

Try it online!

Returns 1 for sphenic numbers and 0 otherwise.

### Explanation

```
≡ḋ3Ẋ≠p    Example input: 30
     p    Prime factors: [2,3,5]
   Ẋ≠     List of absolute differences: [1,2]
≡         Is it congruent to...       ?
 ḋ3           the binary digits of 3: [1,1]

```

In the last passage, congruence between two lists means having the same length and the same distribution of truthy/falsy values. In this case we are checking that our result is composed by two truthy (i.e. non-zero) values.
> 4 votes

# Answer
# Mathematica, 31 bytes

```
SquareFreeQ@#&&PrimeOmega@#==3&

```
> 4 votes

# Answer
# Pyth, 9 bytes

```
&{IPQq3lP

```

Try it here.
> 2 votes

# Answer
# Actually, 7 bytes

```
w♂N13α=

```

Try it online!

Explanation:

```
w♂N13α=
w       Push [prime, exponent] factor pairs
 ♂N     Map "take last element"
   1    Push 1
    3   Push 3
     α  Repeat
      = Equal?

```
> 2 votes

# Answer
# Haskell, 59 bytes

```
f x=7==sum[6*0^(mod(div x a)a+mod x a)+0^mod x a|a<-[2..x]]

```

Try it online!
> 2 votes

# Answer
# Japt, 14 bytes

```
k
k@è¥X ÉÃl ¥3

```

Try it online!
> 2 votes

# Answer
# , 15 bytes

```
7&(=2#.~:@q:)~*

```

Try it online!

## Explanation

```
7&(=2#.~:@q:)~*  Input: integer n
              *  Sign(n)
7&(         )~   Execute this Sign(n) times on n
                 If Sign(n) = 0, this returns 0
          q:       Prime factors of n
       ~:@         Nub sieve of prime factors
    2#.            Convert from base 2
   =               Test if equal to 7

```
> 2 votes

# Answer
# Dyalog APL, 26 bytes

```
⎕CY'dfns'
((≢,∪)≡3,⊢)3pco⎕

```

Try it online!
> 2 votes

# Answer
# Mathematica, 44 bytes

```
Plus@@Last/@#==Length@#==3&@FactorInteger@#&

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~54~~ 53 bytes

```
lambda n:sum(1>>n%k|7>>k*k%n*3for k in range(2,n))==6

```

*Thanks to @xnor for golfing off 1 byte!*

Try it online!
> 2 votes

# Answer
**C, 91 102 bytes, corrected (again), golfed, and tested for real this time:**

```
<strike>s(c){p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}c==p&&f==2&&!d;}</strike>
s(c){int p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}return c==p&&f==2&&!d;}

```

/\* This also works in 93 bytes, but since I forgot about the standard rules barring default int type on dynamic variables, and about the not allowing implicit return values without assignments, I'm not going to take it:

```
p,f,d;s(c){for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}p=c==p&&f==2&&!d;}

```

(Who said I knew anything about C? ;-)

Here's the test frame with shell script in comments:

```
/* betseg's program for sphenic numbers from
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h> /* compile with -lm */

/* l,j;a(i){for(l=1,j=0;l<i;i%++l?:(i/=l,j++));l=i==1&&j==3;} */
#if defined GOLFED
l,j;a(i){for(l=1,j=0;l++<i;fmod((float)i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}
#else
int looker, jcount;
int a( intval ) {
  for( looker = 1, jcount = 0;
    looker++ < intval;
    /* Watch odd intvals and even lookers, as well. */
    fmod( (float)intval/looker, looker )
      ? intval % looker /* remainder? */
        ? 0 /* dummy value */
        : ( inval /= looker, jcount++ /* reduce the parameter, count factors */ )
      : ( jcount = 9 /* kill the count */ )
  )
    /* empty loop */;
  looker = intval == 1 && jcount == 3; /* reusue looker for implicit return value */
}
#endif

/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */

```

I borrowed betseg's previous answer to get to my version.

This is my version of betseg's algorithm, which I golfed to get to my solution:

```
/* betseg's repaired program for sphenic numbers
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int sphenic( int candidate )
{
  int probe, found, dups;
  for( probe = 2, found = dups = 0; probe < candidate && !dups; /* empty update */ )
  {
    int remainder = candidate % probe;
    if ( remainder == 0 )
    {
      candidate /= probe;
      ++found;
      if ( ( candidate % probe ) == 0 )
        dups = 1;
    }
    ++probe;
  }
  return ( candidate == probe ) && ( found == 2 ) && !dups;
}

int main( int argc, char * argv[] ) { /* Make it command-line callable: */
  int parameter;
  if ( ( argc > 1 )
       && ( ( parameter = (int) strtoul( argv[ 1 ], NULL, 0 ) ) < ULONG_MAX ) ) {
    puts( sphenic( parameter ) ? "true" : "false" );
  }
  return EXIT_SUCCESS;
}

/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */

```
> 2 votes

# Answer
# J, 23 bytes

```
0:`((~.-:]*.3=#)@q:)@.*

```

Try it online!

Handling 8 and 0 basically ruined this one...

`q:` gives you all the prime factors, but doesn't handle 0. the rest of it just says "the unique factors should equal the factors" and "the number of them should be 3"
> 1 votes

# Answer
# Python 2, ~~135~~ 121 bytes

* Quite long since this includes all the procedures: prime-check, obtain-prime factors and check sphere number condition.

```
lambda x:(lambda t:len(t)>2and t[0]*t[1]*t[2]==x)([i for i in range(2,x)if x%i<1and i>1and all(i%j for j in range(2,i))])

```

Try it online!
> 1 votes

# Answer
# Python 2, 59 bytes

```
lambda x:6==sum(5*(x/a%a+x%a<1)+(x%a<1)for a in range(2,x))

```

Try it online!
> 1 votes

# Answer
# Javascript (ES6), 87 bytes

```
n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])

```

Example code snippet:

```
f=
n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])

for(k=0;k<10;k++){
  v=[30,121,231,154,4,402,79,0,60,64][k]
  console.log(`f(${v}) = ${f(v)}`)
}
```
> 1 votes

# Answer
# PHP, 66 bytes:

```
for($p=($n=$a=$argn)**3;--$n;)$a%$n?:$p/=$n+!++$c;echo$c==7&$p==1;

```

Run as pipe with `-nR` or try it online.

Infinite loop for `0`; insert `$n&&` before `--$n` to fix.

**breakdown**

```
for($p=($n=$a=$argn)**3;    # $p = argument**3
    --$n;)                  # loop $n from argument-1
    $a%$n?:                     # if $n divides argument
        $p/=$n                      # then divide $p by $n
        +!++$c;                     # and increment divisor count
echo$c==7&$p==1;            # if divisor count is 7 and $p is 1, argument is sphenic

```

**example**
argument = `30`:
prime factors are `2`, `3` and `5`
other divisors are `1`, 2\*3=`6`, 2\*5=`10` and 3\*5=`15`
their product: `1*2*3*5*6*10*15` is `27000` == `30**3`
> 1 votes

# Answer
# J, ~~15~~ ~~14~~ 19 bytes

Previous attempt: `3&(=#@~.@q:)~*`

Current version: `(*/*3=#)@~:@q: ::0:`

# How it works:

```
(*/*3=#)@~:@q: ::0:  Input: integer n
               ::0:  n=0 creates domain error in q:, error catch returns 0
            q:       Prime factors of n
         ~:@         Nub sieve of prime factors 1 for first occurrence 0 for second
(*/*3=#)@            Number of prime factors is equal to 3, times the product across the nub sieve (product is 0 if there is a repeated factor or number of factors is not 3)

```

This passes for cases 0, 8 and 60 which the previous version didn't.
> 1 votes

# Answer
# VB.NET (.NET 4.5), 104 bytes

```
Function A(n)
For i=2To n
If n Mod i=0Then
A+=1
n\=i
End If
If n Mod i=0Then A=4
Next
A=A=3
End Function

```

I'm using the feature of VB where the function name is also a variable. At the end of execution, since there is no return statement, it will instead pass the value of the 'function'.

The last `A=A=3` can be thought of `return (A == 3)` in C-based languages.

Starts at 2, and pulls primes off iteratively. Since I'm starting with the smallest primes, it can't be divided by a composite number.

Will try a second time to divide by the same prime. If it is (such as how 60 is divided twice by 2), it will set the count of primes to 4 (above the max allowed for a sphenic number).

Try It Online!
> 1 votes

# Answer
# JavaScript (ES6), 80 bytes

```
n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)

```

Using a recursive function to get the smaller factor.
Output 1 if sphenic, false if there are 2 or less factors and 0 otherwise

**Test**

```
F=
n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)

;[30,121,231,154,4,402,79,0,60,64,8,210].forEach(
  x=>console.log(x,F(x))
)
```
> 1 votes

# Answer
# Dyalog APL, ~~51~~ ~~49~~ ~~48~~ ~~46~~ ~~45~~ 43 bytes

```
1∊((w=×/)∧⊢≡∪)¨(⊢∘.,∘.,⍨){⍵/⍨2=≢∪⍵∨⍳⍵}¨⍳w←⎕

```

Try it online! (modified so it can run on TryAPL)

I wanted to submit one that doesn't rely on the dfns namespace whatsoever, even if it is **long**.
> 1 votes

# Answer
# Regex (ECMAScript), 46 bytes

```
^((?=(xx+?)\2*$)(?=(x+)(\3+$))\4(?!\2+$)){3}x$

```

Try it online!

This works similarly to Match strings whose length is a fourth power and very similarly to part of Is this a consecutive-prime/constant-exponent number:

```
^
(                   # Loop the following:
    (?=(xx+?)\2*$)  # \2 = smallest prime factor of tail
    (?=
        (x+)(\3+$)  # \3 = tail / {smallest prime factor of tail}; \4 = tool to make tail = \3
    )\4             # tail = \3
    (?!\2+$)        # assert that tail is no longer divisible by \2
){3}                # Execute the loop exactly 3 times
x$                  # assert tail == 1

```
> 1 votes

# Answer
# Thunno 2, 9 bytes

```
Ƒsfç⁼lp3=

```

Attempt This Online!

Explanation:

```
Ƒ          # unique prime factors
 s         # swap so input is back on top
  f        # prime factors
   ç       # apply each to the stack, and wrap results:
    ⁼      #   exactly equal?
     l     #   length
      p    # product
       3=  # equal to 3?

```
> 1 votes

# Answer
# Vyxal, 8 bytes

```
ǐ₌ÞuL*3=

```

Try it Online!

Seems Vyxal always beats Thunno 2 by just a byte or two...this is basically the same as my Thunno 2 answer.
> 1 votes

# Answer
# Desmos, 96 bytes

```
f(k)=0^{(3-∑_{n=2}^k0^{mod(k,n)}sgn(∏_{d=3}^nmod(n,d-1))log_n(gcd(k,n^{ceil(log_nk)}))^2)^2}

```

Try It On Desmos!

Try It On Desmos! - Prettified

Port of Dennis's Jelly answer so make sure to upvote that one too. There is probably a shorter way to go about this though, but this is the most straightforward way I saw that could easily be ported to Desmos.

I might put a longer explanation on how this works if I have time.
> 1 votes

# Answer
# Arturo, 43 bytes

```
$=>[x∧3=size x:=unique<=<=factors.prime&]

```

Try it!

Simply asks "are its prime factors unique and are there three?"
> 1 votes

# Answer
# Perl 6, 43 bytes

```
{3==grep ->\a{a.is-prime&&$_%%(a^a*a)},^$_}

```

Try it online!

The `grep` produces a list of the numbers `a` up to, but not including, the argument to the function `$_`, such that:

* `a` is prime (`a.is-prime`); and
* exactly one of `a` and `a*a` (`a ^ a*a`) divide the argument.

The latter condition excludes prime factors that occur in multiplicities of higher than one.
> 0 votes

# Answer
# Mathematica, ~~66~~ 57 bytes

```
Length@#1==3&&And@@EqualTo[1]/@#2&@@(FactorInteger@#)&

```

Defines an anonymous function.

is Transpose.

## Explanation

`FactorInteger` gives a list of pairs of factors and their exponents. E.g. `FactorInteger[2250]=={{2,1},{3,2},{5,3}}`. This is transposed for ease of use and fed to the function `Length@#1==3&&And@@EqualTo[1]/@#2&`. The first part, `Length@#1==3`, checks that there are 3 unique factors, while the second, `And@@EqualTo[1]/@#2` checks that all the exponents are 1.
> 0 votes

# Answer
# Python 99 bytes

```
def s(n):a,k=2,0;exec('k+=1-bool(n%a)\nwhile not n%a:n/=a;k+=10**9\na+=1\n'*n);return k==3*10**9+3

```

First submission. Forgive me if I did something wrong. Kinda silly, counts the number of factors of `n`, and then the number of times `n` is divisible by each (by adding 10\**9).

I'm pretty sure there are a few easy ways to cut off ~10-20 characters, but I didn't.

Also this is *intractably* slow at 10\**9. Could be made *okay* by changing `'...a+=1\n'*n` to `'...a+=1\n'*n**.5`, as we only need to go to the square root of `n`.
> 0 votes

# Answer
# Pari/GP, 34 bytes

```
n->if(n,moebius(n)*omega(n)==-3,0)

```

Try it online!
> 0 votes

# Answer
## Forth, 153

```
: w swap ;
: d 2dup ;
: o rot ;
: sp 0 w 1
begin 1+ d mod 0= if w over / w d mod 0= if o 16 + o o then o 1+ o o then
d > 0= until drop 1 = w 3 = and ;

```

( 153 including spaces. Spaces are required delimiters in Forth. )

( Test frame for compressed version: )

```
: testsp
  0 do i 8 .r space
    i sp if ." true" else ." false" then
    cr
  loop
;

```

( This uses a corrected version of betseg's answer.)

( Uncompressed, with comments: )

```
: sphenic ( n -- f )
  0 ( counter )
  swap 1 ( counter n probe )
  begin
    1+ ( increment probe )
    2dup mod ( Remainder? )
    0= if
      swap over / ( reduced-n )
      swap ( bring probe back )
      2dup mod 0= if
        rot 128 + rot rot
      then
      rot 1+ rot rot ( count and put count back )
    then ( counter reduced-n probe )
    2dup > 0=
  until
  drop 1 =
  swap 3 = and
;

: testsphenic
  0 do i 8 .r space
    i sphenic if ." true" else ." false" then
    cr
  loop
;

```
> 0 votes

# Answer
# C#, 172 Bytes

I'd appreciate improvement suggestions:

```
n=>{var r=Enumerable.Range(2,n).Where(i=>Enumerable.Range(2,i-2).All(a=>i%a!=0));return r.SelectMany(x=>r.SelectMany(y=>r.Select(z=>x==z|x==y|y==z?-1:x*y*z))).Contains(n);}

```

With formatting:

```
n =>
{
    var r = Enumerable.Range (2, n).Where (i => Enumerable.Range (2, i - 2).All (a => i % a != 0));
    return r.SelectMany (
        x => r.SelectMany (
            y => r.Select (z => x == z | x == y | y == z ? -1 : x * y * z))).Contains (n);
}

```

And as whole programm:

```
using System;
using System.Linq;

namespace S
{
    class P
    {
        static void Main ()
        {
            Func<int, bool> s =
                    n =>
                    {
                        var r = Enumerable.Range (2, n).Where (i => Enumerable.Range (2, i - 2).All (a => i % a != 0));
                        return r.SelectMany (
                            x => r.SelectMany (
                                y => r.Select (z => x == z | x == y | y == z ? -1 : x * y * z))).Contains (n);
                    }
                ;

            for (var i = 0; i < 1000; i++)
                if (s (i))
                    Console.WriteLine (i);
            Console.ReadLine ();
        }
    }
}

```

If you add the byte count of the using directives (which are needed for the code to compile), you'd get **203 Bytes**.

Try it online!
> 0 votes

# Answer
# C#7 122 bytes

```
bool F(int n){int P(int m,int f=2)=>m%f>0?P(m,f+1):f;int a,b,c;return(a=P(n))<n&&(b=P(n/=a))<n&&(c=P(n/=b))==n&a<b&b<c;}

```

porting of my JS answer
> 0 votes

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


title: Negate a number

text:
# Question
Title: Negate a number
You are to accept, on standard input, one number. You will then output the negation of that number. Your code will do nothing else. You may accept various formats if you wish (like "one" or ("uno+2.4e10i"). You may also output it how ever you wish. Note that these formats mush have existed somewhere on the internet before this question. The thing you can't do is **use the same 6 character sequence twice** in your code. Also, if any set of characters can be removed, and your code still functions the same, they must be removed (no making huge useless strings, since they could just be removed.)

This is code bowling, so the answer with the most characters wins!

Note: In case you were wondering, negation means "multiply by negative one." The representation of the numbers is up to you, but the meaning of negation is not.

# Answer
# CJam, 278,548 characters

Stack Exchange has a 30,000 character limit, so I've uploaded my code to Google Drive.

The online interpreter chokes when decoding the lookup tables (*Maximum call stack size exceeded*), so I suggest using the standard interpreter (requires Java).

### I/O

Input should be an integer (in whatever format CJam understands). Output is in British English.

```
$ cjam negate.cjam <<< 9990001
negative nine million nine hundred and ninety thousand and one
$ cjam negate.cjam <<< -1001000000
one milliard and one million
$ cjam negate.cjam <<< 0
zero

```

### Validity

All code is functional, so removing parts should not be possible. Note that all linefeeds are part of strings and cannot be removed.

There are no repeated sequences of six characters:

```
$ tr \\n \\t <negate.cjam | grep -P '(.{6}).*\1' | wc -c
0

```

### How it works

I've started with a list of the first one thousand natural numbers and a list of the first three thousand three hundred and thirty-four powers of one thousand.

Sadly, both lists repeat the same 6 character sequences over and over again, so I had to encode them in a way that would avoid those repeated sequences. The following CJam code accomplishes that task:

```
q
2G#b
94b
{32+}%
{c}%
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}"
"}|{zyxwvutsrqponmlkjihgfedcba`_^]~[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#
! "
er

```

It reads the list from STDIN (`q`), converts the resulting string into a base 65536 number (`2G#b`), converts the resulting integer into an array by considering it a base 94 number (`94b`), adds 32 to each integer in the array (`{32+}%`) to avoid unprintable characters, converts the array into a string (`{c}%`) and performs a character transliteration (`"…""…"er`) to get rid of characters that require escaping. This required a little trial-and-error; the natural choice (`95b`) resulted in repeated sequences.

The final code does the following:

```
{                             " Define a decoding function for the lists.               ";
  "…""…"er{32-}%94b2G#b{c}%   " Perform the steps from above in reverse order.          ";
  "
  "/                          " Split the result by linefeeds.                          ";
}:D;

"…":H;"…":P;                  " Store the encoded lists in variables.                   ";

q~                            " Interpret the input from STDIN.                         ";
__                            " Duplicate twice.                                        ";
0<!{}{-1*}?                   " If the input is negative, multiply the last copy by -1. ";
`_                            " Stringify and duplicate the last copy.                  ";
,3%3\-"0"*\+                  " Prepend 0's to make the string length a multiple of 3.  ";
3/-1%                         " Split into string of three characters and reverse.      ";
-1:C;                         " Initialize variable C to -1. ";
{                             " For each substring:                                     ";
  ~                           " Interpret it (i.e., cast to integer).                   ";
  H=_                         " Retrieve the correspond English number from H.          ";
  'z'e'r"o"+++=               " Push 1 if the number is zero.                           ";
  C):C;                       " Increment C.                                            ";
  {;}{" "+CP=+}?              " Remove 0 or append the corresponding modifier from P.   ";
 }%
-1%_                          " Reverse the array and duplicate it.                     ";
,1>                           " If the array has more than one element…                 ";
{
  )_"and"/,1=                 " …and the last element doesn't contain the string 'and'… ";
  'a'n'd" "+++*\+a+           " …prepend the  string 'and ' to it.                      ";
}{_,0={H0=a+}*}?              " If the array is empty, replace it with [ 'zero' ].      ";
\0>                           " If the input was positive,                              ";
{
  'n'e'g'a't'i'v"e"+++++++a\+ " prepend the string 'negative'.                          ";
}{}?
" "*                          " Join the array of strings with spaces.                  ";
"
"                             " Append a linefeed.                                      ";

```
> 8 votes

# Answer
# Tcl, 1073741823 (1G-1 bytes, cheating)

This is (obviously) cheating. It can be even larger in some languages like Bash, which doesn't load the whole program when it starts. Tcl runs very slow at starting, and finally refuses to run the program if the file size is about 2147483647 bytes or more.

```
set b binary
$b scan [$b format i [expr {[gets stdin]-1^3+[file size $argv0]*4}]] i a
puts $a
exit
#!!!!!#"!!!!#%!!!!#&!!!!#'!!!!#(!!!!#)!!!!#*!!!!#+!!!!#,!!!!#-!!!!#.!!!!#/!!!!#0!!!!#1!!!!#2!!!!#3!!!!#4!!!!#5!!!!#6!!!!#7!!!!#8!!!!#9!!!!#:!!!!#<!!!!#=!!!!#>!!!!#?!!!!#@!!!!#A!!!!#B!!!!#C!!!!#D!!!!#E!!!!#F!!!!#G!!!!#H!!!!#I!!!!#J!!!!#K!!!!#L!!!!#M!!!!#N!!!!#O!!!!#P!!!!#Q!!!!#R!!!!#S!!!!#T!!!!#U!!!!#V!!!!#W!!!!#X!!!!#Y!!!!#Z!!!!#[!!!!#^!!!!#_!!!!#`!!!!#a!!!!#b!!!!#c!!!!#d!!!!#e!!!!#f!!!!#g!!!!#h!!!!#i!!!!#j!!!!#k!!!!#l!!!!#m!!!!#n!!!!#o!!!!#p!!!!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|%#e,Y|%#f,Y|%#g,Y|%

```

It computes the result with its own file size. So deleting anything will change the behavior.

The above program is generated by the C++ program below.

```
#include<fstream>
#include<string>
#include<cstring>

std::ofstream f("a.tcl");
const long long size = 0x3fffffffLL;

const std::string init = "set b binary\n"
             "$b scan [$b format i [expr {[gets stdin]-1^3+[file size $argv0]*4}]] i a\n"
             "puts $a\n"
             "exit\n";
const std::string charset = "!\"%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[^_`abcdefghijklmnopqrstuvwxyz{|~";
const int ncharset = 88;

int main() {
    f<<init;
    long long p = init.length();

    int b[5] = {};
    char ch[6] = "!!!!!";

    while(p < size) {
        f<<"#";
        p++;
        if(size-p > 5) {
            f.write(ch, 5);
            p += 5;
        }
        else {
            f.write(ch, size-p);
            break;
        }
        int i=0;
        while(b[i] == ncharset-1) {
            ch[i] = charset[b[i]=0];
            i++;
        }
        ch[i] = charset[++b[i]];
    }
    f<<std::flush;
    return 0;
}

```

The 7-zipped version of the complete program has only 18MB. Maybe I can upload it somewhere if someone request for it.

I chose Tcl because it has only a small number of special characters. So I could be sure one cannot implement the same functionality by selecting some characters not to delete. I guess Lisp is better on this.
> 2 votes

# Answer
## Wolfram Mathematica 10↑↑3.1955 characters

Bowling-ed:

```
ToExpression[FromCharacterCode[StringLength["¡¢£¤¥¦§..."]~IntegerDigits~Nest[Hyperfactorial, 10, 2]]]

```

This is closely based on my answer to Biggest Irreducible Hello World

Where the string is the length-6 DeBruijn Sequence of every unicode character over 128. This guarantees that it never repeats any set of 6 in itself, or outside the code since 6 never show up. Since there are only points over 128, even if there are valid symbols, none of them can read user input.

Golfed / decoded:

```
Print[-Input[]]

```

Which is converted to it's character code (80, 114, 105...) and read back as a base-Nest\[Hyperfactorial, 10, 2\] number. This cannot be broken down to any number besides 109, which is not at least 117 for 'u'.

This means the string length is (k!)^k^(n-1)/k^n, where k is the number of unique characters, and n is the length of each non-repeating group (6).

Oddly enough, I think this is the hard limit to this question. If it wasn't for the 6-character restriction, or unicode only have 1 million characters, then the answer would have been a tad over

```
80 * Nest[Hyperfactorial, 10, 9]]^15

```

or

```
10↑↑11.289

```
> 1 votes

# Answer
## C# 865

Uses DateTime parsing since a negative will throw an exception. Since Console was already used the answer is output to a Form. Also C# has string and String object.

Edit: removed some duplicate char sequences.

```
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
namespace Golf
{
    class Code
    {
        String num;
        bool isPos;
        Code() { }
        void In()
        {
            num = Console.ReadLine();
        }

        void Out()
        {
            try
            {
                DateTime.Parse(this.num);
                isPos = true;
            }
            catch (Exception)//if negative throw exception
            {
                isPos = false;
            }
            int res;
            double pi = Math.PI;
            if(Int32.TryParse(num, out res))
            {
                res = (int)((isPos) ? Math.Cos(pi) * res : Math.Sin(3 * pi / 2) * res);
            }

            Form f = new Form();
            Label l = new Label();
            l.Text = res.ToString();
            f.Controls.Add(l);
            f.ShowDialog();
        }

        public static void Main(string[] args)
        {
            Code code = new Code();
            code.In();
            code.Out();
        }

    }
}

```
> 0 votes

---
Tags: restricted-source, code-bowling
---