text:
Appearing a unique number of times
Your task is to write a program or function that takes as input a list of positive integers and determines if there are any two integers in the list, that both appear the same number of times.
For example the list
[1, 2, 3, 2]

Has one 1 and one 3 so it satisfies the condition.
But the list
[3, 2, 2, 1, 2, 3]

does not satisfy the condition since every member appears a unique number of times.
Additionally your program should not satisfy this condition when its source code is interpreted as a list of bytes.
For example
abcb

Would not be a valid submission since both a and c appear exactly once.
Here is a verifier you can use if your source is in ASCII.
Output
Your submission when executed should output one of two possible values, one when the input satisfies the condition, one when the input does not.
This is code-golf so answers will be scored in bytes with fewer bytes being better.

I feel like the scoring is going to be basically "minimize the number of distinct characters", since you can probably pad in useless copies to make them appear 1..n times for a triangular score.

@xnor That seems like a good strategy.

How about providing a scoring program for the programs?  In some languages, the program will not be able to evaluate itself as the inputs are specified as integers, not bytes or strings.

@Xcali Scoring is just regular code-golf.

@AdHocGarfHunter  I should have been more clear.  A validator that checks the second condition.

@AdHocGarfHunter Can you provide a solution validator?

@S.S.Anne I don't think I can provide a universal solution validator, but I can make one for ASCII.

@AdHocGarfHunter That works.

05AB1E, 6 bytes
D¢DD¢Q

Try it online! or validate more test cases.
Outputs 1 if each item appears a unique number of times, 0 otherwise.
D           # duplicate the input
 ¢          # count occurences of each item in the input
  DD        # triplicate the list of occurence counts
    ¢       # count occurences of each occurence count in the list of occurence counts
     Q      # check whether this is equal to the list of occurence counts

Without the source restriction, this could be 4 bytes: ¢Ð¢Q.

Nice one! I was about to post an answer (21 bytes though, 6 unique bytes.. so nvm, haha). Here a test suite of your answer. (Enjoy the weekend!)

@KevinCruijssen Thanks :D

Jelly, 1+2+3+4 = 10 bytes
ĠQQẈQƑẈĠĠĠ

A monadic Link which accepts a list and returns an empty list, [], if the input satisfies the condition, or a list with a list containing a one, [[1]] if the input does not satisfy the condition.
Try it online!
How?
Without the source code restriction we could do the four byte ĠẈQƑ: Ġ, group indices by value; Ẉlength of each; Ƒ, is invariant under; Q de-duplication.
So for the \$1+2+3+4=10\$:
ĠQQẈQƑẈĠĠĠ - Link: list, L
Ġ          - group indices by value -> list of lists (which when flattened would contain the integers 1 to len(L) inclusive)
 Q         - de-duplicate (a no-op)
  Q        - de-duplicate (again a no-op)
   Ẉ       - length of each (group) 0> how many times each element appeared
     Ƒ     - is invariant under?:
    Q      -   de-duplication -> 0 if satisfies, 1 if not
      Ẉ    - length of each -> [] if satisfies, [1] if not
       Ġ   - group indices by value -> [] if satisfies, [[1]] if not
        Ġ  - group indices by value (a no-op)
         Ġ - group indices by value (another no-op)

Python 2, 136 126 120 bytes
A slight improvement of @xnor's solution, posted with permission. Source code has 15 distinct characters.
n=input()
print(not
sum(())==sum(sum(r==m
for
m
in
n)==sum(u==m
for
m
in
n)for
r
in
n
for(u)in(n)if(r==u)==(r==n)))#ouu)

Try it online!
Input: A string representation of a list/iterable, from stdin.
Output: True if the list has 2 elements with the same frequency, False otherwise.
Base solution
n=input()  # read a list/iterable from stdin
           # This is Python2, so the input string is implicitly evaluated
print(0 != sum(     # return True if sum is not 0 (aka at least one of the following is True)
  sum(r==m for m in n)==sum(t==m for m in n) # check if frequency of r and t are the same
  for r in n for t in n if r!=t              # ignore when r==t
))

Try it online!

Old solution using exec
Python 2, 158 bytes
e=s=110;"tt)e";exec"e=%c%x%c%x%c%x%cx:%ce%c(set(x))-%ce%c(set(%c%x%c(x%cc%c%c%ct,x)))"%(e-2,10,e-1,11,100,10,0x20,e-2,e,s-2,s,s-1,10,s--2,0x2e,s--1,120-2-1,s)

Try it online!
Input: a list or iterable.
Output: a positive number if the list has 2 elements with the same frequency. 0 otherwise.
Base solution
e=lambda x:len(set(x))-len(set(map(x.count,x)))

Try it online!

My approach is inspired by this answer, which discussed how to construct any Python programs using only the characters exc="%\n. The idea is to convert the program into exec"<program>", then use string modulo (%x and %c) to build program string from number.

I don't have time to develop it, but I got a solution with 16 distinct chars without exec: TIO If you're interested, you're welcome to try making it work w/ padding (renaming variables) and post it.

Oops, the code should be this: Try it online!

It's amazing that you managed with only 16 characters! Unfortunately, the exec approach doesn't work, as I will have to add the character set ecx="%(), and your code is too long for substitution to work. However, simply padding your code with the extra characters is enough to beat my solution! 153 bytes

Nice! This works out simpler than I thought. Feel free to post it. I wonder if you can further avoid a distinct #. No-ops can be done as or stuff, where if the thing before the or is true, the stuff won't evaluate, so it can be any string of letters, though it does not be be syntactically valid.  Like, (()is(a))) could probably do a or stuff. Another place to stuff letters is as for stuff in l. See the crack to this for ideas. The colon might be trickier -- could it be a singleton? Parens also have parity constraints.

The colon can be a singleton. However, I can't seem to figure out a way to have unbalanced parentheses :(

I don't know of a way to unbalance parens, unfortunately. Could you make there be an equal number of each in the padding by choosing different totals for them, or is that too constrained?

Zsh, \$\sum_{i=1}^{18} i = 171\$ bytes
((f--))
for u (${(u)@})((n[$#-${#@:#$u}]--))
((f-(${${(@on)n}[f]})))
#              rrrrrr[[[[[[]]]]]]]nnnnnnnn@@@@@@@@@#########{{{{{{{{{{}}}}}}}}}}}-----------))))))))

Try it online!
Tricks used: We use subtraction instead of adding. We reuse characters we need from for, (on), and (u) as parameter names. ((f--)) gets us f=-1, which saves us from using 1.

Haskell (No monomorphism), 245 bytes
import Data.List
g1L=all o111111111LLLLLLLLLLaaaaaaaeeeeeeeegggggggghhhhhhhiiiiillllnnnnoooooppppprrrrsssstuu.map length.group.sort.map length.group.sort
o111111111LLLLLLLLLLaaaaaaaeeeeeeeegggggggghhhhhhhiiiiillllnnnnoooooppppprrrrsssstuu i=i==1

Try it online!

Here is a work in progress towards a better answer, it solves the problem using 9 distinct characters.  However currently there are some characters that appear the same number of times (e.g. ( and )).  I'm going to take a break from this, if anyone wants to use this to make a more complete answer go ahead.
s+|(ss:sss)|s==ss=1+s+|sss|1==1=s+|sss
s+|ss=1
s|+(ss:sss)|s==ss=s|+sss|1==1=ss:s|+sss
s|+ss=ss
s(ss:sss)=ss+|sss:s(ss|+sss)
s(ss)=ss
ss(1:s)=ss(s)
ss(s:ss)=1==11
ss(s)=1==1
sss(sss)=ss(s(s(sss)))

Try it online!

Raku, 66 57 bytes
*.Bag{*}.Bag{*}.all≠'l.}}}}****{{{{{{{gggggBBBBBBB'.Bag

Try it online!
10 unique characters, *.Bag{}l' and the 3 byte character ≠. This uses .Bag{*} to get the number of times each element appears, then repeats that to get the number of times those appear and then confirms that not all of them are equal to one.

JavaScript (ES6), \$\sum\limits_{i=1}^{16}i= 136\$ bytes
Returns \$1\$ if the condition is satisfied or \$0\$ if it's not.
p=>p.map(aa=m=a=>aa|=1^(p[[,a]]||(m[p.map(m=>pp+=a==m,p[[,a]]=pp=1),pp]^=1)))|aa//((((((,,...........11111===>>>>>>>>>>>[[^mmmmmppp|||||

Try it online!
How?
To minimize the number of distinct characters, we only use map() loops and variable names made with m, a and p.
Character usage breakdown:
  + |  / |  ^ |  ) |  ] |  , |  [ |  1 |  | |  ( |  m |  a |  . |  > |  = |  p
----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----
  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |  9 | 10 | 11 | 12 | 13 | 14 | 15 | 16

Commented
In the following source, the variables have been renamed for readability.
a =>                       // a[] = input array, also used to keep track of the
                           //       values that have already been counted
  a.map(r = o = v =>       // r = result flag
                           // o = object used to keep track of the character counts
                           //     that have already been encountered
                           // for each value v in a[]:
    r |=                   //   set r if ...
      1 ^ (                //     ... the test below is false:
        a[[, v]] || (      //       v has already been counted, or this is ...
          o[               //         ... the first time this count is encountered:
            a.map(V =>     //           for each value V in a[]:
              n += v == V, //             increment n if V is equal to v
              a[[, v]] =   //             mark v as counted
              n = 1        //             and start with n = 1
            ),             //           end of inner map()
            n              //
          ] ^= 1           //         toggle o[n]
        )                  //       end of count update
      )                    //     end of test
  ) | r                    // end of outer map(); return r

Can you somehow replace 1 with other symbols?

Anyway 120

R, 78 bytes
all(table(table(scan()))==all(c()))#nss==bbbcccceeeeettttttaaaa(((()))))llllll

Try it online!
table(x) gives a table of the counts of each value in x (here x will be the input taken by scan); table(table(x)) counts how many times each count occurs. We therefore want to check whether all(table(table(x))==1). Adding # and all the necessary characters to obey the constraint would lead to a score of 91.
The trick is to avoid the character 1 by using instead all(c()), which is all of an empty vector, i.e. TRUE, which gets converted to 1.
I haven't looked yet into using octal codes for this challenge; they might lead to a better score.

MATL (unreleased master), 10 bytes
&u&uqaaaa&

Try it on MATL Online
Multiple test cases
Try it online!, but not really - link is to an equivalent 12 byte (non-conforming) version that works on TIO, since &u isn't available in it yet.
0 = input satisfies the condition, 1 = does not.
Actual code is &u&uqa& - take the counts of unique values in the input, take the counts of unique values in that, decrement that by one, and see if any of it is non-zero (which would mean the count was greater than 1, hence condition not satisfied). Repeating the non-zeroness check doesn't change anything, but takes a's count to 4 and so makes it occur a unique number of times.
A conforming version that can run on TIO is 888#8#u8#uqaaaa Try it online!

You can run the commited compiler with &u in MATL Online: https://matl.suever.net/?code=%60+i+tZN+%3F+x.+%5D+XH%0A%26u%26uqa%26%0AXD+Zx+T%5D&inputs=%5B%27%26%27%2C+%27u%27%2C+%27%26%27%2C+%27u%27%2C+%27q%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27%26%27%5D%0A%5B1%2C+2%2C+3%2C+2%5D%0A%5B3%2C+2%2C+2%2C+1%2C+2%2C+3%5D%0A%5B%27a%27%2C+%27b%27%2C+%27c%27%2C+%27b%27%5D%0A%5B%27b%27%2C+%27a%27%2C+%27b%27%2C+%27b%27%2C+%27b%27%5D%0A%5B%27a%27%2C+%27a%27%2C+%27a%27%2C+%27B%27%2C+%27c%27%2C+%27c%27%2C+%27c%27%5D%0A0%2F0&version=ee8bd433

@LuisMendo Thank you, I've updated the answer. (Didn't realize it's been almost a whole month since I was last here...)

Wolfram Language (Mathematica), 253 bytes
(*!!!!!!!!!!!!!!!!!!!!!o*=L=L=L=L*Ln*n*n*nUUU))))))))))))))))))UUUUUUTTTTTTTTTTSSSSSSSSSSSrrnnrrrrrrrrrrLLLLLLLLiiiiiiiiiiiiii//ss&&########*#######@#####&&&&&&&&&&&&&&&&s/ss/ss/s/ss/ss/ss/ss//////((((((((((((((((a*aaaa*)Union@(l=Last/@Tally@#)!=Sort@l&

Try it online!

( and = both appear exactly once.

@JonathanAllan fixed

Python 3, 406 \$\sum\limits_{i=1}^{26}i= 351\$ bytes
Saved \$27+28=55\$ bytes thanks to Surculose Sputum!!!
lambda l:all(l.count(a)^l.count(p)for a,p in itertools.combinations(set(l),2))
import itertools##22:::^^^^dddddffffff,,,,,,bbbbbbbuuuuuuuu........ccccccccceeeeeeeeeemmmmmmmmmmmpppppppppppprrrrrrrrrrrrsssssssssssss             (((((((((((((()))))))))))))))nnnnnnnnnnnnnnnnaaaaaaaaaaaaaaaaiiiiiiiiiiiiiiiiilllllllllllllllttttttttttttttttoooooooooooooooo

Try it online!
A veritable triple double super-sized whopper!!!
Returns False if the input (any sequence) satisfies the condition, True otherwise.

351 bytes by reducing the number of distinct characters by 2

@SurculoseSputum Wow that's sweet - thanks! :-)

Charcoal, 40 23 bytes
⁼№θＥθι⁼Ｅθ№θιＥθ№Ｅθ№θλ№θι

Try it online! Link is to verbose version of code. Outputs - only if the condition is satisfied. Port of @Grimmy's 05AB1E answer. Explanation: The leading ⁼№θＥθι exists to consume characters to meet the source layout restrictions and also happens to complement the result. The rest of the code is as follows:
 Ｅθ№ ι              List of counts of elements
    θ               In list
⁼                   Equals
      Ｅθ№     №θι   List of counts of counts
         Ｅθ№θλ      In list of counts

Wolfram Language (Mathematica), 66 55 bytes
####>Count@s@@o@uuunnnntttttssssss@s&@@Counts@Counts@#&

Try it online!
Returns True if occurrence counts are not unique, and False otherwise.
                                              Counts@#  occurrence counts
                                       Counts@          count of counts
####                                &@@                 squared product
    >Count@s@@o@uuunnnntttttssssss@s                      >1

Count@s@@o@uuunnnntttttssssss@s simplifies to (Count@s)@uuunnnntttttssssss@s = Count[...[s],s] = 1. The product of positive integers can only be \$\not>1\$ if they are all 1.

Japt -!, 36 bytes
ü mÊ
e       UUâââmÊmÊmÊmÊÊ

eUâ

Try it

JavaScript (Node.js), 253 bytes
n=>new(Set)(n).size>new(Set)(n.map(e=>n.filter(r=>r==e).length)).size//(======ghgmmmmmmmaaaaaaaapppppppppppwwwwwwwwwwwllllllllllllhhhhhhhhhhhhhrrrrrrrrrrrrrggggggggggggggzzzzzzzzzzzzzzzzSSSSSSSSSSSSSSSSSttttttttttttttttnnnnnnnnnnnnnnssssssssssssssssssss

Try it online!
unavoidable new Set size length map filter

JavaScript (Node.js), 91 bytes
p=>"">p[")||]m",mp="","map"](m=>[p["map"](pa=>a-=m==pa,a=[]),mp|=p[a]>m|m>p[a],p[a]=m])==mp

Try it online!
Optimized from
A=>"">A["",E="map"](B=>[A["map"](C=>D-=B==C,D=[]),E|=A[D]>B|B>A[D],A[D]=B])>=E

Only 5 bytes of direct waste!

p=>p[")|]m,]]]]",mp="","map"](m=>[p["map"](pa=>a-=m==pa,a=[]),mp|=p[a]>m|m>p[a],p[a]=m])|mp same length more waste

Pip, 28 bytes
gNUM_NMQUQNUUgg:_NgMUQgUQgQg

Takes the list as command-line arguments; or, with the -r flag, takes the list of lines of stdin. Outputs 1 if every item's count is unique, 0 if some items have identical counts.
Try it online!
Self-verify it online!
Explanation
gNUM_NMQUQNUUg

No-ops to get the character counts right.
g:_NgMUQgUQgQg
        g       ; List of arguments
      UQ        ; Uniquify (remove duplicates)
     M          ; Map this function to each:
   N            ;   Count of
  _             ;   function argument in
    g           ;   original list
g:              ; Assign the result back to g
         UQg    ; g with duplicates removed
            Q   ; is equal (using string comparison) to
             g  ; g


text:
Best free online resources to learn competitive programming
I am quite proficient in C++ and Java and want to learn competitive programming to participate in contests like Google codejam and other online contests held on sites like CodeChef and Codeforces. I would like to get information about any free resources including websites and courses to learn the "sport". Book suggestions are also welcome.
Please suggest some courses which have some practical work included and not just flat theory. I want to work on my problem solving skills rather than just learning algorithms and data structures.

@a'_' I didn't get you. I mean that I don't even know how to solve algorithmic problems then how can I code golf. I want to know about some resources to learn so then maybe I could make a better use of those tips you are pointing to.

I mean, just try to solve any problem here. You will improve yourself as you solve them. Like, I assume you know how to write "Hello, World", right? Go ahead and post an answer! (You will eventually get used to these tips while you are posting answers.)

Hey there, while I understand your quest, I fear this is not the correct place to ask for help, as the programming challenges and competitions held in this community differ wildly from what it looks like you want to do. Other than that, my best suggestion is to practice hard problems. In trying to solve problems you find hard, you end up learning a lot.

But trying to solve any hard problems without any previous knowledge would be like shooting with a blind eye. Won't it ?

Hey, one of the best learning resources is this one: https://train.usaco.org/usacogate - And after you understand basic algorithms, you will be able to understand more advanced books like "Algorithms" by Cormen, Leiserson, Rivest. (You should ask this question on Quora)

Also, you can find all kinds of free code and resources on GitHub. Here is one collection I found: https://github.com/lnishan/awesome-competitive-programming

@AndriyMakukha, please don't answer off-topic questions in the comments.

Practice Algorithmic Thinking
If there's one thing I believe programmers need to master, it's the process of dissecting a problem statement and planning their approach.
By this, I mean having the ability to approach an unseen challenge and think about what is being asked.
If I were you, I'd look at challenges posted around this website, ranging from trivial to difficult, and take the time to plan how you would solve the problem. That way, you'll be able to have a hands on experience with problem solving.
Once you do this enough, start placing time restrictions on your thinking time. Because I know from personal experience that competitive programming is most often timed. Once you have got that nailed, you should be ready for competitions.
In summary: practice. Y'all need to walk before y'all can run. I hope to see you as an active contributor around here!

I don't think this website is a good place to practice in competitive programming. ICPC and IOI tasks never ask to solve a problem in as few bytes as possible.

source: Stack Exchange

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

sort: votes


text:
Counting polyominoes on (hyper-)cubes
This challenge like some of my previous challenges will have you counting free polyforms, which are generalizations of Tetris pieces.
This code-golf challenge will have you count polyomino-like polyforms on hypercubes. In particular, this challenge is to write a program that takes in three parameters:

n, which represents an \$n\$-dimensional hypercube,
m, which represents \$m\$-dimensional faces of the hypercube, and
k, which represents the number of cells in the polyform,

and outputs the number of ways to choose \$k\$ (\$m\$-dimensional) faces on the \$n\$-cube such that the \$m\$-faces are connected at \$(m-1)\$-faces. These polyforms are "free" which means they should be counted up to the rotations/reflections of the \$n\$-cube.
Again, this is a code-golf challenge, so shortest code wins.

Example 1
Okay, this is all very abstract, so this warrants an example.
When n=3, we're talking about the \$3\$-dimensional (ordinary) cube. When m=2 this means we're talking about the \$2\$-dimensional (square) faces. And we're talking about k of these, joined along \$1\$-dimensional faces (edges).
When k=3, there are two such polyforms (on the left) up to rotations/reflections of the cube. When k=4 there are also two polyforms (on the right).

Example 2
In this second example, n=3 still, so we're again talking about the \$3\$-dimensional (ordinary) cube. When m=1 this means we're talking about the \$1\$-dimensional faces (edges). And we're talking about k of these, joined along \$0\$-dimensional faces (corners).
When k=4 there are four such polyforms.

Data
n | m | k | f(n,m,k)
--+---+---+---------
3 | 2 | 3 | 2       (Example 1, left)
3 | 2 | 4 | 2       (Example 1, right)
3 | 1 | 4 | 4       (Example 2)
2 | 1 | 2 | 1
3 | 0 | 0 | 1
3 | 0 | 1 | 1
3 | 0 | 2 | 0
3 | 1 | 3 | 3
3 | 1 | 5 | 9
3 | 1 | 6 | 14
3 | 1 | 7 | 19
3 | 1 | 8 | 16
3 | 1 | 9 | 9
3 | 3 | 0 | 1
3 | 3 | 1 | 1
3 | 3 | 2 | 0
4 | 1 | 4 | 7
4 | 1 | 5 | 21
4 | 1 | 6 | 72
4 | 1 | 7 | 269
4 | 1 | 8 | 994
4 | 1 | 9 | 3615
4 | 2 | 3 | 5
4 | 2 | 4 | 12
4 | 2 | 5 | 47
5 | 1 | 4 | 7
5 | 1 | 5 | 27
5 | 2 | 0 | 1
5 | 2 | 1 | 1
5 | 2 | 2 | 1
5 | 2 | 3 | 5
5 | 2 | 4 | 20
5 | 3 | 4 | 16
5 | 3 | 5 | 73
5 | 4 | 4 | 3
6 | 1 | 6 | 121

I'm counting f(4,1,6) = 72, f(4, 1, 7) = 269, f(4,1,8) = 994 with all the other test cases being correct. Is this an error in the test cases? I also get f(4, 1, 9) = 3615 so I think those test cases might be off-by-one on k.

You're absolutely correct—I had an off-by-one in the data table. Sorry about that. It's corrected now.

Python 3, 389
import itertools as I
S=sorted
P=I.product
def C(n,m,k):
 Q=[((-1,)*(n-m)+(0,)*m,)]
 for i in' '*(k-1):Q=set(tuple(S(q+(v,)))for q in Q for v in P(*[(-1,0,1)]*n)if sum(map(abs,v))==n-m if not v in q and any(sum((a!=b)*(1+2*a*b)for a,b in zip(v,u))==2for u in q))
 return sum(all(S(q)<=S(zip(*r))for X in I.permutations(zip(*q))for r in P(*((p,tuple(-x for x in p)) for p in X)))for q in Q)

Try it online!
Basically just finds all connected polyominos, and discards ones which can be rotated into a lexicographically smaller polyomino, with rotations being brute-forced.
Can definitely be improved but it's my bedtime.

I’m impressed! This is shorter than what I thought anyone would come up with!

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


text:
Find the binary period
We know that not all fractions have a terminating binary representation.  However every fraction can be written as a leading portion followed by a repeating portion.  For example \$1/3\$ starts with \$0.\$ and then just repeats \$01\$ endlessly.  This corresponds to the bar notation taught in primary school.  For example
$$
1/3 = 0.\overline{01}
$$
Where the portion with the bar is the repeating section.
For numbers with a terminating representation, (e.g. \$1/2 = 0.1\$) the repeating section is just \$0\$, since there are endless implicit zeros at the end of a terminating representation.
We will call the minimum1 length of the repeating section the binary period of the fraction.
Your task is to write a program or function which takes a positive integer \$n\$ as input and outputs the binary period of \$1/n\$.
This is code-golf so answers will be scored in bytes with fewer bytes being better.
OEIS A007733

1: We say minimum because if you duplicate a section again it keeps a valid representation. (e.g. \$0.\overline{01} = 0.\overline{0101}\$)

I feel like we've had a similar challenge mod 10, or maybe about finding the period of the powers of 10 mod n which is similar.

@xnor I gave it a search and came up with nothing.  If you (or anyone else) find it I would like to know.

What do you think about this one? https://codegolf.stackexchange.com/q/68031/20260

@xnor If I am understanding correctly to do this challenge divide the number by 2 until it is odd, compute the result from that challenge and then take its binary length.  Is that the relationship?

Some test cases wouldn't go amiss.

Is the binary period of 1/2 1 or 0?

@HyperNeutrino the post describes it as period 1 (a repeating zero).

Almost, I don't think you take binary length, just divide by two until odd, then take the result from that challenge.

I like my challenge better since the other has a weird odds only input, but I have closed it as a duplicate.

Jelly, 9 bytes
2*Ɱ%µẠȧQL

A monadic Link accepting a positive integer, n, which yields a positive integer, the period.
Try it online! Or see the test-suite.
How?
2*Ɱ%µẠȧQL - Link: integer, n
2         - literal two
  Ɱ       - map across [1..n]
 *        - exponentiate -> [1,2,4,8,...,2^n]
   %      - modulo n -> [1%n,2%n,4%n,8%n,...,2^n%n]
    µ     - start a new monadic chain - call that X
     Ạ    - all (X)? -> 0 if we reach zero, else 1 - i.e. 0 if n is a power of 2
       Q  - de-duplicate (X) -> the repeating 2^k%n values
      ȧ   - logical AND -> 0 if n is a power of 2 else Q(X)
        L - length (0 has a length of 1 (after an implicit make_digits))

Wolfram Language (Mathematica), 30 bytes
Length@@#&@@RealDigits[1/#,2]&

Try it online!

Python 3, 70 bytes
f=lambda k,a=1:k%2and(a/k%1and f(k,a*2+1)or len(bin(a))-2)or f(k//2,a)

Try it online!

Charcoal, 33 bytes
Ｎθ⊞υ¹Ｗ¬№﹪υθ﹪⊕Συθ⊞υ⊕ΣυＩ⊕⌕﹪⮌υθ﹪⊕Συθ

Try it online! Link is to verbose version of code. Sadly all my attempts to golf this down tended to break on edge cases such as 1 or other powers of 2. Explanation:
Ｎθ

Input n.
⊞υ¹

Start with a list containing just 2⁰.
Ｗ¬№﹪υθ﹪⊕Συθ

See if the next power of 2 is equivalent (modulo n) to any of the elements in the list.
⊞υ⊕Συ

If not then push that power of 2 to the list.
Ｉ⊕⌕﹪⮌υθ﹪⊕Συθ

Print the difference in the two exponents.

Python, 49 bytes
lambda n:len({2**-~k%n*(n&~-n)for k in range(n)})

An unnamed function accepting a positive integer, n, which returns a positive integer, the period.
Try it online!


text:
Bot Factory KoTH
Note: Bot Factory KoTH (2.0) is now posted; you're probably looking for that one instead!
In this challenge, bots (consisting of JS functions) move around an infinite factory (playing field), collecting characters (UTF-16). These characters can be used to build worker bots, or droppedfor other bots to pick up.
Results
Average number of characters collected per game (20k rounds)
[1484.5] The Forsaken Farmer
[1432.9] The Replicator
[957.9] Safe Player V2
[739.1] Hunter
[101.65] First
[9.75] IDKWID

The Factory
All bots start out randomly placed around the center of the factory, [0, 0], where coordinates are arrays [x, y]. North is -Y, and west is -X. Each round consists of up to 100000 turns. A bot may move one space in any cardinal direction (or build a worker, or drop a character) per turn.
Bots can move by returning north(), east(), south(), or west().
Characters
Characters will be randomly distributed, centered around [0, 0]. There are always up to a total of 4 characters per bot at any given time (excluding those from dead bots).
Character's positions may overlap, and their character value (such as a or () is selected from a pool of the source code of every bot and worker currently in the factory.
Bots collect characters by moving into the same position in the factory, and these collected characters are stored within the bot.
Bots may also drop a character they have previously collected in any of the four cardinal directions. This character is then removed from the bot's collected characters array.
Bots drop characters by returning drop.north(c), drop.east(c), drop.south(c), or drop.west(c), where c is a string.
Score
Bots have a score, which is initially -floor(sqrt(LEN)), where LEN is the length of the bot's source code in characters. Worker bots start with a score of 0 regardless of their length.
Whenever a character is collected, this score value increments; when a character is dropped, it decrements.
Collisions
When two or more bots collide (occupy the same position), whichever has the highest score survives (if there is a tie, none survive). All bots that die "drop" the characters they have collected, which are randomly distributed centered around the position they collided in.
Bots can switch places by moving into each others' previously occupied positions without colliding.
Workers
Bots can use the characters they have collected to build a worker bot. A worker bot's source code (provided as a function or arrow function) must be entirely made up of characters its owner has collected, which are then removed. Half of the length of the worker's source code is deducted from the owner's score.
Worker bots are placed randomly around the position of their owner, using the same system as characters, and are not immune to collision. Worker bots can also build worker bots, whose owner would be the worker.
Workers can be built by returning the result of the function build(source), where source is a string. If the bot cannot be built (such as not having all necessary characters), nothing happens.
Functions
All bots are functions. They are provided a single argument, an object that can be used for storage, and can access information about other bots and characters using the following functions:

bots(): Returns an array of bots (as objects)
chars(): Returns an array of characters (as objects)
self(): Returns the bot that called it (as an object)
owner(): Returns the owner of the bot that called it (as an object, null if owner is dead, or self() if no owner)

A bot object has the following properties:

uid: An integer ID unique to each bot, randomly selected
owner: The UID of the bot's owner
score: The score of the bot
pos: The position of the bot formatted as [x, y]

A bot object also has the following properties if it is the owner or worker of the bot:

chars: An array of characters the bot has collected
source: A string with the bot's source code

A character object has the following properties:

char: A string
pos: The position of the character formatted as [x, y]

There are also the following library functions:

center(): Get average of bots' positions weighted by score
turn(): Get current turn (starts at 0)
dir(from, to): Get direction from from to to, which should be arrays formatted [x, y]
dirTo(pos): Same as dir, uses self().pos as from
dist(from, to): Get taxicab distance from from to to, which should be arrays formatted [x, y]
distTo(pos): Same as dist, uses self().pos as from

Winning
Once all surviving bots are direct or indirect workers of the same initial bot, characters will no longer generate. Games automatically end when all characters are collected.
The winner is the bot which, after some number of rounds, has collected (or had workers collect) the most characters.
Rules

Bots may not use global variables in a way which produces side effects other than intended (such as to sabotage other bots or the controller)
Bots which error will be killed and drop their characters
Bots may only attempt to build workers which are valid functions
Bots may not take an unnecessarily long time to run (no hard limitation, but be reasonable)
Bots may not team with other which do not originate from the same owner (directly or not)

Technical Notes

Character and bot spawning radius is based on a geometric distribution (p=0.1), with a random angle. The resulting coordinates are truncated to integers. Repeated until a position is found with no bots within a taxicab distance of 4
For dead bots' drops, p=0.2 and there is no distance requirement
For worker bot spawning, minimum taxicab distance is 3 for the owner
Every time a character is picked up, one attempt is made to generate another. An attempt will only fail if there are already 4 * botCount characters not dropped by a bot (or a bots' death), where botCount is the total number of alive bots (including workers). 4 * botCount characters are generated at the start.

Example Bot
ExampleBot uses an arrow function to keep its starting score higher, but still isn't well golfed. It likes characters which are in the middle of the action, which it finds by sorting the chars() array and using the dist and center library functions. It will not be included in the competition game.
() => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)

Controller: https://gist.github.com/Radvylf/31408373bae12843bfbf482188653a42
Edit: Fixed the controller. Made a few changes before putting it in the gist to clean up some debugging and deleted a few things by mistake. Sorry about that, should be up and running!
Due Date: Challenge completed
Prize: Bounty (100 reputation)
Chatroom: https://chat.stackexchange.com/rooms/105613/bot-factory-koth

The Forsaken Farmer
This entry finds the nearest character and then proceeds to repeatedly drop it and pick it up, netting a total of 1 score per two moves... except it doesn't, because the spec was updated to account for that. No matter, though - winning is dependent on character pick up count, not score.
_=>(c=self().chars).length?drop.west(c[0]):dirTo(chars().sort((a,b)=>(d=distTo)(a.pos)-d(b.pos))[0].pos)

Safe Player V2
_=>dirTo((f=(t,z)=>chars().flatMap(c=>t.reduce((a,b)=>a-(dist(b.pos,p=c.pos)<=(d=distTo)(p)),z)?[]:[p]).sort((a,b)=>d(a)-d(b))[0])(a=bots(),1)||f(a.filter(b=>b.score>self().score),0)||[0,0])

Finds the closest character that it can get to first and goes towards it. If no such character exists, it repeats the process but this time ignoring bots with a lower score than itself. Goes to the center if it still can't lock onto any character.

IDKWID
Short for "I don't know what I'm doing".
_=>dirTo(chars().sort(distTo)[0].pos)

Greedily tries to get the closest character to it. I think. A couple of minutes of thinking have led me to believe that this is not the case. It does something stupid instead. Often loses to Example Bot.

Did you manage to get the rounds to draw something?

@RGS Nope! It's the main reason why this entry is called what it is!

That won't work. distTo works on position arrays. The function in the sort would have to be (a,b)=>distTo(a.pos)-distTo(b.pos). Will clarify, was trying to keep the specification compact. (-:

@RGS That should be fixed now. Deleted a few things I shouldn't have when removing some debugging code...tested and everything works fine.

The Replicator
Presumably replicates itself... very slowly. Probably replicates itself, but if I'm understanding the situation correctly, then a replication attempt currently crashes the runner (hasChars is not defined at runTurn (<anonymous>:205:33)). Rudimentarily code-golfed.
_=>{d=distTo;c=s=>s.reduce((a,v)=>({...a,[v]:(a[v]|0)+1}),{});s=self();a=c(s.chars);b=c((s=s.source).split``);for(v in b)if(!(b[v]<=a[v]))return dirTo(chars().sort((a,b)=>d(a.pos)-d(b.pos))[0].pos);return build(s)}

First
_=>dirTo(chars()[0].pos)

Just go towards the first char. This has an initial score of -4, much better than most.

Hunter
This bot will go towards the closest object that is a char or a bot with less score than it.
_=>dirTo((chars().concat(bots().filter(b=>b.score<self().score))).sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)


text:
All aboard the factorial train
The system
Assume the Earth is flat and that it extends infinitely in all directions. Now assume we have one infinitely long train railway and n trains in that railway. All trains have different speeds and all trains are going in the same direction. When a faster train reaches a slower train, the two trains connect (becoming a single train) and the new train keeps going at the speed with which the slower train was going.
E.g., if we have two trains, one going at speed 1 and another at speed 9, the lines below "simulate" what would happen on the railway:
9               1
         9       1
                 11
                  11
                   11

whereas if the trains start in a different order, we'd have
1 9
 1         9
  1                 9
   1                          9
etc...

With that being said, given a train/position/speed configuration there comes a time when no more connections will be made and the number of trains on the railway stays constant.
Task
Given the number n of trains in the railway, your task is to compute the total number of trains there will be on the railway, after all the connections have been made, summing over all n! possible arrangements of the n trains.
A possible algorithm would be:

Start counter at 0
Go over all possible permutations of the train speeds

Simulate all the connections for this permutation
Add the total number of remaining trains to the counter

Return the counter

Note that you can assume the train speeds are whatever n distinct numbers that you see fit, what really matters is the relationships between train speeds, not the magnitudes of the differences in speeds.
Input
You must take n, a positive integer, as input.
Output
An integer representing the total number of trains that there will be on the railway, summed over all possible permutations of the trains.
Test cases
1 -> 1
2 -> 3
3 -> 11
4 -> 50
5 -> 274
6 -> 1764
7 -> 13068
8 -> 109584
9 -> 1026576
10 -> 10628640
11 -> 120543840
12 -> 1486442880
13 -> 19802759040
14 -> 283465647360
15 -> 4339163001600
16 -> 70734282393600
17 -> 1223405590579200
18 -> 22376988058521600
19 -> 431565146817638400
20 -> 8752948036761600000

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

This is A000254.

@FryAmTheEggman OEIS, removing the fun of all sequence-related challenges since God knows when

always check OEIS before you post...

Interestingly, whether the trains take the speed of the slower or the faster one when they collide doesn't actually change the final answer, though I don't have a rigorous proof for this (yet).

@HyperNeutrino I guess the explanation on my answer is a possible way to prove; the explanation can be perfectly adapted to the case where the faster trains stay fast :)

Jelly,  5  4 bytes
!:RS

Try it online! Or see the test-suite.
How?
When we introduce an \$n^{\text{th}}\$ train it allows:

\$(n-1)!\$ states - by being placed behind none of the \$n-1\$ existing trains and being faster than all of them.
all the previous end states, each in \$n\$ different ways - by being placed behind at least one existing train and being faster than \$[0,n-1]\$ of the \$n-1\$ existing trains

We know \$a(1) = 1\$ so...
n  a(n)
1  1
2  1! + 1*2
3  2! + 1!*3 + 1*2*3
4  3! + 2!*4 + 1!*3*4 + 1*2*3*4
5  4! + 3!*5 + 2!*4*5 + 1!*3*4*5 + 1*2*3*4*5
... etc

Which is:
n  a(n)
1  1
2  1 + 2
3  1*2 + 1* 3 + 2*3
4  1*2*3 + 1*2* 4 + 1* 3*4 + 2*3*4
5  1*2*3*4 + 1*2*3* 5 + 1*2* 4*5 + 1* 3*4*5 + 2*3*4*5
...
n  n!/n + n!/(n-1) + n!/(n-2) + ... + n!/1

Hence the code:
!:RS - integer, n
!    - (n) factorial      n!
  R  - range (n)          [1,...,n-2,n-1,n]
 :   - integer division   [n!/1,...,n!/(n-2),n!/(n-1),n!/n]
   S - sum                a(n)

What sorcery is this?

me: thinks i did something in jelly // jonathan allan: hello

Still submitted a five when there was a four :p

Huh, I had been wondering which algorithm you were using, but because you hadn't added your explanation at the time I had to go and rediscover it for myself...

@RGS golfing languages...

@htmlcoderexe I am pretty sure RGS was not refering to the terseness of the language but rather the underlying method (which I had not described at the time)

@htmlcoderexe Please refer to JonathanAllan's comment above mine :D I have submitted a couple of Jelly answers myself, but I am not very accustomed to its built-ins, so even a short answer like this 4-byter can throw me off... That was what I was referring to :)

This stuff is literal Chinese for me - I've always wondered if a unified score system was possible based on some kind of instructions or something

APL (Dyalog), 5 bytes
+/!÷⍳

Try it online!
Calculates the sum of (+/) the factorial of \$n\$ (!) divided by (÷) the range 1 to \$n\$ (⍳).

JavaScript (ES6), 34 bytes
f=n=>n>1?(n+--n)*f(n)-n*n*f(n-1):n

Try it online!
This is an implementation of the recurrence relation:
$$\cases{
a(0)=0\\
a(1)=1\\
a(n) = a(n-1) \times (2n - 1) - a(n-2) \times (n - 1)^2,\:n>1}$$

I'm sorry for the error in editing, I thought I had checked and assumed it was a bug (which was probably silly).

@FryAmTheEggman No worries! I was just a bit puzzled by the reason for changing it.

Wolfram Language (Mathematica), 15 bytes
Tr[#!/Range@#]&

-1 byte from @Greg Martin
Try it online!

well done beating the builtin Abs@StirlingS1[#+1,2]&

@GregMartin I think now I'm done ;)

I think you can shave one more byte with Tr[#!/Range@#]& :)

05AB1E, 5 bytes
!IL÷O

Try it online!

Python 3, 57 bytes
f=lambda n:n and n*f(n-1)+math.factorial(n-1)
import math

Try it online!
Implements the recurrence relation given by
$$\begin{cases}a(n) = n\times a(n-1) + (n-1)! \\
a(0) = 0 \end{cases}$$
How: If you have \$n\$ trains on the railway, consider removing the faster one from the railway and take the \$(n-1)!\$ permutations of the remaining \$n-1\$ trains. For each permutation of the \$n-1\$ trains, there are \$n\$ places where you can put the \$n\$th train, the fastest one.

If you put it in the front, then the connections made by the other \$n-1\$ trains remain exactly the same, and those never catch up with the faster train. So placing it in the front adds a new train to the total sum.
If you put it in any other of the \$n - 1\$ positions, it will just connect to the train in front and then we are back at the case when we had \$n - 1\$ trains on the railway, so the total number of trains stays the same.

You beat me to it! Took me a while to figure out this recurrent relation. I also missed that Python has a factorial function :(

Python 3.8,  50  49 bytes
-1 thanks to Surculose Sputum (using walrus in 3.8 to save some ~-s)
f=lambda n:n>1and(2*n-1)*f(n:=n-1)-n*n*f(n-1)or n

Try it online!

A 52 using a different approach:
f=lambda n,k=2:n*k and~-n*f(n-1,k)+f(n-1,k-1)or n==k

Try it online!

49 bytes using walrus operator

@SurculoseSputum thanks!

@SurculoseSputum I keep seeing your username and thinking it says "Sucralose Spectrum". I need to go to bed.

Charcoal, 12 bytes
≔…·¹ＮθＩΣ÷Πθθ

Try it online! Link is to verbose version of code. Explanation:
≔…·¹Ｎθ

Create a range from 1 to n.
    θ   Range `1`..`n`
   Π    Product i.e. `n!`
  ÷     Vectorised divide by
     θ  Range `1`..`n`
 Σ      Sum
Ｉ       Cast to string
        Implicitly print

Python 2, 57 52 50 bytes
-2 bytes thanks to @JonathanAllan !

i=x=0
f=1
exec"i+=1;x=i*x+f;f*=i;"*input()
print x

Try it online!

If the sequence is 0-indexed, we can cut down 2 more bytes
Python 2, 48 bytes
i=x=f=1
exec"i+=1;x=i*x+f;f*=i;"*input()
print x

Try it online!

How:
This solution uses the exec trick, which repeats the code n times, then exec the repeated code.
f is the current factorial.
x (the solution function) is defined by the recurrent relation:
$$x(i)=ix(i-1)+(i-1)!$$
and
$$x(0)=0$$
@RGS's answer has a really nice explanation for this formula.

50 bytes

@JonathanAllan Thanks!

Perl 6, 22 bytes
{sum [*]($_)X/$_}o^*+1

Try it online!
Returns the sum of the factorial of \$n\$ divided by the range 1 to \$n\$.

W j, 5 4 bytes
After scanning through the source, I realized an undocumented feature - the j flag can actually sum the output at the end!
7Uëÿ

Uncompressed:
*rak/

Explanation
*r     % Reduce via multiplication
       % (Contains implicit range)
  ak   % Range from input to 1
    /  % Division (integer division when
       % none of the operands are floating-points)
Flag:j % Sum the resulting list

J, 9 bytes
1#.!%1+i.

Try it online!
1#.           the sum of (by conversion to base 1)
   !          n factorial
    %         divided by
     1+i.     the list 1..n

K (oK), 16 12 bytes
-4 bytes thanks to ngn!
+/*/'1+&:'~=

Try it online!

this one was hard to beat: {+/*/'1+&:'~=x} or +/*/'1+&:'~=:

actually, in oK it also works without the final :

@ngn Very nice use of the identity matrix! (I forgot about the monadic use of =) Thanks for your lesson!

@ngn I tried a different approach

.. and i forgot oK has atom^ :) one of the things i tried was a^/:a:1+!x

Haskell, 34 bytes
a 0=0
a n=n*a(n-1)+product[1..n-1]

Try it online!
This implements the OEIS definition.

C (gcc), 38 bytes
f(n){n=n>1?(n+n--)*f(n)-n*n*f(n-1):n;}

Port of Jonathan Allan's Python 3.8 answer.
Try it online!

C (gcc), 70 \$\cdots\$ 64 63 bytes
Saved a byte thanks to ceilingcat!!!
Saved a byte thanks to Surculose Sputum!!!
l;c;i;t;f(n){l=0;for(c=i=1;i<n;l=c,c=t)t=-l*i*i+c*(i+++i);n=c;}

Try it online!
Uses Arnauld's formula.

63 bytes by rearranging the operations a bit

@SurculoseSputum Nice refactor - thanks! :-)

Racket, 70 bytes
(λ(x)(let([a(range 1(+ 1 x))])(apply +(map(λ(y)(/(apply * a)y))a))))

Try it online!

Factor, 61 bytes
: f ( n -- n ) [1,b] dup [ product ] dip [ / ] with map sum ;

Try it online!

MathGolf, 5 bytes
╒k!╠Σ

Try it online.
Or
!k╒/Σ

Try it online.
Explanation:
╒      # Push a list in the range [1, (implicit) input-integer]
 k!    # Push the input-integer again, and pop and push its factorial
   ╠   # Divide the factorial by each value in the list (b/a builtin)
    Σ  # And sum that list
       # (after which the entire stack joined together is output implicitly as result)

!      # Push the factorial of the (implicit) input-integer
 k╒    # Push the input-integer again, and pop and push a list in the range [1, input]
   /   # Divide the factorial by each value in the list
    Σ  # And sum that list
       # (after which the entire stack joined together is output implicitly as result)

Jelly, 9 bytes
Œ!«\€Q€FL

Try it online!
this is the non-smart trivial approach
Explanation
Observe that if we have a list of trains' speeds, moving left, then we can cumulatively reduce by minimum to get the final list of trains' speeds.
Œ!«\€Q€FL  Main Link
Œ!         all permutations (defaults over a range)
    €      For each permutation
   \       Cumulatively reduce by
  «        minimum
      €    For each permutation
     Q     remove duplicate values
       F   join all of the trains (flatten)
        L  and get the final length

Japt -x, 5 bytes
ÆÊ/°X

Try it


text:
Ah, why is there a bug in my program?
This challenge is inspired by @LuisMendo's MATL answer to my "binary multiples" challenge.
Task
Pick a code-golf challenge that is open and that has been posted before this one; let me call it the "linked challenge". The linked challenge must be a challenge whose task involves producing output.
Write the shortest code possible that satisfies the following restrictions:

Your code must contain the characters b, u and g in your program, in this order and consecutively (case-insensitive, so "bug", "BUG", "Bug", "bUg", ... are all fair game.);
Your code must not contain the letters b, u and g more than once (case-insensitive);
Your code should be a valid submission for the linked challenge;
When any subset of the (case-insensitive) characters bug are removed, your program no longer fulfils the task of the linked challenge. This may happen because your program now produces the wrong output (i.e. fails test cases), because it halted with an error, because it runs indefinitely and never returns (if this is the case, be prepared to prove your program runs indefinitely), etc.
Your code should not be an integral copy - nor a trivial modification* - of a submission that already exists in the linked challenge (for example, you may not copy @LuisMendo's MATL answer to my "binary multiples" challenge);

Input
Your program takes input as per the specs of the linked challenge you choose.
Output
Your program, in its correct state (i.e. with a bug**), must abide by the output specs of the linked challenge you choose.
* This is subjective so I appeal to your common sense; any imaginative modification should be fair game, even if in retrospective it is "trivial". This "no trivial modifications" rule will be "enforced" by me downvoting answers I think disrespect this...
** Sit down, take a moment to let this sink in. Your program has a bug. And yet your program is correct.
Posting an answer
When you post your answer, please provide a link to your linked challenge.

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your written feedback. Happy golfing!

@a'_' I do not understand how that challenge presents a loophole; can you please clarify?

@RGS Interesting challenge. I wonder if the challenge can be more focused by specifying just 1 linked challenge to solve. As of right now, my effort is divided between picking a linked challenge, and golfing/solving the linked challenge.

your program now produces the wrong output -> I assume it's fine if the program is still producing the correct output for some inputs, but a wrong output for at least one input?

If there is a only a newline in between the characters, does that still count a 'consecutively'?

@Arnauld you assume correctly, will make it more clear

@ouflak nope, the three characters must be really really consecutive :) so that they spell "bug" :)

@a'_' I imagine a Python solution to the "Do nothing challenge" is x,y,z="bug"

@SurculoseSputum I could arbitrarily pick a challenge, but I wanted to give you more freedom... Of course it comes at a cost! You have to pick a challenge..

But the consecutive letters 'bug' can have other consecutive letters around them, yes?

Yes yes, of course! They can even be part of a bigger word / function name / string / wtv.

If any of the people who downvoted would be so kind as to give me some feedback, I would be really pleased! :)

@JoKing The "posted before" was already in the specs; will add the bit about being open

It's impossible to do this in brainfuck...

Python has a built-in constant called __debug__ which is True by default. Removing some of its bug will obviously be an error. Though I can't find a suitable challenge for that...

There might be an esolang where a variation of BUG can solve this challenge...

@RGS The title of this question has affected other new users to think that we are another place for programming Q&A. For example, this and this (deleted) are low-quality posts that are affecting the quality of questions on this site. You really need to change the title.

@a'_' it is frequent, although unfortunate, to have new users post SO questions here; do you think this frequency has increased significantly because of my post? Either way, I am open to changing the title for something that induces less errors from newcomers, as long as it preserves the spirit of the current title. Do you have any suggestions? I haven't come up with anything nice yet.

@RGS Yes, the frequency is much higher after your post; there are already 2 posts with an interval of 15 minutes! Currently the only title I can think of is Why does my program contain the string "bug"?

Title suggestion: The Correct Bug which doesn't lead to confusion.

@a'_' I think the title right now is fine. If a new user cannot figure out the purpose/theme of the site, then that should be a problem of the UI anyway.

I give up. Tried to find a way to do this in Java, but it's impossible due to that source restriction of bug. I know five different ways of creating a program in different versions of Java, but none of them work here. Usually I could get around that by using \u-unicode escaped characters in the program, which works in other challenges where certain characters are banned, but since u is banned, that's not an option either.. Ah well, I tried.

@KevinCruijssen but I assume you can still write an arrow function or something, right? I think it is fair to say the source restrictions only show up in the part of the answer that usually goes in the Code section of TIO... Wouldn't you say so?

@RGS Hmm, a function is indeed possible. Was under the impression it required a full program. Will try to come up with a function in that case. :)

When any subset of the (case-insensitive) characters bug are removed suggest non-empty subset?

@S.S.Anne Actually, it may be possible using a [tag:restricted-source] or a [tag:self-referential] challenge

When you say a subset of bug will be removed, does that include the entire string bug?

@Shaggy yes, it does include. So your program may not work when the three letters B, U and G are removed from your program

Japt, 4 bytes
Challenge: Output with the same length as the code
BUG³

Test it
Explanation
B, U, and G are variables for 11, the input, and 16 respectively.
When applied to a number, ³ brings it to the third power.
In Japt, only the last expression is outputted, so only \$16^3 = 4096\$ is outputted, which is the same length as the code (4).
Since B and U are ignored, removing them have no effect on the output. However, their removal changes the length of the program, making it invalid. Removing G raises either the input (U) or 11 (B) to the third power. While \$11^3 = 1331\$ is 4 bytes, the program B³ is only two bytes, making the output invalid. The variable U defaults to 0 when there is no input given, and \$0^3 = 0\$, which is only one byte long.

This seems like a pretty clever answer. Why did you delete it?

@ouflak the first version had a bug, I deleted it to give me some time to edit it

@EmbodimentofIgnorance ba-dum crash!

Fail ³ also work

Polyglot,  31 bytes
Linked challenge: “Hello, World!”
This is a full program, as per the original challenge requirements.
print('Hello, World'+'bug!'[3])

Try it in JavaScript (V8)!
Try it in Python!
Try it in Ruby! (thanks to @Steffan for pointing this out)

This works in Ruby too.

JavaScript (ES7), 47 bytes
Linked challenge: How many petals around the rose
a=>a.map(n=>t+=n**3&parseInt('bug',35)%9,t=0)|t

Try it online!
How?
This is a port of my Python answer to the linked challenge. This answer requires a bitwise AND with a constant, which happens to be \$6\$.
This \$6\$ is obtained with the cumbersome parseInt('bug',35)%9 and removing any subset of characters from bug would produce a different (and therefore invalid) constant.
   s   | parseInt(s, 35) | mod 9
-------+-----------------+-------
 'bug' |      14541      |   6
 'ug'  |       1066      |   4
 'bg'  |        401      |   5
 'bu'  |        415      |   1
 'g'   |         16      |   7
 'b'   |         11      |   2
 'u'   |         30      |   3
 ''    |        NaN      |  NaN

'bug'.length*2  is an alternative

@SurculoseSputum That's actually not possible: there's a 'g' in 'length'.

That's unfortunate :( I was thinking of Python when writing that comment.

a=>a.map(n=>t+=n**3&('bug'[2]&&6),t=0)|t for 40 bytes

@EmbodimentofIgnorance There's also &!!'bug'[2]*6 for 39 bytes, but I think I'll stick with my sub-optimal version for this answer, so feel free to use it in another one!

C (gcc), 156 bytes
Answer to 99 bugs in the code. Not competitive, but funny.
#define S"%d bugs in the code\n"
d;f(i){for(i=99;i;i=d)printf(S S"Take one down and patch it aro\x75nd\n"S"\n",i,i,d=(d=i+rand()%21-16)<0?0:d);printf(S,0);}

Also beats the C solution there.
Try it online!

+1 for the "right" challenge to solve.

Triangular, 6 bytes
Linked to Challenge: Shortest code to produce infinite output
bug>%<

Try it online!

Basically the same thing works in Hexagony, probably other layout languages, too.

PHP, 16 bytes
Solving Output programming language name
echo'2=7'^'bug';

Try it online!
Omitting any of the letters in bug outputs a wrong string. However, it won't cause any errors so that error messages containing PHP can never be outputted. All PHP answers in that challenge exploit either PHP flags, which cannot contain the word bug, or PHP errors, which omitting a letter from bug could still result in an output that fulfils the requirements.

Python 3, 24 bytes
while __debug__:print(1)

Try it online!
Linked challenge: Shortest infinite loop producing output
Uses the fact pointed out by @Bubbler:

Python has a built-in constant called __debug__ which is True by default. Removing some of its bug will obviously be an error. Though I can't find a suitable challenge for that...

Removing the bu from your answer still gives the correct answer -- the rules state that any subset of the characters in bug being removed should cause the problem to return something different, not just the bug as a whole!!

@ValueInk I changed the language and used python instead.

Quoting my spec, "The linked challenge must be a challenge whose task involves producing output."

@RGS that's been fixed now. I've really lost the ability to read challenges today. :P

I really like the use of __debug__, however simply using "bug"[2] should be shorter (and more boring). TIO.

So de-bugging __debug__ gives you an error to debug?

@user253751 yeah, that's pretty much the case. Ironic, isn't it! :P

Lua and perhaps a polyglot in concept, 25 28 32 bytes
Along the lines of Arnauld's answer, linked to challenge Output programming language name.
print('\076\117\097 5.'..#'bUg')

Try it online!
Added 3 bytes Thanks to @RGS spotting the 'u' in 'Lua'
Added 4 bytes Thanks to @MariaMiller for the 'L' and the 'a' as well

This is not a valid answer because the letter "u" appears twice in your code!

@RGS, Oh my God. You're right! Let me fix this up.

It still uses L, u, and a. This answer won't work for Lua, as you need a u for bug, but you can't use a u since it's in Lua.

@MariaMiller, Refresh your browser. Unless I'm misunderstanding your comment, RGS already pointed that out and I've already updated the answer.

According to the linked kata, your code cannot include any characters of the language's name, but case sensitive so it can be fixed: You can fix L and a with the same way you fixed u, and I just noticed that you can change bug to bUg or BUG or whatever and this will be alright. Sorry if I was confusing.

Didn't they realize that both l and A aren't banned in outputting the language name? 25 bytes

@a'_', It's a little bit trickier balancing the rules between two challenges than I thought it would be. Especially as they both have multiple subtle restrictions. Think I'll just stick with the 'safest' interpretation of both/either.

There's a lowercase u in bug that's also in Lua. You need to get rid of it or it's not valid.

@S.S.Anne, Thanks. Done.

APL (Dyalog Extended), 6 bytes
Solves Output with the same length as the code.
×'BUG'

Try it online!
Prints 1 1 1\n, 6 bytes in total.
In regular APL, monadic × is Signum for numbers (-1 if negative, 1 if positive, 0 if zero). Extended provides an extended (no pun intended) definition for characters (-1 for lowercase, 1 for uppercase).
Because numeric arrays are printed with a space between items, deleting one char out of BUG will remove two bytes (<space>1) from the output, thus failing to solve the challenge. Deleting two chars will remove four output bytes, and deleting all of them gives only a single newline.

Zsh/Bash/others, 15 bytes
Challenge: Output with same length as code
echo BUG{1..3}

Try it online (Zsh)!
Try it online (Bash)!

The second submission is invalid because the linked challenge should produce output!

Argh, thanks. Fixed.

CJam, 4 bytes
Challenge: Output with the same length as the code
It's working. But I still didn't manage a 3-byte solution.
BUG^

Try it online!
Why it works
B    "Constant for 11";
 U   "Constant for 0";
  G  "Constant for 16";
   ^ "Bitwise XOR";

0 XOR 16 is 16, therefore it outputs 1116.
Removing a single character
UG^

It just outputs 16 without other calculations.
BG^

It outputs 27 because 11 XOR 16 is 27.
BU^

It outputs 11 because 11 XOR 0 is 0.
Removing 2 characters
CJam doesn't have implicit input, so all these programs would throw an error.

Create output twice the length of the code
MathGolf, 6 bytes
╘╘BUG]

Try it online!

05AB1E, 4 bytes
Linked challenge: Output with same length as the code.
Port of Embodiment of Ignorance's Japt answer.
bugт

Try it online!

C (gcc), 24 bytes
This one for real.
Answer to Swap the parity.
f(x){x=-(-x^!"bug"[3]);}

Try it online!

Your code work because format string is just placed after "bug", or to say your solution relies on existance of printf

C (gcc), 26 bytes
Answer to Shortest code to produce infinite output
f(){printf("bug"+2)&&f();}

Try it online!

Maybe I'm missing something but your TIO link produces no output

@RGS I forgot the footer. Hang on...

Woops, I only noticed now... The character u shows up twice in your answer!

@RGS Fixed.....

why &&? then .

@l4m2 That was originally so it didn't produce any output if the string was modified. I might be able to remove it, but it's an old challenge and it only saves two bytes.

Javascript, 8 characters
Linked question: Output with the same length as the code
bug=>1e7

Outputs 10000000, which has the same length as the program. Removing 1 or 2 characters would make it print the same thing, but wouldn't match the length of the program anymore. Removing all 3 is a syntax error.

Jelly, 8 bytes
Reverse Bit Order of 32-bit Integers
%Ø%BUGƇḄ

Try it online!
I managed to find a challenge that actually uses two of the letters in a productive way.
There's no Jelly answer to the challenge at the time of writing this answer.
Explanation
%Ø%BUGƇḄ Main monadic link
%        Modulo
 Ø%        2^32
   B     Convert to binary
    U    Reverse
      Ƈ  Filter by
     G   Format as a grid
       Ḅ Convert from binary

Linked to challenge: Find the number of integers in the range from 1 to N that ends with 2
Python 2, 95 \$\cdots\$ 39 35 bytes
Saved a byte (in a previous version) thanks to Maria Miller!!!
Saved a byte (in an other previous version) thanks to Surculose Sputum!!!
def f(n):print((n+len("bug")+5)/10)

Try it online!

74 bytes

@MariaMiller Nice one - thanks! :-)

30 bytes

Ruby, 24 bytes
Linked to Find the number of integers in the range from 1 to N that ends with 2
->n{(n+5+"bug".size)/10}

Try it online!

What is the challenge this problem is linked to?

Sorry, I accidentally deleted it. Added.

Linked to challenge: Find the number of integers in the range from 1 to N that ends with 2
C (gcc), 51 42 40 bytes
i;f(n){for(i=0;n+=2,"bug"[i++];);n/=10;}

Try it online!

JavaScript (Node.js), 39 bytes
Linked Challenge: How many petals around the rose
a=>a.map(n=>t+=n**3&!!'bug'[2]*6,t=0)|t

Try it online!
Originally posted as a golf to Arnauld's answer.

Python 2, 13 bytes
Solves Output with the same length as the code.
print 'bug'*4

Try it online!
Prints bugbugbugbug\n.

Python 2, 27 bytes
Solves Hello, World!
print'bugHello, World!'[3:]

Try it online!
Removing some of bug will chop off characters from the beginning of 'Hello, World!'.

The middle answer isn't valid because the linked challenge has to produce output!

I mean in my spec :) you have to pick a challenge where you have to produce output "The linked challenge must be a challenge whose task involves producing output."

@RGS Oops, sorry, I missed the restriction.

W, 6 bytes
Challenge: Output the same length as code
BUG"2*

Repeats the string "BUG" multiple times.

Io, 18 bytes
Challenge: Output programming language name
(Joke ruiner over here, never mind.)
This errors (outputting the language name) when the bug is inside, and it doesn't error when any part of the bug is removed.
If you think that this uses the i character (taken from the question):

Note that this is case sensitive. I can still use the char 'b' because it's different from 'B'.

if("bug"size>2,iO)

Try it online!
Explanation
        size       // Is the length of
   "bug"           // the string "bug"
            >2     // larger than 2?
if(           ,    // If so,
               iO  // Access an undefined variable
                 ) // Otherwise, do nothing

Io, 19 bytes
Challenge: Output with the same length as the code
"bug"at(2)cos print

Try it online!
Explanation
"bug"               // The sequence "bug"
     at(2)          // The 3rd index of that
                    // (Out-of-bounds indexing returns nil)
                    // This returns an integer for an in-bound index
          cos       // Find the cosine of that
                    // (Cosine over nil throws an error)
              print // Print that value to STDOUT. (WITHOUT a newline)

Io, 19 bytes
Challenge:Shortest infinite loop producing no output
while("bug"at(2),0)

Try it online!
Explanation
      "bug"         // Base string "Bug"
           at(2)    // Try to access the 3rd item of the string
                    // (Out-of-bounds returns nil)
while(          ,   // While that's true:
                    // (So a string is always true and nil is always false)
                 0) // No action needed

What does the last one solve?

J, 7 bytes
Solves I double the source, you double the output!
>:Debug

Try it online! Try it online!Try it online!
Prints 1 as given, 2 doubled.
How it works
Monadic >: is "increment" (add 1), dyadic >: is "greater or equal" (x >= y).
>:Debug    NB. increment 0; gives 1

>:Debug>:Debug
  Debug>:Debug    NB. 0 >= 0; gives 1
>:                NB. increment it; gives 2

J, 12 bytes
Solves Output with the same length as code.
echo 6#Debug

Try it online!
Somewhat similar to Python, J has a stdlib variable Debug which is initialized to the number 0. 6# replicates the zero 6 times, and echo prints it. The output formatting is identical to APL's (space-separated numbers), so the output is 0 0 0 0 0 0\n.
Being a terse language, I suspect there could be a more suitable challenge for J which gives a shorter solution using Debug.

Java 8, 88 87 bytes
Linked challenge: Is this number a prime?
Given a number, outputs truthy/falsey depending on whether it is a prime number.
n->{int i="BUG".charAt(2)-70;for(;n%++i%n>0;);System.console().printf("%s",""+(n==i));}

Try it online (Note: System.console() is System.out on TIO, since TIO doesn't support console).
Explanation:
n->{                // Method with integer parameter and no return-type
  int i=            //  Integer `i`, starting at:
    "BUG".charAt(3) //  Get the third character from String `"BUG"` as unicode value
     -70;           //  and subtract 70 from it, so it'll become 1
  for(;n%++i        //  Increase `i` by 1 first before every iteration with `++i`
            %n>0;); //  And loop as long as `n` modulo-`i` is not 0
                    //  NOTE: The second `%n` is to stop the loop for input n=1
  System.console().printf("%s",
                    //  Print to STDOUT with String format:
    ""+(            //   Convert the following boolean to String:
        n==i));}    //   Check if `n` and `i` are equal

Prime checker credit goes to @SaraJ's answer here, which is rather ingenious.
Things I had to do to comply to the challenge:

The challenge description mentions program (and technically the linked challenge as well), but this isn't possible in Java. I know five different ways of creating a full program in Java, but each of them requires at least one of the letters bgu. Usually I can get past source-restrictions by using \u-unicode escapes, but since u is one of the restricted characters that's also not an option here. Luckily OP allowed functions as well, which is (much) shorter anyway.
I couldn't use return since it contains an u. And I also couldn't use System.out.print(...), since it contains an u as well. So instead, I use System.console().printf("format",...)
Since I wanted to print a boolean, the format to use in the printf would be "%b". Unfortunately, b is blocked, so instead I use "%s" and convert the boolean to a string.
And last thing to tackle was of course sneaking bug in, so it works with it, but doesn't work anymore without it. I've done this by changing the int i=1; to int i="BUG".charAt(2)-31;, which grabs the third character in the String (the 'G') as unicode value (71), and subtracts 70 from it to make it 1. If any of the B, U, and/or G is removed, the .charAt(2) will fail with a StringIndexOutOfBoundsException.

Kevin, I fear you missed something very important: as soon as any part of "bug" is removed, your program should no longer work. So assigning it as variable somewhere doesn't really work, because having bu=0 still works...

@RGS Should be fixed now.

R, 15 bytes
Linked challenge: Output with the same length as the code
strrep("bug",5)

Try it online!
(or 18 bytes if we include the default [1] "" formatting with which R surrounds its ouput, but this restriction did not seem to be applied to the original linked challenge).

Batch, 11 bytes
Linked challenge: Output with the same length as the code
@echo %bug%

Outputs ECHO is on. when run regularly or when some of bug is removed, and outputs % when all of bug is removed.

Javascript (82 characters)
Linked challenge: Integer lists of Noah
c=>eval('O\x62ject').keys(x={},c.map(a=>x[a]=(x[a]||0)+1)).some(z=>x[z]!=2)&&'bug'

It's a bit lame, but I'm defining my outputs as producing 'bug' when input list is not a Noah list, and false when it is.
I love this challenge though. Maybe I can find a better solution. :)

Wait, I didn't notice the b in Object until now. doh.

I'm glad you like my challenge :D Like you noted, "Object" has an extra "b"; ping me when you find a valid solution!

I assume that escape sequences are allowed, so eval("O\x62ject") should be able to replace Object?

TI-Basic, 6 bytes
Linked challenge: Output with the same length as the code
BUG
ᴇ5


text:
What can you see on a hexagonal spiral?
This code-golf challenge will have you computing OEIS sequence A300154.

Consider a spiral on an infinite hexagonal grid. a(n) is the number of cells in the part of the spiral from 1st to n-th cell that are on the same [row*] or diagonal (in any of three directions) as the n-th cell along the spiral, including that cell itself.

(*I have very slightly changed the definition to match the orientation of the GIF below.)
The sequence begins
1, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 6, 7, 7, 8, 7, 8, 9, 8, 9, 8, 9, 10, 9, 10, 11, 9, 10, 11, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 11, 12, 13, 14, 12, 13, 14, 15, 12, 13, 14, 15, 13, 14, 15, 16, 13, 14, 15, 16, 17, 14

Example
Below is an example of the first fifteen terms of the sequence. On a hexagonal tiling, go in a spiral, and after each step, count the number of cells that you can "see" from that position, including the cell itself.

Challenge
The challenge is simple, write a program that takes a positive integer n and computes \$A300154(n)\$. Again, this is code-golf so shortest code wins.
(Note: I will also award an additional bounty of 200 rep to the first person who completes this challenge in Hexagony.)

The format of this challenge ought to make it easy in hexagony but I'm not experienced enough in it to do it.

Hardly anything is easy in Hexagony...

I love how the OEIS page links to this challenge

Jelly, 14 bytes
A monadic link taking an integer as input; computes the first n terms of the sequence.
÷3Ḟ,ĊƊḶ+
ŻÇ€Fḣ

Try it online! This is a port of Bubbler's answer, so be sure to upvote him as well!
How it works:
ŻÇ€Fḣ      Main link: monad taking integer n as input
Ż          Create the range [0, ..., n]
 Ç€        Map the auxiliar link over the range.
   F       Flatten...
    ḣ      and take the first n elements of that.

÷3Ḟ,ĊƊḶ+   Auxiliar link: monad taking integer k as input
÷3         Divide by 3.
   , Ɗ     Create a pair (a, b)
  Ḟ Ċ      with the floor and ceiling of the division.
      Ḷ    Finally create the ranges [0, ..., a-1] and [0, ..., b-1]
       +   and add k to each number in each range.

JavaScript (ES6),  178 169  168 bytes
Returns the \$n\$ first terms as an array.
n=>(X=[1],Y=[L=1],d=5,j=x=y=0,g=a=>--n?g([...a,(X[x+=~-'210012'[d%=6]]=-~X[x])+(Y[y+=~-'1221'[j?d:d++]]=-~Y[y])+(Z[x+y]=-~Z[x+y])-2],++j%L?0:(j%=L*6)?d++:L++):a)(Z=[1])

Try it online!
How?
This is a rather naive approach that actually computes the spiral with cube coordinates \$(x,y,x+y)\$ and keeps track of the number of cells on each row \$Z[x+y]\$, each diagonal \$Y[y]\$ and each anti-diagonal \$X[x]\$.
Commented
n => (                            // n = input
  X = [1], Y = [L = 1],           // X[] = anti-diagonals, Y[] = diagonals, L = layer
  d = 5,                          // d = direction in [0..5]
  j =                             // j = cell index in the current layer
  x = y = 0,                      // (x, y) = coordinates
  g = a =>                        // g = main recursive function taking the output a[]
    --n ?                         // decrement n; if we haven't computed enough terms:
      g(                          //   recursive call:
        [ ...a,                   //     append the previous terms
          ( X[x +=                //     update x and increment X[x]
              ~-'210012'[d %= 6]  //       pick dx according to d
            ] = -~X[x]            //
          ) +                     //
          ( Y[y +=                //     update y and increment Y[y]
              ~-'1221'[j ? d      //       pick dy according to d
                         : d++]   //       increment d afterwards if j = 0
            ] = -~Y[y]            //       (i.e. this is the 1st cell of the layer)
          ) +                     //
          (Z[x + y] = -~Z[x + y]) //     increment Z[x + y]
          - 2                     //     subtract 2 from X[x] + Y[y] + Z[z] because
        ],                        //     the current cell is counted three times
        ++j                       //     increment j
        % L ?                     //     if it's not the last cell of this side:
          0                       //       do nothing
        :                         //     else:
          (j %= L * 6) ?          //       if it's not the last cell of the layer:
            d++                   //         increment d
          :                       //       else:
            L++                   //         increment L
      )                           //   end of recursive call
    :                             // else:
      a                           //   we're done: return a[]
)(Z = [1])                        // initial call to g with a[] = Z[] = [1]

I'm always delighted to see when you attempt a challenge of mine!

APL (Dyalog Unicode), 23 bytesSBCS
⊢↑∘(∊⊢+∘(⍳¨⌊,⌈)¨÷∘3)⍳,⊢

Try it online!
A tacit function that returns the first n terms of the sequence.
Observation
n m | f(n,m): m consecutive integers starting at n
---------------
1 0 |
1 1 | 1
2 0 |
2 1 | 2
3 1 | 3
3 1 | 3
4 1 | 4
4 2 | 4 5
5 1 | 5
5 2 | 5 6
6 2 | 6 7
6 2 | 6 7
7 2 | 7 8
7 3 | 7 8 9
8 2 | 8 9
8 3 | 8 9 10
9 3 | 9 10 11
9 3 | 9 10 11
---------------
Flattened: 1 2 3 3 4 4 5 5 5 6 6 7 6 7 7 8 7 8 9 8 9 8 9 10 9 10 11 9 10 11

Though I don't have a rigorous argument that the pattern is mathematically correct, the test cases show that the first 3000 terms agree with Arnauld's JS answer.
How it works: the code
Uses ⎕IO←0, so ⍳ n gives 0 1 2 .. n-1.
⊢↑∘(∊⊢+∘(⍳¨⌊,⌈)¨÷∘3)⍳,⊢  ⍝ Input: n
                    ⍳,⊢  ⍝ Generate 0..n
   (               )     ⍝ For each number k...
                ÷∘3      ⍝ Divide k by 3
        (     )¨  ⍝ For each item of above,
           ⌊,⌈    ⍝ Collect its floor and ceil;
                  ⍝ (0 0)(0 1)(0 1)(1 1)(1 2)(1 2)(2 2)...
         ⍳¨       ⍝ For each number i, generate 0..i-1
                  ⍝ (2 3) -> ((0 1)(0 1 2))
     ⊢+∘  ⍝ Add k to each pair of ranges (results of f(n,m))
    ∊     ⍝ Enlist; collect all numbers into a vector
⊢↑∘       ⍝ Take first n numbers

MATL, 48 bytes
0i:"J_Q@q:gJJq1_J_tQ5$h@Y"&h]YsG:)&Zjyy+vt0Z)=as

Try it online! Or verify all test cases.
Explanation
This uses coordinate axes 60 degrees apart, so that cell coordinates are integer values. In addition, coordinates (r,s) are stored as a complex number r+j*s, where j is the imaginary unit.
The code first creates n layers of the spiral, which is enough (for most inputs, it is much more than enough). This is done by a loop that adds one layer in each iteration. The first cell is at the origin. For each new layer, the displacements from one cell to the next are defined (in the chosen system of complex coordinates): a displacement "outward" (to create room for the layer) and then several displacements "around" to complete a turn. Once all displacements for all layers have been specified, a cumulative sum produces the cell positions.
To see what is meant by "layer" and how the spiral is built, you can graphically depict the spiral with n layers. Note that the spiral is deformed because the plot uses orthogonal axes (real and imaginary), instead of axes with 60-degree separation.
Once the spiral has been created, the first n cells are kept. From these, the last cell is the reference. To detect which cells are in the same row/diagonal as the reference cell, the condition is that the candidate cell should have either the same value of the first coordinate as the reference cell, or the same value of the second coordinate, or the same value of the sum of coordinates.
0        % Push 0. This is the initial cell
i:"      % Input n. For each k in [1 2 ... n]
  J_Q    %   Push 1-j
  @q:g   %   Push [1 1 1 ... 1] (k-1 entries)
  J      %   Push j
  Jq     %   Push -1+j
  1_     %   Push -1
  J_     %   Push -j
  tQ     %   Duplicate, add 1: pushes 1-j
  5$h    %   Concatenate 5 elements into a row vector: [j -1+j -1 -j 1-j]
  @Y"    %   Repeat each entry k times
  &h     %   Concatenate everything into a row vector
]        % End
Ys       % Cumulative sum
G:)      % Keep first n entries. Gives a row vector of size n
&Zj      % Push real and imaginary parts. Gives two row vectors
yy+      % Duplicate top two elements in the stack, add
v        % Concatenate the three row vectors into a 3-row matrix
t        % Duplicate
0Z)      % Keep last column
=        % Equal? Element-wise with broadcast. Gives a true-false matrix
a        % Any: true for columns that contain at least one true entry
s        % Sum. Implicit display

Husk, 15 bytes
↑ṁ₁N
†+¹ṁŀSe→÷3

Try it online!