title: yes is 91 lines long

text:
# Question
Title: yes is 91 lines long
`yes`, from coreutils, is 91 lines long. Many of them are comments, but that is still **WAY** too long.

Edit from September 2019: the source file grew over the past five years and is now 126 lines long.

Write a program that imitates `yes`:

* outputting to `stdout` an infinite stream of "y\n"'s
* there must be an option to stop it other than killing the process with `SIGKILL`: but `SIGINT` and `SIGPIPE` are fine
* you are not allowed to use "y" or "\n" or their ASCII values (121, 0x79, 0171, 10, 0xA or 012)

Shortest answer wins.

Bonus:

* subtract 10 from your code length, if you can receive a phrase in `stdin` and print it out instead of "y" (but still including the line-break). The program doesn't have to print `y` on an empty input.

# Answer
> 38 votes
# CJam, 13 bytes - 10 = 3

```
l_'x)?{_oNo}h

```

You'll need to use the Java interpreter for this, because the online interpreter only returns once the program terminates.

You can abort the program with SIGINT (by pressing Ctrl-C). It will read a line from STDIN, and print that line, or `y` if the input was empty.

## Explanation

```
l             "Read line from STDIN.";
 _            "Duplicate.";
  'x          "Push character x.";
    )         "Increment to get y.";
     ?        "Ternary operator. Replaces line with y if it was empty.";
      {    }h "Repeat while true. Leaves condition on the stack, which is the output string.";
       _o     "Duplicate line and print.";
         No   "Push string with newline and print.";

```

After clarification of the OP, the following seems more to spec:

```
l{_o9c)o1}g

```

I'll wait with updating the submission until the OP replies to my comment, though.

# Answer
> 23 votes
# Brainfuck - 38 bytes

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

```

It doesn't use 10 or 121, because `+-<>.,[]` are all the meaningful characters in the language anyway, but it does calculate them pretty naively (0+1+1+1+1+1+1+1+1+1+1=10, 10\*12+1=121).

This probably depends on the interpreter, but it dies to `^C` on my machine.

# Brainfuck - (63-10)=53

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

```

# Answer
> 22 votes
# Python 3, 27 bytes

Works with at least CPython and Jython.

```
while 1:print(str(help)[1])

```

SIGINT stops it.

# Answer
> 19 votes
# Pyth, ~~10~~ ~~9~~ 6 bytes - 10 = ~~0~~ ~~-1~~ -4

```
#|zePG

```

I've been trying for ages to get one that I'm satisified with. Basically converts to:

```
#      = while True
(implied print)
|      = or
z      = (automatically initialized from stdin)
ePG    = second-to-last lowercase letter = 'y'

```

# Answer
> 17 votes
# Marbelous 14 bytes

```
0978
]]/\++
!!

```

This is pretty straightforward, the '/\\' device places two copies on its left and right, the right one is incremented by `++` and then falls off the board and is printed. The `]]` device pushes any marble to the right if STDIN is empty but lets the first byte on STDIN fall down if it isn't. This will then trigger the `!!` device, which exits the board. So this will print y\n until you enter anything on stdin.

This only works in the python interpreter.

# Answer
> 13 votes
# C#, ~~81~~ ~~78~~ 76 bytes

Cannot compete with the other languages, but here it is anyway:

```
class A{static void Main(){for(;;)System.Console.WriteLine((char)('x'+1));}}

```

Can be killed with SIGINT by pressing `Ctrl`+`C`.

No bonus, because it would take more than 10 bytes to get it.

# Answer
> 12 votes
## Java, 178

```
class C{public static void main(String[]a)throws Exception{for(char c='x'+1;;)((java.io.PrintStream)Class.forName("java.lang.S"+c+"stem").getField("out").get(null)).println(c);}}

```

Printing requires `System`, but the `y` character is forbidden. Hence, I had to use reflection.

# Answer
> 10 votes
# Perl: 18 bytes - 10 = 8

The string is from STDIN.

```
$_=<>;{print;redo}

```

# Answer
> 9 votes
# Ruby, ~~30~~ ~~23~~ 18 bytes

```
loop{puts ?x.succ}

```

Can be killed with SIGINT by pressing `Ctrl`+`C`.

Thanks to manatwork for sharing improvements!

# Answer
> 8 votes
# Perl, 26 bytes

```
{print chr$=*2+1,$/;redo}

```

## Custom input from argument (like `yes` actually works), 22 bytes-10=12

```
{print @ARGV,$/;redo}

```

## Custom input from stdin, 22 bytes-10=12

```
while(<>){print;redo}

```

# Answer
> 8 votes
# Linux Bash - 19 bytes

This is probably cheating and subject to failure if you don't have /usr/bin/yes or have a /usr/bin/xes or /usr/bin/zes:

```
/usr/bin/[x-z]es $*

```

I think it meets the requirements, though maybe it's violating the "nothing that evaluates to y" rule. And perhaps imitating `yes` by actually running `yes` is against the rules.

This could be optimized a bit (though less likely to work) to take it down to 11 bytes:

```
/*/*/?es $*

```

I couldn't figure out how to get the 10 point bonus by reading a string from stdin without adding more than 10 bytes to the code

# Answer
> 7 votes
## C, ~~64~~ ~~55~~ ~~53~~ ~~45~~ 40 - 10 = 30

`main(int c,int**a){for(;;)puts(a[c>1]);}`

I'm not hugely happy with this, as it requires the program to be named "y", and to be called with \`y\` only, so it has to be in $PATH, but hey, first codegolf :)

Alternative:

## C, 30 (+ 1 filename)

`main(){for(;;)puts(__FILE__);}`

Using the same technique as my esteemed colleague @Matt Windsor

* EDIT: turns out getting round the no \n character made it shorter
* EDIT2: "int" is shorter than "char"
* EDIT3: didn't need that variable at all
* EDIT4: a bit of slightly undefined behaviour never hurt anyone
* EDIT5: add alternative version

# Answer
> 6 votes
# dc, 12

```
[30986Pdx]dx

```

Only outputs `y\n`. Doesn't read from stdin, so no bonus.

30986 is 0x790A (i.e. "y\n"). The `P` command simply converts the number to base 256, and prints the corresponding character for each base 256 digit.

# Answer
> 5 votes
## Common Lisp : (30-10) = **20**

```
(format t"~@{~a~%~:*~}"(read))

```
* `(read)` from input stream
* print to output stream: `(format t ... )`
* iterate over all `format` arguments (only one here) : `~@{ ... ~}`
* inside the loop, for each argument:

+ print argument `~A` followed by a newline `~%`
    + rewind *current element* to the previous one `~:*` (infinite loop)

You can break the loop with `Ctrl+C`, which signals an error with restart options (continue/abort).

# Answer
> 5 votes
## **Linux Bash, 33-10 = 23**

```
read a; while :; do echo $a; done

```

Can be killed with SIGINT by pressing `Ctrl`+`C`.

# Answer
> 5 votes
# Rust, 52 chars

```
fn main(){loop{println!("{}",'Y'.to_lowercase())}}

```

There just isn't seemingly a nice way of computing `y` without being cheeky in Rust-- they've made too good a job of doing chars safely. I:

* Can't supply a non-literal string to `println!`, so no tricks allowed there;
* Can't add 1 to `'x'`, because in Rust chars aren't numbers;
* Can't ROT13 (why doesn't Rust have ROT13 in its standard library!?);
* Can't easily do anything unsafe like dropping to C strings, converting from numbers to chars, etc without being incredibly verbose and going over 52c.

Nor is going for the code bonus worth it, because reading from `stdin` would require error handling =3

Much of the code reductions I could find involved doing increasingly rule-flouting things with the compiler environment:

# Rust, 44 chars (+ at least 1 char for filename)

```
fn main(){loop{println!("{:.1}", file!())}}

```

**Obsoleted by below.** This one probably doesn't count, as the name of the *source* file needs to begin with `y`.

# Edit: Rust, 36 chars (35 source, 1 filename)

```
fn main(){loop{println!(file!())}}

```

As above, but the file *has* to be called `y` (not `y.rs`, `y`). Humorously, Rust will overwrite the source with the binary! At least on my machine, the binary does work after that though.

# Rust, 37 chars (+ equivalent of `env K='y'` on your platform)

```
fn main(){loop{println!(env!("K"))}}

```

This one is even worse: you need to set the environment variable `K` to `y` at *compile time*.

**Edit**: if you set `K` to `y\n`, you could drop the `ln` in `println!`, for a grand total of ~~35 chars and~~ several facepalms:

```
fn main(){loop{print!(env!("K"))}}

```

# Answer
> 4 votes
## Commodore 64 Basic: 14 13 bytes

```
1?C|(11↑2):R╭

```

As usual, I've made substitutions for characters in PETSCII that are not present in Unicode. `|` is used to represent `SHIFT+H`, while  represents `SHIFT+U`. Note that this outputs ASCII 'y' (byte value 121) rather than a character that the default Commodore character set displays as 'y'.

BASIC is supposedly an easy-to-learn, English-like programming language. Throw in the typing shortcuts present in many early dialects, and you get something that is shorter and less readable than Perl.

**EDIT**: In "shifted mode", this gets two bytes shorter, thanks to lowercase "y" being encoded at decimal value 89. Using a non-ASCII character set to get around the "not allowed to use their ASCII values" rule might be cheating, though.

```
1?cH(89):rU

```

# Answer
> 4 votes
# Fission, 5 bytes

```
Rx+!N

```

This is fairly competitive for Fission. :)

Control flow starts with a `(1,0)` right-going atom at `R`. `x` sets the mass to `120`, and `+` increments it to give `(121,0)`. Then `!` prints the corresponding character (`y`) and `N` prints a newline. The source code wraps around at the edges, so the atom passes `R` again (which doesn't do anything now), `x` sets the mass to `120` again, `+` increments it and so on and so on...

# Answer
> 3 votes
## AWK, 38 bytes

```
BEGIN{for(;;)printf("%c%c",60+61,5+5)}

```

Variant which will read the string on stdin: 14 bytes-10 = **4**

```
{for(;;)print}

```

But since it cannot do both (revert to "y" if no stdin is provided), I'm not sure it counts... :o)

Both can be exited with Ctrl+C.

# Answer
> 3 votes
# Ruby, 27 bytes - 10 = 17

It's just @ProgramFOX's solution with the bonus (it took my 9 bytes to solve the bonus question).

```
loop{puts ARGV[0]||?x.succ}

```

# Answer
> 3 votes
# Haskell, 29 bytes

```
main=putStrLn[succ 'x']>>main

```

I believe this is stopped by both `SIGINT` and `SIGPIPE`.

# Answer
> 3 votes
# dc, 21 bytes - 10 = 11

```
C1st?st[ltP[]ps0dx]dx

```

Note that the input needs to be wrapped in `[]`, e.g. `[no]`, because `?` is the only way to take input, which executes it as `dc` code.

# Answer
> 3 votes
# C, 32 bytes

Requires little endian machine and compilation with -O2 (to avoid stack overflow).

```
a=11*11;main(){main(puts(&a));}

```

# Answer
> 3 votes
## Perl, 31

Here is a Perl version that actually behaves like GNU `yes`, as far as I can tell:

```
{print "@ARGV"||chr 11**2;redo}

```

This works if it is okay to use perl's command line switches (`-l` for the newline), otherwise it would become 3 characters longer:

```
{print "@ARGV"||chr 11**2,$/;redo}

```

# Answer
> 3 votes
### Javascript, 39 37 bytes

```
for(;;)console.log(''+Function()[13])

```

### Shorter alternative that only works in the browser, 36 bytes

```
for(n=''+crypto;;)console.log(n[10])

```

### Alternative without console.log, only works in NodeJS, 58 57 56 bytes

```
for(n=''+Function()};;)process.stdout.write(n[13]+n[19])

```

# Answer
> 2 votes
## PowerShell, 27 − 10 = 17

```
param($s=$Host[1])for(){$s}

```

Might not work in Pash. A more robust alternative should be

```
param($s="$(gal gh*)"[2])for(){$s}

```

# Answer
> 2 votes
# Lua, 42 bytes - 10 = 32

```
while 1 do print(...or('').char(90+31))end

```

# Lua, 49 bytes - 10 = 39

```
y=...or(string.char(60+61))while 1 do print(y)end

```

Both were tested with Lua 5.1.4 and can be killed with SIGINT (`Ctrl`+`C`).

# Answer
> 2 votes
## Fortran, 28

```
do1;1 print'(A1)',11**2;end

```

Compile with `gfortran -ffree-form`.

# Answer
> 2 votes
# APL (Dyalog APL), 5 - 10 = -5 bytes

Warning: relies on an undocumented and unsupported feature/bug.

```
⎕←⍣≢⍞

```

Empty STDIN prints empty lines (not "y"), which is allowed and has been suggested.

Try it online!

STDOUT with trailing newlines,

gets

repeatedly until

it differs from

STDIN

i.e. never, but uninterruptible by pausing the thread.

# Answer
> 2 votes
# Ahead, 8 bytes

```
~W-1z'N~

```

Try it online!

# Answer
> 2 votes
## `s`, 1-10 = -9 bytes

```
I

```

## Explanation

```
Flag: s % We have to read from STDIN :(
 P      % Newline-print
a       % the STDIN input
  I     % Forever

```

# , 7 bytes

```
i12 1CE

```

## Explanation

```
i     E % Foreach from 1 to positive infinity:
         % (Implicit print a newline on each iteration)
 12 1    % Space does nothing. Basically just pushes 121.
     C  % Convert to a character, rendering 'y'

```

# Answer
> 2 votes
## Zsh + POSIX utilities, 22 bytes

```
f()(tr 01 x-z<<<1;f);f

```

Thanks to pxeger for the shorter way to print `y`.

Try it online!

## Pure zsh, 24 bytes

```
f()(<<<$SPROMPT[29];f);f

```

Try it online!

### Bonus: mandatory phrase from stdin — 21 - 10 bytes

```
read a;f()(<<<$a;f);f

```

Try it online!

# Answer
> 2 votes
# Zsh, 14 bytes

```
x=Y;<<<$x:l;$0

```

Try it online!

Set `x=Y`, then print `$x`, `:l`owercased. `$0` recurses.

# Answer
> 2 votes
# Python 3, 25 bytes

```
while 1:print(chr(97|25))

```

Try it online!

# Answer
> 1 votes
**Apparently this isn't totally portable. My** `sys.version` **is** `2.7.9 (default, Dec 11 2014, 04:42:00) \n[GCC 4.9.2]`**, so if yours is different this might not work I guess.**

# Python 2 - (76-10)=66

```
import sys
s=sys.stdin;a=`help`[1]if s.isatty()else s.read()
while 1:print a

```

Pretty long, but I wanted to go for the bonus (even though it cost more than 10 bytes). Checking if stdin is empty or not without prompting for input is long, apparently.

At first, I misread the bonus as taking an argument instead of stdin. I'm proud of my solution for that, so I'm posting it anyway ;)

# Python 2 - (52-10+∞)=∞ (invalid!)

```
import sys
while 1:print(sys.argv+[0])[1]or`help`[1]

```

`sys.argv` is a list where the zeroth element is the filename and every element afterwords is an argument given to the program. I add a falsey value to the end of the list; if there are no arguments, the first element is that falsey value, otherwise it's the first argument. `a or b` in Python returns the first value that confirms what the outcome will be: If `a` is truthy, we already know that the whole thing will be true, so it just gets returned. If it's false, `b` is returned (since `False or b` == `b`).

# Answer
> 1 votes
# Plan 9 rc: 20-10=10 (but not quite there)

```
f=`{cat};while()echo $f

```

The problem with this almost-solution is that it *must* have something on stdin. I haven't yet been able to find a way to get it to print `y` if stdin isn't there.

# Answer
> 1 votes
# Windows Batch: 24 bytes

A yes.bat file with this content will work on most Windows XP and later systems with default settings:

```
@echo %COMSPEC:~12,1%&%0

```

Else this slightly larger yes.bat file (34 bytes) will work in all cases:

```
@set "T=%~n0"
@echo %T:~0,1%
@%0

```

Can be made down to 13 bytes if the file is called y.bat instead of yes.bat, but I feel that's cheating:

```
@echo %~n0&%0

```

# Answer
> 1 votes
# linux (Ba)sh, 13 to 26 (23 to 36 chars) (repeats 'y' or the input, like yes)

create an executable (+x) file, named as you like (ex: `my_yes`), containing one of those possible contents:

```
echo ${*:-y};exec $0 $*  #23 chars, score 13, but loses spaces, and will choke on many inputs

```

*or*

```
echo "${@:-y}";exec $0 "$@"  #27 chars, score 17, but will choke on some inputs

```

*or*

```
printf "%s\n" "${@:-y}";exec $0 "$@"  #36 chars, score 26, a tiny more robust, but "longer"

```

and then execute it with the arguments you want, it will repeat them ad-lib. (With no arguments, it repeats "y", as the yes command does too)

```
$ chmod +x my_yes
$ ./my_yes
y
y
y
[ctrl-C]

$ ./my_yes '  It looks ok!'
  It looks ok!
  It looks ok!
  It looks ok!
  It looks ok!
[ctrl-C]

```

# Answer
> 1 votes
# C89, ~~31~~ 37 chars

```
main(){for(;;)printf("%c\n",'z'-1);}

```

Built on the idea of @LordAro, without filename requirements.

# Answer
> 1 votes
# CFML, 247 bytes

This is more a "just for the heck of it" answer, as it's obviously hideously long (CFML earns no points for terseness); and I just realized it can't actually be *killed* without restarting the service, although it will indeed stop printing to the browser on an ESC character.

```
<html><body><cfflush><cfif isDefined("URL.i")><cfscript>a=URL.i;if(a is ""){a=chr(asc("x")+1);}while(1){writeOutput("#a#<br>");getPageContext().getOut().flush();}</cfscript><cfelse><form action="a.cfm"><input name="i"/></form></cfif></body></html>

```

# Answer
> 1 votes
# C, 35 bytes

```
main(a,b){b='x'+1;for(;;)puts(&b);}

```

I don't know if this will compile correctly with all compilers on all platforms or not; if it doesn't work for you, let me know. I used several things here that I have never thought of using before. :)

# Answer
> 1 votes
# Node.js, 53 chars (63 if you count `node -e ""`)

**update**:

* Reduced another 5 chars.
* Silly extra char removed.
* Reduced 2 chars, from 61 to 59.

---

The real `yes` does not uses stdin, but an argument, like:

```
yes n

```

Well, this answer works like that, it will print `y\n` over and over:

```
node -e "for(;;)console.log(process.argv[1]||34 .toString(36))"

```

And if you append an `n` after the line, it will print `n\n` instead:

```
node -e "for(;;)console.log(process.argv[1]||34 .toString(36))" n

```

No bonus, since I'm not using stdin.

# Answer
> 1 votes
## CAPL1.5+ ; 6 without input; 10 - 10 = 0 with input

**Sidenote**
I have read somewhere \[link?\] that custom languages aren't allowed in golfing questions, as they could make built-in functions that do exactly what the question is asking, however I made CAPL to make golfing easier *in general*. If you think this is not allowed here, let me know!

I got some ideas from \>\<\> and Befunge (You can move between lines and use hexadecimal characters to push numbers), some from Ruby and some from my own to make golfing easier.
CAPL reads from left to right, and goes one line down at the end of the line. If it is as the last line, the program will quit.

As no-one knows this language yet, I'll try to explain as much as possible.

**Outputting y. 6 bytes**

`bb*.n<`

`bb*` `b` is hexadecimal for `11`, so `bb*` is `11*11`=`121`, which is the UTF-8 equivalent of `y`. This value is pushed to the stack.
`.` Pops the top value from the stack, and outputs as UTF-8. As `121` is on top of the stack, the index is ignored here.
`n` Outputs a newline
`<` Sends the pointer back to the beginning of the line, thus repeating that line. As we don't expect input, we can do this safely without re-asking for the input.

**Outputting from input. 10 bytes, 0 after bonus**

`i~a&{X:.)}`

`i` Takes input from the user, pushes as UTF-8 on the top of the stack, and pushes the length after that. I.e. `[72,101,108,108,111,5]`
`~` Pops a number from the stack, then reverses that amount of bytes. I.e. `[111,108,108,101,72]`
`a` Hexadecimal for `10`, the newline character
`&{...}` Makes an infinite loop. We have input, so we can't send the pointer back to the line. I could place the function on the line below, which would safe me a byte, but newlines aren't allowed in this challenge.
`X` Removes the top value from the stack (The index from the loop)
`:.` Duplicates the top value, then outputs as UTF-8
`)` Turns stack right. (`[1,2,3,4,5]` -\> `[5,1,2,3,4]`)

Howver, this means we start with a newline, then start outputting the input, then a newline, then the input, etc. If we're not allowed to start with a newline, use the following code with 12 bytes, or 2 after subtracting the bonus.

`iXa#~&{X:.)}`

The only new command here is `#`, which pushes the amount of items on the stack to the stack.
I removed the length from `i`, because adding 1, then swapping with the newline is longer than removing and getting the length again.

**Just for fun, here is a "Hello World" program**

```
"Hello World"#~
#?!;.<

```

The `?!` operation is the same as \>\<\>'s

# Answer
> 1 votes
# SmileBASIC, 19 bytes - 10 = 9

```
INPUT C$@L?C$GOTO@L

```

# Answer
> 1 votes
# QC 26 (26 - 10 = 16) bytes

`(00600F014"0178)0101A01$14`

The program requires an input on stdin because QC doesn't have a way to get arguments. Empty input just prints y.

### Explanation

```
(00 read string into memory at address 00, address 00 is length, next bytes are the string itself
600F014 jump if values at 00 and F0, if not equal jump to address 14
"0178 Write 78(lowercase x) to address 01
)0101 increment value at address 01 by 01 which gives y
A01 print string and newline from address 01 until 00 is reached
$14 jump to address 14(print the next line)

```

# Answer
> 1 votes
# Vitsy, 15 - 10 = 5 bytes

Because Vitsy waits for STDIN to be entered, I have made the bonus input come in as command line arguments.

```
zl)[bD*][:ZaOu]

```

Explanation:

```
z               Grab the entirety of the input stack and patch it on the current.
 l)[   ]        If the stack has no members...
    bD*         Push 11^2 to the stack (this is the ASCII value for 'y').
        [     ] Loop infinitely.
         :      Duplicate the current stack.
          Z     Push the entire contents of the stack to output, top first.
           aO   Push out a newline to the out.
             u  Flatten the top two stacks.

```

# Answer
> 1 votes
# C(GCC) - 161 bytes

```
main(int argc,char**argv){if(argc>1){while(1){for(int i=0;i<argc-1;i++){printf("%s ",argv[i+1]);}puts("");}}else{char*c=malloc(1);c[0]='x'+1;while(1){puts(c);}}}

```

Uses malloc to allocate 1 byte and set its value `'x' + 1` If any input is provided as an argument(mulitple words work too) it will print it instead of y.

Ungolfed version:

```
main (int argc, char**argv) {
    if (argc > 1) {
        while (1) {
            for (int i=0; i < argc - 1; i++) {
                printf("%s ",argv[i+1]);
            }
            puts("");
        }
    } else {
        char* c = malloc(1);
        c[0] = 'x' + 1;
        while(1) {
            puts(c);
        }
    }
}

```

# Answer
> 1 votes
# Ohm, 17 - 10 = 7 bytes

```
IDö?.x1+;Ω
D,∞

```

Explanation:

```
IDö?.x1+;Ω  ■Main link
I           ■Input
 Dö?    ;   ■If(!input){
    .x1+    ■  Push 'x' and increment
            ■}
         Ω  ■Call link below

D,∞         ■Helper link
  ∞         ■while (true){
D,          ■  duplicate and print
            ■}

```

# Answer
> 1 votes
## R, 51 bytes

```
while(T){cat(paste0(letters[25],'\\',letters[14]))}

```

Literally outputs "an infinite stream of "y\n"'s", rather than "y\[newline\]".

In RStudio the output is truncated but it is otherwise infinite.

# Answer
> 1 votes
# R, 27-10 = 17 bytes

```
x=scan(,'');repeat print(x)

```

Repeats `stdin` over and over and over. No `y` or `\n` in the code.

# Answer
> 1 votes
# \>\<\>, 6 bytes

```
b:*oao

```

By not including a `;` at the end, the **\>\<\>** will keep on swimming until he's released by a SIGINT.

### Explanation

```
b:*oao
b         Push 11
 :        Duplicate
  *       Multiply top elements to get 121
   o      Print as character
    a     Push 10
     o    Print as character (yielding '\n')
          No program terminator, so our ><> will
          keep on swimming this path forever.
^----'

```

# \>\<\>, 17 - 10 = 7 bytes

The previous is quite a boring solution, so here's one that takes input from stdin. This abuses the fact that the default way of supplying input to a **\>\<\>** program is `echo 'input' | fish.py yes.fish`, where `echo` provides the `\n` character.

```
 i:0)?!v
0r}o:r~<

```

### Explanation

```
 i:0)?!v     Load STDIN into the stack (reversed)

             NOP           <----------,
 i           Push a byte from STDIN   |
  :          Duplicate top element    |
   0         Push 0                   |
    )?       If (i > 0):              |
      !        Wrap around  ----------'
             Else:
       v       Move to the second part

0r}o:r~<     Print STDIN until halted

       <     Go right         <---------------,
      ~      Remove top element (duplicated   |
                -1 from EOF)                  |
     r       Reverse stack                    |
    :        Duplicate top element            |
   o         Output as character              |
  }          Rotate stack to right (go to     |
                next character)               |
 r           Reverse the stack                |
0            Push 0                           |
             Wrap around       ---------------'

```

The `0r` at the end allow sfor the loop to happen by wrapping around, where we still assume the stack to be reversed with a `-1` on top.

# Answer
> 1 votes
# Perl 5 - (10-10) = 0 bytes

```
print;redo

```

Requires the `-ne` flags. Takes in a character(s) from STDIN, repeats the character(s) infinitely.

### Example execution

```
perl -ne 'print;redo'

```

### Explanation

This takes advantage of the `-n` flag in `Perl`, where it explicitly wraps `while (<>) { ... }` around the source code. The use of `redo` without an explicit label is also used. According to the documentation: `If the LABEL is omitted, the command refers to the innermost enclosing loop.`

# Answer
> 1 votes
## Mumps (M), 12 bytes - 10 = 2 bytes

Quite simple in Mumps (M), as the language allows single character commands and a newline is denoted by '!'...

```
R I F  W I,!

```

Breakdown:

**R**ead STDIN into **I**, **F**or (with two spaces) = infinite loop, **W**rite contents of **I**, then newline (**!**)

Works on both InterSystems & YottaDB (GT.M).

# Answer
> 1 votes
# Husk, 1 - 10 = -9 bytes

The wonderful thing about Husk's laziness is that computations involving infinite lists can be managed and used to produce useful output, like in this case :)

Try it online!

## Explanation

```
   Implicit argument
∞  Build an infinite list repeating forever
   Implicit join by newlines

```

# Answer
> 1 votes
# Raku (raku -n) 9-10 = -1 bytes

```
.say;redo

```

Idea for redo from @booshlinux (I would have done: loop{.say})

# Answer
> 1 votes
# 05AB1E, -8 bytes

```
[,

```

Try it online!

```
[,  # full program
[   # forever...
 ,  # output...
    # implicit input

```

# Answer
> 1 votes
# BRASCA, -3 bytes (7-10)

```
l,[:mo]

```

Try it online!

## Explanation

```
<implicit input>
l           - Push 10 (\n)
 ,          - Reverse stack
  [   ]     - While non-zero:
   :mo      - Duplicate, move the duplicate to bottom, output top of stack

```

# Answer
> 1 votes
# brainfuck, 60-10=50 bytes

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

```

Try it online!

Explanation:

```
+>> add one (120 to be adden on later yeilding 'y')
,[[>,]>+<]  if there is input, read it and set a flag to skip the next loop
++++++++++>-  '\n'
[
  <[<+<++++++++++++>>-] add 10*120 to first cell, shift \n back one cell
]
<[[<]>[.>]<] print the input or 'y\n'

```

# Answer
> 1 votes
# JavaScript (Node.js), ~~86~~ 80 bytes

with strict adherence to the `you are not allowed to use "y" or "\n" or their ASCII values (121, 0x79, 0171, 10, 0xA or 012)` rule

```
for(;;)console.log(eval('T\\u'+(+[])+(+[])+(38+38+3)+'peError').toString()[6+4])

```

Try it online!

-6 bytes thanks to me

# Answer
> 1 votes
# Vyxal, -8 bytes <sup>(2-10 bytes)</sup>

Not the most original method, but it's short.

```
{,

```

## Explanation

```
{         - While non-zero
 ,        - Print implicit input

```

Try it Online!

# Answer
> 1 votes
# JavaScript, <sup>32</sup> 31 bytes

```
for(;;)console.log((""+1/0)[7])

```

## Edits

* **-1 byte**: `while(1)` =\> `for(;;)`

## Explanation

* `for(;;)` is an infinite loop)
* `1/0`: A division by zero returns `Infinity` in javascript
* `""+` converts `Infinity` into a string
* `[7]` access the 8th character of `"Infinity"` (`y`)

To terminate the process do `Ctrl`+`C` (`SIGINT`)

# Answer
> 1 votes
# Go, ~~92~~ 102 bytes

```
package main;import(."os";."fmt");func main(){s:=string('x'+1);if len(Args)>1{s=Args[1]};{Println(s)}}

```

Attempt This Online!

# Go, ~~172~~ 182 - 10 = ~~162~~ 172 bytes

```
package main;import(."os";."fmt";"io");func main(){s:=string('x'+1);if len(Args)>1{s=Args[1]}else if f,_:=Stdin.Stat();f.Size()>0{b,_:=io.ReadAll(Stdin);s=string(b)};for{Println(s)}}

```

Attempt This Online!

+10 bytes for removing "y" and newlines.

# Answer
> 1 votes
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 - 10 \\$ \approx \\$ -0.95 bytes

```
[z011D*C~ZK

```

Attempt This Online!

If calculating "11 squared" is cheating, here's one which doesn't have any numeric literals:

## Thunno, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 - 10 \\$ \approx \\$ -0.12 bytes

```
[z0AzZHAK~ZK

```

Attempt This Online!

#### Explanations

```
[z011D*C~ZK  # Implicit input (if given)
[            # while True:
 z0          #  Push the first input if it
             #  was given, or [] if it wasn't
   11        #  Push 11
     D*      #  Square to get 121
       C     #  Get chr(121) ("y")
        ~    #  Do a logical OR, yielding the input
             #  if it was given, and "y" if it wasn't
         ZK  #  Print with a trailing newline

```

```
[z0AzZHAK~ZK  # Implicit input (if given)
[             # while True:
 z0           #  Push the first input if it
              #  was given, or [] if it wasn't
   Az         #  Push the lowercase alphabet
     ZH       #  Remove the last element, to get
              #  "abcdefghijklmnopqrstuvwxy"
       AK     #  Get the last element, i.e. "y"
         ~    #  Do a logical OR, yielding the input
              #  if it was given, and "y" if it wasn't
          ZK  #  Print with a trailing newline

```

# Answer
> 1 votes
# GolfScript, ~~15~~ 10-10=0 bytes

```
{.puts.}do

```

Try it online!

For some reason I thought the *only* way to get input from STDIN was `"#{STDIN.read}`, but I then realized that STDIN is already left on the stack by default.

# Answer
> 1 votes
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 - 10 \\$\approx\\$ -8.354 bytes

```
(,

```

Try it online!

Prints the input forever. Simple.

# Answer
> 1 votes
# Python, 25 Bytes

```
while 1:print(chr(~-122))

```

Never knew you could do bitwise operations on non-binary numbers!

# Answer
> 1 votes
# Trilangle `-f`, 9 bytes

Doesn't contain a *line* feed (`\n`) but it does contain a *form* feed (`\f`).

```
"x")oo:,

```

Try it on the online interpreter! The `-f` flag has no meaning in the online version, but in the command line it means that closing stdout will terminate the program (e.g. `trilangle -f yes.trg | head -n 10`).

Since the form feed doesn't render, here's a hexdump (reversible with `xxd -r`):

```
00000000: 2278 2229 0c6f 6f3a 2c                   "x").oo:,

```

Notepad renders the form feed character as an up arrow, so I'll be using the symbol  in place of the form feed for the explanation.

The code unfolds to this:

```
   "
  x "
 ) ↑ o
o : , .

```

For lack of redirections, this simply executes in order:

* `"x`: Push the value of x (120) to the stack.
* `)`: Increment the top of the stack
* `o`: Output the character corresponding to the top of the stack ('y')
* `"↑`: Push the value of ↑ (12) to the stack.
* `:`: Divide the two values, so the stack now contains a single number (10). Line feeds are ignored by the interpreter anyways, so doing arithmetic is the only way to get a 10 on the stack.
* `o`: Output the character corresponding to the top of the stack ('\n')
* `,`: Pop the value from the stack, keeping memory bounded since it loops forever
* `.`: No-op

For lack of an explicit exit instruction, this loops forever.

# Answer
> 0 votes
# JAGL V1.0 20 - 10 = 10 With Bonus, 14 Without

```
Tdn{78h[}Sf{p9[pDd}u

```

Coulda probably done better, but here is the explaination:

```
Td                               Get a line of text input, and duplicate on stack
  n                              Negate its truth value (for the if)
   {78h[}                        Push a block which will push the y character, if called
         Sf                      Swap top two values on stack and if no input, push y
           {p9[pDd}              Push block which prints the input (or y) and a newline
                   u             Do until loop. Output always evaluates to true

```

Can be killed by SIGINT

Without bonus:

```
'x  '{1+}/{pd}u

```

explaination:

```
'x  '                            Pushes the string '\tx'
      {1+}                       Adds 1 to each character in the string, making it 'y\n'
          {pd}u                  Infinitely prints and duplicates

```

# Answer
> 0 votes
# Java, ~~157~~ 154 bytes

Despite the common misconception that you have to use `System.out` to print anything to the console in Java, this program outputs to the console using a `FileOutputStream` to the file described by `FileDescriptor.out`. Accoding to the specification for `FileDescriptor.out`, it is *"A handle to the standard output stream. Usually, this file descriptor is not used directly, but rather via the output stream known as System.out"*.

```
class A{public static void main(String[]a)throws Exception{for(;;)new java.io.FileOutputStream(java.io.FileDescriptor.out).write(new byte[]{120+1,9+1});}}

```

# Answer
> 0 votes
# Pascal: 40 characters

```
begin while 1=1do Writeln(Succ('x'))end.

```

Outputs “y”, stops on SIGINT.

# Answer
> 0 votes
# Lazy K, 167 bytes

<pre><code>`k````ssi``s`k``ss`k``siik``s`k`s``si`k```s``s`kski``s``s`ksk``s``s`ksk```s``s`kski``s``s`ksk``s``s`kski``s`kk``s`k`s``si`k``s``s`ksk```s``s`kski``s``s`ksk``s``s`kskik
</code></pre>

It is probably too long...

<pre><code>```ssi``s`k``ss`k``siik                                              fixed-point combinator
``s``s`ksk```s``s`kski``s``s`ksk``s``s`kski                          \n
```s``s`kski``s``s`ksk``s``s`ksk```s``s`kski``s``s`ksk``s``s`kski    y
</code></pre>

# Answer
> 0 votes
## C 42

```
main(){while(1){putchar(11*11);puts("");}}

```

# Answer
> 0 votes
This works in my Befunge interpreter:

```
"z"1-.25*.

```

10 chars. "z" means push the ascii value of the characted "z", 1 means push the number one, - means subtract, . means print the ascii value of it and * means multiply. For more info: http://en.wikipedia.org/wiki/Befunge

# Answer
> 0 votes
# Microscript, 19-10=9

`If['w2s]1{CaI#!Zx}h`

Besides the initial input, takes an extra input after each iteration and halts when and if any of the additional inputs is non-empty (the specs for the question said to provide a way to make it halt).

# Answer
> 0 votes
# PHP, 34 bytes - 10 = 24

```
for(;;)echo$argc>1?$argv[1]:y,"
";

```

Run with `php -nr '<code>'` or `php -nr '<code>' '<string>'`.

Or 56 bytes for an exact port:

```
for(;;)echo$argc>1?join(" ",array_slice($argv,1)):y,"
";

```

<sup>(-2 bytes with extended ASCII; -1 for the not-so-complete version)</sup>

# Answer
> 0 votes
# Jelly, 7 - 10 = -3 bytes

```
ØyṪ³ȯṄß

```

Try it online!

## Explanation

```
Øy             # The string "AEIOUYaeiouy"
  Ṫ            # Take the last element, namely "y"
    ³          # The cmdline argument (empty list if none supplied)
     ȯ         # Either the cmdline if supplied or "y"
      Ṅ        # Print with a newline
       ß       # Recurse

```

Thankfully Jelly programs can always be C-c-ed.

## Alternative Sans Y; 10 - 10 = 0 bytes

```
“¢³ƒ»Ṫ³ȯṄß

```

If the 'y' in the original answer is unacceptable, here's one without. This works on the same principle, the string `“¢³ƒ»` is the compressed version of "Jelly"

# Answer
> 0 votes
# Python 3, 40 bytes - 10 = 30

```
i=input()
while 1:print(i or chr(11**2))

```

Stops with SIGINT (Ctrl+C)

# Answer
> 0 votes
# OIL, 23 bytes noncompeting

```
120
8

17

1

4

11
6
6

```

Increments 120, transforms it to a "y", and repeatedly print it and a newline.

Can be stopped with SIGINT / `Ctrl`+`C`.

Variant that receives something from stdin instead:

# OIL, 13-10 = 3 bytes

```
5

4

11
6
2

```

# Answer
> 0 votes
# AHK, 38 bytes - 10 = 28

```
c=%1%
Loop,3
FileAppend,% c Chr(9+1),*

```
* I may have misunderstood, but I think the `9+1` is allowed. If not, I'll delete this.
* If `Loop` is used without brackets `{}`, it is assumed that only the next line is part of the loop.
* If `Loop` is used without a count, it will repeat until it encounters a `Break`.
* Per the help file, if an asterisk is passed as the filename into `FileAppend`, it outputs to `stdout`.
* `%1%` is the first passed argument.
* If I could use the input variable `%1%` directly, that would have been nice. It gets funny with the `Chr` function following it, though, and would have ended up being more bites.

# Answer
> 0 votes
# TI-BASIC, 8 bytes

```
While not(getKey:Disp Str0:End

```

# Answer
> 0 votes
# Chip, 15+3 = 18 bytes

+3 for flag `-w`, which ignores stdin and generates an endless stream of null bytes for input instead.

```
dbae
*}++g
 `zf

```

Try it online!
Note about the TIO: instead of using the `-w` flag, it uses input. The behavior is the same, except that input is finite. One byte of output per byte of input.

### Explanation

```
*}+
 `z

```

This is a 1-clock. On the first byte, the `+` is active, and on the second byte, the other three elements are active. The two states alternate endlessly.

```
d ae
* ++g
   f

```

This produces the output corresponding to 'y'. These letters each map to a bit: `_gfed__a` -\> `0b01111001` -\> `0x79` -\> 'y'.

```
db
*}
 `z

```

This produces the output corresponding to '\n'. Similar to above, but we have these bits: `____d_b_` -\> `0b00001010` -\> `0x0a` -\> '\n'.

# Answer
> 0 votes
# Tcl, 39 bytes

```
while 1 {puts [format %c [expr 11*11]]}

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 5 bytes - 10 = -5

```
a{:o!

```

Try it online!

Takes input via the `-s` flag and repeats it forever until the program is interrupted.

# Answer
> 0 votes
# MathGolf, 8 bytes -10 = -2

```
╜É'x)Äo∟

```

Try it online!

## Explanation

```
╜É         else without if (executes block of 3 chars if input is empty)
  'x)      increment "x" to get "y"
     Ä     start block of length 1
      o    print TOS without popping
       ∟   do while true without popping

```

Quite straightforward, but gets the job done.

# Answer
> 0 votes
# Python 3, 25 bytes

```
while 1:print(chr(11*11))

```

Try it online!

# Answer
> 0 votes
Python 3, 26-10=16 bytes

```
x=input()
while 1:print(x)

```

Seems too easy. Never posted here before so probably done something dumb. What did I miss?

**UPDATE** I don't think this is cheating (35-10=25):

```
exec("x=input()\nwhile 1:print(x)")

```

# Answer
> 0 votes
# Kotlin, 23 - 10 = 13 bytes

```
{while(1>0)println(it)}

```

Try it online!

# Answer
> 0 votes
# C (gcc), 30 - 10 = 20 bytes

```
f(a){for(gets(&a);puts(&a););}

```

Try it online!

# Answer
> 0 votes
# Pxem, filename: 22 bytes + content: 4 bytes - bonus: 10 bytes = 16 bytes.

* Filename (escaped unprintables): `.w.i.c\001.+.a\013.+l.w.el.a`
* Content: `.v.p`

Try it online!

## With comments

```
XX.z
# while size==0 || pop!=0; do
.a.wXX.z
  # push getchar; dup; push 1; push pop+pop;
  # NOTE EOF is -1
  .a.i.c\001.+XX.z
# done
.a.aXX.z
# push 11; push pop+pop;
.a\013.+XX.z
# push whatever not zero; while pop!=0; do call content; push whatever not zero; done
.al.w.el.a

```

```
XX.z
# get called, with my stack initialized to original one
# reverse; pop all to putchar for each of them
# implicitly return, pushing each content of
# my stack from bottom to pop to original one
.a.v.p

```

---

# Pxem, filename: 14 bytes + content: 0 bytes = 14 bytes.

* Filename: (unprintables are escaped) `.w\005\005.+\001x.+.p.a`
* Content: empty.

Wow, shorter than above!

Try it online!

# Answer
> 0 votes
# Zsh, 29 bytes

```
for ((;;))<<<${(#)$((11*11))}

```

tio example (times out)

Not cheating like the bash answer...

# Answer
> 0 votes
# Nooklang, 14 bytes

```
{120 1 + c p}t
```

Right now this isn't available on any online coding platform yet, so you will have to run the code from your computer.

Explaination:

```
{
  120 1 + # Returns 121 (aka ASCII value of y)
  c # Converts the value to character
  p # Prints out the character
} t # Infinite loop

```

# Answer
> 0 votes
# Nim, 37 - 10 = 27 bytes

```
var x=readLine stdin;while 1>0:echo x
```

Attempt This Online!

---
Tags: code-challenge, restricted-source
---


# Question
Title: Check if computer is connected to the internet
Write a program which, according to whether the script has access to the internet, produces an output which is "Truthy/Falsey". You may try and connect to any existing site, **at your own discretion** (don't use a shady site which only has 10% uptime - try to keep to above 80% annual uptime). If the site is down, your program does *not* have to work.

It must be a **standalone program** or a **function**. You may use libraries outside of the standard library to achieve this. Standard loopholes are forbidden. This is code golf, so the code with the shortest byte-count wins.

Example pseudocode:

```
function a:
    try:
        connect to internet
        return 1
    catch error:
        return 0

```

This is my first post on code golf, so if this violates any rules in any way or is a dupe, please alert me.

EDIT: Due to numerous suggestions, I have removed the UTF-8 byte count restriction

# Answer
# Bash (with *dnsutils*), 3 bytes

Sends a DNS request for "." (DNS root), exit code is 0 for success and \>0 otherwise.

**Golfed**

```
dig

```

**Test**

```
% dig >/dev/null; echo $?;
0

% nmcli nm wifi off
% dig >/dev/null; echo $?;
9

```

**Disclaimer**

This will obviously only work if your *DNS* server is sitting in the provider's network, i.e. in the "Internet" (as your provider network is normally a part of it), or if your system is using a public DNS server (like 8.8.8.8 from Google, which Android based systems use), as otherwise, you can get a cached copy from a local *LAN* server (or localhost).

But I assume this is not against the rules, as there are obviously more than one system where this does work as intended.

Pure-HTTP methods can also give false positives, due to an intermediate caching proxy, and are not guaranteed to work everywhere, so that is not something unique to this method.

**A slightly more reliable version, 8 bytes**

```
dig +tra

```

(a little tribute to @**Dig**ital **Tra**uma !)

Enables the "trace mode", which will force *dig* to do the recursive search by itself (see https://serverfault.com/a/778830), avoiding any cache issues.
> 33 votes

# Answer
# Bash + GNU utils, 8

* 5 bytes saved thanks to @Muzer.

```
wget to.

```

The other shell answers check the return code and echo some status output accordingly. This is unnecessary. The shell return code is already a usable Truthy/Falsey code and accessible in the `$?` parameter which is idiomatic for bash. Return code 0 means True. Return code \>0 means False.

In use:

```
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:10:51--  http://to./
Resolving to. (to.)... 216.74.32.107, 216.74.32.107
Connecting to to. (to.)|216.74.32.107|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11510 (11K) [text/html]
Saving to: ‘index.html.6’

index.html.6        100%[===================>]  11.24K  --.-KB/s    in 0.04s

2017-01-13 09:10:51 (285 KB/s) - ‘index.html.6’ saved [11510/11510]

ubuntu@ubuntu:~$ echo $?
0
ubuntu@ubuntu:~$ sudo ifconfig ens33 down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:00--  http://to./
Resolving to. (to.)... failed: Temporary failure in name resolution.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$ sudo ifconfig ens33 up
ubuntu@ubuntu:~$ # Local network up, upstream link down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:34--  http://to./
Resolving to. (to.)... failed: Name or service not known.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$

```
> 19 votes

# Answer
## Batch, 8 bytes

```
ping to.

```

`ping` will set `ERRORLEVEL` to `1` if the address cannot be resolved or reached.
> 9 votes

# Answer
# 05AB1E, ~~11~~ 9 bytes

Saved 2 bytes on "to." courtesy of *ev3commander*

```
…to..wgX›

```

Checks if the length of the content at http://to. is greater than 1.
`.w` returns 0 on error.
> 8 votes

# Answer
## R, 20 bytes

```
curl::has_internet()

```

There's a function for exactly this task in the `curl` package.
> 8 votes

# Answer
## Bash ~~66~~ ~~62~~ 21 bytes

```
ping -c1 g.gl echo $?

```

Thanks @Alex L. for the URL shortening tip.

Ungolfed version:

```
r=$(ping -c1 g.gl)
if [ $? -ne 0 ];
 then echo "0"
else echo "1"
fi

```

This is my first answer in Bash , i'm not sure i have shortened the script enough.
> 6 votes

# Answer
# Java, 72 bytes

```
a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);

```
> 6 votes

# Answer
# MATL, ~~15~~ 14 bytes

*One byte saved thanks to Kevin Cruijssen's suggestion*

```
'http://to.'Xi

```

Output is through STDOUT. This displays a non-empty string containing non-zero chars (which is truthy) if there is an Internet connection; and displays nothing (which is falsy) if there's no connection.

This can't be tested online because the `Xi` is not allowed in the online interpreters.

### Explanation

```
'http://to.'  % Push this string
Xi            % Return contents of that URL as a string. If there is no Internet
              % connection this gives an error, with no output on STDOUT

```
> 5 votes

# Answer
## C#, 87 bytes

```
_=>{try{new System.Net.WebClient().OpenRead("http://g.gl");return 1;}catch{return 0;}};

```

If an exception is considered falsey, which I don't think it is, then this is 65 bytes:

```
_=>new System.Net.WebClient().OpenRead("http://g.gl").ReadByte();

```

I also tried using the link `http://to.` as stated by @KevinCruijssen but it didn't seem to work.
> 4 votes

# Answer
# 8th, ~~23~~ 21 bytes

*Two bytes saved thanks to Kevin Cruijssen's suggestion* and to my discovery: http://to seems to work as well as http://to. (saving another byte)

```
"http://to" net:get .

```

If site http://to can be reached, it then prints `true`. Otherwise it prints `false`. It leaves retrieved data on the stack.
> 4 votes

# Answer
## Perl, 15 bytes

```
print`curl to.`

```

Run with:

```
perl -e 'print`curl to.`' 2> /dev/null

```

`curl` outputs stuffs on `STDERR`, don't mind them. If the computer has access to internet, it will print a few lines of html (truthy), otherwise, it will print nothing (falsy).

*Saved 1 bytes by using `to.` (instead of my previous `b.io`) thanks to @Kevin Cruijssen.*
> 4 votes

# Answer
# Javascript, 16 bytes

```
navigator.onLine

```

Returns `true` or `false`.

Try It!

I'm new here, so IDK if I counted bytes properly, or if builtins are cheating...
> 4 votes

# Answer
# MATLAB, ~~32~~ 22 bytes

```
urlread('http://g.gl')

```

**Explanation:**

If the internet connection is up, this will result in `ans` (the default variable) being a string with the entire html-code in plain text (which is **true** in MATLAB).

If the internet connection is down, this will write an error message to STDERR and leave the workspace empty (which is **false** in MATLAB).

Unfortunately, `urlread` requires a *full url-address*, so `g.gl` is not enough. 11 of the 22 bytes are therefore just the url-address.

---

**Alternative approach:**

A solution that catches the error and leave a 0 (also **false**) in the workspace if the connection is down:

```
0;try urlread('http://g.gl'),end

```

`0;` initializes the default variable `ans` to `0`, which is `false` in MATLAB. Then we `try` to read the url. This will give an error if the internet connection is down, or a character array if not (which is `true` in MATLAB).

We don't need to catch anything, so we just end. If the urlread call was successful, then `ans` will be a long string with the content of the website, otherwise `ans=0`.
> 3 votes

# Answer
## Bash, 39 bytes

```
exec 4<>/dev/tcp/to./80&&echo 1||echo 0

```
> 3 votes

# Answer
# JavaScript ES6, 71 43 bytes

```
fetch``.then(a=>alert(1)).catch(a=>alert``)

```

Alerts 1 if online, alerts an empty string if offline. Thanks to Patrick Roberts for helping me shave off some bytes

Old version

```
_=>fetch('http://enable-cors.org').then(a=>alert(a)).catch(a=>alert(0))

```

Alerts `[object Reponse]` if online, alerts `0` if offline

Removed the code snippet, it doesn't work because it loads from a different domain without CORS, but it works in the browser console
> 3 votes

# Answer
## Mathematica 10 Bytes

Assuming you have a valid copy of Mathematica, and login credentials on user.wolfram.com

```
CloudPut@1

```

will write the value 1 to the cloud. Truthy: CloudObject\[""\] Falsey: $Failed

```
CloudGet@%

```

Will return the value 1 that was uploaded to the cloud.
> 3 votes

# Answer
# PHP, 23 PHP + Curl, 14

Using PHP's backtick operator:

```
<?=`curl to.`;

```

---

*Orignal answer:*

I will try to make a start:

```
<?=file('http://x.gl');

```

This outputs nothing if x.gl can't be reached and `Array` if it is.

Another version where I'm not quite sure if they fit:

```
<?=getmxrr('x.gl',$a);  // 22 chars

```
> 2 votes

# Answer
## Powershell, ~~64~~ ~~26~~ 23 bytes

Saved 38 bytes, thanks to Shawn Esterman

Saved 3 bytes, and repaired script, thanks to briantist

```
Test-Connection -q g.gl

```
> 2 votes

# Answer
# JavaScript ES6, 90 81 Bytes

```
f=a=>{i=new Image();i.src="//placehold.it/1x1";i.onload=b=>a(1);i.onerror=c=>a()}

```

# JavaScript ES6, 22 21 bytes (Invalid)

Some browsers don't fully support, or produce the expected result when using navigator.onLine.

```
f=a=>navigator.onLine

```
> 2 votes

# Answer
# Scala, 54 bytes

```
x=>(Runtime.getRuntime exec "ping -c 1 ai."waitFor)<1

```

Pretty simple; executes a ping command to `http://ai./`, and returns true if it exits with 0, or false otherwise.
> 2 votes

# Answer
# Python 3 + requests, ~~59~~ ~~55~~ ~~53~~ 39 bytes

There has to be a requests answer, right?

```
from requests import*
get("http://to.")

```

Exit status is 0 for internet, 1 for no internet. Example:

```
$ python inet.py
$ echo $?
0
$ # Remove ethernet cable
$ python inet.py
$ echo $?
1

```

Changelog:

* -4 bytes (thanks Mego)
* -14 bytes (thanks pppery)
> 2 votes

# Answer
# Vyxal, 8 bytes

```
`g.gl`¨U

```

*Wait, `¨U` exists?*

Doesn't work on the online interpreter. Exits with error for falsy, runs successfully with no output for truthy.

```
`g.gl`   # string literal g.gl
      ¨U # GET request to that URL

```

For fun, here's a fairly cheaty version. Ports JavaScript:

# Vyxal `E`, 13 bytes

```
`ƈ⌈(₍†.on¬ḣ)`

```

Try it Online!

Just runs the JavaScript `alert(navigator.onLine)` using the `E` flag
> 2 votes

# Answer
## Python 2.7, 70 ~~77~~ Bytes

```
from urllib import*
a=1
try:urlopen('http://to.')
except:a=0
print a

```
~~```
import urllib as l
try:
 l.urlopen('http://a.uk')
 print 1
except:
 print 0

```~~

Uses 1 for truthy, 0 for falsy. a.uk redirects to a motorbike clothing company. Saved 3 bytes by assigning to a variable and printing that. And another one for the "to." trick (confirmed to work with urllib), two for getting rid of the pesky indents.
> 1 votes

# Answer
# Elixir, 33 bytes

```
{:ok,_}=:inet.getaddr('to',:inet)

```

0 if connected, 1 otherwise.
> 1 votes

# Answer
# Julia + Bash (with dnsutils), 10 bytes

```
run(`dig`)

```

``command`` in julia creates a `cmd` object that can be run with `run`.
> 1 votes

# Answer
# PowerShell, 12 bytes

```
!!(irm g.gl)

```
> 1 votes

# Answer
# Arturo, 21 bytes

```
download"http://x.gl"

```

Outputs via exit code.
> 1 votes

# Answer
# , 18 bytes

(2 bytes shorter than the previous R answer; additionally, this solution does not require an external package to be installed.)

```
!is.null(nsl("a"))

```

Try it online!

The `nsl` function looks up the IP address of a hostname. If there is no Internet connection, it outputs `NULL`, otherwise it outputs an IP address.

Note that we do not need to specify an existing domain name: when the domain name does not resolve (and as long as it does not end in a `.`), the domain name is instead appended to the server domain name. So we can use any 1-letter domain name, and the output of `nsl` is the non-NULL server IP. I think this behaviour is not specific to R.
> 1 votes

# Answer
# Scratch (scratchblocks3 syntax), 32 bytes

```
define
say(translate(1)to(Zulu v

```

"1" on success and an empty string on failure. Relies on Google Translate.

(Also, a slightly more amusing solution that actually outputs "true" but was unfortunately not optimal:)

```
define
say(translate(gwir)to(English v

```
> 1 votes

# Answer
# Clojure, 49 bytes

```
#(try(slurp"http://to.")1(catch Exception _ nil))

```

Returns `1` if it can connect, and `nil` otherwise.

Just attempts to `slurp` the page; throwing a `NoRouteToHostException` exception on failure, which is caught.

Unfortunately, the protocol and dot seem to be mandatory.
> 0 votes

# Answer
# Javascript (Nashorn), 61 bytes

```
print(new java.net.InetSocketAddress("to.",80).getAddress())

```

Based on Huntro's Java answer.
> 0 votes

# Answer
# Lua, 90 bytes

```
_,c=require('socket.http').request('http://g.gl')if string.find(c,'not')then os.exit(1)end

```

Sends a request to `g.gl` \- exits with code `1` if can't connect
> 0 votes

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


title: Find the Prime Signature

text:
# Question
Title: Find the Prime Signature
The Prime Signature of a number is the list of the exponents of the prime factors of a number, sorted in descending order (exponents of `0` are ignored). Inspired by Combo Class's "The Magnificent Patterns of Prime Signatures" video.

For example, the prime factorization of `6860` is `2 * 2 * 5 * 7 * 7 * 7`, or `2^2 + 5^1 + 7^3`. The exponents are `2`, `1`, and `3`, so the Prime Signature is `{3, 2, 1}`

# I/O

You will be given an integer on the interval `[1, 10,000,000]`.

You must output an array/list/vector or a string (in the format below) of the input's prime signature.

# Examples/Test Cases

| Numbers | Signature |
| --- | --- |
| 1 | ∅ or {} |
| 2, 3, 5, 7, 11 | {1} |
| 4, 9, 25, 49, 121 | {2} |
| 6, 10, 14, 15, 21 | {1, 1} |
| 8, 27, 125, 343 | {3} |
| 12, 18, 20, 28 | {2, 1} |
| 16, 81, 625, 2401 | {4} |
| 24, 40, 54, 56 | {3, 1} |
| 30, 42, 66, 70 | {1, 1, 1} |
| 32, 243, 3125 | {5} |
| 36, 100, 196, 225 | {2, 2} |
| 12345 | {1, 1, 1} |
| 123456 | {6, 1, 1} |
| 1234567 | {1, 1} |
| 5174928 | {5, 4, 3} |
| 8388608 | {23} |
| 9999991 | {1} |

Note that these are not sets in the computer science sense because they can contain duplicate values and have an ordering (admittedly, some set implementations are ordered).

# Scoring

This is , so the fewest bytes wins!

# Answer
> 6 votes
# APL (Dyalog Extended), 6 bytes

```
∨2⌷2⍭⊢

```

Try it online!

descending sort of…

`2⌷` the second row of…

`2⍭` the table of primes (in the first row) and their exponents (in the second row) of…

the argument

# Answer
> 5 votes
# Vyxal, 4 bytes

```
∆ǐsṘ

```

Try it Online!

So uh turns out the prime exponents built-in doesn't include 0s by complete accident - it's not a bug, just a consequence of how it's implemented and a different understanding of what a prime exponents built-in should do lol.

## Explained

```
∆ǐsṘ
∆ǐ   # prime exponents of the input
  s  # sorted
   Ṙ # reversed

```

# Answer
> 5 votes
# MATL, 5 bytes

```
_YFSP

```

Try at **MATL Online**!

### Explanation

```
_YF   % Implicit input. Prime factor exponents without zeros
S     % Sort
P     % Flip. Implicit display

```

# Answer
> 5 votes
# Factor \+ `math.primes.factors`, 37 bytes

```
[ group-factors values [ >=< ] sort ]

```

Try it online!

* `group-factors` Get the prime factorization of an integer as an assoc where keys are factors and values are exponents.
* `values` Get the exponents.
* `[ >=< ] sort` Sort into descending order.

# Answer
> 5 votes
# PARI/GP, 27 bytes

```
n->-vecsort(-factor(n)[,2])

```

Attempt This Online!

# Answer
> 5 votes
# Charcoal, 56 bytes

```
Ｎθ≔²ηＷ⊖θ¿﹪θη≦⊕η«≔⁰ζＷ¬﹪θη«≦⊕ζ≧÷ηθ»⊞υζ»≔⟦⟧ζＷ⁻υζＦ№υ⌈ι⊞ζ⌈ιＩζ

```

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

```
Ｎθ

```

Input the integer.

```
≔²η

```

Start trial division at `2`.

```
Ｗ⊖θ¿﹪θη≦⊕η

```

Until the integer has been reduced to `1`, keep incrementing the trial divisor until it divides the integer.

```
«≔⁰ζＷ¬﹪θη«≦⊕ζ≧÷ηθ»⊞υζ»

```

Calculate the multiplicity of the trial divisor and push it to the predefined empty list.

```
≔⟦⟧ζＷ⁻υζＦ№υ⌈ι⊞ζ⌈ιＩζ

```

Sort the list in descending order and output the result.

36 bytes by importing Python modules:

```
≔▷”8±J≧∕*}G⦃⬤t；⁼hsλ”ＮθＩ⮌▷SＥ▷listθ§θι

```

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

```
≔▷”8±J≧∕*}G⦃⬤t；⁼hsλ”Ｎθ

```

Use `sympy.ntheory.factorint` to get a dictionary of prime factors and their multiplicities.

```
Ｉ⮌▷SＥ▷listθ§θι

```

Extract the multiplicities, sort them, and output the reversed result.

This can be reduced to 26 bytes if you run the latest version of Charcoal locally:

```
Ｉ⮌▷SＥ▷”8±J≧∕*}G⦃⬤t；⁼hsλ”Ｎι

```

Unfortunately you can't try this online because the version of Charcoal on TIO can't enumerate dictionaries and the version of Charcoal on ATO can't import `sympy`.

# Answer
> 4 votes
# Pyt, ~~6~~ ~~9~~ 8 bytes

```
Đϼ1\⇹ḋɔŞ

```

Try it online!

```
Đ            implicit input (n); duplicate top of stack
 ϼ           get the unique prime factors of n
  1\        remove any pesky 1s
     ⇹ḋ      get the prime factors of n (with duplicates)
       ɔ     count the number of occurrences of each unique prime factor
        Ş    sort in descending order

```

# Answer
> 4 votes
# JavaScript (Node.js), 77 bytes

```
f=(n,i=2,w)=>n%i?n-!w?f(n,i+1).concat(w||[]).sort((a,b)=>b-a):[]:f(n/i,i,-~w)

```

Try it online!

Thank Arnauld for -1 or real`[]`ify(was two solutions)

# Answer
> 4 votes
# Python, 71 bytes

`-4` bytes for both code segments thanks to `Neil`.
`-8` bytes thanks to `corvus_192`

```
lambda n:sorted(factorint(n).values())[::-1]
from sympy import*

```

Attempt This Online!

# Python, 128 bytes

Uses a recursive helper function to calculate the prime factors of a number.
Failed on the test cases `1234567, 9999991` due to `RecursionError: maximum recursion depth exceeded`

```
lambda n:sorted(Counter(f(n)).values())[::-1]
f=lambda n,i=2:n//i*[0]and f(n,i+1)if n%i else[i]+f(n//i)
from collections import*

```

Attempt This Online!

# Answer
> 4 votes
# SageMath, 45 bytes

```
lambda n:sorted(e for p,e in factor(n))[::-1]

```

Try it online!

# Answer
> 3 votes
# Jelly, 6 bytes

```
ÆE¹ƇṢU

```

Try it online!

A port of my vyxal answer.

## Explained

```
ÆE¹ƇṢU
ÆE     # Prime exponents of the input - contains 0s
  ¹Ƈ   # so filter out those 0s
    Ṣ  # sort the list
     U # and reverse it

```

# Answer
> 3 votes
# Octave, ~~58~~ ~~51~~ 47 bytes

```
@(n)-sort(-diff(find(diff([0 factor(n) n<2]))))

```

**Try it online!**

### Explanation

```
@(n)                                              % Define anonymous function
                             factor(n)            % Prime factors of input
                          [0                      % Prepend 0 and...
                                       n<2]       % ...postpend 1 if n<2, 0 otherwise
                     diff(                 )      % Consecutive differences
                find(                       )     % Indices of nonzeros
           diff(                             )    % Consecutive differences
    -sort(-                                   )   % Negate, sort, negate

```

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
Ó0K{R

```

Try it online or verify all test cases.

**Explanation:**

```
Ó      # Get a list of the prime factorization of the (implicit) input-integer
 0K    # Remove all 0s
   {   # Sort it (from lowest to highest)
    R  # Reverse it (from highest to lowest)
       # (after which the result is output implicitly)

```

# Answer
> 3 votes
# , 71 bytes

```
f=\(n,m=2,l=0)`if`(n%%m,-sort(-c(if(l)l,if(n>1)f(n,m+1))),f(n/m,m,l+1))

```

Attempt This Online!

Recursive function that directly calculates prime exponents, and sorts them on every recursive call (which is unneccessary except for the outermost call, so overflows the stack for large inputs).

---

# , ~~74~~ 67 bytes

*Edit: -7 bytes thanks to pajonk*

```
\(n,`?`=\(n,m)if(n>1)`if`(n%%m,n?m+1,c(m,n/m?m)))-sort(-table(n?2))

```

Attempt This Online!

Uses recursive helper function `?` to calculate prime factors, and then sorts their exponents a single time (and thus copes with much larger inputs, but at the expense of 3 more bytes of code).

# Answer
> 2 votes
# Retina 0.8.2, 59 bytes

```
.+
$*
m(+`\A(1+)(\1)+$
$1¶$#2
(?=(¶.+))(\1)+$
¶$#2
1A`
O^#`

```

Try it online! Outputs prime signature on separate lines but link is to test suite that joins on commas for convenience. Explanation:

```
.+
$*

```

Convert to unary.

```
m(`

```

Run the rest of the script in multiline mode where `$` matches at the end of any line.

```
+`\A(1+)(\1)+$
$1¶$#2

```

Repeatedly extract the smallest prime factor of the input number. (`$#2` is actually one less than the smallest prime factor but it's consistent and we only care about the multiplicities anyway.) As this is slow for large numbers the test suite omits some of the slower cases.

```
(?=(¶.+))(\1)+$
¶$#2

```

Get the multiplicities of each factor.

```
1A`

```

Remove the `1` remaining after all of the prime factors have been extracted.

```
O^#`

```

Sort the multiplicities in descending numeric order.

# Answer
> 2 votes
# , 12 bytes

```
__\:~@{:@q:]

```

Independently found, but essentially a port of Adám's APL answer. An exact port would be `1\:~@{__ q:]`, at 12 bytes as well.

Attempt This Online!

```
__\:~@{:@q:]
__       q:]  NB. find prime exponents excluding zero
      {:@     NB. take the tail of the result
  \:~@        NB. descending sort the result

```

# Answer
> 2 votes
# Japt, 8 bytes

-6 thanks to @Shaggy

```
k ü mÊñn

```

Try it

```
k ü mÊñn
k        Get the prime factors of the input
  ü      Group the factors to lists of the same element
    mÊ   Map each group to its length
      ñn Sort them in descending order

```

# Answer
> 2 votes
# Husk, 6 bytes

```
↔OmLgp

```

Try it online!

```
     p  # get the prime factors
    g   # group identical elements
  mL    # get the length of each group
        # (these are the prime exponents)
 O      # sort into ascending order
↔       # and reverse

```

# Answer
> 2 votes
# Japt, 8 bytes

Gave Jacob my initial solution, so here's an alternative.

```
k òÎmÊÍÔ

```

Try it

```
k òÎmÊÍÔ     :Implicit input of integer
k            :Prime factors
  ò          :Partition between elements where
   Î         :  The sign of their differences is truthy (non-zero)
    m        :Map
     Ê       :  Length
      Í      :Sort
       Ô     :Reverse

```

# Answer
> 1 votes
# Arturo, 45 bytes

```
$=>[factors.prime&|tally|values|sort|reverse]

```

Try it

# Answer
> 1 votes
# Burlesque, 7 bytes

```
fCf:)-]

```

Try it online!

```
fC   # Prime factors
f:   # Count occurrences
)-]  # Map-Take counts

```

# Answer
> 1 votes
# Thunno, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
Zhwz;

```

Attempt This Online!

#### Explanation

```
Zhwz;  # Implicit input
Zh     # Prime factor exponents
  w    # Without zeros
   z;  # Reverse-sorted
       # Implicit output

```

# Answer
> 0 votes
# Desmos, 97 bytes

```
A=[2...n]
P=A[∑_{N=3}^A0^{mod(A,N-1)}=0]
L=log_P(gcd(n,P^n))
F=L.sort[L.length...1]
f(n)=F[F>0]

```

Try It On Desmos!

Try It On Desmos! - Prettified

This theoretically works for all inputs \\$\le19998\\$, but in reality, because of floating point issues, this only works for numbers up to around \\$15\\$ or so.

Below is a version that works for all numbers up to \\$19998\\$, at the cost of a few bytes:

### 133 bytes

```
A=join([1....5n],n)
P=A[∑_{N=2}^{floor(A^{.5})}0^{mod(A,N)}=0]
L=log_P(gcd(n,P^{floor(log_Pn)}))
F=L.sort[L.length...1]
f(n)=F[F>0]

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 0 votes
# Stax, 7 bytes

```
òT║≥Q{U

```

Run and debug it

This is a packed stax program which unpacks to the following 8 bytes:

```
|n0-or|u

```

Run and debug it

# Explanation

```
|n       # list of prime exponents
  0-     # remove 0s
    o    # sort
     r   # reverse
      |u # uneval (print array as array)

```

# Answer
> 0 votes
# Mathematica, 38 bytes

Golfed vesrion, try it online!

```
f=Reverse@Sort[Last/@FactorInteger@#]&

```

Ungolfed version

```
PrimeSignature[n_Integer] := Module[{factorization, exponents},
  factorization = FactorInteger[n];
  exponents = Last /@ factorization;
  Sort[exponents]//Reverse
]

PrimeSignature[6860]//Print

```

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


title: Does the sequence shut the box?

text:
# Question
Title: Does the sequence shut the box?
Determine whether a given sequence could be a winning sequence for the game shut the box.

## Background

There are a few variants to this game, so I'll clarify the rules here. Play begins with 12 tiles (1 through 12) face up. Each turn the player rolls two six sided dice, and must then flip over one or more tile(s) which sum to the given roll. The game ends when you roll a number that cannot be summed to with tiles that remain face up. Your score then is the sum of the values of the remaining face up tiles. If one manages to flip over all tiles (obtaining a score of 0), this is referred to as "shutting the box".

An example of a winning game may go as follows:

```
roll | sum | face up tiles remaining
4, 3   7     [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12]
1, 4   5     [1, 2, 3, 4, 6, 8, 9, 10, 11, 12]
6, 6   12    [1, 2, 3, 4, 6, 8, 9, 10, 11]
2, 2   4     [1, 2, 3, 6, 8, 9, 10, 11]
5, 1   6     [6, 8, 9, 10, 11]
3, 6   9     [6, 8, 10, 11]
5, 3   8     [6, 10, 11]
6, 5   11    [6, 10]
4, 2   6     [10]
5, 5   10    []

```

## The challenge

For this challenge you will take a sequence of roll sums (ie. `[7,5,12,4,6,9,8,11,6,10]`) as input, and output a truthy value which will denote whether or not this sequence of rolls could be used to "shut the box" exactly (no extra rolls either).

Standard i/o rules apply, input can be taken in any reasonable form for a sequence, and output can be anything as long as truthy and falsy are distinct and consistent. You may assume that the input will consist only of integers 2-12.

This is , so the shortest answer in bytes wins.

## Test cases

#### Truthy:

```
[2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12]
[3, 4, 5, 6, 7, 8, 9, 12, 12, 12]
[12, 12, 12, 12, 12, 12, 6]
[12, 12, 12, 12, 12, 11, 7]
[7, 7, 7, 7, 8, 9, 10, 11, 12]
[12, 4, 5, 7, 8, 9, 10, 11, 12]
[2, 5, 7, 7, 7, 8, 9, 10, 11, 12]

```

#### Falsy:

```
[]
[2]
[12, 5, 6]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8]
[3, 3, 4, 5, 6, 8, 9, 12, 12, 12, 4]
[2, 2, 5, 6, 6, 7, 8, 9, 10, 11, 12]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12, 2, 2, 2]
[8, 8, 8, 10, 10, 10, 12, 12]

```

# Answer
# Vyxal, 10 bytes

```
vṄΠ'fs12ɾ⁼

```

Try it Online! Outputs an empty list for falsy, a non-empty list for truthy. Link is for a much smaller version as this is \\$O\left(\prod\_{i=0}{n\_i}^2\right)\\$, that is, takes time proportional to the square of the product of the inputs. -1 by stealing some ideas from Kevin Cruijssen's 05AB1E answer.

```
vṄ         # Take the integer partitions of each number
  Π        # Take the cartesian product of this
   '       # Filter all possible partitions by...
    fs     # Flattened and sorted
         ⁼ # Is the result equal to...
      12ɾ  # range(1, 12)?

```
> 9 votes

# Answer
# Python3, 230 bytes:

```
def C(d,n,c=[]):
 if(K:=sum(c))==n:yield{*c};return
 for j in d:
  if K+j<=n:yield from C(d-{j},n,c+[j])
def f(d):
 q=[({*range(1,13)},d)]
 while q:
  s,d=q.pop(0)
  if not s:return 1
  if d:
   for r in C(s,d[0]):q+=[(s-r,d[1:])]

```

Try it online!

Outputs `1` for Truthy and `None` for Falsy.
> 6 votes

# Answer
# Curry (PAKCS), 62 bytes

```
(!12)
[]!0=1
(0:a)!n=a!n
(a++b:c)!n|b>=n&&n>0=(a++b-n:c)!(n-1)

```

Try it online!

Returns `1` for truthy, and nothing otherwise. It might return the same `1` multiple times for truthy result.
> 6 votes

# Answer
# JavaScript, ~~61~~ 57 bytes

```
f=(s,k=12)=>s.some((v,i)=>k?f(t=[...s],k-1,t[i]-=k):v)^!k

```

Try it online!

Takes an `Array`.

`k` counts down from 12 to 1. Each number is tried at each position in the array; each time, spread syntax is used to make a copy of the array, in which `k` is subtracted from that position and the function is recursively called.

When `k` hits 0, the function passed to `some` instead returns each value in the array, and then `some` returns `true` if any of the values are nonzero and `false` otherwise. `^!k` inverts the result for `k`=0, to be 1 if all the values are zero.
> 5 votes

# Answer
# 05AB1E, 12 bytes

```
Åœ.«âʒ˜ê12LQ

```

Outputs `[]` as falsey result; and a nested integer list as truthy result.

Port of *emanresuA*'s Vyxal answer, so make sure to upvote him/her as well!

(Don't) try it online (try it with a smaller example, which won't time out).

**Explanation:**

```
Åœ           # Map each integer in the (implicit) input-list to: all positive integer
             # lists that sum to that value
  .«         # (Right-)reduce this list of lists by:
    â        #  Taking the cartesian power between two lists
     ʒ       # Then filter this list of nested lists by:
      ˜      #  Flatten the nested list
       ê     #  Sorted-uniquify the list
           Q #  And check if it's now equal to
        12L  #  a list in the range [1,12]
             # (after which the filtered result is output implicitly)

```
> 4 votes

# Answer
# C (GCC), ~~123~~ 117 bytes

*-6 bytes thanks to @ceilingcat*

```
f(r,x,t,s,b,R)int*r;{for(R=0,t=8192;t--;R|=!x||s==*r&(t&x)==t&&f(r+1,x&~t))for(s=0,b=13;b--;)s+=t&1<<b?b:0;return R;}

```

Attempt This Online!

Note that it is exponentially slow; if you want it to run in a reasonable amount of time, add `if(R)return R;` after the `x&~t);`
> 2 votes

# Answer
# Bash (+cureutils+bc), 145 160 *fail* bytes

```
f(){
test `echo 0 $@|sed -e s/\ /+/g|bc` = 78||return 1
y=12
echo $@|fmt -w1|sort -rn|while read x&&test $y -ge 6
do
[ $x -lt $y ]&&return 1
: $(( y-- ))
done
}

```

Try it online!

Based on my observation above:

> Two necessary conditions that are sufficient to eliminate the Falsy examples: the sum of the sequence must be 78. For every n\>=6 there must be at least 13-n entries in the sequence \>= n. I don't know if we are just missing another Falsy sequence, or if this is enough.

And on my fondness for answers in bash, I decided to give it a try.

Input is function parameters. The function exits with either 0=truthy or 1=falsy. The test harness prints expected, actual, if it matched, and the input. It works for all the current test cases.

Previously I wrote

> I'm not quite sure why.

Well, the problem was the lack of a stopping condition. Adding test case `[2, 5, 7, 7, 7, 8, 9, 10, 11, 12]` revealed this, and added 15 bytes to my solution.

And I haven't tried serious golfing yet.

## Second Edit:

A couple more test cases:

```
[ 2, 5, 2, 5, 7, 7, 8, 9, 10, 11, 12]
[ 2, 2, 2, 12, 12, 12, 12, 12, 12]

```

Since no possible Truthy sequence can have two 2s, or three 3s, and probably some other combinations, my answer current fails. And I'm not sure how it can be fixed... or even if.

## Third Edit:

I generated some complete lists. There are 636 distinct valid sorted sequences. There are 220295 distinct sorted sequences totaling to 78. If we discard the sequences before "12 11 10 9 8 7 6 5 4 3 2", which would not be able to remove all the numbers, and discard any sequence of more than 11, we are left with 6638 sequences.

My original 145 byte answer got 315 false negatives, and 124 false positives. My (first) 160 byte answer got no false negatives and 3075 false positives. My current 160 byte answer (`test $x -ge 6` changed to `test $y -ge 6`) gives no false negatives and 1600 false positives. (I had been hoping for some simple special cases.)
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~124~~ ~~108~~ 84 bytes

```
Max[Length/@Fold[Select[Join@@@Tuples@{##},0!=##&@@#&]&,IntegerPartitions/@#]]===12&

```

Try it online!

Thanks to @att!!
> 2 votes

# Answer
# Charcoal, 41 bytes

```
⊞υ⊕…¹²ＦＡ≔∧υΣＥυＥΦＥＸ²ＬκΦκ＆μＸ²π⁼ιΣμ⁻κμυ∧υ¬Συ

```

Attempt This Online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for flipped, nothing if not. Explanation:

```
⊞υ⊕…¹²

```

Start with a list of the numbers `1` to `12`.

```
ＦＡ

```

Loop through the input roll sums.

```
≔∧υΣＥυＥΦＥＸ²ＬκΦκ＆μＸ²π⁼ιΣμ⁻κμυ

```

For each position found so far, find all the subsets of unflipped tiles that sum to the current sum, remove them from the position, and save all of the resulting positions for the next iteration. Note that `Sum` doesn't know what to do with an empty list (which happens when the previous move was impossible) so there's a short-circuit for that case.

```
∧υ¬Συ

```

Check that we were able to flip over all of the tiles.
> 1 votes

# Answer
# Husk, ~~13~~ ~~11~~ 13 bytes

*Edit: +2 bytes to fix bug that failed to realise that incomplete 'shut the box' sequences can't themselves 'shut the box'.*

```
¬€ṁö→½Ṗ∫Pḣ12∫

```

Try it online (using only 6 tiles to avoid timing out)

```
 €               # first index (or 0 if not found) of
              ∫  # cumulative sum of the input
                 # in
  ṁö             # list conctructed by mapping over
          P      # all permutations of
           ḣ12   # 1..12
       Ṗ         # and taking all ordered sublists of
        ∫        # the cumulative sum of each permutation
                 # BUT: we need to include the last element
                 # to avoid matching incomplete seqeunces, so
     ½           # split it in half (longer half comes first)
    ←            # and take the second half, containing all the
                 # sublists that contain the last element;
¬                # and finally return the logical NOT of this

```
> 1 votes

# Answer
# Haskell, 129 bytes

```
p[]=[[]]
p(x:y)=[x:s|s<-p y]++p y
t#[]=null t
t#(r:q)=length t>0&&any(#q)[filter(`notElem`s)t|s<-p[1..12],sum s==r,all(`elem`t)s]

```

Attempt This Online!
> 1 votes

# Answer
# Scala, 382 bytes

It can be golfed more.

Golfde version, try it online!

```
type S=Set[Int]
type L=List[Int]
def c1(d:S,n:Int,c:L=Nil):List[S]={val k = c.sum;if(k==n)List(c.toSet);else if(k>n)Nil;else d.toList.flatMap(j=>c1(d-j,n,j::c));}
def f(d:L):Int={val q=Queue[((S,L))]((1 to 12).toSet->d);while(q.nonEmpty){val (s,ds)=q.dequeue();if(s.isEmpty)return 1;if(ds.nonEmpty){val remaining= ds.tail;c1(s,ds.head).foreach(r=>q.enqueue((s--r,remaining)));}}
0;}

```

Ungolfed version

```
import scala.collection.mutable.Queue

object Main extends App {

  def combinations(d: Set[Int], n: Int, c: List[Int] = Nil): List[Set[Int]] = {
    val k = c.sum
    if (k == n) List(c.toSet)
    else if (k > n) Nil
    else d.toList.flatMap(j => combinations(d - j, n, j :: c))
  }

  def f(d: List[Int]): Int = {
    val q = Queue[((Set[Int], List[Int]))]((1 to 12).toSet -> d)
    while (q.nonEmpty) {
      val (s, ds) = q.dequeue()
      if (s.isEmpty) return 1
      if (ds.nonEmpty) {
        val remaining = ds.tail
        combinations(s, ds.head).foreach(r => q.enqueue((s -- r, remaining)))
      }
    }
    0
  }

  val truthy_tests = List(
    List(2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12),
    List(3, 4, 5, 6, 7, 8, 9, 12, 12, 12),
    List(12, 12, 12, 12, 12, 12, 6),
    List(12, 12, 12, 12, 12, 11, 7),
    List(7, 7, 7, 7, 8, 9, 10, 11, 12),
    List(12, 4, 5, 7, 8, 9, 10, 11, 12)
  )
  val falsy_tests = List(
    List(),
    List(2),
    List(12, 5, 6),
    List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
    List(3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12),
    List(7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8),
    List(3, 3, 4, 5, 6, 8, 9, 12, 12, 12, 4)
  )

  truthy_tests.foreach { t => println(f(t)) }
  println("-" * 30)
  falsy_tests.foreach { t => println(f(t)) }
}

```
> 1 votes

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


title: Guessing on straws

text:
# Question
Title: Guessing on straws
*Dedicated to Martin Gardner, taken from his book*

## Background

In the old days, the Slavs had a divination method for finding out whether a girl would get married. The girl would clutch six straws in her hand so that the ends would poke out the top and bottom of her fist. Then her friend would join together the ends of pairs of straws, first at the top and then at the bottom. If after all ends had been joined, the straws formed a single cycle/loop, then the girl would get married.

## Goal of challenge

Given the number of straws \\$N\\$ and the binding scheme (how the ends of the straws are tied together), determine whether the straws form a single cycle/loop. In the scheme, every straw is described with a unique index from \\$1\\$ to \\$N\\$.

## Input

* Number of straws \\$N\\$ (which is an even integer \\$\geq 2\\$)
* Two schemes for top and bottom links. It may be nested arrays of pairs`[[1, 4], [2, 5], [6, 3]]`; or a list of values from \\$1\\$ to \\$N/2\\$ where paired indices have the same value; or any format suitable for your language.

You may suppose that schemes are valid. For example in 1-indexed format every scheme has \\$N/2\\$ sublists with length \\$2\\$ and contains all (and only) numbers from \\$1\\$ to \\$N\\$. No self-links (`[1, 1]`); no tautologies (`[[1, 2], [2, 1], …]`), no broken lists (`[[1], [ ], …]`), no missing pairs etc.
**UPD**
For this reason, the number of straws \\$N\\$ is not required as input and can be derived from the length of schemas, if it shortens your code.

Please note, that pairs are unordered, so e.g. `[[1, 4], [2, 5], [6, 3]]` and `[[4, 1], [2, 5], [3, 6]]` are both valid (and equivalent) schemes.

## Output

Any two distinct symbols for "No/many loops" and "Single loop" cases. Suitable for golfing on your language:

* `-1`, `1`
* `False`, `True` etc.

## Example

Number of straws: `4`
Top links: `[[1, 4], [3, 2]]` (At the top, straw #1 is linked with straw #4, and #3 with #2)
Bottom links: `[[3, 1], [2, 4]]` (At the bottom, straw #1 is linked with straw #3, and #2 with #4)
We can start from #1 at the top (or any other straw) and move from top to bottom and back according to the links: `1 → 4 → 2 → 3 → 1`. For this input we get the loop, that include all straws, so the answer is `True`.

## Test cases

```
N: 2, TopLinks: [[1, 2]], BottomLinks: [[2, 1]]  → True

N: 4, TopLinks: [[1, 2], [3, 4]], BottomLinks: [[2, 1], [3, 4]]  → False

N: 4, TopLinks: [[1, 4], [3, 2]], BottomLinks: [[3, 1], [2, 4]] → True

N: 8, TopLinks: [[1, 2], [3, 4], [6, 5], [7, 8]],
BottomLinks: [[8, 1], [3, 2], [4, 5], [7, 6]]  → True

```

# Answer
# Wolfram Language (Mathematica), 22 bytes

```
ConnectedGraphQ@*Graph

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 10 bytes

```
æʒ˜D¢ÈP}g<

```

Try it online!

Takes as input a list of pairs such that two straws have the same first element if they are connected at the top, and the same second element if they are connected at the bottom. Requires the top and bottom values to be disjoint. Can take them as two separate lists at a cost of +1 byte.

Returns an 05AB1E boolean, which is 1 for true and any other value for false. Can be made to return a 1 or 0 by adding `Θ` (05AB1E truthified) at the end.

## Explanation

We return the number of subsets of straws which aren't connected to any straw not in the subset minus one. Those subsets are the ones which can be partitioned to cycles. If there is a single cycle, the only such subsets will be the entire set and the empty set, and we will return 1. However, if there are any more cycles, there will be more than 2 such sets (for example - the empty set, all the straws, and the straws in any cycle), so we will return a number greater than 1 which is falsey in 05AB1E

```
æ     for all subsets of straws
ʒ     only keep those such that:
 ˜     after flattening the pairs
 D     if we duplicate the list
 ¢     and count the number of occurrences of each value
 È     and check that it's even
 P     the product will be 1 - that is, all values appear an even number of times
}
g     count how many such sets are there
<     decrease it by 1 (and implicitly output)

```
> 7 votes

# Answer
# Arturo, ~~58~~ 56 bytes

```
$[a,b,n][∨∧n=2a<>b every? a'x->every? b=>[[]<>--x&]]

```

Try it

```
$[a,b,n][               ; a function taking three arguments
    ∨∧n=2a<>b           ; is n equal to 2 and a not equal to b? or is...
    every? a'x->        ; every pair from a
        every? b=>[     ; paired with every pair from b
            []<>--x&    ; not empty when their set difference is taken?
        ]               ; end every
]                       ; end function

```
> 4 votes

# Answer
# JavaScript (ES6), 68 bytes

Expects `(N)(list)`, where `list` contains all 0-indexed pairs. Returns \\$0\\$ or \\$1\\$.

```
(n,m=1)=>g=a=>a.some(([x,y,q=1<<x|1<<y])=>m&q&&m^(m|=q))?g(a):m+1>>n

```

Try it online!

### Commented

```
(              // outer function taking:
  n,           //   n = number of straws
  m = 1        //   m = bit mask, initialized to 1
) =>           //
g = a =>       // inner recursive function taking the array of links a[]
a.some(([      // for each link
  x, y,        // with x, y = straw indices
  q = 1 << x | // and q = corresponding bit mask for these indices:
      1 << y   //
]) =>          //
  m & q &&     //   if m and q have at least one bit in common:
    m ^        //     test whether m is changed when
    (m |= q)   //     the bits of q are merged with those of m
)              // end of some()
?              // if truthy:
  g(a)         //   do a recursive call
:              // else:
  m + 1 >> n   //   return 1 if the n least significant bits of m are set

```

### 65 bytes

Same input format, but returns \\$1\\$ for *true* and some integer \\$\>1\\$ for *false*.

```
(n,m=1)=>g=a=>a.some(([x,y,q=1<<x|1<<y])=>m&q&&m^(m|=q))?g(a)-1:n

```

Try it online!
> 3 votes

# Answer
# Charcoal, 33 bytes

```
Ｆ§θ⁰⊞υιＷΦＥ⁺θη⁻κυ⁼¹ＬκＦι⊞υ⊟κ⊙⁺θη⁻ιυ

```

Try it online! Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. nothing if the straws are linked, `-` if they are not. Explanation:

```
Ｆ§θ⁰⊞υι

```

Make a copy of the first link.

```
ＷΦＥ⁺θη⁻κυ⁼¹Ｌκ

```

While links between previously linked straws and as yet unlinked straws exist...

```
Ｆι⊞υ⊟κ

```

... push all newly linked straws to the list.

```
⊙⁺θη⁻ιυ

```

Check whether any unlinked straws remain.

Note that the input format guarantees that if the straws are all linked then they will be in a single cycle.
> 3 votes

# Answer
# Vyxal, 17 bytes `A`

```
vṅ÷:Ld1$(voÞṡḣ‟)₃

```

Input: nested array, output: `1(True)`, `0(False)`

```
vṅ                  # Convert all pairs to strings
  ÷:L               # Split and find length of one list
     d              # Double length (get number of straws N)
      1$            # Push 1 (may be any straw number 1..N) and swap
        (           # Begin "for" loop N times
         vo         # Remove index of current straw
            Þṡ      # Sort by length
              ḣ‟    # Extract head (next index) and rotate
                )₃  # End loop and compare length with 1

```

Try it Online!
> 1 votes

# Answer
# SageMath, 20 bytes

Run it on SageMathCell!

```
g=Graph.is_connected

```
> 1 votes

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


title: Primes with Distinct Prime Digits

text:
# Question
Title: Primes with Distinct Prime Digits
There are 18 primes with distinct prime digits (A124674). Namely, they are:

\\$2, 3, 5, 7, 23, 37, 53, 73, 257, 523, 2357, 2753, 3257, 3527, 5237, 5273, 7253, 7523\\$

Your task is to output this sequence.

# Rules

* rules apply. This means valid solutions may use any of the following formats:

+ Given some index \\$n\\$ it can return the \\$n\\$-th entry of the list.
    + Given some index \\$n\\$ it can return all entries up to the \\$n\\$th one in the sequence.
    + Without taking any index, it can output *all* entries by e.g. ...
        - ...printing them one by one (potentially infinitely) or...
        - ...returning a list (lazy if the sequence is infinite) or...
        - ...returning a generator that represents the whole sequence.
        - Note: the solution may print/generate infinitely, but once the entire sequence is output, subsequent outputs must be blank.
* If taken, you may assume the input \\$n\\$ is always valid. (with 0-based indexing, \\$ 0 \le n \le 17 \\$; with 1-based indexing, \\$ 1 \le n \le 18 \\$)
* This is ; fewest bytes wins.
* Standard loopholes apply.

# Answer
> 6 votes
# Jelly, ~~11~~ 9 bytes

```
;DẒ;ŒQẠµ#

```

Try it online!

Takes \\$1 \le n \le 18\\$ on STDIN and returns the first \\$n\\$

## How it works

```
;DẒ;ŒQẠµ# - Main link. Takes no arguments
       µ  - Previous chain as a monad f(k):
 D        -   Digits of k, D
;         -   Prepnd k
  Ẓ       -   Prime?
    ŒQ    -   Unique sieve; Cast k to digits, replace a digit with a 1 if it hasn't appeared before, else 0
   ;      -   Concatenate the two lists
      Ạ   -   All truthy?
        # - Read n from STDIN. Starting k=0, count up until n k's return true under f(k)

```

The way `ŒQ` works can be shown e.g. with \\$k = 75523\\$:

```
   [7, 5, 5, 2, 3]
ŒQ:[1, 1, 0, 1, 1]

```

It auto-casts \\$k\\$ to digits, then replaces all but the first occurence of each element with `0`.

# Answer
> 5 votes
# Vyxal, ~~12 11~~ 9 bytes

```
Þp~Þu'fæA

```

Try it Online!

Prints the sequence infinitely.

Saved a byte by using a trick from caird's Jelly answer.
Saved 2 bytes thanks to emanresu A.

#### Explanation

```
Þp~Þu'fæA
Þp         # All primes
  ~Þu      # Filtered by are their digits unique
     'fæA  # Filtered by are their digits all prime

```

Old:

```
Þun:fpæA∧)l
         )l  # First n non-negative integers where:
Þu           #  It has unique digits
        ∧    #  And
  n:fp       #  Its digits with it prepended
      æA     #  All are prime

```

# Answer
> 3 votes
# 05AB1E, ~~14 11~~ 10 bytes

```
∞ʒÐÙQiDªpP

```

Try it online!

Doesn't halt after printing all of them so you'll have to press the stop button.

*-1 thanks to @KevinCruijssen*

#### Explanation

```
∞ʒ          # All positive integers filtered by:
  DÙQ       #  Digits are unique
     i      # And:
      Dª    #  Its digits with itself appended
        pP  #  Are all prime

```

# Answer
> 3 votes
# Bash \+ bsdgames \+ coreutils, 40

```
primes 2 7777|egrep -v '[^2357]|(.).*\1'

```

Try it online!

# Answer
> 3 votes
# Python 3, 55 bytes

```
lambda x:ord('%5Iāȋवુಹ෇ᑵᒙ᱕ᵣ'[x])

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 72 bytes

```

1¶11¶111¶4$*
+%1`1
2$'¶$`3$'¶$`5$'¶$`7
A`(.).*\1
.+
$*
A`^(11+)\1+$
%`1

```

Try it online! Outputs all the terms of the sequence. Explanation:

```

1¶11¶111¶4$*

```

Insert 1, 2, 3, and 4 `1`s.

```
+%1`1
2$'¶$`3$'¶$`5$'¶$`7

```

Expand into all possible integers with up to 4 prime digits.

```
A`(.).*\1

```

Remove integers with duplicate digits.

```
.+
$*

```

Convert to unary.

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

```

Filter out composite numbers.

```
%`1

```

Convert to decimal.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 64 bytes

```
Select[FromDigits/@Join@@Permutations/@Subsets@{2,3,5,7},PrimeQ]

```

Try it online!

# Answer
> 2 votes
# Japt, 15 bytes

```
Èì_â fjÃ¶X©j}jU

```

Try it

Outputs the first \\$n\\$ entries in the sequence.

Explanation:

```
Èì_â fjÃ¶X©j}jU  # input stored in U
È           }jU  # get first U numbers where the following is true:
 ì_              # convert to digits
   â             #   keep unique digits
     fj          #   remove non-prime digits
       Ã¶X       # does this result in the same number?
          ©j     # and check the original is prime

```

# Answer
> 2 votes
# Perl 5, 59 bytes

```
(1x$_)!~/^(11+)\1+$/&/^[2357]+$/&!/(.).*\1/&&say for 2..1e4

```

Try it online!

# Answer
> 2 votes
# brainfuck, 213 bytes

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

```

Try it online!

Sets up 3 cells with ASCII 255/5=51 (character `3`) then produces the output hunt and peck style (with increments and decrements as necessary).

Cell 1 is used to print `2` and thereafter the separator `/`

Cell 2 is used to print `3` `5` `7` and thereafter the digits `5` & `7`

Cell 3 is used to print the digits `2` and `3`

It's possible that a 4th cell may lead to shorter code by allowing separate cells to be used for `5` and `7`. I may investigate this later.

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
₄ÅpʒÐÙSpÏQ

```

Outputs the entire sequence.

Try it online.

Alternative 10-byter that I deemed different enough for its own answer. Make sure to upvote *@TheThonnu*'s 10-bytes 05AB1E answer as well!

**Explanation:**

```
₄           # Push 1000
 Åp         # Pop and push a list of the first 1000 prime numbers (up to 7919)
   ʒ        # Filter it by:
    Ð       #  Triplicate the prime number
     Ù      #  Pop one copy, and uniquify its digits
      Sp    #  Check for each unique digit whether it's a prime number
        Ï   #  Pop another copy, and only keep its digits at the truthy indices
         Q  #  Check if the two integers are still the same
            # (after which the filtered list is output implicitly)

```

# Answer
> 1 votes
# JavaScript (V8), 66 bytes

Prints the sequence and keeps looping forever.

```
{for(n=x=2;;)n%--x||x>1|/(.).*\1|[^2357]/.test(x=n++)||print(n-1)}

```

Try it online!

# JavaScript (V8), 71 bytes

Prints the sequence and stops.

```
{for(n=x=2;n<8e3;)n%--x||x>1|/(.).*\1|[^2357]/.test(x=n++)||print(n-1)}

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~58 57~~ 55 bytes

```
n=>'%5Iāȋवુಹ෇ᑵᒙ᱕ᵣ'.charCodeAt(n)

```

Try it online!

Port of Sisyphus's Python answer.

*-3 thanks to @Arnauld*

# Answer
> 1 votes
# Stax, 15 bytes

```
¢\W░i*δÿ╛ñê╠≤▬J

```

Run and debug it

This is Packed Stax, which when unpacked represents the following 18 bytes

```
VIfEccu=^+_+{|pm|A

```

Run and debug it

```
VIf                # filter the following over infinity
   E cu=           # Are all the digits in the number unique?
    c   ^+         # Increment this and add it to the list (yielding prime value 2 for truthy)
          _+       # add the current value to the list
                |A # are all of the values in this list
            {|pm   # prime?

```

# Answer
> 0 votes
# Charcoal, 29 bytes

```
ＩΦ×φχ∧⬤”)∨∧i#”‹№ＩιＩμＩλ⬤…²ι﹪ιλ

```

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

```
   φ                        Predefined variable `1000`
  ×                         Multiplied by
    χ                       Predefined variable `10`
 Φ                          Filtered where
       ”...”                Compressed string `1122121211`
      ⬤                     All characters satisfy
             №              Count of
                 μ          Inner index
                Ｉ           Cast to string
               ι            In outer value
              Ｉ             Cast to string
            ‹               Is less than
                   λ        Current character
                  Ｉ         Cast to integer
     ∧                      Logical And
                     …      Range from
                      ²     Literal integer `2`
                       ι    To current value
                    ⬤       All values satisfy
                         ι  Outer value
                        ﹪   Modulo (i.e. is not divisible by)
                          λ Inner value
Ｉ                           Cast to string
                            Implicitly print

```

34 bytes for a less inefficient version:

```
⊞υωＦυＦ⁺ι⁻⪪2357¹⪪ι¹⊞υκＩΦＩυ∧ι⬤…²ι﹪ιλ

```

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

```
⊞υω

```

Start with the empty string.

```
Ｆυ

```

Loop over the strings of digits.

```
Ｆ⁺ι⁻⪪2357¹⪪ι¹

```

Append each prime digit that isn't yet present.

```
⊞υκ

```

Save the new strings to the list of numbers with distinct prime digits.

```
ＩΦＩυ∧ι⬤…²ι﹪ιλ

```

Output only those strings that represent primes.

33 bytes by using the newer version of Charcoal on ATO:

```
⊞υωＦ⁴«≔ΣＥ2357⁺κΦυ¬№μκυＩΦＩυ⬤…²κ﹪κμ

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
⊞υω

```

Start with the empty string.

```
Ｆ⁴«

```

Loop `4` times.

```
≔ΣＥ2357⁺κΦυ¬№μκυ

```

For each prime digit, prefix it to all previous strings that do not already contain that digit, and concatenate all of the resulting lists.

```
ＩΦＩυ⬤…²κ﹪κμ

```

Output only those strings that represent primes.

# Answer
> 0 votes
# Factor,  ~~64~~  45 bytes

```
[ "%5Iāȋवુಹ෇ᑵᒙ᱕ᵣ"nth ]

```

Try it online!

-19 by porting Sisyphus' Python answer.

Returns the nth number in the sequence.

# Answer
> 0 votes
# Excel, 145 bytes

```
=LET(
    a,SEQUENCE(6^5),
    b,FILTER(a,MMULT(N(LEN(a)-LEN(SUBSTITUTE(a,{2,3,5,7},""))=1),{1;1;1;1})=LEN(a)),
    FILTER(b,MMULT(N(MOD(b,TOROW(a))=0),a^0)=2)
)

```

# Answer
> 0 votes
# SageMath, 288 bytes

Golfed version, run it online!

```
from itertools import permutations, chain, combinations; from sage.all import is_prime; print([int(''.join(map(str, p))) for p in chain.from_iterable(permutations(s) for s in chain.from_iterable(combinations({2, 3, 5, 7}, r) for r in range(1, 5))) if is_prime(int(''.join(map(str, p))))])

```

Ungolfed version, run it online!

```
from itertools import permutations, chain, combinations
from sage.all import is_prime

digits = {2, 3, 5, 7}
subsets = chain.from_iterable(combinations(digits, r) for r in range(1, len(digits) + 1))
perms = chain.from_iterable(permutations(s) for s in subsets)
nums = (int(''.join(map(str, p))) for p in perms)
primes = [n for n in nums if is_prime(n)]

print(primes)

```

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