text:
In how many bits do I fit
For any positive 32-bit integer (1 ≤ n ≤ 0xFFFFFFFF) output the number of bits needed to represent that integer.
Test cases
| n    | n in binary | bits needed |
|----------------------------------|
| 1    | 1           | 1           |
| 2    | 10          | 2           |
| 3    | 11          | 2           |
| 4    | 100         | 3           |
| 7    | 111         | 3           |
| 8    | 1000        | 4           |
| 15   | 1111        | 4           |
| 16   | 10000       | 5           |
| 128  | 10000000    | 8           |
| 341  | 101010101   | 9           |

4294967295 => 11111111111111111111111111111111 => 32

So f(16) would print or return 5
This is code-golf. Shortest code in bytes wins

This is the ceiling of the base-2 logarithm.

@orlp It actually is floor(log2(num))+1

@KritixiLithos Right.

@KritixiLithos What's an example for when ceil(log2(num)) != floor(log2(num)) + 1? I'm racking my brain trying to figure out why the distinction is important.

Nevermind, just realized that the distinct is important when num is a power of two.

This is a trivial challenge with a lot of trivial solutions. There are however some non-trivial solutions too. To voters: Please read the first sentence of this meta post before upvoting builtin functions. (humbly taken from this comment)

Am I wrong that you need 32 bits to represent any 32-bit integer? If I want to represent 1 in binary, I need 31 0's and one 1. I can't store "11" as "11" in memory.

@MatthewRock Technically, you could store 1 in one bit (1). With fixed-width integers, yes, that would take up 32 bits (assuming 32-bit word size), but 31 of those bits are redundant (leading zeroes).

Just out of curiosity, how many bits does it take to store zero (0)?

@Octopus 1 bit.

@BrianJ But this: ceil(log2(num+1)) == floor(log2(num)) + 1

For 64 bit (without the +1).

05AB1E, 2 bytes
bg

Try it online!

Esoteric language won again... bg

@devRicher I expect to be beaten by a 1 byte solution still, to be honest.

At least this answer gets it's upvotes; it's not in the bg.

bg in gaming means bad game :)

@yoyoyonny or battleground haha.

Or (and I may be dating myself a little) Blood-Gulch (halo 3) lol.

JavaScript (ES6), 18 bytes

f=n=>n&&1+f(n>>>1)
<input type=number min=0 step=1 value=8 oninput="O.value=f(this.value)">
<input id=O value=4 disabled>

This is one of the few non-trivial solution here. Nice tactic!

Should it be n>>>1 to support n > 0x7FFFFFFF?

@Arnauld Hmm, didn't know >> failed on n that high. Thanks.

Nice, my first attempt was f=(a,b=1)=>a>1?f(a>>1,++b):b

x86 Assembly, 4 bytes
Assuming Constant in EBX:
bsr eax,ebx
inc eax

EAX contains the number of bits necessary for Constant.
Bytes: ☼¢├@
Hexadecimal: ['0xf', '0xbd', '0xc3', '0x40']

Could you please include a hexdump of the actual 8 byte compiled x86 Assembly code?

Did so. And thank you, because I realized I made a mistake. I added an "inc eax" to fit the rules. I lost a byte. :(

Oh wow you changed my post to proper formatting. Thanks for correcting it!

By the way, Assembly submissions can assume that the input is already stored in a specific register, so I think you could shave off a few bytes that way.

Oh that's nice! Well, then it's down to four!

Is it customary to count assembly submissions as the number of bytes of the compiled machine code rather than the assembly language source code?

Python, 14 bytes
int.bit_length

Try it online!

It works in Python 2, too.

It does indeed. Forgot Python 2‘s int was 64 bits wide, not 32 bits.

Python 3's bit_length is bit_length().

@dfernan This is not a function call; it's a function. If n is an int, int.bit_length(n) and n.bit_length() do exactly the same.

@Dennis, understood. In that case, your answer is not entirely correct and should depict an additional three bytes.

@dfernan I'm sorry, but I don't understand which three bytes you're talking about.

I was referring to (n) from int.bit_length(n), as int.bit_length by its own is not valid, working code.

@dfernan int.bit_length(n) is a function call, and thus a snippet that assumes the input is stored in a variable. This is not allowed by our rules, so appending (n) would make this answer invalid. However, int.bit_length evaluates to a function and can be saved in a variable for later use. This is allowed by default.

@Dennis, thanks for the explanation.

n.bit_length() is the way it would be used in the code e.g., 123 .bit_length(). If the assembly solution may assume that the input is in a registry then Python solution should be allowed to get the input from a variable too. Though if the question is to write a function then int.bit_length works too (f= is implied and Class.method(instance) is allowed in Python in addition to instance.method()).

@J.F.Sebastian I see your point, but Assembly programs may take input from registers is an I/O rule that doesn't apply to all languages.

@J.F.Sebastian The comments of some random answer isn't the place to debate the rules that have been set down. If you disagree with the popular rulings, post your own answer on the relevant meta question, with clearly explained reasoning, including how you think it'll make things better (which, incidentally, can't just be "makes golfing easier"). If people agree (i.e. upvote), then bam! Rules changed. That can't happen if you just discuss it in comments.

Mathematica, 9 bytes
BitLength

Alternatively:
Floor@Log2@#+1&
#~IntegerLength~2&

Labyrinth, 13 12 bytes
 ?
_:
2/#(!@

Try it online!
Explanation
The program simply repeatedly divides the input by 2 until it's zero. The number of steps are kept track of by duplicating the value at each step. Once it's reduced to zero we print the stack depth (minus 1).
The program starts at the ? which reads the input. The main loop is then the 2x2 block below, going counter-clockwise:
:   Duplicate current value.
_2  Push 2.
/   Divide.

Once the value is zero after a full iteration, the linear bit at the end is executed:
#   Push stack depth.
(   Decrement.
!   Print.
@   Terminate.

This solution is complete - it takes input and provides the answer, and does not utilise any existing function for this specific purpose - it calculates the answer manually.  To me this is more in the spirit of the game than most other answers.

C, 31 bytes
f(long n){return n?1+f(n/2):0;}

... Then I thought about recursion. From obscure to obvious, and with one fourth of the length dropped off.
See it live on Coliru

C, 43 bytes
c;
#define f(v)({for(c=0;v>=1l<<c;++c);c;})

Calling f with an unsigned value (e.g. f(42u)) will "return" its bit length. Even works for 0u !
Ungolfed and explained: (backslashes omitted)
c;
#define f(v)
    ({ // GCC statement-expression

        // Increment c until (1 << c) >= v, i.e
        // that's enough bits to contain v.
        // Note the `l` to force long
        // arithmetic that won't overflow.
        for(c = 0; v >= 1l << c; ++c)
            ; // Empty for body

        c; // Return value
    })

See it live on Coliru

OP guarantees n>=1, so n?...:0 is not necessary.

@MadPhysicist well I do have to stop the recursion somewhere, don't I ;)

OIC. Didn't read carefully, feel like a dumbass now. Neat answer either way.

@MadPhysicist no worries, thank you very much :)

For the non-recursive solution assuming gcc statement expressions, I reckon you might have been inclined to use the #define f(n) ({64-__builtin_clzl(n);}) approach as well.

@Moreaki yep. For some reason I was sure that the builtin would be too long -- but now Digital Trauma has pretty much nailed it that way.

Perl 6, 7 bytes
*.msb+1

Try it
Explanation:
* makes it become a WhateverCode lambda, and indicates where to put the input
.msb on an Int returns the index of the most significant bit (0 based)
+1 is combined into the lambda, and adds one to the eventual result of calling .msb.

C preprocessor macro (with gcc extensions), 26
#define f 32-__builtin_clz

Uses GCC's count-leading-zeros builtin.
Call this as a function, e.g. f(100).
Try it online.

Oh wow, I thought about using a builtin but dropped the idea because I thought it was going to be too long... Well played.

Lucky the OP specified n >= 1 :D

Retina, 56 37 bytes
This solution works with all the required input values.
The biggest problem Retina faces in this challenge is the fact that its strings have a maximum length of 2^30 characters, so the usual way of dealing with numbers (unary representation) doesn't work with values greater than 2^30.
In order to solve this problem I adopted a different approach, keeping a sort of decimal representation of numbers, but where each digit is written in unary (I'll call this representation digitunary). For example the number 341 would be written as 111#1111#1# in digitunary. With this representation we can now work with numbers of up to 2^30/10 digits (~ a hundred million digits). It is less practical than standard unary for arbitrary arithmetic, but with a bit of effort we could do any kind of operations.

NOTE: digitunary in theory could use any other base (e.g. binary 110 would be 1#1## in base 2 digitunary), but since Retina has builtins to convert between decimal and unary and no direct way to deal with other bases, decimal is probably the most manageable base.

The algorithm I used is making successive integer divisions by two until we reach zero, the number of divisions we made is the number of bits needed to represent this number.
So, how do we divide by two in digitunary? Here's the Retina snippet that does it:
(1*)(1?)\1#        We divide one digit, the first group captures the result, the second group captures the remainder
$1#$2$2$2$2$2      The result is put in place of the old number, the remainder passes to the next digit (so it is multiplied by 10) and is divided by two there -> 5 times the remainder goes to the next digit

This replacement is enough to divide a digitunary number by 2, we just need to remove possible .5s from the end if the original number was odd.
So, here's the full code, we keep dividing by two until there are still digits in the number, and put a literal n in front of the string at each iteration: the number of n at the end is the result.
.                  |
$*1#               Convert to digitunary
{`^(.*1)           Loop:|
n$1                    add an 'n'
(1*)(1?)\1#            |
$1#$2$2$2$2$2          divide by 2
)`#1*$                 |
#                      erase leftovers
n                  Return the number of 'n's in the string

Try it online!

Updated solution, 37 bytes
Big refactoring with many good ideas that golfed about a third of the length, all thanks to Martin Ender!
The main idea is to use _ as our unary symbol: in this way we can use regular digits in our string, as long as we convert them back to _s when it is needed: this lets us save many bytes on division and on insertion of multiple digits.
Here's the code:
<empty line>    |
#               put a # before each digit and at the end of the string
{`\d            Loop:|
$*_                 Replace each digit with the corrisponding number of _
1`_                 |
n_                  Add an 'n' before the first _
__                  |
1                   Division by 2 (two _s become a 1)
_#                  |
#5                  Wherever there is a remainder, add 5 to the next digit
}`5$                |
                    Remove the final 5 you get when you divide odd numbers
n               Return the number of 'n's in the string

Try it online!

I've used a similar numeric form (but called it Unary-Coded Decimal), which is pretty handy for arithmetic with Sed.

Ruby, 19 16 bytes
->n{"%b"%n=~/$/}

Thanks Jordan for golfing off 3 bytes

You can save a byte with %: ->n{("%b"%n).size}.

Wait, this is shorter: ->n{"%b"%n=~/$/}.

JavaScript ES6, 19 bytes
a=>32-Math.clz32(a)

Math.clz32 returns the number of leading zero bits in the 32-bit binary representation of a number. So to get the amount of bits needed, all we need to do is substract that number from 32

f=
  a=>32-Math.clz32(a)

pre {
    display: inline;
}
<input id=x type="number" oninput="y.innerHTML = f(x.value)" value=128>

Bits needed:
8

The alternative a=>1+Math.log2(a)|0 is also 19 bytes.

@Neil 1+...|0 screams minus tilde! a=>-~Math.log2(a) is 18

@edc65 I count 17... but yes, I was sure I was missing something, thanks for pointing it out.

@Neil Feel free to post it as a seperate answer. It uses a different method than my answer so it would feel unfair to use yours for a reduced byte count

Jolf, 2 bytes
lB

Just convert to binary and then find the length.

Julia 0.4, 14 bytes
!n=log2(2n)÷1

Try it online!

Much more interesting than the other answers. +1

bash / Unix tools, 16 bytes
dc<<<2o$1n|wc -c

Save this in a script, and pass the input as an argument. The number of bits required to represent that number in binary will be printed.
Here's an explanation:
dc is a stack-based calculator.  Its input, parsed into tokens, is:
2 — Push 2 on the stack.
o — Pop a value off the stack (which is 2) and make it the output base (so output is now in binary).
The value of the argument to the bash program ($1) — Push that argument on the stack.
n — Pop a value off the stack (which is the input number) and print it (in binary, because that's the output base) with no trailing newline.
So the dc command prints the number in binary.
The output of dc is piped to the command wc with the -c option, which prints the number of characters in its input.
The end result is to print the number of digits in the binary representation of the argument.

Nice choice of language, but it would be even cooler if you included an explanation.

@NH Thanks.  I've added an explanation.

Google Sheets, 15 Bytes
Takes input from cell A1 and outputs to the cell that holds the formula
=Len(Dec2Bin(A1

or
=Int(1+Log(A1,2

or
=Int(Log(2*A1,2

Excel, 17 Bytes
Same as above but formatted for MS Excel
=Len(Dec2Bin(A1))

or
=Int(1+Log(A1,2))

or
=Int(Log(2*A1,2))

Pyth, 3 bytes
l.B

Test suite available here.
Explanation
l.BQ    Q is implicitly appended
   Q    eval(input)
 .B     convert Q to binary string
l       len(.B(Q))

Alternatively: hsl or .El, in which l computes the log base 2, and hs or .E compute ceiling.

Jelly, 2 bytes
BL

Converts to binary, finds length.

C#, 63 45 31 bytes
Saved 18 bytes, thanks to Loovjo, and TuukkaX
Saved 14 bytes, thanks to Grax
 b=>1+(int)System.Math.Log(b,2);

It uses, that a decimal number n has ⌊log2(n)⌋+1 bits, which is described on this page:

Number of Bits in a Specific Decimal Integer
A positive integer n has b bits when 2^(b-1) ≤ n ≤ 2^b – 1. For example:

29 has 5 bits because 16 ≤ 29 ≤ 31, or 2^4 ≤ 29 ≤ 2^5 – 1
123 has 7 bits
because 64 ≤ 123 ≤ 127, or 2^6 ≤ 123 ≤ 2^7 – 1
967 has 10 bits because
512 ≤ 967 ≤ 1023, or 2^9 ≤ 967 ≤ 2^10 – 1

For larger numbers, you could
consult a table of powers of two to find the consecutive powers that
contain your number.
To see why this works, think of the binary representations of the
integers 2^4 through 2^5 – 1, for example. They are 10000 through 11111,
all possible 5-bit values.
Using Logarithms
The above method can be stated another way: the number of bits is the
exponent of the smallest power of two greater than your number. You
can state that mathematically as:
bspec = ⌊log2(n)⌋ + 1
That formula has three parts:

log2(n) means the logarithm in base 2 of n, which is the exponent to
which 2 is raised to get n. For example, log2(123) ≈ 6.9425145. The
presence of a fractional part means n is between powers of two.

⌊x⌋ is the floor of x, which is the integer part of x. For example,
⌊6.9425145⌋ = 6. You can think of ⌊log2(n)⌋ as the exponent of the
highest power of two in the binary representation of n.

+1 takes the exponent to the next higher power of two. You can think of this step as accounting for the 2^0th place of your binary number,
which then gives you its total number of bits. For our example, that’s
6 + 1 = 7. You might be tempted to use the ceiling function — ⌈x⌉,
which is the smallest integer greater than or equal to x — to compute
the number of bits as such:

bspec = ⌈log2(n)⌉
However, this fails when n is a power of two.

You have an extra space in there ...)+ 1)... -> ...)+1.... Also, I think you can return the value directly instead of printing it.

You can drop it down to 31 by doing b=>1+(int)System.Math.Log(b,2);  The int conversion provides the same output as Math.Floor and you don't need the using statement if you only reference System once.

C#, 32 bytes
n=>Convert.ToString(n,2).Length;

Converts the parameter to a binary string and returns the length of the string.

Befunge-93, 23 21 Bytes
&>2# /# :_1>+#<\#1_.@

Befunge is a 2D grid-based language (although I'm only using one line).
&                      take integer input
 >2# /# :_             until the top of the stack is zero, halve and duplicate it
          1>+#<\#1_    find the length of the stack
                   .@  output that length as an integer and terminate the program

Try it online!

@JamesHolderness Thanks, I figured it could be shortened since it had so many hash/spaces, but I couldn't quite get it.

17 bytes

Haskell, 20 bytes
succ.floor.logBase 2

Composes a function that takes logarithm base 2, floors, and adds 1.

Jellyfish, 4 bytes
p#bi

Try it online!
Print (p), the length (#) of the binary representation (b) of the input (i).

CJam, 5 bytes
ri2b,

Try it online!
Read input (r), convert to integer (i), get binary representation (2b), get length (,).

Octave, 19 bytes
@(x)ceil(log2(x+1))

Anonymous function that adds 1, computes binary logarithm and rounds up.
Try it online!

Well, I tried ;-)

QBIC, 18 bytes
:{~2^q>a|_Xq\q=q+1

That's incredible Mike! But how does it work?
:        Read input as integer 'a'
{        Start an infinite DO-LOOP
~2^q>a   If 2 to the power of q (which is 1 by default) is greater than a
|_Xq     Then quit, printing q
\q=q+1   Else, increment q
[LOOP is closed implicitly by QBIC]

Java 8, 34 27 bytes
For once, Java has some useful builtins! Now, we just need some shorter names...
x->x.toString(x,2).length()

Try it online!
Of course, you can do this without builtins (see Snowman's answer), but for a higher byte count.

Octave, 19 bytes
@(x)nnz(dec2bin(x))    % or
@(x)nnz(de2bi(x)+1)    % or
@(x)nnz(de2bi(x)<2)    % or
@(x)numel(de2bi(x))    % or
@(x)rows(de2bi(x'))

Octave has two functions for converting decimal numbers to binary numbers.
dec2bin converts a number into a string of the characters 1 and 0 (ASCII-values 48 and 49). The length of the string will be equal to the necessary number of bits, unless specified otherwise. Since the characters 1 and 0 are non-zero, we can use nnz to find the number of elements like this: @(x)nnz(dec2bin(x)). This is 19 bytes, so it's tied with Luis Mendo's other Octave answer.
Can we do better using de2bi?
de2bi is a function that returns the binary numbers as a vector with the numbers 1 and 0 as integers, not characters. de2bi is obviously two bytes shorter than dec2bin, but we can no longer use nnz. We can use nnz if we either add 1 to all elements, or makes it into a logical vector with only true values. @(x)nnz(de2bi(x)+1) and @(x)nnz(de2bi(x)<2) are both 19 bytes. Using numel will also give us 19 bytes, @(x)numel(de2bi(x)).
rows is one byte shorter than numel, but de2bi returns a horizontal vector, so it must be transposed. @(x)rows(de2bi(x)') just so happens to be 19 bytes too.

Python 2, 28 Bytes
def f(a):print len(bin(a))-2

lambda a:len(bin(a))-2

Pyke, 3 bytes
b2l

Try it here!

Retina,  44  23 bytes
Requires too much memory to run for large input values. Converts to unary, then repeatedly divides by 2, counting how many times until it hits zero. Byte count assumes ISO 8859-1 encoding.
.*
$*
+`^(1+)1?\1
$1_
.

Try it online

I'm not sure this is valid. This isn't a case of "it requires more memory than you'll probably have" but "it requires more memory than Retina itself can handle". In particular, the initial conversion to unary will fail for inputs of order 2^30 and above, due to limitations in Retina's implementation.

If it is valid, it could be shortened a lot though: https://tio.run/nexus/retina#@6@nxaWixaWdEKdhqK1paB9jyKViGM@l9/@/saUhAA

Perl, 21 bytes
21 bytes, (ab)use the fact that $= must be an integer
say$==1+log(<>)/log 2

25 bytes, naïve implementation
say length sprintf"%b",<>

28 23 byte version without whitespaces
$-++while$_>>=1;say++$-

1while($i//=<>)>=1<<++$_;say

Usage
$ echo 128 | perl -E '$-++while$_>>=1;say++$-'
8
$ echo 128 | perl -E 'say length sprintf"%b",<>'
8

Nice use of forcing the cast, but I think you can use 0| or $-= instead of $#_= for -1 byte!

@DomHastings yes, you're right. Thanks for the tip!

Japt, 2 bytes
¢l

¢ converts the input into a base-2 string
l returns the length
Thanks ETHproductions for shaving off 3 bytes.

Awesome, thanks! ¢ is a shortcut for Us2) (see the Unicode Shortcuts section of the docs), which allows you to just do ¢l for 2 bytes. (I should add an implicit U at the beginning of every program...)

JavaScript (ES6), 17 bytes

f=
a=>-~Math.log2(a)
<input type=number min=0 oninput=o.textContent=f(this.value)>
Bits:

Saved 2 bytes thanks to @edc65.

PHP, 21 bytes
<?=-~log($argv[1],2);

log(x,2) Computes log2(x)
~ is the binary negation operator that also cast to int
- take opposite

28 bytes
<?=strlen(decbin($argv[1]));

decbin convert to binary
strlen takes length

28 bytes
<?=floor(log($argv[1],2))+1;

log(x,2) compute log2(x)
floor ... +1 takes floor plus 1

32 bytes (Thanks Titus)
for(;2**++$i<=$argv[1];);echo$i;

2**$n compute 2^n ie. pow(2,n) until superior to $argv[1]

It would appear you no longer need the log(x,2) or floor ... +1 explanations

OK, seems like a display bug (see my edit)

Your looping solution fails for powers of 2 (1,2,4,8 etc.); fix with <= instead of <. And for(;2**++$i<=$argv[1];);echo$i; is two bytes shorter.

Java 8, 43 41
v->{int b=0;for(;v>0;++b,v/=2);return b;}

Counts the bits the old fashioned way and returns the count. Lambda fits into a LongFunction<Integer>.

I always forget that lambda syntax is so forgiving, when Java in general is more rigid.

I've linked your answer in mine, as I feel guilty for just cheating with builtins :)

@FlipTack don't feel guilty, built-ins are not cheating (unless specified otherwise). Our answers are separate solutions so they are not duplicates either.

Do you not need class {void main() {}...} for Java answers?

@ericw31415 unless otherwise specified, a "program or function" is allowed, and output may be to standard output or a return value. This allows non-golfing languages to be a bit more competitive because we can use functional interfaces (lambdas).

@Snowman Java doesn't really have functions though, right? Aren't they all methods of a class? If the class isn't defined, the method couldn't exist.

@ericw31415 yes, Java has functions and yes, they must all be scoped to a class - either static, or belonging to an object with an implicit this pointer (similar to member functions in C++). Functions in the context of a lambda are a single function belonging to an implicit anonymous (compiler-generated) class that implements a functional interface. In other words, you are correct, but Java has syntactic sugar to make lambdas appear like first-class functions.

@ericw31415 lambda expressions, functional literals, etc. are all allowed. only if the post specifies "full program" must you include the boilerplate (and the default is "programs or functions")

Hello from the future! Increment b (or halve v) in the loop body to save 1 byte!

Actually, 2 bytes
├l

Try it online!
Explanation:
├l
├   binary representation (without leading zeroes)
 l  length

Since Actually uses arbitrary-width integers, this will work for any input, so long as there is enough memory and time.

awk, 32 bytes
Iterate 2's exponent and see when it's greater than given value. Return the value in exit:
{for(;++i<=32;)if(2^i>$0)exit i}

Run it:
$ echo 4294967295| awk '{for(;++i<=32;)if(2^i>$0)exit i}'
$ echo $?
32

C, 27 bytes
f(n){return n?1+f(n/2u):0;}

Inspired by the answer by Quentin. Uses an unsigned literal to avoid overflow when using 32-bit integers. Might be able to cut the unsigned part if int is 64-bit, but it's more interesting this way.

Matlab, 21 Bytes
c=@(x)nnz(dec2bin(x))

Yay for anonymous functions!
Example usage:
c(6)

ans =

     3

Julia, 15 bytes
n->ndigits(n,2)

This is an anonymous function that wraps Julia's built-in ndigits function that counts the number of digits of the input in the given base. Here we're giving it a base of 2.
Try it online!

J, 11 bytes
2&(1+<.@^.)

This is a monadic verb that accepts input on the right.
2&(    @^.)  NB. Base 2 logarithm of the input
     <.      NB. Floor
   1+        NB. Add 1

Could likely be improved using # (tally) and #: (binary representation) but I haven't figured that part out yet.
Try it online!

It's just #@#:

ForceLang, 88 bytes
Noncompeting, requires the latest interpreter release, which postdates the question. (The ln implementation used previously was too inaccurate with large values)
set i math.ln io.readnum()
set j math.ln 2
set k math.floor i.mult j.pow -1
io.write k+1

APL, 6 bytes
1+⌊2⍟⍵
Omega is the right argument, which is replaced with the number in question.
Try it online!

As it is, this would require curly brackets to make it a function. However, you can make it a function train with ⌊1+2⍟⊢. (link)

Julia, 16 bytes
n->endof(bin(n))

Anonymous function.

endof is shorter than length.

C, 47 39 bytes
int L(uint32_t X){return X?1+L(X/2):0;}

Not using a library function. The algorithm counts the number of bits needed by  shifting right (or the equivalent divide by 2) until 0.

RProgN, 4 Bytes.
~2BL

Explained
~2BL    #
~        # Zero Space Segment, The rest of this code is interpreted as if it were a bunch of characters separated by spaces.
 2B     # Convert implicit input to Base 2
   L    # Get the length of that, and implicitly output.

Try it online!

"ZSS" is not an explanation of ~ to anyone who didn't already know.

Sorry, Added a bit of detail.

Pyth - 3 bytes
Alternative 3 byte answer. Takes floor(log2(n))+1
hsl

Test Suite.

TI-Basic, 8 bytes
1+int(logBASE(Ans,2

Lithp, 30 bytes
 #N::((length(to-string N 2)))

Pretty simple. Convert the number to binary (to-string N 2) and return the length of the string.
Try it online!
Alternate entry (no binary builtin), 38 bytes
 #N::((if(!= 0 N)((+ 1(x(>> N 1))))0))

Try it online!
Recursively shifts right by 1 each time the function is called, until we get to 0. This is an unsigned shift, so can support the full range of 0x0 - 0xFFFFFFFF. The Lithp >> operator is equivalent to Javascript's >>> operator.

Powershell, 66 48 bytes
-18 bytes thanks to @briantist

function l {[math]::floor([math]::log($args[0])/[math]::log(2))+1}

($m=[math])::floor(m::log($args[0])/m::log(2))+1

Doing anything in Powershell is complicated, but it's better than Batch! In just Batch, this challenge isn't even possible (no decimal numbers=no logarithms).

Our respective PowerShell solutions use different methods, but yours can still be shortened by getting rid of function l { } because it's completely superfluous for the challenges here; $args[0] counts for args passed to the script itself. You could also do ($m=[math])::log($args[0]) and then replace the other 2 instances of [math] with $m, like $m::floor.

VBScript, 45 bytes
Sub l(n)
WScript.Echo Log(n)/Log(2)+1
End Sub

See result by adding l(whatever the number is) to the end of the file. Run with cscript.exe if you want the result in a command window.

You may consider adding a  flag to this and all of your future VBS answers, so that they may have syntax highlighting

@TaylorScott Thanks, I'll consider doing that in the future.

Perl, 19 bytes
$_=0|1+(log)/log 2

The score includes 1 byte for the -p switch the program requires.
Try it online!

Some mad golfing skills here... just when I thought there was no more room for improvement in my answer :)

Javascript, 23 bytes
x=>x.toString(2).length

f=x=>x.toString(2).length
document.write(f(341)) // 9

SmileBASIC, 20 bytes
INPUT N?LEN(BIN$(N))

Ruby, 19 bytes
->i{i.to_s(2).size}

C, 39 36 bytes
f(n,*p){*p=0;while(n){n/=2;(*p)++;}}

Ungolfed version:
 void f(long int n, int *p)
 {
   *p=0;
    while(n!=0)
    {
      n/=2;
     (*p)++;
    }
  }

The main() function that accepts number from stdin, would look like this:
   int main()
   {
       int b=0
       long int num;
       scanf("%ld",&num);
       f(num,&b);
       printf("%d\n",b);
       return 0;
   }
`

Alternative:
f(long n){i=0;while(n!=0){n/=2;i++;}return i;}

Ungolfed version:
int f(int n)
{
  int i=0;

  while(n!=0)
  {
    n/=2;
    i++;

  }
   return i;
}

You can shave off some bytes by removing "n!=0" since n evaluates as true if nonzero.

This is also invalid, won't compile.
This, however, will. p;f(n){p=0;while(n)n/=2,++p;} works with only 29 bytes.
p;f(n){for(p=0;n;n/=2)++p;} works with only 27.

Python 2, 39 bytes
lambda x:__import__('math').frexp(x)[1]

Not even kind of the shortest, but it showcases a neat function that could be useful elsewhere!
frexp(n) represents n as n = m * 2**e with 0.5 <= abs(m) < 1 and then returns the tuple (m, e) as output. For positive integers, e is exactly the number of bits required to represent the number.

You could save a few bytes by just using import.

Common Lisp, 39 bytes
(defun f(i)(length(format nil "~B" i)))

Try it online!

Python 2, 22 bytes
lambda n:len(bin(n))-2

Try it online!

Dodos, 60 bytes
	' S ' g
g
	S dab
	g S ' dab f
f
	f ' '
	S dab
'
	dip
S
	dot

Try it online!
(S computes the sum, S ' dab f divides by 2)

Vyxal, 2 bytes
bL

Try it Online!
Explained
bL
b  # binary
 L # length

68020 assembler, 2 4 bytes (I think)
BFFFO D0, D1
INC D1

The BFFFO instruction finds the position of the first set bit in parameter 1, and stores the result in parameter 2. I think it is a 2-byte instruction. Unfortunately, it is indexed from 0, not 1. Hence you need an INC on D1 afterwards.

Pushy, 11 bytes
0{${h}2/;}#

Try it online!
This works by continually doing x = x // 2 until x = 0, and counting the number of divisions taken:
0            \ Push a 0 (initial counter)
 {$     ;    \ While input > 0:
   {h}       \  Increment counter
      2/     \  Floordiv input by 2
         }#  \ Output final counter

PowerShell v3+, 37 34 bytes
param($n)(1..32|?{!($n-shr$_)})[0]

Try it online!

Taking input as param($n) is 3 bytes shorter -- param($n)(1..32|?{!($n-shr$_)})[0]

@TimmyD so it is! Can't believe I missed that.

Groovy, 32 bytes
{Long.toBinaryString(it).size()}

This is an unnamed closure.
Try it here !

J, 4 bytes
#&#:

Explanation:
#      NB. Counts length of bit list
&      NB. Connects # and #:
#:     NB. Creates list of bits

MATL, 2 bytes
Bn

The shortest solution in MATL seems to be just direct, by measuring the length of the binary representation (as a vector).  Other options are ZlkQ, which takes the base-2 logarithm, floors it and adds 1, or YBn which converts the input to a binary string and finds the length.

K/Kona, 4 bytes
#2\:

\: gets the representation of right-hand in base left-hand - in this case, base 2 of the input. # then just counts this
k)2\:341
1 0 1 0 1 0 1 0 1
k)#2\:341
9

Befunge-98 (PyFunge), 19 16 bytes, Thanks to @JoKing
&#\<_$.@j3:/2\+1

Try it online!
19 bytes:
&0#;1+\2/:!3j@.$_\;

Try it online!
5 bytes shorter than Befunge-93 :)

Whitespace, 70 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T   S S N
_If_0_jump_to_Label_PRINT][S S S T  S N
_Push_2][T  S T S _Integer_division][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Integer i = STDIN as integer
Integer r = 0
Start LOOP:
  if i is 0:
    Call function PRINT_AND_EXIT
  i = i integer-divided by 2
  r = r + 1
  Go to next iteration of LOOP

function PRINT_AND_EXIT:
  Print r as integer
  Exit with error

Example run (n=16):
Command   Explanation                 Stack       HEAP     STDIN   STDOUT  STDERR

SSSN      Push 0                      [0]
SNS       Duplicate top (0)           [0,0]
SNS       Duplicate top (0)           [0,0,0]
TNTT      Read STDIN as integer       [0,0]       {0:16}   16
TTT       Retrieve                    [0,16]      {0:16}
NSSN      Create Label_LOOP           [0,16]      {0:16}
 SNS      Duplicate top (16)          [0,16,16]   {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [0,16]      {0:16}
 SSSTSN   Push 2                      [0,16,2]    {0:16}
 TSTS     Integer-divide (16/2)       [0,8]       {0:16}
 SNT      Swap top two                [8,0]       {0:16}
 SSSTN    Push 1                      [8,0,1]     {0:16}
 TSSS     Add (0+1)                   [8,1]       {0:16}
 SNT      Swap top two                [1,8]       {0:16}
 NSNN     Jump to Label_LOOP          [1,8]       {0:16}

 SNS      Duplicate top (8)           [1,8,8]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [1,8]       {0:16}
 SSSTSN   Push 2                      [1,8,2]     {0:16}
 TSTS     Integer-divide (8/2)        [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 SSSTN    Push 1                      [4,1,1]     {0:16}
 TSSS     Add (1+1)                   [4,2]       {0:16}
 SNT      Swap top two                [2,4]       {0:16}
 NSNN     Jump to Label_LOOP          [2,4]       {0:16}

 SNS      Duplicate top (4)           [2,4,4]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [2,4]       {0:16}
 SSSTSN   Push 2                      [2,4,2]     {0:16}
 TSTS     Integer-divide (4/2)        [2,2]       {0:16}
 SNT      Swap top two                [2,2]       {0:16}
 SSSTN    Push 1                      [2,2,1]     {0:16}
 TSSS     Add (2+1)                   [2,3]       {0:16}
 SNT      Swap top two                [3,2]       {0:16}
 NSNN     Jump to Label_LOOP          [3,2]       {0:16}

 SNS      Duplicate top (2)           [3,2,2]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [3,2]       {0:16}
 SSSTSN   Push 2                      [3,2,2]     {0:16}
 TSTS     Integer-divide (2/2)        [3,1]       {0:16}
 SNT      Swap top two                [1,3]       {0:16}
 SSSTN    Push 1                      [1,3,1]     {0:16}
 TSSS     Add (3+1)                   [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 NSNN     Jump to Label_LOOP          [4,1]       {0:16}

 SNS      Duplicate top (1)           [4,1,1]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [4,1]       {0:16}
 SSSTSN   Push 2                      [4,1,2]     {0:16}
 TSTS     Integer-divide (1/2)        [4,0]       {0:16}
 SNT      Swap top two                [0,4]       {0:16}
 SSSTN    Push 1                      [0,4,1]     {0:16}
 TSSS     Add (4+1)                   [0,5]       {0:16}
 SNT      Swap top two                [5,0]       {0:16}
 NSNN     Jump to Label_LOOP          [5,0]       {0:16}

 SNS      Duplicate top (0)           [5,0,0]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [5,0]       {0:16}
NSSSN     Create Label_PRINT          [5,0]       {0:16}
 SNN      Discard top                 [5]         {0:16}
 TNST     Print as integer            []          {0:16}           5
                                                                            error

Program stops with an error: No exit found.

Brain-Flak, 48 bytes
({<({<(({}[()]))>{()(<{}({}[()])>)}{}}{})>()}{})

Try it online!
Readable version:
({< # Start a loop

  #devide by two:
  ({<(({}[()]))>{()(<{}({}[()])>)}{}}{})

>()} # Count interations
{} # pop the zero
) # push the result

Thunno 2 L, 1 byte
ḃ

Attempt This Online!
ḃ converts to binary; the L flag takes the length.


text:
Clone yourself!
You are to create a program that creates exact clones of itself infinitely until stopped. Whatever is in the original program must be in the clones. In other words, the clones and original program are the same in every way except for that the clones don't have to be in the same type of file as the source code (they can be text files).
Example:
If my original program is:
for i in range(0, 10):
     print i

the clone must also  be:
for i in range(0, 10):
     print i

Rules and Clarifications:

Standard loopholes are forbidden
The clones must be the exact copy of the original
The clones must be readable files that can be run if put inside the correct interpreter
The program can read its own source code
All clones must be separate files
Printing your program out is not allowed
File names count into the number of bytes
The clones don't have to be in the same directory as the source file nor share the same file name
At least 1000 clones should be able to be created

Winning:
Least bytes wins!

Zsh, 19 17 9 bytes
#!/bin/zsh
<$0>$$;$0

Per consensus on meta, the shebang is excluded from the byte count.
Try it online!
Note that TIO's forkbomb protection will kill the process after 113 files have been generated. It can easily generate 1000 files on a system without such conservative resource limits.

I like yes `<$0`|split -1 a lot better, but that doubles the byte count...

Too bad the in-out redirection like that does not work  well in bash  :(
For one moment, I naïvely thought to have outgolfed you :)

Batch, 32 bytes
set/an=%1+1
copy %0 %n%
%0 %n%

Not using @ because there's no restriction on STDOUT. %1 defaults to the empty string, so n becomes 1 the first time and increments on every pass. Alternatively, this might work for 28 bytes, but I have no idea how random %random% actually is when used like this:
copy %0 %random%%random%
%0

IIRC %random% is based off the current time and can generate anything from 0 to something slightly above 32,000.

To clarify, %random% is a variable that, when accessed, yields a random number as @user2428118 mentioned.

Bash, 25, 16, 12, 11 bytes
EDITS:

Removed the newline (-1 byte), Added "Try It Online". Thanks @Dennis !
Use background job PID $! as the filename (will be reused every ~32k files, but that is now allowed), -4 bytes

Golfed
#!/bin/bash
$0&cp $0 $!

Explained
Re-spawns itself as a background job with &, before doing a copy, so each iteration will run under its own PID.
Uses the last job PID as the filename.
This can run infinitely (or until stopped) but will be reusing clone filenames approx. every ~32k iterations.
Could be a bit nasty to kill, but AFAIK is not against the rules.
Try It Online!

Do you have a testing place where I can try this out for myself?

@PythonMaster, I will normally use Tutorial Point's online testbed, but it does not have uuid installed, and does not like the script doing so much IO.

TIO doesn't have a problem with I/O. Also, you don't need the newline after &. https://tio.run/nexus/bash#VY5BS8NAEIXP7q943W5tq6QpelMRRCIIGg/2mEuyO@kG42zY3agH/3tMaBWcw8A83nx8pK3Dcj5Lq4bTqgx2UNtT3UFtoWbDEt@wVBokGskFbqFbxySEtu/O4PzreG/SYx5aog6XmCNo33QR2nFsuKeA6OB7RsOIllCV@m3vXc9GiM43HGvIRTjgAmz5MVaIGHti8mUksyk4maZgCbVqwyj2OTq1ayFq51FP4LNrGCdOfnkPj09ZfvecXRW8CH/v9y/5Lst3r/9TCanqaa1uVL2Wwoweww8

Ruby, 78 bytes, 77 43 + 4 (filename: a.rb) = 47 bytes

Version 1.2

43 bytes + name / Thanks to @Alexis
So much shorter!!!
loop{File.write "#{$.+=1}",open("a.rb",?r)}

that's about as golfed as I think it's going to get

Version 1.1

73 bytes + name / Thanks to @Alexis Anderson
i=0
loop do
File.open("#{i}",?w){|b|b.puts File.read("a.rb",?r)}
i+=1
end

Version 1.0

74 bytes + name
i=0
loop do
File.open("#{i}","w") do{|b|b.puts File.read("a.rb")}
i+=1
end

This is my first Ruby answer so all inprovements are welcome.

kernel open forwards to file open, you should be able to omit the File. altogether. ?w in place of "w". I think the do on the File.open is useless, since you have the curly braces.

open('a.rb',?r) in place of File.read('a.rb')

?w is a character w. A string in it's own right. ?w == 'w'. so you don't need the quotes in "?w"

i=0
loop do
File.write "#{i}",open("a.rb",?r)
i+=1
end

actually, you can also use curly braces for the loop method too

loop{File.write "#{$.+=1}",open("a.rb",?r)}
that's about as golfed as I think it's going to get

Which version of Ruby? In latest 2.4.0 Kernel#open returns an IO object, resulting things like “#<File:0x0055b7ad129bd8>” in the clones.

You can omit the space between write and ". Also, is it really necessary to have "a.rb" instead of "a" or, say, $/ (which, hilariously, would create a file whose name is a newline, but hey, it works!)?

sh, 24 bytes
yes cp $0 '`uuid`'|sh -s

C#, 104 102 bytes
-2 bytes thanks to berkeleybross
namespace System.IO{class a{static void Main(){int i=0;while(1>0){i++;File.Copy("c{i}.cs");}}}}

No, it's not the shortest. But it's C#. What did you expect?

You don't need a namespace so you can fully qualify the File.Copy. Changing to a for loop so you can inline the int declaration and remove the 1>0 part. And pre increment the i in the File.Copy statement, that gives you 86 bytes I believe: class P{static void Main(){for(int i=0;;)System.IO.File.Copy("c.cs","c"+ ++i+".cs");}}

Actually this won't work because c.cs won't be in the output directory and has to be copied there manually. How does this work?

Dont forget about string interpolation $"c{++i}.cs" is 2 bytes shorter than "c"+ ++i+".cs"

Python 2, 61 bytes (unix) 65 (cross-platform)
Unix - 61 bytes
import os;i=1
while os.popen('cp %s %i.py'%(__file__,i)):i+=1

On unix cp is the systems copy-file - command. Using the console via popen allows me to copy the file by cp. new files will spawn in old-files directory.
CrossPlatform - 65 bytes
i=0
while 1:i+=1;open('%i.py'%i,'w').write(open(__file__).read())

This works, as open on default allows reading.
Funfact: replace 1:i+=1 with i:i-=1 and it will stop at i copies.
Other than that, I see no way of making it shorter than @muddyfish did it.

Python 2, 54 bytes
from shutil import*
a=__file__
while`copy(a,a*2)`:a*=2

Don't you have to import sys?

@SamuelShifterovich I would have had. I'm not sure how that edit survived as the byte count I was using was for the program now shown

Processing, 55 + 5 (name of file) = 60 bytes
I don't know if the filename counts as extra bytes
for(int i=0;;)saveStrings(i+++"",loadStrings("a.pde"));

Pretty much a series of builtins all chained together
Explanation
for(int i=0;;)           //A complex piece of code that cannot be explained in words alone
saveStrings(             //Save param2 (String[]) into file param1 (String)
 i+++"",                 // filename: the int i (and then is incremented)
 loadStrings("a.pde")    // content: load the content of file a.pde as a String[]
);

That "complex code" is smiling

ForceLang + the ForceLang-JS module, 162 bytes
set j require njs
j var a=function(){for(;;){var p=new java.io.PrintStream(Math.random()+".txt");p.println("set j require njs");p.print("j var a="+a+";a()")}};a()

PHP, 91 60 bytes
Saved 31 bytes thanks to manatwork
<?for(;;)file_put_contents(++$i,file_get_contents("f.php"));

Usage: $ php f.php clones f.php and its code reproducing infinitely itself in filenames like 1, 2, 3...  until timeout.
Previous version:
<?for($i=0;;$i++)$p=fwrite(fopen("$i.php","w"),fread(fopen($f="f.php","r"),filesize($f)));

Usage: $ php f.php clones f.php and its code reproducing infinitely itself like f1.php, f2.php, f3.php ... f(n).php until timeout.

As the clone file name can be anything, why not use just numbers without extension? <?for(;;)file_put_contents(++$i,file_get_contents("f.php"));

Mathematica, 41 bytes
For[a=0,1>0,$Input~CopyFile~ToString@a++]

Full program. Copies its own source file into 0, 1, 2, etc. in the current directory.

awk, 29 (21) bytes,
{while(close(i++)||1)print>i}

awk is not really the tool for this as it requires close() when running indefinitely. Otherwise all it produces are empty files.
If the clone count had a limit, for example 5:
{while(++i<5)print>i}

the program would be 21 bytes.
Paste the program to a file a and run:
$ awk -f a a

Python, 69 bytes
a=open(__file__).read()
i=0
while 1:i+=1;open(`i`+'.py','w').write(a)

I tried using a for the file name, but (unsurprisingly) Windows does not like files named a=open(__file__).read()\ni=0\nwhile 1:i+=1;open(i+'.py','w').write(a). I also tried this:
a=open(__file__).read()
i=''
while 1:i+='.py';open(i,'w').write(a)

However it gives me this error:
Traceback (most recent call last):
  File "C:/Python27/codeGolfCopy.py", line 3, in <module>
    while 1:i+='.py';open(i,'w').write(a)
IOError: [Errno 2] No such file or directory: '.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py'

It creates 83 files, but that is not even close to the needed 1000.
If you would like to remove these files, you can use this:
import os;i = 1
while 1:os.remove(`i`+'.py');i+=1

source: Stack Exchange

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

sort: votes


text:
What time is it in unicode?
The challenge is simplistic, given an input time as a string in any one of the following formats:
hh, hh:mm or hh:mm:ss with 0 ≤ hh ≤ 23, 0 ≤ mm ≤ 59 and 0 ≤ ss ≤ 59.
Output what time it currently is using the following symbols:
AA  LABEL FOR CHARACTER     CODE POINT   HEXADECIMAL
==  ====================    ==========   ===========
  Clock Face 01 Oclock    128336       0x1F550
  Clock Face 02 Oclock    128337       0x1F551
  Clock Face 03 Oclock    128338       0x1F552
  Clock Face 04 Oclock    128339       0x1F553
  Clock Face 05 Oclock    128340       0x1F554
  Clock Face 06 Oclock    128341       0x1F555
  Clock Face 07 Oclock    128342       0x1F556
  Clock Face 08 Oclock    128343       0x1F557
  Clock Face 09 Oclock    128344       0x1F558
  Clock Face 10 Oclock    128345       0x1F559
  Clock Face 11 Oclock    128346       0x1F55A
  Clock Face 12 Oclock    128347       0x1F55B

In the following format:
It is currently {Clock Face 1} with {mm} minutes and {ss} seconds until {Clock Face 2}.

Examples (Including all fringe cases):
Case with only hours...
f("12") = "It is currently ."

Case with hours and minutes...
f("12:30") = "It is currently  with 30 minutes until ."

Case with only hours, but has minutes included as 00...
f("12:00") = "It is currently ."

Case with hours, minutes and seconds...
f("12:30:30") = "It is currently  with 29 minutes and 30 seconds until ."

Case with hours and minutes, but has seconds included as 00...
f("12:30:00") = "It is currently  with 30 minutes until ."

Case with hours and minutes, with less than a minute until the next hour...
f("12:59:59") = "It is currently  with 1 seconds until ."

You do not have to change from plural to singular.

Case with hours and minutes, with 1 minute to the next hour...
f("12:59") = "It is currently  with 1 minutes until ."

You do not have to change from plural to singular.

Case using military time (yes you must handle this)...
f("23:30:30") = "It is currently  with 29 minutes and 30 seconds until ."

Invalid cases...
f("PPCG") = This cannot occur, you are guaranteed a valid format by the definition of the problem.
f(66:66:66) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.
f(24:60:60) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.

You do not have to conform to any style of output for invalid cases, errors are fine.

Overall the challenge is rather simplistic, but seemed to be dynamic enough to be fun in my opinion. The shortest code here is the winner as there isn't much variable aspect to the code other than length.

Closely related.

Should this be a whole program or is a function/lambda enough?

I think that instead of 0 < hh < 24, 0 < mm < 60 and 0 < ss < 60, you meant 0 ≤ hh ≤ 23, 0 ≤ mm ≤ 59 and 0 ≤ ss ≤ 59.

Assume UTF-8, do the clock emojis count full byte count, or none, or one byte?

@devRicher http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet?answertab=votes#tab-top also, use byte counting utilities like http://bytesizematters.com/ to determine the answer to the second question. The clock, if used directly in your code, counts for 4 bytes.

Is a language specific Date/DateTime struct allowed as input?

@devRicher No, the input is a string, exactly as described.

Why do we have to support military time? It doesn't add much to the challenge.

@EasterlyIrk hh%12 isn't hard to support either.

@JamesHolderness updated with answers, if the quantity of the time is 0, you drop it. You do not have to change plural versions to singular versions.

Case 12:00:01 should be with 59 minutes and 59 seconds until ... Correct?

@carcusocomputing You specify that the code must handle 24 hour time, does the code have to handle AM or PM tags?

If the language only supports UCS-2, would it be OK to output the 2 characters that would produce the clock symbol if they were UTF-16?

@12Me21 if it's a limitation of the language you may, but that limitation must be explained in depth.

May we, if need be, take the input as a string in brackets ([HH:MM:SS]) rather than in double quotes ("HH:MM:SS")?

@R.Kap yeah sure.

JavaScript (ES6), 201
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):''))

Less golfed
t=>(
  T=h=>String.fromCodePoint(128336+h%12),
  [h,m,s]=t.match(/\d+/g),
  'It is currently '+T(h-=~10)
   +(
      // if seconds is not 0, increment m else just convert to number
      // have to use '- -' to force conversion to number
     (m -= - !!-s)
-s?++m:m)
      ? ` with ${60-m ? 60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h)
      : ''
    )
)

Test

F=
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):'')
)

var tid=0

function getTime(t)
{
  var a=t.match(/\d+/g)
  if (a) {
    var [h,m,s]=a
    h|=0, s|=0, m|=0
    if(h>=0 & h<24 & m>=0 & m<60 & s>=0 & s<60)
      return [h,m,s]
  }
  return null
}

function update()
{
  clearTimeout(tid)
  var t=I.value, a=getTime(t)
  if (a) {
    O.textContent = F(t)
    tid = setTimeout(again,5000)
  }
  else {
    O.textContent = 'invalid ' + t
  }
}
function again()
{
  var t=I.value, a=getTime(t)
  if (a) {
    var [h,m,s]=a
    ++s>59?(s=0,++m>59?(m=0,++h):0):0
    h%=24
    s<10?s='0'+s:0
    m<10?m='0'+m:0
    t = h+(-m-s?':'+m+(-s?':'+s:''):'')
    I.value = t
    O.textContent=F(t)
    tid = setTimeout(again, 1000)
  }
}

update()
#O { font-size:16px }
Time <input id=I value='12' oninput='update()' onkeydown='update()'>
(modify current time as you wish - but use valid values)

I don't know how to select a winner for this, you both posted within 2 minutes of each other with 201 bytes in the same language.

@carusocomputing of course you should select me. Me. ME ME ME! ...

@carusocomputing or else you could select the answer that has less votes (with no reason) just to regain a balance

Or you could replace the word String in your code with "" an empty string to save yourself 4 bytes :). Ah, crap, he can too though.

Shows It is currently  with 60 minutes until . I think it should It is currently .

@RomanGräf fixed, thanks for noticing

Befunge, 256 250 bytes
>&~85+`v
8~-&"<"_00v`+5
0v%\-&"<<"_
v>:00p!!-"<"%10p65++:66+%0" yltnerruc si tI">:#,_$"Hu 5x"2*,3*,+,2*+,10g00g+
_".",@,".",+*2,+,*3,*2"x5 uH"%+66+1$_,#!>#:<v0
" litnu  htiw ",,,,,,10g:>#v_$"sdnoces"00g.^>
_>,,,,,,,>" dna ">,,,,,00^ >."setunim"00g!#^

Try it online!
The results are encoded as utf-8, since that works best with TIO, but if you're testing locally, you may need to adjust your system's default code page to see the clock faces correctly. Otherwise just redirect the output to a file and open that in a utf-8 compatible editor.
Explanation
The first three lines read the hours minutes and seconds from stdin, checking for EOF or a linefeed after each value, and substituting zeros for the componenents that are missing from the input. On line four, we adjust the minute value if the seconds are non-zero, convert the hour value into the range 0 to 11 (to match the appropriate unicode character for each hour), and write out the initial part of the output, including the the first clock face.
It's at this point that we need to follow different branches depending on what components are non-zero. The first test, at the start of line five, just checks if both minutes and seconds are zero. If so, we write out a final . and exit. Otherwise lines six and seven deal with the remaining cases - writing out the appropriate text and values, before the paths all combine again on line five to write out the final clock face (executing right to left).

JavaScript (ES6), 201 bytes
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minutes`:``}${+s&&m?` and `:``}${+s?60-s+` seconds`:``} until `+c(-~h):``}.`

226 bytes if you take plurals into account:

f=
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minute`+(m-1?`s`:``):``}${+s&&m?` and `:``}${+s?60-s+` second`+(59-s?`s`:``):``} until `+c(-~h):``}.`
<input oninput=o.textContent=f(this.value)>

PowerShell, 250 243 bytes
$h,$m,$s=$args-split':'
$f={[char]::ConvertFromUtf32(128336+(11+$args[0])%12)}
$u=(60-$s)%60
$v=(59-$m+!$u)%60
"It is currently $(&$f $h;"with $(("$v minutes"|?{$v}),("$u seconds"|?{$u})-match'.'-join' and ') until $(&$f (1+$h))"|?{$u-or$v})."

Try it online!

C, 241 bytes
Writes UTF-8 to stdout.
#define p printf(
c(v,h){p"%s \xf0\x9f\x95%c",v,144+h%12);}f(t){int h=0,m=0,s=0;sscanf(t,"%d:%d:%d",&h,&m,&s);m=(59-m+!s)%60;c("It is currently",h-1);m&&p" with %d minutes",m);s&&p" %s %d seconds",m?"and":"with",60-s);m|s&&c(" to",h);p".");}

Try it online!
Code with whitespace:
#define p printf(

c(v, h) {
    p"%s \xf0\x9f\x95%c", v, 144 + h % 12);
}

f(t) {
    int h = 0, m = 0, s = 0;

    sscanf(t, "%d:%d:%d", &h, &m, &s);
    c("It is currently", h - 1);
    m = (59 - m + !s) % 60;
    m && p" with %d minutes", m);
    s && p" %s %d seconds", m ? "and" : "with", 60 - s);
    m | s && c(" to", h);
    p".");
}

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


text:
A challenge about colours

Above, you can see an image full of different colours.
Click here for a hex-dump.
One possible way to generate this image is by using a linear gradient rotated 90 degrees, however, this may not be the only way.
Your task is to create a self-contained program that takes no input, and outputs an image with the same RGBA pixels as the above image, and in the exact same location, with the output image being in a file format that was created before this challenge, with the dimensions of the image being 4096x4096px, same as the original.
The shortest such program, scored in bytes, is the winner.
Cheating and standard loopholes are not allowed.

Related

Earlier versions of this challenge in the sandbox weren't [tag:code-golf], but this version is. I'll go fix the tags for the OP.

What should the dimensions of the image be?

@Kritixi Lithos 4096x4096px.

I assumed them to be 255x255px and have already posted my answer

@Kritixi Lithos Sorry for not making it clear then, you'll have to modify your answer.

No alpha channel is present in the posted image. There is just a change in colors, slowly going to all white

I have already checked. Using 'save image' in the browser, the saved png file has no alpha channel. Probably the PPCG site modified your original image. But in fact there is no image to compare with (and I will not parse the hex dump to get the image back)

How is this thing generated, please properly define this better.

This image file: https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Hue_alpha_2.svg/4096px-Hue_alpha_2.svg.png has no alpha channel according to my tools

For instance: http://exif.regex.info/exif.cgi gives Color Type RGB. When an alpha channel is present, it gives Color Type RGB with Alpha

Voting to close because I think it should be stated how the pixels are arranged, rather than leaving that as an exercise to the solver. Describe the image.

@TheBitByte Anyone could brute force it, but it's recognizing the pattern that's hard. Note that some people saw the pattern on their own, but you should put the info in the question anyway.

@TheBitByte It's not saying how to code it, it's specifying the pattern. Look at ANY other graphical output challenge, like the flag ones. The don't just give an image, they specify the dimensions and widths and how the image is generated. Simply saying "output this image. The end." isn't enough.

If you don't know how it's specified or created, you probably shouldn't make a challenge on it. The HTML answer seems to see it as a linear gradient rotated 90deg.

Processing, 197 195 bytes
void setup(){size(255,255);int r=255,a=r,g=0,b=0,i,j,k;background(a);for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)for(j=0;j<a;point(i,j++))stroke(r,g,b,a-j);}

This outputs the image in a 255x255 sized window
Explained
void setup(){            //this is required
  size(255,255);         //size of sketch
  int r=255,a=r,g=0,b=0,i,j,k; //declaring our vars
  background(a);         //set the background colour as white
  //for-loop for the x-coordinates, it also increments/decrements rgb values
  //  based on the x-coordinate
  for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)
    //for-loop for the y-coordinate (alpha)
    for(j=0;j<a;point(i,j++))   //2) then draw the point at the location
      stroke(r,g,b,a-j);        //1) set the colour of point
}

Edits

Used int instead of float
THIS SOLUTION IS INVALID DUE TO NEW RULES BEING ADDED. I WILL UPDATE ANSWER SOON

Where is update?

Python, 407 404 381
I just golfed the svg
d='<svg HBdefsTg"BS G"N:redM0YyellowM0.17Y#00ff00M0.33YcyanM0.5YblueM0.67Y#ff00ffM0.83YredM1"/B/LTw" x1Ex2Ey1Ey2="1"BS G"N:white;F:0" O"0YwhiteM1"/B/LB/defsUgVUwVB/svg>'
for R in zip("VTBUEYMNFGOHSLX",')" xEyEH/|BL id="|><|><rect fill="url(#|="0" |"/><S G"N:|;F:1" O"|S-color|S-opacity|style=|offset=|widthXheightX|stop|linearGradient|="4096" '.split('|')):d=d.replace(*R)
print d

A raster image can be generated using imagemagick :
~$ python snippet.py |convert svg:- hue.png
~$ file hue.png
hue.png: PNG image data, 4096 x 4096, 8-bit/color RGBA, non-interlaced

@TheBitByte the generated SVG starts with, <svg width="4096" height="4096" > so yes

HTML/CSS, 166 bytes

p{width:4096px;height:4096px;background:linear-gradient(0deg,#FFF,#FFF0),linear-gradient(90deg,red,#FF0 18.513%,lime 34.256%,aqua 50%,blue 65.43%,#F0F 81.199%,red)
<p>

Requires a browser that supports #RGBA colours, such as Firefox 49, Chrome 52 or Safari 9.1. I've taken the stops from the original SVG and rounded them to 5sf as that shouldn't make any difference on a 4096 pixel image, but if it does, they could be restored at a small cost. On the other hand, if rounding to either 4sf or whole pixels is OK, then that saves me a further 4 bytes.

@TheBitByte Sorry I didn't actually try it on Chrome or Safari, I just looked up the compatibility info which suggested that Chrome 52 should work.

R, 95 91 88 bytes
frame();n=4096;for(i in 1:n){l=matrix(NA,n,n);l[,i]=1:n;image(l,a=T,c=rainbow(n,s=i/n))}

When creating plots in while running an R script, by default they are saved to file, either as PNG or PDF. My PC struggles creating the 4096x4096 pixel plot taking up gigs of RAM, but if I change n to 256 it matches the correct output.
There are probably some bytes to be saved by making the arguments of image shorter, but I'll look at that when I get the supposed output.


text:
ASCII Jigsaw Puzzle
This is a 3x3 ASCII jigsaw puzzle:
 _____ _____ _____
|    _|     |_    |
|   (_   _   _)   |
|_   _|_( )_|_   _|
| (_) |_   _| (_) |
|  _   _) (_   _  |
|_( )_|_   _|_( )_|
|    _| (_) |_    |
|   (_       _)   |
|_____|_____|_____|

This is also a 3x3 ASCII jigsaw puzzle:
 _____ _____ _____
|     |_   _|     |
|  _   _) (_   _  |
|_( )_|_   _|_( )_|
|    _| (_) |_    |
|   (_   _   _)   |
|_   _|_( )_|_   _|
| (_) |_   _| (_) |
|      _) (_      |
|_____|_____|_____|

Each line in a ASCII jigsaw puzzle (excluding the edge cases i.e. the pieces literally on the edges) consists of the following pattern:
   _           _           _
 _( )_ _   _ _( )_ _   _ _( )_
|_   _| (_) |_   _| (_) |_   _|
 _) (_   _   _) (_   _   _) (_
|_   _|_( )_|_   _|_( )_|_   _| ...
  (_)         (_)         (_)

Given 2 integers H and W where H is the height (vertical amount) and W is the width (horizontal amount) and H and W are >1 output a possible HxW ASCII jigsaw puzzle.
Examples
Test Case 1
Input: 2, 4
Output:
 _____ _____ _____ _____
|     |_   _|     |_    |
|  _   _) (_   _   _)   |
|_( )_|_   _|_( )_|_   _|
|    _| (_) |_   _| (_) |
|   (_       _) (_      |
|_____|_____|_____|_____|

Test Case 2
Input: 4, 4
Output:
 _____ _____ _____ _____
|     |_   _|     |_    |
|  _   _) (_   _   _)   |
|_( )_|_   _|_( )_|_   _|
|    _| (_) |_   _| (_) |
|   (_   _   _) (_   _  |
|_   _|_( )_|_   _|_( )_|
| (_) |_   _| (_) |_    |
|  _   _) (_   _   _)   |
|_( )_|_   _|_( )_|_   _|
|    _| (_) |_   _| (_) |
|   (_       _) (_      |
|_____|_____|_____|_____|

Test Case 3
Input: 3, 5
Output:
 _____ _____ _____ _____ _____
|     |_   _|     |_   _|     |
|  _   _) (_   _   _) (_   _  |
|_( )_|_   _|_( )_|_   _|_( )_|
|    _| (_) |_   _| (_) |_    |
|   (_   _   _) (_   _   _)   |
|_   _|_( )_|_   _|_( )_|_   _|
| (_) |_   _| (_) |_   _| (_) |
|      _) (_       _) (_      |
|_____|_____|_____|_____|_____|

Test Case 4
Input: 2, 2
Output:
 _____ _____
|    _|     |
|   (_   _  |
|_   _|_( )_|
| (_) |_    |
|      _)   |
|_____|_____|

Clarifications

The height and width for each puzzle piece should not be scaled up or down.
With H and W being greater than one, the smallest dimensions possible are 2x2 (see IO 4).
You can have a full program or a function.
The input will be 2 lines with H on the 1st and W on the 2nd if you're using a function you can have them in the parameters.
Output to stdout (or something similar).
This is code-golf so shortest answer in bytes wins.

Must the tabs of the pieces be in alternating directions?

Should I output at random or can I output just one puzzle each time around? If at random, should all puzzles be uniformly available?

@Zgarb yes, i edited in the basic pattern each line in the jigsaw puzzle follows

@zyabin101 you just need to output a possible "ASCII jigsaw puzzle" so only 1 output for 1 input

First attempt is looking like it is going to end up at about a megabyte. Nice question.

@ElPedro thx :)

Assuming per your spec that dimensions of 1 are allowed, it might be nice to add a 1xn and/or nx1 test case.

Can you relax the input format? This challenge clearly isn't about parsing a string, so I'd allow any program or function that takes two numbers, in any format.

@HWalters your right this isn't clear, i totally forgot to mention this. the dimensions are any integers >1 ... give me sec ill edit this in

@RainerP. sorry, ill change the format…

JavaScript (ES6) 272 277 271
Edit bug fix
Edit 2 saved 6 bytes thx @L.Serné
Edit 3 bug fix again
(w,h,z=(s,q=3,i=h)=>'|  '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+`  |
`.slice(~q))=>eval("t=z(' _____',0,0)+z('|_   _|     ',2,--h)+z(b=' _) (_   _  ')+z(c='|_   _|_( )_',0);for(a='|_   _| (_) ';--h;)t+=z(a,2)+z(b)+z(c,0)")+z(a,2)+z(' _) (_      ')+z('|_____',1)

Less golfed
(w,h,
  z=(s,q=3,i=h)=>'|  '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+'  |\n'.slice(~q),
  a='|_   _| (_) ',
  b=' _) (_   _  ',
  c='|_   _|_( )_',
  t=z(' _____',0,0)+z('|_   _|     ',2,--h)+z(b)+z(c,0)
)=>{
  for(;--h;)
    t+=z(a,2)+z(b)+z(c,0);
  return t+z(a,2)+z(' _) (_      ')+z('|_____',1)
}

Test

F=
(w,h,z=(s,q=3,i=h)=>'|  '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+`  |
`.slice(~q))=>eval("t=z(' _____',0,0)+z('|_   _|     ',2,--h)+z(b=' _) (_   _  ')+z(c='|_   _|_( )_',0);for(a='|_   _| (_) ';--h;)t+=z(a,2)+z(b)+z(c,0)")+z(a,2)+z(' _) (_      ')+z('|_____',1)

function update() {
  var w=+W.value,h=+H.value
  O.textContent=F(w,h)
}

update()
W<input id=W value=2 oninput='update()' type=number min=2>
H<input id=H value=2 oninput='update()' type=number min=2>

Very nice!  The golfed version is giving me trouble, though: Nx2 does not work (e.g. 3x2 yields
undefined|    | () |_    |
|   (_       _)   |
|||_____|
and submitting an odd height results in the top-right piece missing its top border.  Looks like something got lost in golf-lation.
Edit: the "odd height" bug results from both golfed and non-golfed code.

@BenceJoful Not enough test after the last golfing. Now fixed

You could move the declaration of last argument (t) and the fourth argument (a) to the for loop (and move the declaration of b and c inside the declaration of t like this: for(t=z(' _____',0,0)+z('|_   _|     ',2,--h)+z(b=' _) (_   _  ')+z(c='|_   _|_( )_',0);--h;a='|_   _| (_) '). This saves 4 comma's, so you end up with only 273 characters. EDIT: The test snippet is still bugged...

@L.Serné bugged how? You cannot put t=... inside the for, it fails for h==2. It's exactly the bug I fixed today.

@L.Serné thx anyway for the hint about a,b,c.

np, I played around with your code, and the cause of the undefined turned out to be declaring a in the last part of the for loop. I changed the code a bit, and ended up with this. You should be able to integrate that with the eval for another 2B save. (w,h,z=(s,q=3,i=h)=>'|  '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-2*q+1)+'  |\n'.slice(~q),a='|_   _| (_) ')=>{for(t=z(' _____',0,0)+z('|_   _|     ',2,--h)+z(b=' _) (_   _  ')+z(c='|_   _|_( )_',0);--h;)t+=z(a,2)+z(b)+z(c,0);return t+z(a,2)+z(' _) (_      ')+z('|_____',1)} (276 B).

Python, 513 bytes
def r(m,n):
 r=3*m
 c=6*n
 l=3-(n%2)*3
 z=[1,2,3,4,5,0]
 p=zip
 return"\n".join("".join(" |_()"[[[((j%6,i%3)in[(1,0),(5,0)])*2or((j%6,i%3)in[(0,1),(0,0)])or((j%4,i%6)in[(1,1),(1,2),(3,4),(3,5)])*2or((i%6,j%12)in p(z,[10,2,10,4,8,4]))*4or((i%6,j%12)in p(z,[8,4,8,2,10,2]))*3,1,0][j in[0,c]or((j,i%6)in p([1,1,2,2],[1,2]*2)+p([c-1,c-1,c-2,c-2],[1+l,2+l]*2)or(i,j%12)in[(1,8),(1,9),(1,10),(2,8),(2,9),(2,10),(r-1,9)]or(i,j%12)==(r-1,3+6*(m%2)))*2],2*(j%6>0)or i>0][i in[0,r]]]for j in range(c+1))for i in range(r+1))

Perhaps more of an exercise in obfuscation than in golfing, this one works by deciding what character each (x,y) coordinate goes to rather than building up each pattern by string. Ungolfed it looks like
char_codes = " |_()"
def base(row, col):
    if col % 6 in [5] and row % 3 in [0, 2]:
        return 1
    if col % 6 in [0, 4] and row % 3 in [2]:
        return 2
    return 0

def underscores(row, col):
    if col % 4 in [0] and row % 6 in [0, 1] or col % 4 in [2] and row % 6 in [3, 4]:
        return 2
    return 0

def parentheses(row, col):
    if (row % 6, col % 12) in [(0, 9), (1, 1), (2, 9), (3, 3), (4, 7), (5, 3)]:
        return 4
    if (row % 6, col % 12) in [(0, 7), (1, 3), (2, 7), (3, 1), (4, 9), (5, 1)]:
        return 3
    return 0

def value(row, col):
    return base(row, col) + underscores(row, col) + parentheses(row, col)

def new_value(last_row, last_col, row, column):
    if row in [0, last_row]:
        return 2*(column % 6 > 0) or row>0
    if column in [0, last_col]:
        return 1
    if column in [1,2] and row % 6 in [1, 2]:
        return 0
    if column in [last_col - 1, last_col - 2] and row % 6 in [[4,5],[1,2]][last_col%12>0]:
        return 0
    if row in [1, 2] and column % 12 in [8,9,10]:
        return 0
    if row == last_row - 1 and column % 12 == 9:
        return 0
    return value(row - 1, column - 1)

def puzzle(rows, cols):
    last_row = rows * 3
    last_col = cols * 6
    return "\n".join("".join(new_value(last_row, last_col, row, col) for col in range(last_col + 1)) for row in range(last_row + 1))

The patterns themselves look like
we can see this as a lookup table from integers with columns taken mod 6 and
rows mod 3
 012345
0     |
1
2_   _|

 0123
0_
1_
2
3  _
4  _
5

 0123456789AB
0       ( )
1 ) (
2       ( )
3 ( )
4       ) (
5 ( )

This strategy of combining different patterns has not really worked out for me here because expressing them is quite cumbersome (though I think I could have golfed more) and because the edge cases take up so many characters to fix. I'm putting this up regardless because it took me a minute and it might be of interest.

You are able to save 7 bytes by putting the entire thing on 1 line separated by semicolons

@Blue Thanks mate, it's been a while since my last golf and I've forgotten some tricks.

Mathematica, 384 bytes
(m=#~Mod~2&;a=#~Array~Y&;s=(h="   _  ")[o="|_( )_",z="|_   _",w=" _) (_",z,p="| (_) "];l="|  _  "[o,"|    _",u="|   (_",z,p];r=h[o,q="|_    ",t=" _)   ",z,p];{X,Y}=#;a[" _____"&]<>" \n"<>Join[{a[If[#<Y,z,q]["|     "][[m@#]]&]},Table[Which[y<2,l,y<Y,s,0<1,r][[Mod[x+3y,6]]],{x,3,3X-1},{y,1,Y}],{a[If[#<2,"|     "[u],"      "[If[#<Y,w,t]]][[m[X+#]]]&],a["|_____"&]}]~Riffle~"|\n"<>"|")&

Unnamed function taking an ordered pair of integers as its argument, and returning a string containing appropriate newlines. With spaces and newlines added:
(m = Mod[#1, 2] &; a = Array[#1, Y] &;
 s = (h = "   _  ")[o = "|_( )_", z = "|_   _", w = " _) (_", z, p = "| (_) "];
 l = "|  _  "[o, "|    _", u = "|   (_", z, p];
 r = h[o, q = "|_    ", t = " _)   ", z, p];
 {X, Y} = #1;
 a[" _____" &] <> " \n" <>
 Riffle[
   Join[
     {a[If[#1 < Y, z, q]["|     "][[m[#1]]] &]},
     Table[
       Which[y < 2, l, y < Y, s, 0 < 1, r][[Mod[x + 3 y, 6]]],
       {x, 3, 3 X - 1}, {y, 1, Y}
     ],
     {a[If[#1 < 2, "|     "[u], "      "[If[#1 < Y, w, t]]][[m[X + #1]]] &],
     a["|_____" &]}
   ], "|\n"
 ] <> "|") &

Batch, 562 528 bytes
@echo off
set t=!  !
set w=%2
set a= _) (_!_   _! (_) !        _  !_( )_!_   _ _) (_
call:d "!     !_   _" 2 " _____ _____" 4
for /l %%j in (2,1,%1)do call:t
call:d "!_____!_____" 1 "%a:~18,6%%a:~-6%" 3
exit/b
:t
set a=%a:~24%%a:~0,24%
call:d "%a:~6,6%%a:~30,6%" 1 "%a:~0,6%%a:~24,6%" 3
call:c "%a:~12,6%%a:~36,6%" 2
exit/b
:d
call:c %3 %4
:c
set s=
for /l %%i in (%w%,-2,1)do call set s=%~1%%s%%&if %%i==1 call set s=%%s:~6%%
if %2 lss 4 set s=%s%!&call set s=%%t:~0,%2%%%%s:~%2,-%2%%%%t:~-%2%%
echo %s:!=^|%

Proved resistant to golfing, as the repetition tended to cost too many bytes to eliminate, for example, I manually pass in the line number mod 3 because it's too expensive to compute. Edit: Furthermore, I had inadvertently golfed extra |s every third line, which is incorrect. Fixing this actually saved me 2 bytes (4 bytes on my original version). Explanation: a contains various bits of jigsaw. The :t function swaps them over each set of three rows, then extracts the required substrings which the :c function then repeats in pairs, but deleting the first column if w is odd. The left and right edge cases are then handled before the row is output. The other edge case is the very first row in which the !s are changed to spaces instead of |s (the code avoids |s because they are tricky to handle in Batch).

Befunge, 263 243 bytes
|_   _| (_)
 _) (_   _
|_   _|_( )_

|
|
|_____
 _____
>&:08p3*28p&:18p6*38pv
@#!`g82:,_v0+55+1p84:<_
\g82+g84<| `g83:+1,g\%*6-g852+*6/3+2g84\++%3+2\!:g84*4p85:!!+*`0%6\!*`
6/08g+2%^>>::::48g3/2%2*`\48g3/18g+2%!2*+38g\`*!48g3%0`*\::6/2%!48g\`\

Try it online!
The way this works is by iterating over the x,y coordinates of the area we want to output, and mapping those x,y values to u,v coordinates in the puzzle pattern (stored on the first three lines of the playfield). This mapping is achieved with the following basic formulae:
u = (x+(y+2)/3*6) % 12
v = (y+2)%3 + (y==0)

The u coordinate repeats every 12 columns, but also needs to be offset by 6 every 3 rows. The v coordinate repeats every 3 rows, but we add y==0 to the value so the very first row can be rendered as a special case. However, to handle the edges, we need to introduce an additional boolean value, e, which is true for various edge locations, and which adjusts the formulae as follows:
u = (x+(y+2)/3*6) % (e?6:12)
v = (y+2)%3 + (y==0) + e*4

Thus if we're on an edge, we add 4 to the v coordinate so as to use the simpler edge pattern on lines 5 to 7. And we also now need to mod the u coordinate by 6 rather than 12, since this edge pattern repeats every 6 columns.
As for the e value itself, that requires a fairly complex formula, since the edge locations encompass a somewhat irregular area of the puzzle border.
elr = (x <= 2*y/3%2 or x >= w-2*!(y/3+cols)%2) and (y%3 > 0)
etb = (y <= !(x/6%2) or y >= h-(x/6+rows)%2) and (x%6 > 0)
e   = elr or etb

Without going into too much detail, the basic breakdown is that elr matches the edge locations along the left and right borders, while etb matches locations along the top and bottom borders.

JavaScript (ES6), 285 bytes

f=
(h,w,a=` _) (_|_   _| (_)    _  |_( )_|_   _      |     |_____`.match(/.{6}/g),g=(l,r,j)=>a[7].slice(0,j)+(a[l]+a[r]).repeat(w).slice(j,w*6+1-j)+`  |`.slice(-j))=>[` _____`.repeat(w),g(1,7,2),...[...Array(--h*3)].map((_,i)=>g(i%6,(i+3)%6,"312"[i%3])),g(h=h%2*6,6-h,3),g(8,8,1)].join`
`

<input id=h type=number min=1><input id=w type=number min=1>

This is a port of my Batch answer, just to see whether it competes with @edc65's answer. The annoyingly long string contains jigsaw pieces. The first six pieces represent two rows of one column of the interior of the jigsaw. The seventh piece is used for the penultimate line of the jigsaw, in place of the fourth piece. The eighth piece is used on the second line of the jigsaw, in place of the fifth piece, and also does double duty as the left edge of the jigsaw. The ninth piece is the last line of the jigsaw.


text:
Animate tacky light decorations
This challenge is in honor of the tacky Christmas lights at my in laws' house.

The challenge is to create a graphical output showing the decoration in "real time".
The video (gif or other format) will have n-by-m vertical and horizontal "lights". 5 <= m,n <= 40. The frame size and resolution may vary dependent on n  and m, but must be at least 50x50 pixels for n,m=5 (vector graphics is OK). A picture with n=6 and m=5 will look something like this:

The decoration:
Colors:
All lights will have one of the following 6  RGB-colors {255,0,0}, {0,255,0}, {0,0,255}, {255,255,0}, {0,255,255} and {255,0,255}.
Animation:

n and m will be taken as input on any reasonable format and in the order you like
The image will change every dt = 25 ms. Deviations are OK if it's due to "outside factors" such as limitation in the interpreter, slow computer etc.

If it's impossible to set the time step manually, then the default time step is accepted.

All lights will be red ({255,0,0}) at t=0.
There's always a 5% chance that the first light (top-left) will change color. All colors (except the color it currently has) should be equally likely.
Each light (except the first) will get the color of the light to its left. If the light is at the far left then it will get the color of the light on the far right on the row above. The lights are numbered as shown below. Light number k will get the color of the light number k-1.
 1  2  3  4  5  6
 7  8  9 10 11 12
13 14 15 16 17 18

The output should in theory run for ever (unless your language / interpreter has some limitation that prevents this).
Please provide a sample of at least 5 seconds, preferably more in the answer (this is an encouragement, not a requirement). (A link to TIO or similar is of course OK too :D )
Frames, axes, grid lines etc are accepted.

6-by-5

15-by-30

If the interpreter is slow, should be adjust the pause time so the total time between image updates is similar to that in the examples? What about if the pause is not needed (the code is already slowe enough)? That would save bytes, maybe against the spirit of the challenge

Since you picked the colors for ease of implementation--in languages like QBasic that have a limited builtin set of colors, is it acceptable to use the closest available colors to the ones you specified? (Red, green, blue, yellow, cyan, magenta)

If it's impossible to use the specified colours then yes, it's ok to use the closest alternatives. If it's just a bit longer then no. r,g,y,b, etc are shorter in several languages.

@LuisMendo, apologies for the late reply. I like the way you did it in your answer. It would be OK to use 25 ms, even if that would make the animation slower. I avoided drawnow when I implemented this in MATLAB, since the result was too slow. I think the answer must be: If it's a design choice that the interpreter has a fixed minimum time resolution of >=25 ms then it's OK. If it's due to poor/simple implementation, an online interpreter that is overloaded/slow etc. then it's not OK.

@Stewie Got it, thanks. And nice challenge!

How exactly did you implement this in MATLAB? For me, simply calling imshow on each step takes >.07 seconds for a 15x15 image; did you use a trick to make it faster, or is my laptop dying slowly?

@Sanchises I wrote it to a gif using imwrite with 'DelayTime',0 and pause(0.025) (it might be the other way around (no pause, but 'DelayTime',0.025)). After timing the gif it looks like there was an additional 3 ms delay per step. 0.07 seconds was very slow, but it might be just as slow for me. I don't have MATLAB here so I can't test it.

@Sanchises, have you tried running Chelsea's answer? Is imagesc equally slow?

Oh OK. I'll check later, but at least I know what's what. Is the delay due to MATLAB's massively slow imshow acceptable or should I write to a gif?

MATLAB, 255 210 bytes
This is my first golf, so there are probably improvements to be made.
Thanks to Luis for helping me save 45 bytes :)
function f(n,m)
c=dec2bin(1:6)-48;r=1;p=c(r,:);x=zeros(1,n*m,3);x(:,:,1)=1;while 1
x=circshift(x,[0,1,0]);if rand>0.94;r=randi(6);end
x(1,1,:) = c(r,:);imagesc(permute(reshape(x,n,m,3),[2 1 3]));pause(1/40);end

Explanation:
c=dec2bin(1:6)-48  % c is the colormap
r=1;p=c(r,:);                % p is color number r (starting at 1) from the colormap c
x=zeros(1,n*m,3);x(:,:,1)=1; % 2D matrix in the third dimension. The first layer is 1
while 1                      % while true
x=circshift(x,[0,1,0]);      % shift the vector horizontally along the second dimension
if rand()>0.94;              % 5 percent chance of changing color
k=randperm(6);k=k(k~=r);r=k(1); % Create a vector with color numbers 1..6. Discard the current color, and choose the first color
x(1,1,:) = c(r,:);           % The first light gets color number r
imagesc(permute(reshape(x,n,m,3),[2 1 3]));  % Reshape the vector so that it's a 3D matrix
% Permute it so that the dimensions are correct
% Use imagesc to display
pause(1/40)  % 0.025 seconds pause

Unfortunately, this doesn't save the animation, it just runs it. In order to save it I either need a screen capture program, or rewrite it all using imwrite. Instead, I'll provide two pictures showing different times, for n=15,m=30.

Some golfing suggestions: dec2bin([4 2 1 6 3 5])-48 instead of [1 0 0;0 1 0;0 0 1;1 1 0; 0 1 1;1 0 1]. .95 instead of 0.95. You can also replace .95 by .94 and get rid of k=k(k~=r); (because 0.94 + 0.06/6 = 0.95; see my answer for a more detailed explanation)

Better yet, c=dec2bin(1:6)-48, as order doesn't matter

Nice first answer! However, I'm afraid I have outgolfed you by 40%.

Golfed it down a bit :) Thanks for the help Luis. ! :) Well done Sanchises!

Mathematica, 186 161 158 bytes
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[Pause@.025;If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];b=RotateRight@b;b[[1]]=b[[2]];b,#],ImageSize->50#])&

Explanation
b=Table[{1,0,0},1##];

Create the initial board in 1D, filled with red. Store that in b.
Pause@.025

Pause for 25ms
If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3]

If a (pseudo-)random real number is less than 0.06, replace the first element of b with a random sample length 3 of the list {1,1,0,0}. (i.e. any one of {1, 1, 0}, {1, 0, 1}, {1, 0, 0}, {0, 1, 1}, {0, 1, 0}, {0, 0, 1})
b=RotateRight@b

Cyclic rotate right.
b[[1]]=b[[2]]

Change the first cell value to the second cell value (i.e. undo the shift of the first cell)
Partition[ ... ;b,#]

Partition b into (height).
Dynamic@Image[ ... ,ImageSize->50#]

Make that into a dynamic (constantly updating) image, whose width is 50(width)
Cellular automaton version (186 bytes)
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[Pause@.025;If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];i=2;b={#[[2-Boole[i--<0],2]]&,{},{1,1}}~CellularAutomaton~b,#],ImageSize->50#])&

Sample Output (inputs: 16, 10)

JavaScript/CSS/HTML, 436 bytes

b="red"
f=_=>{o.textContent='';o.style.width=w.value*10+"px";o.style.height=h.value*10+"px"}
setInterval(_=>o.insertBefore(document.createElement("s"),o.firstChild).style.background=b=["red","yellow","lime","aqua","blue","fuchsia"][Math.random()*100|0]||b,25)
#o{overflow:hidden;background:red}s{display:block;float:left;width:10px;height:10px}

<input id=h type=number min=1><input id=w type=number min=1>

MATL, 52 47 bytes
6:BoHZGKipY"`tGe!2YG50Yr3>?t1)}6Yr]0(1YS.015Y.T

Input is an array [ncols nrows]. Output is a figure with vector graphics.
Example run for 15 cols × 10 rows:

How it works
Pause time has been set to 15 ms (for the same byte count as 25 ms) to try  compensate for the processing time.
To keep the color with 19/20 probability (change it with 1/20), we proceed as follows:

With 47/50 probability we keep the color.
With 3/50 probability we pick a new color choosen uniformly among the 6 colors. It may happen that the "new" color is the same as the old, and this occurs with probability 1/6.

Thus the probability of keeping the color is 47/50 + 3/(50*6) = 19/20.
6:        % Push [1 2 3 4 5 6]
B         % Convert to binary. This gives a 6×3 matrix, where each row
          % corresponds to a number. First row is [0 0 1] (blue), second is
          % [0 1 0] (green), etc
o         % Convert to double
HZG       % Set as colormap (creates a figure)
K         % Push 4
i         % Take input array
p         % Product of array. This gives the total number of squares
Y"        % Repeat 4 that many times. This gives a row vector representing the
          % image. The initial value, 4, corresponds to red in the colormap
`         % Do...while
  t       %   Duplicate
  Ge      %   Reshape to size given by the input. Gives a matrix where each
          %   entry  will be interpreted as a pointer to the colormap
  !       %   Transpose. This is required because the color shifting will be
          %   done in column-major order: down, then across; whereas we want
          %   the opposite
  2YG     %   Show matrix as image using the defined colormap
  50Yr    %   Push a uniformly distributed random integer between 1 and 50
  3>      %   True if greater than 3. This happens with probability 47/50
  ?       %   If true
    t1)   %     Duplicate and get first entry (to repeat the first color)
  }       %   Else
    6Yr   %     Push a uniformly distributed random integer between 1 and 6.
          %     This is the new color (possibly the same as the old)
  ]       %   End
  0(      %   Assign that color (repeated or new) to the last entry of the row
          %   vector representing the image
  1YS     %   Circularly shift to the right. The last value becomes the first
 .015Y.   %   Pause 0.015 ms
 T        %   Push true
          % End (implicit). Since the top of the stack is true, this creates
          % an infinite loop

MATLAB, 153 147 bytes
Note: The GIF shown is of the older version, which is nice as it does not display axes (see edit history), but was extremely slow due to the implementation of imshow. For the current version, Chelsea G.'s MATLAB answer or Luis Mendo's MATL answer show the same result as my current version.
Size is taken as a 2x1 vector, so call as e.g.:
>> l([5 5])

function l(s)
c=eye(3);x=eye(s);while 1
a=rand>.94;x=[a*randi(6)+~a*x(1),x(1:end-1)];imagesc(reshape(x,s)',[1,6]);colormap([c;1-c])
pause(.025)
end

This answer exploits the subtleties of the MATLAB language. For example, x is initalized as an m x n zero matrix, but so-called linear indexing allows for circular shifting with 1-dimensional indices. Weak typing allows for multiplication with logicals, so that if statements are avoided (a trick I heavily used back in the days of programming on a TI-84 calculator). Even though a colormap is read row-wise, MATLAB treats it as a normal matrix, so that eye(3) can be used to create red, green and blue, and 1-eye(3) the other three colours. A simple reshape brings the linear vector back into matrix form, which is mapped to the desired colours using ind2rgb. Finally, imagesc, shows the image, shown at default figure size (which is big enough for the requirements). As luck would have it, imagesc does not mind values being outside the specified range, so eye can be used to initialize the matrix since both 1 and 0 are considered red.

Oops, forgot to upvote you... I love all your small tricks :-)

Is it correct that the random color never is red in the updated version? It appears that way in Octave at least (don't have MATLAB).

@StewieGriffin I must've been sleeping when I made this. You are of course perfectly right - and it saved me a byte as well...

(make that two bytes)

Python 3.6 (316 Bytes)
Using ANSI colour codes and the new formatted string literals of Python 3.6 (PEP 489) (the f"{X}" magic).
Otherwise it’s just pretty basic, but obfuscated python. Width and Height are passed as arguments on the command line.
import random as n,time,sys
r=range
X="\x1b["
C=[f"{X}1;4{x}m " for x in r(1,7)]
w,h=list(map(int,sys.argv[1:]))
a=[C[0]for i in r(w*h)]
while 1:
 print(f"{X}0m{X}2J{X}f");f=a[0];a.pop();a[:0]=n.choice([x for x in C if x!=f])if n.random()<=.05 else f,
 for i in r(0,h*w,w):print(*a[i:i+w],sep="")
 time.sleep(.025)

You can spare 6 bytes by using w,h=map(int,sys.argv[1:]), unpacking works with any iterable (of the right size), the call to list is superfluous.

Another few byte down: "\x1b[" => "\33[" (using octal instead of hex escapes), then the X abbreviation and the format strings actually make it longer (and by getting rid of f"" you get compatibility with any python3). (this will bring it down to 301 bytes).

Oops, you use {x} once ... but you still win with getting rid of X.

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


text:
Close your tags!
This is based off a previous deleted challenge of mine with the same name
Introduction
You are tasked with writing a program that returns a truthy or falsey value based on if the input has all its XML-like1 tags appropriately opened and closed and in the right order. Consider the following as input:
<Apple>

This would return a falsey value because the tag is not closed correctly. This:
<Apple></Apple>

On the contrary returns a truthy value because it is closed correctly. The program should also check nested tags to make sure they are in the correct position. For example, take this as input:
<mango><Apple></mango></Apple>

All the tags are closed correctly, but not in the correct order. Your program must check for correct tag hierarchy and nesting.
Definitions
Let me define a few things before I get into the rules and assumptions.
Tag
A basic XML-style tag. For example: <Apple>. They can have at most, one leading and trailing space (or else it's invalid and falsey), so < Apple > and <Apple> are the same.  These tags can also contain attributes like foo="bar" (with required double quotes, or else invalid and falsey), and the attribute name can only contain any alphanumeric character or _, :, -, and .. The attribute names also do not require an attribute value, and values can contain anything except " before the closing double quote. The closing tag must not contain attributes, and no tags should have newlines in them.
Tag Name
Tag names are the tags' names. For example, <Apple>'s tag name is Apple. Tag names can contain the same characters as attribute names, and are case-sensitive. This means <Apple> is not <apple>.
Self-Closing Tag
A regular tag that closes itself such as <Apple /> or <Apple/> (they are the same). The space between the slash and the tag name is allowed.
Plain Text
A string of characters that can contain anything and are not enclosed in < and >.
"Simple" Tag
Either an opening, closing, or self-closing tag.
Rules

Output may be returned or printed, and input may be taken any way you like
Input is a string, consisting of either tags, plain text, or both
Your program can be a function or a whole working program
Plain text can be anywhere; if the input consists only of plain text, the program should return a truthy value.
Recognition of nested tags is required for the program. If a tag is nested in a tag, that nested tag must be closed before the parent is closed, just like regular XML, or else a falsey value should be returned

Assumptions

You can assume that input will always be one or more "simple" tag(s)
You can assume that input will always follow the format for tags defined above

Test Cases
Falsey
<apple>

<apple></Apple>

<apple></mango>

<apple><mango>

Text

<pear attr=foo></pear attr=foo>

<Ketchup flavor=spicy></Ketchup>

<Ap ple></Apple>

Truthy
Text

<Apple />

<Apple></Apple>

< Apple ></ Apple>

<mango><Apple/></mango>

<mango>Text
More text \o/
</mango>

<food group="fruit">Fruits:<orange :fruit-variety="clementine" /><pear _fruit.type="asian" /></food>

<example foo="abcdefghijklmnopqrstuvwxyz1234567890-/:;()$&@.,?!'" noValue>Any characters allowed! (0.0)</example>

Scoring
This is code-golf, so the shortest code in bytes wins. Standard loopholes are prohibited as usual.

1Note: This is not real XML, but a pseudo-XML with different rules for the challenge. Tag and attribute names differ from specification.

If a tag has more than one space before or after it, do we have to mark it false?

@JayDepp Yes - let me clarify that in my post

Can we use builtins that parse strings to XML?

@obarakon The problem is this isn't necessarily valid XML. See the footnote.

Is it correct to say, that this is a truthy input: < : : :><:/><: :=":=:" ::></:>< /:>?

@insertusernamehere Yes, that is truthy.

The attribute names also do not require an attribute value ? Example please?

@edc65 <example attrWithoutVal></example> just like <input required>.

Retina, 76 74 Bytes
+`< ?([-.:\w]+)( ?[-.:\w]+(="[^"]*")?)* ?(/>|>[^<>]*< ?/ ?\1 ?>)

^[^<>]*$

Since I've seen that retina is really good for golfing regexes, I figured I'd try it out. Follows the same logic as my Ruby answer and prints 0 or 1.
Try it online!

You don't need the `M``. If the final stage only has a single part, match mode is implied.

Ruby (2.3.1), 103 101 100 Bytes
->s{s.sub!(/< ?([-.:\w]+)( ?[-.:\w]+(="[^"]*")?)* ?(\/>|>[^<>]*< ?\/ ?\1 ?>)/,'')&&redo;!(s=~/<|>/)}

Anonymous function called by appending .call("<Apple></Apple>"). Substitutes matching or self closing tags until there arent any, and then returns whether the string has no angle brackets remaining.
Try it online!

This marks

 as Falsey, but it shouldn't be.

@orlp 'values can contain anything except " before the closing double quote.'

Oh it's not real XML...

Real XML should never be parsed with regex :)


text:
Optimally reach a number in deadfish!
Goal:
Given any natural number k such that k<256, produce an deadfish program that gives the smallest solution possible.
Background:
Deadfish is a joke esoteric programming language. It has a single unsigned byte of memory, called the accumulator, initialized at 0. There are four commands which form a string.

i = accumulator += 1
d = accumulator -= 1
s = accumulator = accumulator * accumulator
o = print(accumulator)

For example, the string iiisis would produce 100, as this would be the memory after each command:

i -> 1
i -> 2
i -> 3
s -> 9
i -> 10
s -> 100

Specification:

Read a number through any reasonable means (from a file, STDIO, or a function argument), and output an optimal string of commands producing that number.
A solution is considered optimal if there are no solutions that use fewer commands.
Output through any reasonable means (to a file, STDIO, or a return value).
The accumulator may not exceed 256.

Examples:
0 -> (Empty string, nothing, or error)
1 -> i
4 -> iis
8 -> iiisd
35 -> iisiisd
150 -> iiisiiisiiiiii
256 -> (Empty string, nothing, or error)

Related, although weirdly a code-challenge

I recommend you just say "input is guaranteed to be in the range 0-255" rather than including 256 in the test cases. also, should 0 be an empty string, not an error?

This might be useful to test programs.

For 150, iiissisisddd is two instructions shorter than the given solution.

is ioiisddsio a valid output for 150? (+1 [1], print, +1 [2], +1 [3], ^2 [9], -1 [8], -1 [7], ^2 [49], +1 [50], print)

@GabrielBenamy The challenge says that the number must be in memory, not printed. Also, the official interpreter prints a newline after each number, which would render that solution invalid. (This was discussed in the previous very similar challenge, where it was decided that it was valid in order to keep existing answers valid, though.)

LegionMammal978: 1, 2, 3, 9, 10, 11, 12, 144, 145, 146, 147, 148, 149, 150

@JulianLachniet iiissisisddd gives the shorter sequence 1, 2, 3, 9, 81, 82, 68, 69, 153, 152, 151, 150.

82 -> 68 what the heck?

@JulianLachniet You state that the accumulator is an unsigned byte. 82^2 = 6724 ≡ 68 (mod 256).

You cannot go outside of the range. See edit to original post

Editing a question so that it invalidates an already-existing answer is bad practice.

What should the output be for 254?

Mathematica, 164 bytes
a=#~Mod~256&;Switch[#2,#+1,"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1/.256->#,#-1,If[#<16,#^2,#]}]&)/@0~Range~255],0,#],2,1]&

Anonymous function. Takes a number as input and returns a list of instructions as output. Previous solution before requirements were changed:
Mathematica, 148 bytes
a=#~Mod~256&;Switch[#2,a[#+1],"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1,#-1,#^2}]&)/@0~Range~255],0,#],2,1]&

Anonymous function. Takes a number as input and returns a list of instructions as output. First, the edges for a graph of value transitions are generated. Then, FindShortestPath is used to find the shortest path from 0 to the requested value. Finally, pairs of values are taken and compared to find the instructions used. All outputs of this program can be found here.