text:
Equality Comes in Threes
Taken from: OEIS-A071816
Your task, given an upper bound of n, is to find the number of solutions that satisfy the equation:
a+b+c = x+y+z, where 0 <= a,b,c,x,y,z < n

The sequence starts out as described on the OEIS page, and as below (1-indexed):
1, 20, 141, 580, 1751, 4332, 9331, 18152, 32661, 55252, 88913, 137292, 204763, 296492, 418503, 577744, 782153, 1040724, 1363573, 1762004, 2248575, 2837164, 3543035, 4382904, 5375005, 6539156, 7896825, 9471196, 11287235, 13371756

For n = 1, there's only one solution: (0,0,0,0,0,0)
For n = 2, there are 20 ordered solutions (a,b,c,x,y,z) to a+b+c = x+y+z:
(0,0,0,0,0,0), (0,0,1,0,0,1), (0,0,1,0,1,0), (0,0,1,1,0,0), (0,1,0,0,0,1),
(0,1,0,0,1,0), (0,1,0,1,0,0), (0,1,1,0,1,1), (0,1,1,1,0,1), (0,1,1,1,1,0),
(1,0,0,0,0,1), (1,0,0,0,1,0), (1,0,0,1,0,0), (1,0,1,0,1,1), (1,0,1,1,0,1),
(1,0,1,1,1,0), (1,1,0,0,1,1), (1,1,0,1,0,1), (1,1,0,1,1,0), (1,1,1,1,1,1).

I & O

Input is a single integer denoting n.
Output is a single integer/string denoting f(n), where f(...) is the function above.
The indexing is exactly as described, no other indexing is acceptable.

This is code-golf, lowest byte-count wins.

Ahhh crappp, I didn't notice the direct formula on OEIS, I thought this wouldn't be that easy. Oh well, I'm not +1'ing direct ports of that equation ;P.

At least the formula wasn't perfectly golfed :P

Then again, it gives reg-langs a chance against the eso-langs.

Would it be better if the title is "equality comes in triplets"?

Jelly, 9 6 bytes
ṗ6ḅ-ċ0

O(n6) solution.
Try it online!
How it works
ṗ6ḅ-ċ0  Main link. Argument: n

ṗ6      Cartesian power 6; build all 6-tuples (a, x, b, y, c, z) of integers in
        [1, ..., n]. The challenge spec mentions [0, ..., n-1], but since there
        are three summands on each side, this doesn't matter.
  ḅ-    Unbase -1; convert each tuple from base -1 to integer, mapping (a, ..., z)
        to a(-1)**5 + x(-1)**4 + b(-1)**3 + y(-1)**2 + c(-1)**1 + z(-1)**0, i.e.,
        to -a + x - b + y - c + z = (x + y + z) - (a + b + c). This yields 0 if and
        only if the 6-tuple is a match.
    ċ0  Count the number of zeroes.

Ha! Gotta love the theoretical answers (my basis for a theoretical answer is now does it run on TIO for large values of n, this is probably bad). I was hoping to see a O(n^6) though :P.

Mathematica 17 or 76 Bytes
Using the formula:
.55#^5+#^3/4+#/5&

(Saved 3 bytes per @GregMartin and @ngenisis)
Rather than using the formula, here I literally compute all the solutions and count them.
Length@Solve[a+b+c==x+y+z&&And@@Table[(0<=i<#),{i,{a,b,c,x,y,z}}],Integers]&

Thanks for posting the non-brute-force way :). +1 for any mathematica answer that isn't an equation or a built-in.

As per this answer, you can replace 11/20 by .55 for a two-byte savings.

You also don't need the asterisk in the first term.

Haskell, 48 bytes
I didn't notice the formula before writing this, so it's definitely not the shortest (or fastest) general method, but I thought it was pretty.
f n=sum[1|0<-foldr1(-)<$>pure[1..n]`mapM`[1..6]]

Try it online!
f n generates all lists of 6 elements from [1..n], then counts the ones whose alternating sum is 0. Uses the fact that a+b+c==d+e+f is the same as a-(d-(b-(e-(c-f))))==0, and also that it doesn't matter if we add a 1 to all the numbers.

I've noticed that, often, the shortest answer is the least impressive ;). This is a pretty cool use of fold that I wouldn't've considered before seeing this answer.

MATL, 12 bytes
l6:"G:gY+]X>

Try it online!
Explanation
I couldn't miss the chance to use convolution again!
This makes use of the following characterization from OEIS:

a(n) = largest coefficient of (1+...+x^(n-1))^6

and of course polynomial multiplication is convolution.
l        % Push 1
6:"      % Do the following 6 times
  G:g    %   Push a vector of n ones, where n is the input
  Y+     %   Convolution
]        % End
X>       % Maximum

Pyth, 13 12 bytes
JsM^UQ3s/LJJ

Saved one byte thanks to Leaky Nun.
Explanation
JsM^UQ3s/LJJ
   ^UQ3         Get all triples in the range.
JsM             Save the sums as J.
        /LJJ    Count occurrences of each element of J in J.
       s        Take the sum.

+1 for not using the direct formula :P.

You might like to post a link to the online interpreter.

Also, you can use /LJJ instead of m/JdJ.

Jelly, 9 bytes
ṗ3S€ĠL€²S

Not as short as @Dennis's, but it finishes in under 20 seconds for input 100.
Try it online!
How it works
ṗ3S€ĠL€²S  Main link. Argument: n

ṗ3         Cartesian power; yield all subsets of [1, ..., n] of length 3.
  S€       Sum each.
    Ġ      Group indices by their values; for each unique sum S, list all indices whose
           values are equal to S.
     L€    Length each; for each unique sum S, yield the number of items in the original
           array that sum to S.
       ²   Square each; for each unique sum S, yield the number of pairs that both sum to S.
        S  Sum; yield the total number of equal pairs.

Can you explain this method? I'm currently in the process of learning Jelly, but I'm still not good enough to submit real answers yet; I always look to you, Dennis and a few others for good examples.

@carusocomputing Finished the explanation. Let me know if you still have any questions :-)

Awesome, I'm mostly confused on the optimization of answers from the most basic of brute-force implementation that I would do to the crazy short code I see you guys posting; but I feel like every explanation is a step closer thank you!

Python 3, 28 bytes
lambda n:.55*n**5+n**3/4+n/5

Try it online!

TI-BASIC, 19 bytes
:Prompt X
:.05X(11X^4+5X²+4

Evaluates the OEIS formula.

How are you counting the bytes here? Prompt x = 2 bytes?

@carusocomputing TI-BASIC is scored by tokens

Kinda sad that I've posted a TI-BASIC answer 5 times before and never scored it correctly now that I look through my history ._.

Oasis, 17 bytes
5m11*n3m5*nz++20÷

5                   n 5             implicit n for illustration
 m                  n**5
  11                n**5 11
    *               11*n**5
     n              11*n**5 n
      3             11*n**5 n 3
       m            11*n**5 n**3
        5           11*n**5 n**3 5
         *          11*n**5 5*n**3
          n         11*n**5 5*n**3 n
           z        11*n**5 5*n**3 4*n
            +       11*n**5 5*n**3+4*n
             +      11*n**5+5*n**3+4*n
              20    11*n**5+5*n**3+4*n 20
                ÷  (11*n**5+5*n**3+4*n)÷20

Try it online!
Oasis is a stack-based language optimized for recurring sequences. However, the recursion formula would be too long for this case.

Brachylog, 17 bytes
{>ℕ|↰}ᶠ⁶ḍD+ᵐ=∧D≜ᶜ

Try it online!
Explanation
{  |↰}ᶠ⁶           Generate a list of 6 variables [A,B,C,D,E,F]...
 >ℕ                  ...which are all in the interval [0, Input)
        ḍD         Dichotomize; D = [[A,B,C],[D,E,F]]
          +ᵐ=      A + B + C must be equal to D + E + F
             ∧
              D≜ᶜ  Count the number of possible ways you can label the elements of D while
                     satisfying the constraints they have

I guess ᶜ should automatically come with ≜

@LeakyNun You can't run ᶜ by itself, it's a metapredicate.

But still if it is used on a list, labeling that list could be made the default predicate, no?

@mat It could be made that way, but right now you cannot use a metapredicate on a variable.

JavaScript, 24 bytes
x=>11*x**5/20+x**3/4+x/5

Uses the formula from the OEIS page.
Try it online!

I think you can save two bytes with x=>x**5*.55+x**3/4+x/5

@ETHproductions there are floating point errors if I use *.55 instead of *11/20

Octave, 25 23 21 bytes
@(n).55*n^5+n^3/4+n/5

Try it online!
Uses the formula from the OEIS-entry. Saved two four bytes by rearranging the formula and using .55 instead of 11/20, thanks to fəˈnɛtɪk.

Python 2.7, 109 105 99 96 bytes
Thanks ETHproductions and Dennis for saving a few bytes:
from itertools import*
lambda s:sum(sum(x[:3])==sum(x[3:])for x in product(range(s),repeat=6))

Interesting, doesn't Python 3 have shorter range functions than 2.7?

sum(sum(x[:3])==sum(x[3:])for x ...) would be even shorter. Also, from itertools import* saves a byte.

You don't need the space before for. Also, we don't require functions to be named by default, so you can remove h=.

Octave, 41 bytes
@(n)round(max(ifft(fft(~~(1:n),n^2).^6)))

Try it online!
Similar to my MATL answer, but computes the convolution via a discrete Fourier transform (fft) with a sufficient number of points (n^2). ~~(1:n) is used as a shorter version of ones(1,n). round is necessary because of floating point errors.

Mathematica, 52 bytes
Kelly Lowder's implementation of the OEIS formula is way shorter, but this computes the numbers directly:
Count[Tr/@#~Partition~3&/@Range@#~Tuples~6,{n_,n_}]&

Well, it actually counts the number of solutions with 1 <= a,b,c,x,y,z <= n. This is the same number, since adding 1 to all the variables doesn't change the equality.
Explanation: Range@#~Tuples~6 makes all lists of six integers between 1 and n, #~Partition~3&/@ splits each list into two lists of length 3, Tr/@ sums these sublists, and Count[...,{n_,n_}] counts how many pairs have the same sum. I got very lucky with the order of precedence between f @, f /@ and ~f~!

Clojure, 79 bytes
#(count(for[r[(range %)]a r b r c r x r y r z r :when(=(+ a b c)(+ x y z))]1))

Tons of repetition in the code, on larger number of variables a macro might be shorter.

CJam, 17 bytes
ri,6m*{3/::+:=},,

Input of 11 times out on TIO, and 12 and higher run out of memory.
Try it online!
Explanation
ri                e# Read an int from input.
  ,               e# Generate the range 0 ... input-1.
   6m*            e# Take the 6th Cartesian power of the range.
      {           e# Keep only the sets of 6 values where:
       3/         e#  The set split into (two) chunks of 3
         ::+:=    e#  Have the sums of both chunks equal.
              },  e# (end of filter)
                , e# Get the length of the resulting list.


text:
Tips for golfing in Logo
Logo is a programming language that was designed back in 1967 that has great potential for creating graphics in relatively few bytes compared to other languages.
Logo is an educational programming language that utilizes Turtle Graphics.
There are multiple interesting implementations of Logo including:

Apple Logo
Atari Logo
LibreLogo (my personal favorite)
Texas Instruments Logo
UCBLogo
And many others...

In addition, multiple Logo interpreters can be found online.
This page is intended to be a hub for code golf tips regarding any implementation of the Logo programming language.

Source: The Great Logo Adventure (1998) by Jim Muller

LibreLogo
Shorten Color Definitions:
It is documented that colors can be defined by name, identifier, RGB value, or HEX code.
In the majority of cases, if you have the opportunity to use an identifier for a color constant, that is typically the shortest option.
On the other hand, a little known fact is that you can also use the decimal value to define a color, and you can occasionally save bytes.
Color Chart:
+------------------------------------------------------------------------+   +-------------+
| Name                | Identifier | RGB           | HEX      | Decimal  |   | Best Option |
|------------------------------------------------------------------------|   |-------------|
| "BLACK"             | [0]        | [0,0,0]       | 0x000000 | 0        |   | 0           |
| "SILVER"            | [1]        | [192,192,192] | 0xc0c0c0 | 12632256 |   | [1]         |
| "GRAY"/"GREY"       | [2]        | [128,128,128] | 0x808080 | 8421504  |   | [2]         |
| "WHITE"             | [3]        | [255,255,255] | 0xffffff | 16777215 |   | [3]         |
| "MAROON"            | [4]        | [128,0,0]     | 0x800000 | 8388608  |   | [4]         |
| "RED"               | [5]        | [255,0,0]     | 0xff0000 | 16711680 |   | [5]         |
| "PURPLE"            | [6]        | [128,0,128]   | 0x800080 | 8388736  |   | [6]         |
| "FUCHSIA"/"MAGENTA" | [7]        | [255,0,255]   | 0xff00ff | 16711935 |   | [7]         |
| "GREEN"             | [8]        | [0,128,0]     | 0x008000 | 32768    |   | [8]         |
| "LIME"              | [9]        | [0,255,0]     | 0x00ff00 | 65280    |   | [9]         |
| "OLIVE"             | [10]       | [128,128,0]   | 0x808000 | 8421376  |   | [10]        |
| "YELLOW"            | [11]       | [255,255,0]   | 0xffff00 | 16776960 |   | [11]        |
| "NAVY"              | [12]       | [0,0,128]     | 0x000080 | 128      |   | 128         |
| "BLUE"              | [13]       | [0,0,255]     | 0x0000ff | 255      |   | 255         |
| "TEAL"              | [14]       | [0,128,128]   | 0x008080 | 32896    |   | [14]        |
| "AQUA"              | [15]       | [0,255,255]   | 0x00ffff | 65535    |   | [15]        |
| "PINK"              | [16]       | [255,192,203] | 0xffc0cb | 16761035 |   | [16]        |
| "TOMATO"            | [17]       | [255,99,71]   | 0xff6347 | 16737095 |   | [17]        |
| "ORANGE"            | [18]       | [255,165,0]   | 0xffa500 | 16753920 |   | [18]        |
| "GOLD"              | [19]       | [255,215,0]   | 0xffd700 | 16766720 |   | [19]        |
| "VIOLET"            | [20]       | [148,0,211]   | 0x9400d3 | 9699539  |   | [20]        |
| "SKYBLUE"           | [21]       | [135,206,235] | 0x87ceeb | 8900331  |   | [21]        |
| "CHOCOLATE"         | [22]       | [210,105,30]  | 0xd2691e | 13789470 |   | [22]        |
| "BROWN"             | [23]       | [165,42,42]   | 0xa52a2a | 10824234 |   | [23]        |
| "INVISIBLE"         | [24]       | N/A           | N/A      | N/A      |   | [24]        |
+------------------------------------------------------------------------+   +-------------+

LibreLogo
Use Abbreviated Commands:
Abbreviated commands, also called "short names," are used across most implementations of Logo.
Here is the full list of abbreviated commands for LibreLogo.
+-----------------------------------------------+
| Full Command    | Short Command | Bytes Saved |
|-----------------------------------------------|
| forward 10      | fd 10         | 5           |
| back 10         | bk 10         | 2           |
| left 90         | lt 90         | 2           |
| right 90        | rt 90         | 3           |
| penup           | pu            | 3           |
| pendown         | pd            | 5           |
| position 0      | pos 0         | 5           |
| heading 0       | seth 0        | 3           |
| hideturtle      | ht            | 8           |
| showturtle      | st            | 8           |
| clearscreen     | cs            | 9           |
| pensize 10      | ps 10         | 5           |
| pencolor 0      | pc 0          | 6           |
| fillcolor 0     | fc 0          | 7           |
| picture [ ... ] | pic [ ... ]   | 4           |
+-----------------------------------------------+

LibreLogo
Random Numbers:
Use any instead of random when possible.
Random Integer (0 - 9):
x = int random 10     ; 17 bytes
x = int(ps any)       ; 15 bytes

Random Floating-Point Number (0 - 9):
x = random 10         ; 13 bytes
x = (ps any)          ; 12 bytes

Directly Assigned to Setting:
pensize random 10     ; 17 bytes
ps random 10          ; 12 bytes
ps any                ; 6 bytes

LibreLogo
Use PAGESIZE to your Advantage:

PAGESIZE is a variable that is dependent on the Paper Format in LibreOffice Writer and returns an array containing the [width, height] of the page in points (pt).

This could be useful for a variety of situations, but I personally found it useful for generating a number without using the digits [0-9].
https://help.libreoffice.org/Writer/LibreLogo_Toolbar#PAGESIZE

Value Chart:
+-------------------------------------------------------------------+
| Paper Format           | PAGESIZE                                 |
|-------------------------------------------------------------------|
| A6                     | [297.35433070866145, 419.75433070866137] |
| A5                     | [419.75433070866137, 595.4456692913386]  |
| A4                     | [595.4456692913386, 841.6913385826772]   |
| A3                     | [841.6913385826772, 1190.8913385826772]  |
| B6 (ISO)               | [354.2456692913386, 498.95433070866136]  |
| B5 (ISO)               | [498.95433070866136, 708.4913385826771]  |
| B4 (ISO)               | [708.4913385826771, 1000.8]              |
| Letter                 | [612.0, 792.0]                           |
| Legal                  | [612.0, 1008.0]                          |
| Long Bond              | [612.0, 936.0]                           |
| Tabloid                | [792.0, 1224.0]                          |
| B6 (JIS)               | [362.8913385826771, 516.2456692913386]   |
| B5 (JIS)               | [516.2456692913386, 728.6456692913387]   |
| B4 (JIS)               | [728.6456692913387, 1031.7543307086614]  |
| 16 Kai                 | [521.2913385826771, 737.2913385826771]   |
| 32 Kai                 | [368.64566929133855, 521.2913385826771]  |
| Big 32 Kai             | [396.7086614173228, 575.2913385826771]   |
| User                   | CURRENT PAGE SIZE                        | ← Current Paper Format
| DL Envelope            | [311.7543307086614, 623.5086614173229]   |
| C6 Envelope            | [323.29133858267716, 459.3543307086614]  |
| C6/5 Envelope          | [323.29133858267716, 649.4456692913386]  |
| C5 Envelope            | [459.3543307086614, 649.4456692913386]   |
| C4 Envelope            | [649.4456692913386, 918.7086614173228]   |
| #6¾ Envelope           | [261.35433070866145, 468.0]              |
| #7¾ (Monarch) Envelope | [279.35433070866145, 540.0]              |
| #9 Envelope            | [279.35433070866145, 639.3543307086613]  |
| #10 Envelope           | [297.35433070866145, 684.0]              |
| #11 Envelope           | [324.0, 747.3543307086613]               |
| #12 Envelope           | [342.0, 792.0]                           |
| Japanese Postcard      | [283.69133858267713, 419.75433070866137] |
+-------------------------------------------------------------------+

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Reachable numbers
Definitions

Euler Phi Function (AKA totient function): a function which takes in a positive number and returns the number of positive numbers less than the given number which are co-prime with given number. It is denoted as φ(n).
Reachable number: if there exists a positive integer x such that φ(x) == n, then n is reachable.

Task
Write a function/program to determine if a given positive integer is reachable.
Input
A positive number, in any reasonable format. One can assume that the number is within the capability of the language. Unary input is accepted.
Output
Two consistent values, one for reachable numbers, and the other for unreachable numbers. The two values can be anything, as long as they are consistent.
Testcases
The reachable numbers bellow 100 are:

1, 2, 4, 6, 8, 10, 12, 16, 18, 20, 22, 24, 28, 30, 32, 36, 40, 42, 44, 46, 48, 52, 54, 56, 58, 60, 64, 66, 70, 72, 78, 80, 82, 84, 88, 92, 96

(A002202 on OEIS)
Rules
Standard loopholes apply.
Winning criterion
This is code-golf. Submission with lowest byte-count wins.
References

Euler Phi Function
OEIS A002202

also relevant: https://oeis.org/A264739

I offer a bounty to a one-line Retina answer, where the one line is a plain regex (no backticks).

@LeakyNun I'm little confused, so far I understand that phi(n) = count { m : 1 <= m <= n AND (m,n) are coprime }.. is that true?

@Khaled.K yes, that is true.

Jelly, 7 6 bytes
²RÆṪe@

Not exactly fast. Returns 1 or 0.
Try it online!
How it works
²RÆṪe@  Main link. Argument: n

²       Square; yield n².
 R      Range; yield [1, ..., n²].
  ÆṪ    Compute the totient of each integer in the range.
    e@  Exists swap; test if n occurs in the generated array.

How does it work?

Brute force. There's a lower bound for the totient function, so it's enough to take a large enough range, map totient, and check for occurrences of the input.

Can you prove that the square root is the minimum?

The square root is actually not a lower bound, but the square root divided by sqrt(2) is. I'm positive that doubling is not required, but a proof will have to wait until I've gotten some sleep. Too tired right now.

This is a trivial modification, so I won't post it, but just out of interest, another possibility is to use i: for the last two bytes.

@LeakyNun Actually, lemma 3 of this paper proves that the square root is a lower bound unless n = 2k with odd k. Since k and 2k have the same totient, doubling is not required.

@HyperNeutrino That might work (and if it does, I can double instead of squaring), but I'm not sure.

haha it looks almost like it says rate

I think your Range can start from n+1, since phi(x) <= x-1.

@Khaled.K Well, yes, but that would cost two bytes.

Mathematica, 28 bytes
EulerPhi@Range[#^2]~FreeQ~#&

Like Dennis's Jelly answer, we compute the φ-values of all the numbers up to the square of the input and see if the input appears therein. Returns False if the input is reachable and True if it's not. Yep, that's confusing. But FreeQ is a byte shorter than MatchQ, and hey, the spec said any two consistent values  >:)

JavaScript (ES6), 90 82 bytes
Returns 0 or true.
f=(n,x=n*2)=>x?(p=i=>(c=(a,b)=>a?c(b%a,a):b<2)(i,x)+(i&&p(--i)))(x)==n||f(n,x-1):0

This is based on the assumption that if x exists then x ≤ 2n. If proven false, this should be updated to use x=n*n instead of x=n*2 (same size, much slower).
An edge case is n = 128 which requires to compute ϕ(255).
Demo

f=(n,x=n*2)=>x?(p=i=>(c=(a,b)=>a?c(b%a,a):b<2)(i,x)+(i&&p(--i)))(x)==n||f(n,x-1):0

for(n = 1; n <= 50; n++) {
  console.log(n, f(n));
}

Conveniently the Fermat primes are all consecutive giving rise to consecutive edge cases n=2, n=8, n=128, n=32768 and n=2147483648.

Axiom, 56 bytes
f(x:PI):Boolean==member?(x,[eulerPhi(i)for i in 1..2*x])

i don't know if it is right...test code and results
(35) -> [i  for i in 1..100|f(i)]
   (35)
   [1, 2, 4, 6, 8, 10, 12, 16, 18, 20, 22, 24, 28, 30, 32, 36, 40, 42, 44, 46,
    48, 52, 54, 56, 58, 60, 64, 66, 70, 72, 78, 80, 82, 84, 88, 92, 96, 100]

The range 1..(2*x) would be ok until input x=500...

05AB1E, 5 bytes
nLÕså

Explanation:
n       Square [implicit] input
 L      Range [1 .. a]
  Õ     Euler totient
   s    Put first input at the top of the stack
    å   Is it in the list?

Try it online!

Pari/GP, 34 bytes
x->![n|n<-[1..x^2],eulerphi(n)==x]

Returns 0 if reachable, 1 if not.
Try it online!

05AB1E, 13 12 bytes
EDIT: Saved a byte because input is reused if the stack doesn't have enough elements.
Outputs 1 if reachable, 0 if not.
Relies on assumption that x ≤ 2n if it exists.
xGNÕQi1,q}}0

Try it online!
How it works
              # implicit input
x            # push input, 2 * input
 G           # for N in 1..2*input
             # implicit push input
  N          # push N
   Õ         # push totient of N
    Q        # check if both are equal
     i.      # if equal
      1,     # print 1
        q    # quit program
         }   # end if
          }  # end for
           0 # push 0 if condition never reached
             # implicit print

C, 123 bytes
g(a,b){return!a?b:g(b%a,a);}
i;r;f(n){for(i=2,r=1;i<n;i++)r+=(g(i,n)==1);}
t;k;s(m){for(k=m,t=0;!t&(k<m*m);)f(++k),t=(r==m);}

Try Online
#include <stdio.h>

// gcd function
g(a,b){return!a?b:g(b%a,a);}

// Euler phi(x) function
i;r;f(n){for(i=2,r=1;i<n;i++)r+=(g(i,n)==1);}

// check if m is reachable, phi(x) for x in (m , m^2]
t;k;s(m){for(k=m,t=0;!t&(k<m*m);)f(++k),t=(r==m);}

main()
{
    // print all reachable number below 50
    for(int x=1; x<50; x++)
    {
        s(x);

        if(t)
        {
            printf(" %d ~ phi(%d) \n", x, k);
        }
    }
}

102 bytes

Whispers v2, 63 bytes
> Input
>> 1²
>> [2]
>> φ(L)
>> Each 4 3
>> 1∈5
>> Output 6

Try it online!
Works by brute force. We square the input, then generate the range [1, 2, ..., x²]. Next we calculate \$\phi(i)\$ for each \$i\$ in this range. Finally, we check if the original input \$x\$ is in the array of  \$\phi(i)\$ values.

Stax, 6 bytes
┬$τ▀Ω♀

Run and debug it
I'm not sure why 3 golflangs have an Euler Totient function, but I guess it's convenient for these challenges.
0 for reachable and 1 for non-reachable.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Appends or Prepends? Depends

Brain-flak turns one year old tomorrow! In honor of it's birthday, we're having a PPCG style birthday party, where several users post brain-flak related questions! Help us celebrate! :)

Brain-flak is an esoteric language I wrote where all of the commands are brackets and all of the brackets must be fully matched. To borrow my own definition:

For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
()
[]{}

Or if every subelement inside of it is also matched.
[()()()()]
{<[]>}
(()())

Subelements can also be nested several layers deep.
[(){<><>[()]}<>()]
<[{((()))}]>

A string is considered "Fully matched" if and only if:

Every single character is a bracket,

Each pair of brackets has the correct opening and closing bracket and in the right order

In celebration of brain-flak's first birthday, today's challenge is about taking an unbalanced set of brackets, and determining what types of operations are needed to make it valid brain-flak.

For example, (( is not valid brain-flak code, but if we append )) to it, it becomes (()), which is fully balanced, and therefore valid brain-flak. That makes this input appendable.

Similarly, >} is not valid, but we can prepend {< to it to make {<>}, which is valid. That makes this input prependable.

Some inputs are slightly more complicated. For example, )][({ cannot be made valid purely by appending or prepending. But it can be made valid by prepending [( and appending })]. Therefore, this input is both prependable and appendable.

Lastly, some inputs can never be made valid brain-flak code by any combination of appending or prepending. For example, (> can never be made valid. (Prepending < creates <(>, and appending ) creates (>), neither of which are valid) Therefore, this input is neither appendable or prependable.

For today's challenge, you must write a program or function that takes a string of brackets and determines if the string is
appendable
prependable
both
neither

You may pick what values you use to represent for each case. For example, outputting 1, 2, 3, 4, or 'a', 'p', 'b', 'n', or 1, 'foo', 3.1415, -17, or whatever is fine. As long as each output is distinct and consistent, that's fine. You must however, clearly specify which output corresponds to which case.
You may return this value in whichever format is most convenient (for example, returning from a function, printing to STDOUT, modifying arguments, writing to a file, etc.).
You can assume that the input will never be valid brain-flak or empty.
Examples
The following inputs are all prependable:
))
(((()()())))}
)>}]
()[]{}<>)

These are all appendable:
(({}{})
((((
([]()())(
{<<{

These are all both:
))((
>()[(()){
>{

And these are all neither:
)(}
{(((()()()))>
[}
((((((((((>
((((((((((<>()]

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

This challenge is particularly difficult in brain-flak, so maximum brownie points to any and every answer written in brain-flak. :)

maximum brownie points I think that offering maximum brownie points and cookies instead would encourage Brain-Flaking this challenge more than just brownie points, since I don't think it's trivial at all in any language, let alone Brain-Flak. :P

FYI: All the both tests end with open brackets, all the neither tests end with close brackets.

I would argue that 'both' is the wrong term. A string like ][ is not appendable, as nothing you can append can make it valid. Similarly, it's not prependable. It's... 'insertable'! You can insert it into a string to make the whole valid Brainflak.

Are already balanced strings both or neither?

@wheatwizard Balanced strings won't be given as input. You can assume that the input will never be valid brain-flak or empty.

Jelly, 33 32 37 35 34 bytes
bug found, horrible fix +5 bytes, better fix - 2 bytes, using a trick of Adnan's I saw here for -1 more.
“({[<“)}]>”Z;@WœṣF¥/µÐLO‘&2µIṀ>0ȯQ

Return values:
prepends [2]
 appends [0]
    both [2,0]
 neither 1

(Invalid input returns spurious results, although valid Brain-flack, returns [].)
Try it online! - a test suite (prints mushed representations, so 20 for [2,0], and ignores lines containing any -).

Retina, 41 40 41 bytes
1 byte saved thanks to @MartinEnder
+`\(\)|\[]|{}|<>

[]})>]+
1
\W+
0
...+
01

Try it online!

Prependable is 1
Appendable is 0
Both is 10
None is 01

Edits

Gained 1 byte to fix bug noticed by @Neil

[]})>] saves a byte.

@MartinEnder Ah, it's because character sets can't be empty, thanks!

This doesn't work for all non-appendable inputs, for example (][). I think it can be fixed at a cost of one byte by changing 101 to ...+.

@Neil Thanks for noticing the bug, I wonder if there are such cases with Both as well

No, I think 10 is the only valid combination for Both.

Batch, 337 bytes
@echo off
set/ps=
:g
set "t=%s:<>=%
set "t=%t:()=%
set "t=%t:[]=%
set "t=%t:{}=%
if not "%t%"=="%s%" set "s=%t%"&goto g
set "s=%s:<=[%
set s=%s:>=]%
set s=%s:(=[%
set s=%s:)=]%
set s=%s:{=[%
set s=%s:}=]%
:l
if %s:~,2%==]] set s=%s:~1%&goto l
:r
if %s:~-2%==[[ set s=%s:~,-1%&goto l
if not _%s:~2%==_ set s=[]
echo %s%

Outputs ] for prepend, [ for append, ][ for both, [] for neither.

Haskell, 115 108 bytes
EDIT:

-7 bytes: Use more guards.

(""#)
s#""=[s>"",1>0]
s#(c:d)|Just a<-lookup c$zip"([{<"")]}>"=(a:s)#d|(a:b)<-s=[1|a==c]>>b#d|0<1=take 1$s#d

Try it online!
Use like (""#) "))". Results are given as:
[False,True]: needs nothing
[False]: prependable
[True,True]: appendable
[True]: both
[]: neither

How it works

The output encoding is chosen such that a need to prepend is signaled by dropping the second element of the result for the remainder, if any, while a complete mismatch is signaled by dropping all of them.
s#d parses a remaining string d, given a string/stack s of expected closing brackets.

The s#"" line checks if all closing brackets have been found by the end of the string, otherwise appending is needed.
The first branch of s#(c:d) checks if the next character c is an opening bracket, and if so leaves the corresponding closing bracket on the stack for the recursion.
Otherwise, if the stack contains closing brackets, the second branch checks if the top one matches the next character, and if not, returns an empty list instead of recursing.
Lastly, in the last branch the stack is empty, and we have an unmatched closing bracket that may be fixed by prepending, before recursing.

PHP, 137 Bytes
for($c=1;$c;)$a=preg_replace("#<>|\(\)|\[\]|\{\}#","",$a=&$argn,-1,$c);echo($a=preg_replace(["#[]})>]+#","#[[{(<]+#"],[1,2],$a))<13?$a:0;

1 =>appendable,
2 =>prependable,
12=>both,
0 =>neither
Testcases

"As long as each output is distinct and consistent, that's fine". This doesn't appear to have a consistent value for neither.

@Cyoce It is now Fixed

Japt, 44 bytes
=Ue"%(%)|%[]|\{}|<>" ®c -1&2|1})f31 |UfD |Ug

Outputs 1 for prependable, 3 for appendable, 13 for both, and 31 for neither.
Test it online! or Verify all test cases at once.
How it works
 =Ue"%(%)|%[]|\{}|<>" ®   c -1&2|1})f31 |UfD |Ug
U=Ue"%(%)|%[]|\{}|<>" mZ{Zc -1&2|1})f31 |UfD |Ug

                    // "(((()()())))}"  "([({}{})"    ">()[(()){"  "((((<>()]"
Ue"%(%)|%[]|\{}|<>" // Recursively remove all instances of "()", "[]", "{}", and "<>" from U.
                    // "}"              "(["          ">[{"        "((((]"
mZ{Zc -1&2|1}       // Replace each char Z with (Z.charCodeAt() - 1) & 2 | 1.
                    // "1"              "33"          "133"        "33331"
U=                  // Save the result in U.
f31 |UfD |Ug        // Match all instances of "31" and "13" (D = 13) and bitwise-OR the results with the first char.
                    // null|null|1      null|null|3   null|13|1    31|null|3
                    // 1                3             13           31
                    // Implicit: output result of last expression


text:
The bunker of the math lecturer
After giving back the results of the last topology exam to his students, Pr. Manifold was worried about complaints.
Since he is aware his students know where his office is located, Prof. Manifold decided to transform his office into a bunker with a 10 digit password (all characters are digits).
But he suspected his students to be very clever (despite having tremendously bad grades).
Knowing that, he's not going to pick a password containing certain sequences, such as his StackExchange ID, university parking spot number, and annual salary.
Your task
Your program or function will take as input an array of integers. No single integer will contain duplicate digits, which implies that none of the integers will have more than 10 digits.
Your code will output how many unique 10 digit passwords Prof. Manifold can choose, taking into account that correct passwords

must contain each digit 0-9 exactly once, and
must not contain any of the sequences present in the input array.

Example
Input: [18062,6042,35876]

1806234579, 6042135789, 3587612409, 3418062579, 1237896042, and 1243587609 are all incorrect passwords, because they each contain at least one of the sequences present in the input array.
0113456789 is an incorrect password, because the professor's password must contain each digit exactly once.
0123456789 is a correct password, because it doesn't contain any sequence present in the array, and it contains each digit exactly once.

Test case:
[18062,6042,35876] -> 3622326

This is code-golf, so the shortest answer in bytes wins!

You should add test cases.

@Luke Ok But since i'm on my phone I only have the calculator ^^

Jelly, 14  11 bytes
-3 bytes thanks to Dennis (avoid a chain separation allowing some implicit actions; use a filter to avoid the two byte œ& multi-set intersection I was using.)
⁵ḶŒ!Ẇf¥ÐḟDL

Try it online! - the specified version is far too slow for the online interpreter, so this is a proof of concept test suite:
- it does the same thing for only 5 digits 01234,
- the first example is the empty list, yielding 120 as expected (5!),
- the last returns 1 as the only permutation still available to the professor is 04321,
- an offline run of the full version with input [18062,6042,35876] yielded 3622326 as expected.
How?
⁵ḶŒ!Ẇf¥ÐḟDL - Main link: list a
⁵           - literal 10
 Ḷ          - lowered range: [0,1,2,3,4,5,6,7,8,9]
  Œ!        - all permutations
         D  - decimal list (vectorises across a)
       Ðḟ   - filter discard (from the permutations) if: (note - non-empty is truthy)
      ¥     -   last two links as a dyadic operation:
    Ẇ       -     all sublists (of the current permutation)
     f      -     filter keep (if in the decimal list)
          L - length

⁵ḶŒ!Ẇf¥ÐḟDL saves a few bytes.

Thanks Dennis, amazing how often I still miss some tacit tricks.


text:
Sort digits by their first occurrence in pi
Given a non-negative number n, sort the digits of n by their first occurrence in pi.
Input can be taken via function cli argument, or STDIN and as a string, char[] or integer. You may output via return value, exit status or STDOUT.

Related

Can we take input and output as strings, or as arrays of digits?

@ETHproductions Clarified.

Is the input guaranteed to be an integer?

It is guaranteed to be an integer or a string representation of that integer

Will the input ever contain leading zeroes?

@EriktheOutgolfer No.

A few test cases would be nice.

Now that 12 answers are already present, all of which performing the same thing, if you are still unclear what is being asked, then it is not the problem of the question.

You don't really need to specify those i/o methods (the i/o formats are fine though), as they are the PPCG defaults.

Pyth, 8 6 bytes
ox+.n0

Try it here.
-1 thanks to Leaky Nun: The input will provide the 0 if it's ever needed.
Trivial -1 thanks to Jakube: Backtick not needed (ah, how did I miss that, HOW?!?).

Woohoo, this even beats 05AB1E! Edit: it doesn't beat 05AB1E, and I don't wanna steal :(

I found it. You don't need the 0 at the end. If the input has a 0, the 0 would be provided by the input; if the input does not have a 0, it won't matter.

@LeakyNun and you can even save the backtick: ox+.n0

OK, disregard the first comment, thanks to LeakyNun and Jakube, I again beat 05AB1E, I hope for good this time.

That's a beautiful amount of implicit input.

@isaacg One third of the program ox+.n0NNQ can be implicit input, so it's cut away.

Python 3, 40 39 bytes
1 byte thanks to Jonathan Allan.
lambda s:sorted(s,key="145926870".find)

Try it online!

You can drop the 3, since find will return -1 when an item is not found.

05AB1E, 10 9 7 bytes
Saved 1 byte thanks to Leaky Nun noting that filtering out duplicates is unnecessary.
Saved 2 bytes thanks to Adnan.
žqRvy†J

Try it online!
Explanation
žq       # push pi to 15 decimals (contains all digits but 0)
  R      # reverse
   vy    # for each char in pi
     †J  # move it's occurrences in the input to the front

13žsRvy†J for 9 bytes

@LeakyNun: Oh yeah, duplicates doesn't matter. Thanks :)

Can you use žq instead of 13žs?

@Adnan It doesn't seem to work.

@EriktheOutgolfer It works for me

@LeakyNun Whoops, I don't know what I typed then.

@Adnan: Yes of course. I didn't realize there was another pi constant :)

Japt, 10 9 bytes
8 bytes of code, +1 for the -P flag.
¬ñ!bMP+U

Try it online! Takes input as a string.
Explanation
¬ñ!bMP+'0  // Implicit input

¬          // Split the input into chars.
 ñ         // Sort each char in the resulting list by
  !b       //   its index in
    MP+U   //     Math.PI + the input.
-P         // Join the result back into a single string.
           // Implicit: output result of last expression

Jelly, 10 bytes
“ṀSṪw’ṾiµÞ

Try it online!
Takes input as a string of digits.
-3 bytes thanks to @ETHproductions
Explanation
“ṀSṪw’ṾiµÞ
        µ  - Separate chain into function “ṀSṪw’Ṿi and sort atom Þ.
         Þ - Sort the input by
       i   - Each digit's index in:
“ṀSṪw’     - the literal 3145926870 ...
      Ṿ    - transformed into the list 3,1,4,5,9,2,6,8,7,0

I think 3145926870 can be represented as a 4-digit base-250 string (meaning it takes up 6 bytes instead of 10), but I'm not sure how to compress it as such.

Does Jelly not have a builtin for pi?

@mathjunkie but Jelly is not very efficient on string manipulation

@mathjunkie Yes, but the manipulations to the list take too many bytes

“ṀSṪw’ will give you 3145926870.

If you take input and output as strings, can you get rid of the D/Ḍ in the main link?

@ETHproductions The D converts it to a list of numbers, not a string

Try it online!

@ETHproductions hey, that was nice.

which allows you to do “ṀSṪw’ṾiµÞ for 10 bytes

@mathjunkie The pi builtin does not go far enough to include a zero, which is needed in Jelly since it's 1-indexed.

CJam, 15 12 10 8 bytes
r{P`#c}$

Try it online!
-3: Use a string based on the P pi variable instead of a literal.
-2: Decided I don't need to uniquify at all, since finding an index takes the first occurrence anyways.
-2: Thanks to jimmy23013 for an interesting approach using x mod 65536.
Explanation:r{P`#c}$ e# Takes an input token
r        e# Take the integer as a string
 {P`#c}  e# Sorting key:
  P      e#  Push P (defaults to 3.141592653589793)
   `     e#  Convert to string representation
    #    e#  Find char's index in the string we made
         e#  A '.' will never be found in an integer, but it doesn't matter, since the shifting preserves ideal sorting.
         e#  A '0' will be indexed as -1.
     c   e#  Convert index to char
         e#  This first calculates index % 65536, and then converts to char. We need this because otherwise 0 would be indexed as -1, i.e. smallest index.
         e#  We don't need to convert back to integer, since we can use lexicographical sorting.
       $ e# Sort with key

Yay, beats MATL :)

https://tio.run/nexus/cjam#@19UHZCgnFyr8v@/oYGRsYmpmbmFJQA

@jimmy23013 Wow that's clever. It's almost like there's a builtin for int(x)%65536, and ci would even convert back to integer.

Jelly,  8  7 bytes
-1 byte thanks to Dennis (use any existing 0 in the input, clever.)
ØP;ṾiµÞ

Try it online!
How?
ØP;ṾiµÞ - Main link: string s (char list)
     µÞ - sort the characters, c, of s by:
    i   -   first index of c in:
ØP      -     pi yield: 3.141592653589793
  ;     -     concatenate with left: [3.141592653589793, c]
   Ṿ    -     un-evaluate: "3.141592653589793,c" (a char list with the digit character c)
                                if any c is 0 ^ it will then be to the right of all others

...and there I was searching for squares - 3820009 (sqrt of 14592468760081) is still 3 digits in base 250.

The Ṿ in your explanation is misplaced.

@EriktheOutgolfer - thanks, adjusted.

JavaScript (ES6), 54 bytes

f=
s=>[...s].sort((a,b)=>k[a]-k[b],k=`9150236874`).join``
<input oninput=o.textContent=f(this.value)><pre id=o>

Uses strings for I/O.

C (clang), 85 73 bytes
*z=L"9150236874"-48;s(*a,*b){return z[*a]-z[*b];}f(*t,n){qsort(t,n,4,s);}

Try it online!

@ceilingcat, wow, it took my small mind forever to figure out what you did there!!

69, different IO

@l4m2 Nice!! I'll update my answer; when I get back to my laptop. -2 bytes

@l4m2 65 bytes

PHP, 71 Bytes
The regex solution is shorter
for(;~$c=_3145926870[$i++];)echo str_repeat($c,substr_count($argn,$c));

or

for(;~$c=_3145926870[$i++];)echo str_pad("",substr_count($argn,$c),$c);

Online Versions
PHP, 78 Bytes
for(;~$c=$argn[$i++];)$j[strpos("3145926870",$c)].=$c;ksort($j);echo join($j);

PHP, 112 Bytes
$a=str_split($argn);usort($a,function($x,$y){return strpos($d="3145926870",$x)<=>strpos($d,$y);});echo join($a);

Online Version

I've added a 69 byte solution. Maybe we can get it down to 66 byte together ;)

Ruby, 50 bytes
n=gets;"3145926870".each_char{|c|$><<c*n.count(c)}

C (gcc), 78 bytes
f(char*s){for(char*d="3145926870",*p;*d;d++)for(p=s;*p;)*p++-*d||putchar(*d);}

Try it online!

MATL, 14 bytes
YP99Y$uj!y=sY"

Try it online!
Explanation with an example
The symbol ; is used as row separator in matrices. So [1 2 3] is a row vector, [1; 2; 3] is a column vector, and [1 2; 3 4] is a square matrix. The latter can also be represented, for clarity, as
[1 2;
 3 4]

Consider input 2325 as an example.
YP     % Push approximation of pi as a double (predefined literal)
       % 3.14159265358979
99Y$   % Variable-precision arithmetic with 99 digits. Gives a string.
       % The input 3.14159265358979 is recognized as representing pi
       % STACK: '3.141592653589793238462 ··· 707'
u      % Unique entries, keeping order of their first appearance
       % STACK: '3.145926870'
j      % Input line as a string
       % STACK: '3.145926870', '2352'
!      % Transpose
       % STACK: '3.145926870', ['2'; '3';'5'; '2']
y      % Duplicate the second-top element in the stack
       % STACK: '3.145926870', ['2'; '3';'5'; '2'], '3.145926870'
=      % Test for equality, with broadcast. This gives a matrix with
       % all pairwise comparisons)
       % STACK: '3.145926870', [0 0 0 0 0 0 1 0 0 0 0;
       %                        1 0 0 0 0 0 0 0 0 0 0;
       %                        0 0 0 0 1 0 0 0 0 0 0;
       %                        0 0 0 0 0 0 1 0 0 0 0]
s      % Sum of each column
       % STACK: '3.145926870', [1 0 0 0 1 0 2 0 0 0 0]
Y"     % Run-length decoding. Implicitly display
       % STACK: '3522'

PHP, 66 65 bytes
Saved 1 byte thanks to Titus.
while(~$d=_3145926870[++$i])echo preg_filter("/[^$d]/",'',$argn);

05AB1E, 5 6 bytes
Had to realise that 0 is not present in the standard length pi constant.
Σтžsyk

Try it online!
Σтžsyk
Σ      Sort by the result of code
 тžs   Push 100 digits of pi
   yk  Index of digit in pi

Too bad you needed that zero for this method. It should be optimal for this language at least. Can't ask for more than that :)

C# Interactive, 37 36 Bytes
i.OrderBy(c=>"145926870".IndexOf(c))

Actually you have to execute this in the C# interactive for proper results, but I guess this is what you meant with exit status. The variable i actually is the input variable (it can be for example a string), so it's basically the method parameter.
I think the code itself is pretty straight forward.

Where's the 3?

@Paul it's not neccessary, as it returns -1 if the element isn't found.

This is just a snippet of code though, I'm pretty sure even in interactive you have to specify why i is somewhere so it can be taken as input. Also if you're saying C# you have to include using System.Linq; into the byte count. However, if this is Interactive you should specify the language as C# Interactive not solely C#.

@TheLethalCoder I updated it to C# Interactive. The using isn't neccesaary in the interactive, as it's included automatically.

APL (Dyalog Unicode), 13 bytes
{⍵[⍵⍋⍨14⍕○1]}

Try it online!
○1 Pi times 1.
14⍕ convert to a string with 14 decimal digits. This includes all unique digits except 0.
⍵⍋⍨ the indices that would sort the input string ⍵ according to order given by the previous string.
⍵[...] index with those indices into the input to sort it.

PHP, 69 68
for(;(~$d=$argn[$j++])||~$c=_3145926870[$i+++$j=0];)$c==$d&&print$d;

Still beaten by preg_filter but I thought it was quite nice itself. Maybe someone can golf off some bytes.

$c!=$d?:print$d as alternative for $c==$d&&print$d I only see in the moment

_3145926870 instead of `"3145926870" save 1 Byte

for(;(~$d=$argn[$j++])?:~$c=_3145926870[++$i+$j=0];$c!=$d?:print$d); is also a working alternative

Clojure, 38 bytes
#(sort-by(zipmap"3145926870"(range))%)

Input in string, returns a sequence of characters. zipmap creates a "dictionary" object, which can be used in a function context as well.
(f "1234")
(\3 \1 \4 \2)

If input digits were guaranteed to be unique then you could simply do #(filter(set %)"3145926870").

Java 7, 110 bytes
String c(String s){String r="";for(char i:"3145926870".toCharArray())r+=s.replaceAll("[^"+i+"]","");return r;}

Explanation:
String c(String s){                       // Method with String parameter and String return-type
  String r="";                            //  Result String
  for(char i:"3145926870".toCharArray())  //  Loop over the characters of "3145926870"
    r+=s.replaceAll("[^"+i+"]","");       //   Append the result-String with all the occurrences of the current character
                                          //  End of loop (implicit / single-line body)
  return r;                               //  Return the result-String
}                                         // End of method

Test code:
Try it here.
class M{
  static String c(String s){String r="";for(char i:"3145926870".toCharArray())r+=s.replaceAll("[^"+i+"]","");return r;}

  public static void main(String[] a){
    System.out.println(c("12345678908395817288391"));
  }
}

Output:
33311145599922688888770

Husk, 4 bytes
Ö€İπ

Try it online!
Input as a  list of digits.

Pip, 10 bytes
PI.0@?_SKa

Try it online!
Explanation
       SKa  Sort the command-line argument a by this key function:
    @?_      Index of first occurrence in
PI.0         Pi (3.141592653589793) concatenated with 0

If the 0 isn't added, PI@?0 returns nil, which behaves... strangely... when used as a sorting key.

Vyxal, 8 bytes
µ»×₍+=»ḟ

Try it Online!
µ Sort by
ḟ first index in
»×₍+=» compressed integer 145926870

Try it Online! for 6 bytes

k, 19 bytes
{x@<"3145926870"?x}

Explanation:
{                 } /function(x)
    "3145926870"?x  /for each x: "3145926870".index(x)
   <                /get indices with which to sort
 x@                 /sort x by those indices

Perl 6, 34 bytes
*.comb.sort:{3145926870.index: $_}

Try it
*\       # WhateverCode lambda (this is the parameter)
.comb    # split into digits
.sort: { # sort by

  3145926870.index: $_ # its index in this number
}

you can save 1 byte by dropping '3' from the lookup.

Japt, 6 bytes
Input as a string, output as an array of digit strings
¬nUiMP

Try it

TI-Basic, 100 bytes
Input Str1
seq(expr(sub(Str1,I,1)),I,1,length(Str1→A
seq(1+sum(not(cumSum(Ans(I)={3,1,4,5,9,2,6,8,7}))),I,1,dim(Ans→B
SortD(ʟB,ʟA
sum(seq(₁₀^(I-1)ʟA(I),I,1,dim(ʟA

Takes input as a string. Outputs a number that is stored in Ans and is displayed at the end.


text:
Tips for making a golfing language
I am currently working on a golfing language. Do you have any suggestions for this language? What are some helpful features of a good golfing language? What features do you find useful? Do you suggest a language based on variables, stack(s), tapes, registers, etc?
As usual, please post separate tips in separate answers.

Would [tag:code-golf] be relevant in this question?

@KritixiLithos yes, added.

I think this is too broad. We used to have this question which was more specific and we decided that this kind of question is not a good fit for the SE platform. Specific questions about the design of golfing languages could potentially be on-topic and well scoped, but I don't think this is.

@MartinEnder If tips for golfing in  on-topic than why isn't this?

@programmer5000 That's a narrower question, since the tips there should pertain to the majority of languages, specific to shortening them. This one is completely open-ended, and answers could encompass the entirety of language design.

Maybe if you center the question around Do you suggest variables, stack(s), tapes, registers, etc?. I think that is one of the main foundations when making a language and doesn't seem too broad.

@Geobits This is pertaining to shortening, too, it is tagges [tag:code-golf]

@tkellehe Posted

This question is now a duplicate of this one. @programmer5000, why didn't you just edit this question instead of posting a new one?

@mbomb007 I think this could be modified to be a question for general tips for making a golfing language.

I don't feel like this question is useful in any way. The fact that the OP is asking for feature suggestions shows that the OP is missing the point of making a language. That's the sort of question that will make "cookie cutter" languages that are all the same. If you're going to make a language, make it unique, make it well, and make it complete. A better question to ask would be how to implement certain features.


text:
Tips for storage in a golfing language
I am writing a golfing language.
Do you suggest variables, stack(s), tapes, registers, etc for storage in a code-golf language? What about implicit input?
Rough definitions:

A variable is simply a name (usually one character long in golfing languages) that a value can be assigned to, and later retrieved by that name.
A register is like a variable, but it has its own (usually single-byte) commands for setting/getting the value.
A stack is a variable-length array/list of values, where the most recently added values (the values "on top") are the ones that are being modified.
A queue is like a stack, except the values "on the bottom" are the ones that are being modified.
A tape is a static array/list of values where each value has an index. The main difference between a stack and a tape is that values on a tape are modified in-place.

I would appreciate to know the advantages and disadvantages of each option for different scenarios, and overall. Please avoid opinions, and backup statements with reasoning.

I think you should include a definition of these terms in your question

How should the answers be? One tip per answer, or one generalised community-wiki answer for all the tips?

IMHO implicit input belongs in a different question, since it's basically going to be the same no matter which storage method you use.

This question is entirely dependent on what kind of language you're making. Too broad.

@Fatalize Technically the storage method isn't dependent on what kind of golfing language you're making, the kind of golfing language is dependent on the storage method...

@ETHproductions They're totally interdependent.

I agree with @Fatalize, this is too broad. Even though I answered, I unfortunately can't make your golfing language for you.

@Fatalize you say that "This question is entirely dependent on what kind of language you're making", but you also say "They're totally interdependent.". I don't understand.

I added some rough definitions of the various storage terms, feel free to edit or roll back if you don't like them.

@ETHproductions thanks, those are great!

There is a very close relationship between the storage method and the type of language, but I think you have to look at both. For example, "imperative" languages (those which perform their instructions strictly left-to-right) can be stack-based (CJam, 05AB1E), tape-based (BrainF***), or something else entirely (V, which uses one big 2D string called the "buffer", along with a few registers). There's also prefix-based languages (Pyth), infix-based languages (Japt, Pip, and basically every mainstream lang), link-based languages (Jelly), etc. all of which hardly use any of the mentioned methods.

@programmer5000 It's much better now, but it's still a bit broad. If you say, for example, "I would like to know the advantages and disadvantages of each", or something like that, then this would not be too broad. I don't want to put words in your mouth though, so I won't edit.

@programmer5000 Great, I will retract my close vote.

This question is about starting to design a golfing language. When you're starting to design a golfing language, you pretty much have to decide on the best types of storage to use and the type of data flow through the code (e.g. left-to-right for CJam, BF, etc., right-to-left for prefix langs such as Pyth, a combination of both for langs such as Jelly...) at the same time because these two things are very closely related. Because of this, would you mind editing the question to include choosing the type of language? I can edit for you if you'd like.

Golfing languages are about reducing redundancy - being able to express a solution in terms of its logical components with as little boilerplate as possible. You should try to make as many things implicit as you can. Most likely, use of the queue would be implicit. Tapes tend to complicate things, and I can't see how they would be useful if you already have a stack, reqisters, etc as well as a good selection of data types and builtins on those data types.

All of the storage types involve storing something at one point and retrieving it later. To do this in only one operation, you should do either storing or retrieving automatically, and specify the position of the stored value in the other operation.
That is, for explicit storage, you could create an operator to retrieve the nth calculated value before this operation, or put back the current value after n operations. Alternatively, you could use the absolute position from the start of the program, or do more things such as removing some elements automatically after some operations (like in a stack). You could also make multiple operators, retrieving from different copies of the storage with or without these automatic operations. And you should try to make the maximum number needed to specify in the operations reasonably small, so you could assign one operator for each number.
But in most cases, you don't even need an operator and the language will do this implicitly. That is when you need to consider a more standardized model such as stacks or queues. The most successful for now seemed to be tacit programming, which doesn't even mention storage directly.
If you want to design a new such model, you could try expanding the evaluations as a dag, and try to think of a default dag if nothing else is specified. Most likely, the default is just a tree, except for that multiple leaves may be linked to the same input. You could for example use a queue for a balanced tree, or a stack for a deep tree where leaves are mostly constant, or something like Jelly for a deep tree where leaves are mostly copies of the input.
But note that, you could encode the shape of a binary tree in only 2 bits per operator. So, if your language has less than 64 operators, you may actually ignore the traditional models and just encode the complete tree in the spare bits (call them combine_parent and below_leaf flags). Even if there are more operators, you could make a fairly good default (such as the model of Jelly) and 3 modifiers to change it.
You could use the same model for implicit and explicit storage for convenience, but you don't have to. For example, you could use a stack for implicit storage, but don't pop elements in the explicit storage (or in another explicit storage in addition to the implicit one). It's likely it won't be called a stack in the final documentation, but you get the idea.
For reference, the size of the perfect encoding of a binary tree is the logarithm of the Catalan numbers. And the size of the perfect encoding of a "binary" dag is the logarithm of A082161, but obviously impractical. This assumes an operator with different argument order two different operators, adding another bit when it is not.
Sometimes you may still want variables for the loops. It might be possible to rewrite the loops in other ways. But if you really need it, don't use a 1-byte construct in addition to a name to define the variable. unless you are only using the preinitialized values, it's usually more efficient to use a 1-bit flag to specify whether you are reading or writing this variable.

I suggest all of them!
More seriously, they all come in handy some of the time, and the more the better! Implicit input is never bad, just have a flag to turn it off. Variables are helpful so they don't need to be found on a stack or tape; same with registers. Stacks are helpful to store data, and so are tapes. I recommend trying to implement multiple, say a stack and registers, or a stack and variables, like GolfScript. If you can make each function one byte, then your language will probably be effective at golfing, as you can use the advantages of each.
An example:

Say I want to take two numbers as inputs, and add their string lengths
Variables might be better for this (a stack might not)
Example code in GolfScript (with implicit input):
~,\,+
~ # Eval input (e.g. "1 2" > 1, 2)
, # Take Length
\ # Reverse items on the stack
, # Take Length
+ # Add
  # Implicit output

However, with variables (I know it's longer, it just doesn't have to swap places on the stack):
~,:a;,:b;ab+
~ # Eval input
, # Get length
:a# Store in "a"
; # Discard value left on stack
, # Length
:b# Store in "b"
; # Discard
a # Recall a
b # Recall b
+ # Add
  # Implicit output

Overloads
Another thing that can be helpful is overloads. For example, if you have a variable storing function, maybe it could be used as a monad (one-input function; I'm not sure of the term out side of J/K/APL) to add to the stack or tape.
Example:
c12 # Stores "1" into register 2
c1] # Pushes "1" onto the stack ("]" is used to denote the end of the monad)

Maybe if an argument is called with the wrong types, it gets added to a queue which is then used to fill in values if the stack is empty?

I'd suggest having some quickly usable storage (from the given - tape, queue, stack) and some permanent storage (variables, registers) for things to not get in the way while the program is doing something unrelated. I'd say that much more would rarely give anything and leave more characters free for more 1-byte instructions.
From the definitions given, the ones I think would work the best would be a stack and registers.
A stack, because a tape has to use functions just to store a new thing in it, while a stack should have simple push and pop functions (usually built in the commands).
Registers, because they take less bytes usually compared to variables and if you need to store more than 2-4 different things for something, you're doing something wrong.
Don't limit the functions of them only to what their names or definitions suggest trough - some functions like put the 1st thing of the stack on top of the stack can definitely help.

There are basically two sorts of storage that need to be handled differently; access to recently generated values and/or the inputs; and long-term storage.
For long-term storage, variables seem to work best; anything with a limited number of options doesn't scale (although languages with this property, like Jelly, nonetheless can do fairly well even on medium-sized tasks). However, there's no need to provide variable names when storing the variable, most of the time; just have a command to store a value in the variable, and autogenerate the names according to a predictable pattern so that storing and retrieving the value can be one command each in simple cases. (For example, you could have commands to restore the most recently assigned variable, the second most recently, the third most recently, and so on, up to a small fixed number, plus a general command that took an argument.)
For short term storage, you want as much to be implicit as possible. Almost all golfing languages I've seen connect the output of one command to an input of the next, by default; the exact way in which this is done differs from language to language but normally comes to the same thing. However, the second input for a 2-input command is more interesting. Taking it from a stack works well in cases where values are only used once, but doesn't scale well when reusing values. (Try to avoid stack manipulation primitives; if you have to resort to using them, you're wasting a lot of bytes.) Alternatively, using user input or a recently assigned variable as the implicit second argument tends to give a few byte savings on simple programs, although you'll then need a parenthesis equivalent to make it possible to place nontrivial expressions on both sides of a binary operator.
In a golfing language I'm working on at the moment, I use a combination of a very cheap mechanism (a single bit) to specify the shape of the parse tree, automatically filling in missing arguments from user inputs by default, and a checkpointing approach that makes it possible to set the default for missing arguments to something else (plus plenty of special cases). At some point I'm likely going to add variables to communicate information greater distances along the program.

A stack is sufficient for a terse golfing language.
First of all, implicit input is always nice, it's indisputable (it saves a lot from your source code, see this 05AB1E tip.)
I created W as a language which only allows manipulations upon the stack. If you read W's instruction reference, you will realize that W has absolutely no support for queues or tapes. Also, it doesn't even have assignable variables and accumulators! However, it still manages to be competitive, as well as having a similar bytecount as other stack-based golfing languages.
In my opinion, if you ever need an accumulator/variable, there's always a shorter way to re-write your program that purely uses stack manipulation.

I suggest a tape and a register.
I prefer tapes over stacks because tapes tend to have fewer elements, making manipulation of them easy. Also, being able to place elements in the tape in the register and vice versa makes for easy, short code.


text:
The code-golfer way of searching a library
Challenge:
I have thousands of songs in my music collection, and luckily for me, my favorite player has a search function. I also have a great memory—I can remember the title of every song in my collection. However, I'm very lazy and don't like to type—each extra keystroke is a chore!

What is the shortest string I must search for to isolate one song? Help me memorize a list of keys I can use to minimize typing when searching!

This is code-golf, so shortest code wins.

Rules:
Given an input list of song titles, generate a list of search keys subject to the following constraints:

Each song title should have a search key.
The total number of characters in the output list must be as few as possible.
My favorite music player is foobar2000:

The search function is not case-sensitive. (apple is the same as aPpLE).
Each search key must consist of one or more "words", in any order, separated by spaces:

Each word must be a substring of the corresponding song title.
If the same substring is specified multiple times, then it must occur that many times in its corresponding song title.
If a substring itself contains a space, then that substring must be surrounded with quotes.

Hints:

Often, for some song titles, there are multiple search keys meeting rule 2. In such a case, any one key will do, but you get brownie points for listing them all.
You may assume that the input list will only ASCII characters, but brownie points will be awarded for UTF-8 compatibility.
Was Rule 3 hard to follow? Here's how it works:

+----------------------+ +--------+ +----------------+ +------------------------------------+
|         Input        | | Output | |   Statistics   | |             Explanation            |
|----------------------| |--------| |----------------| |------------------------------------|
|                      | | Search | |  Key   |  # of | |                                    |
|      Song title      | |  Key   | | length | words | |   Why is the output what it is?    |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanna Be A Wanna Bea | | e e    | |      3 |     2 | |      ["Wanna Be A Wanna Bea"]      |
|                      | |        | |        |       | |   is the only string containing    |
|                      | |        | |        |       | |            ["e"] twice             |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanta Bea A Wanna B  | | t ea   | |      4 |     2 | |       ["Wanta Bea A Wanna B"]      |
|                      | |        | |        |       | | is the only string containing both |
|                      | |        | |        |       | |          ["t"] and ["ea"]          |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanta Be A Wanna B   | | t "e " | |      6 |     2 | |       ["Wanta Be A Wanna B"]       |
|                      | |        | |        |       | | is the only string containing both |
|                      | |        | |        |       | | ["t"] and ['e' preceding a space]  |
+----------------------+ +--------+ +----------------+ +------------------------------------+

Total number of characters in output (par): 13

Example:
If my music collection consisted only of two albums, Michael Jackson's Off the Wall and Thriler:

+--------------------------------+ +--------+ +----------------+
|             Input              | | Output | |   Statistics   |
|--------------------------------| |--------| |----------------|
|                                | | Search | |  key   | # of  |
|           Song title           | |  key   | | length | words |
|--------------------------------| |--------| |--------+-------|
| Don't Stop 'Til You Get Enough | | Do     | |      2 |     1 |
| Rock with You                  | | Ro     | |      2 |     1 |
| Working Day and Night          | | Wo     | |      2 |     1 |
| Get on the Floor               | | Fl     | |      2 |     1 |
| Off the Wall                   | | ff     | |      2 |     1 |
| Girlfriend                     | | lf     | |      2 |     1 |
| She's out of My Life           | | Sh     | |      2 |     1 |
| I Can't Help It                | | Ca     | |      2 |     1 |
| It's the Falling in Love       | | v      | |      1 |     1 |
| Burn This Disco Out            | | Bu     | |      2 |     1 |
| Wanna Be Startin' Somethin'    | | nn     | |      2 |     1 |
| Baby Be Mine                   | | Ba     | |      2 |     1 |
| The Girl Is Mine               | | G M    | |      3 |     2 |
| Thriller                       | | hr     | |      2 |     1 |
| Beat It                        | | Bea    | |      3 |     1 |
| Billie Jean                    | | J      | |      1 |     1 |
| Human Nature                   | | Hu     | |      2 |     1 |
| P.Y.T. (Pretty Young Thing)    | | .      | |      1 |     1 |
| The Lady in My Life            | | La     | |      2 |     1 |
+--------------------------------+ +--------+ +----------------+

Total number of characters in output (par): 37

You may use the lists above to test your program. Here is the raw version of the second list:
["Don't Stop 'Til You Get Enough","Rock with You","Working Day and Night","Get on the Floor","Off the Wall","Girlfriend","She's out of My Life","I Can't Help It","It's the Falling in Love","Burn This Disco Out","Wanna Be Startin' Somethin'","Baby Be Mine","The Girl Is Mine","Thriller","Beat It","Billie Jean","Human Nature","P.Y.T. (Pretty Young Thing)"]

Do you have an example that requires multiple strings for a key?

How about ["Wanta Be A Wanna B","Wanta Bea A Wanna B","Wanna Be A Wanna Bea"]?

...but what should they / could they be if no spaces are allowed in the substrings themselves - note that all whole words collide.

Why is the raw version in a spoiler?

What is the length of the output (and the individual parts) in the multi-string example? What do we do with a (or even multiple) literal " in our output parts (or are we guaranteed not to receive input containing them)?

@JonathanAllan The input will never contain a " character; each " in the the output is treated as one extra character. I also updated the example to show how length is counted.

Example 2 is not optimal, nt "e " is shorter. And nn nn is the same as just nn, because you specified no order/multiple rules.

Just type one character at a time until the one you want is the only one that shows up.

Related

Does the order of the words in the search key matter?  That is, would "M G" also be a valid search key for "The Girl is Mine"?

@RootTwo No, order doesn't matter.

Python 2, 556 bytes
Try it online.
-10 bytes, thanks to @Riker, @ovs
Took me couple evenings to make everything works.
Outputs song name, array of search keys and lenght of search keys combined (including spaces and quotes)
import re
S=map(str.lower,input())
T=len
for s in S:
 y=s;n=T(s)
 def R(r,t):
    global n,y
    l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t))
    if l>n:return
    if(lambda K:T([s for s in S if T(s)-T(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==T(''.join(K))])==1)(t)and l<n:y=t;n=l
    u=[(lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s))(r,i)for i in range(T(r))]
    for i in range(T(r)):
     for j in range(T(r)-i):R(r[j+T(u[i][j]):],t+[u[i][j]])
 R(s,[])
 print[' 'in x and'"%s"'%x or x for x in y]

Some explanation:
T=len

Function len() used very often here, so this renaming saves bytes

L=lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s)

Evaluates all possible substrings of string s lenght n.
eval(...) creates command zip(s,s[1:],s[2:],...,s[n:])
It creates substrings of lenght n from every index of s if possible.
So for s='budd' and n='2' it will produce bu, ud, dd

F=lambda K:len([s for s in S if len(s)-len(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==len(''.join(K))])==1

Filter to check if provided keys (K) are for unique song name.
re.sub is requered for multiple identical keys, like ['nn','nn'] in examples.

Inner function def R(r,t) is a recursive one to create all possible combinations of substring, that may describe song name.
Every combination is compared with currently shortest one (if there was any) to lower number of created combinations - if it is larger, it won't be accepted as all of it derivatives.
Function uses 2 variable to track state: n for lenght of current shortest key combination and y for combination itself

l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t))

This calculates length of key combination. ' '.join add spaces between keys and 2*sum(...) calculates number of needed quotes for keys with spaces.

u=[L(r,i)for i in range(0,T(r))]

Uses first lambda function to get all possible key combination (of every possible length) for current string.

Two for cycles to look through all generated keys and pass them individually to the next recursive step.
Key place (j) is needed to correctly slice string at the end of it: r[j+T(u[i][j]):].
Slice provides string, that started where current key ends, so there won't be any overlaps.
If place is unknown, equal keys would mess everything up.

[' 'in x and'"%s"'%x or x for x in y]

Much longer than just y, but keys with spaces should be surrounded by quotes

This... is amazing. You're the first one to get rule 3 right!

By the way, you should be able to shave off two bytes by removing the 0, in one of your ranges: u=[L(r,i)for i in range(0,T(r))] => u=[L(r,i)for i in range(T(r))].

You could save a few more bytes: in your output, you don't have to show the input strings and the size of the output strings.

@彩音M Thanks! I've trimmed this few bytes from range and output.

You can replace the S=[x.lower()for x in input()] with S=map(str.lower,input()), for 4 less bytes (I think).

S=map(str.lower,input()) for -5 bytes

Congratulations! You win the bounty. (Although you had the only answer...haha!)

@Riker bytes saved by replacing spaces with tabs, thats why it was 566 and not 587

@DeadPossum ah, sorry. Didn't think of that. (curse SE's tab collapsing..)  Hope skipping the lambdas helped.

@Riker Yeah, it saved bunch of bytes, thank you!


text:
Skip or delete lines between two keywords in a file using python
The problem is I need to skip or delete all the lines between the two keywords in a file and the keyword pair will appear many times in the file.The file looks something like this
.
.
..........
..........
Hello world
..........
..........
welcome
.
.
.
..........
..........
Hello world
..........
..........
welcome
.
.
.
.........
.........
Hello world
..........
..........
welcome
.
.
.
..........
..........

Here the contents between Hello world and welcome are to be deleted (including those keywords). Please help me out with this.

Welcome to PPCG! Please note that this site is for challenges, not general questions on programming. You may want to ask your question on stackoverflow instead.