text:
Exchange capitalization
Given two strings of letters, transfer the capitalization pattern of each string onto the other one. Fewest bytes wins.
Input:   CodeGolf xxPPCGxx
Output:  coDEGOlf XxppCgxx

Both strings will be equal-length and nonempty, with only letters a..z and A..Z.
You may output the two resulting strings in either order relative to the inputs.
You may represent a pair of strings as one string with a non-letter single-character separator for input and/or output.
You may represent a string as a list of characters or one-character strings, but not as a sequence of code point values unless these are simply strings in your language.
Your input and output may represent strings differently.

Test cases:
CodeGolf xxPPCGxx -> coDEGOlf XxppCgxx
lower UPPER -> LOWER upper
MiXeD lower -> mixed LoWeR
A A -> A A
ABcd EfGh -> AbCd EFgh

Java (JDK 10), 66 bytes
a->b->{for(int i=a.length,t;i-->0;b[i]^=t)a[i]^=t=(a[i]^b[i])&32;}

Try it online!
Explanations
a->b->{                           // Curried lambda
 for(int i=a.length,t;i-->0;      //  Descending loop on i,
                                  //  Declare t
     b[i]^=t                      //   Apply the case difference to b[i]
   )
  a[i]^=t=(a[i]^b[i])&32;         //   Assign the case difference of the two letters to t, and apply it to a[i].
}

Completely unrelated to this answer of yours, but it's easier than creating a chat. ;p Did you notice the Java-10 TIO has a bug when using array[i++%n]+=...;? array[t=i++%n]=array[t]+...; works fine; and array[i%n]+=...;i++; works fine as well, but using i++ or ++i with a modulo and += to append to a row in an array doesn't work.. Here a Java 10 TIO as example to see the problem. Is this a bug (or feature :S) in the Java 10 JDK or in the Java 10 TIO compiler?

@KevinCruijssen I see the issue, but it seems weird. I see that the version used on TIO is 10.0.0_46 (of 20-03-2018). The latest version is 10.0.1. We should probably ask TIO to update their version of Java.

@KevinCruijssen Dennis updated the version to 10.0.1 and the issue is still happening (I don't have Java 10 installed yet so I rely on TIO, just like you). I've asked on Stack Overflow as I just don't know what happens here... It's baffling!

I've upvoted and favorited your SO question. It seems array[something] += a; is interpret by the compiler correctly as int temp = something; array[temp] = array[temp] + a; in Java 8, but incorrectly as array[something] = array[something] + a; in Java 10 (NOTE: This is just pseudo-code, no idea if the compiler is exactly like this). The test cone by @DidierL. is pretty good and seems to confirm this, though: String[] array = {""}; array[test()] += "a"; with static int test() { System.out.println("evaluated"); return 0; } will print evaluated twice.

Ah, I see adding a counter for the iterations will result in 50 for the bugged Java 10 code, but 100 for the Java 8 code. So i++ (and everything else inside the block-quoted of [...] +=) is evaluated twice. PS: Sorry to spam this answer of yours. As soon as the "Move to chat" option appears it would be best to do so. ;)

@KevinCruijssen It's ok, it's not like this answer attracts a lot of upvotes :P Anyways... The thing is that you actually found a bug. Since the spec says it should be acting as you would think it does, keep writing your answer that way, optimized for Java 10 if you require so. That way, you have a valid Java 10 answer, but untestable because of that bug. Just write it and test it in Java 8, then make the proper Java 10 changes like changing String to var.

I think it's really neat that you found a bug in JDK 10. Good job :]

@Poke It indeed is. :) And rofl at that 500 upvotes. XD Anyway, if anyone want to use it in their java 10 answers, as provided by the accepted answer on SO, adding the compiler-flag -XDstringConcat=inline seems to work. Try it online in Java 10.

@KevinCruijssen That post is crazy. It got featured on Hacker News, on Reddit, and the OpenJDK bug was raised from "Major loss of functionality" to "Crash, loss of data, major memory leak". Even my colleagues saw it and asked me if I was the one posting it. I've hit the rep-cap 4 days in a row now, and I think I might hit it again today. Personally, I don't think it's such a big deal given the corner case it is. Only codegolfers could have find it.

I think it was mentioned in the SO post but the thing to remember is that JDK 9 and 10 are not LTS versions. If you're using java in a professional environment you're hopefully on JDK 8 waiting for 11 to be released in September. All that aside, though, it's a pretty big bug

C (gcc), 86 58 55 53 bytes

Saved twenty-eight bytes thanks to Cows quack.
Saved three bytes.
Saved two bytes thanks to Olivier Grégoire.

c(a,s,e)char*a,*s;{for(;*s++^=e=(*s^*a)&32;)*a++^=e;}

Try it online!

Bit manipulation gives f(S,Z)char*S,*Z;{for(int d;d=(*Z^*S)&32,*Z++^=d;)*S++^=d;}

@Cowsquack Wow; thanks a lot.

c(a,s,e)char*a,*s;{for(;*s++^=e=(*s^*a)&32;)*a++^=e;} (53 bytes)

@OlivierGrégoire Thanks.

Jelly, 9 bytes
O&32^/^OỌ

Try it online!
How it works
O&32^/^OỌ  Main link. Argument: [s, t] (pair of strings)

O          Ordinal; replace each character with its code point.
 &32       Perform bitwise AND with 32, yielding 32 for lowercase letters, 0 for
           uppercase ones.
    ^/     Reduce by XOR, yielding 32 for letter pairs with different
           capitalizations, 0 for letter pair with matching capitalizations.
      ^O   XOR the result with each of the code points.
        Ọ  Unordinal; replace each code point with its character.

...we knew it was gonna happen :D

APL (Dyalog Classic), 13 12 bytes
⊖⊖819⌶¨⍨∊∘⎕a

Try it online!
input and output is a 2×N character matrix
⎕a is the uppercase English alphabet 'ABC...Z'
∊∘⎕a returns a boolean matrix indicating which letters in the input are uppercase
819⌶ converts its right argument to uppercase or lowercase depending on its boolean left argument ("819" is leetspeak for "BIG")
819⌶¨⍨ does that for each (¨) character, swapping (⍨) the arguments
⊖ means reverse vertically; one ⊖ acts as the left argument to 819⌶ and the other is the final action

"819" is leetspeak for "BIG" ... Seriously? That's the actual explanation for why it's 819? 0_o

@DLosc yes :) see chat

Pyth, 10 bytes
rVV_mmrIk1

Try it here!
Explanation & neat Pyth tricks used

rVV_mmrIk1 — Full program. Input is taken from STDIN as a list of two strings, and the output is written to STDOUT as a list of two lists of characters.

mm — For each character in each of the strings:

Ik — Check if it is invariant under...
r...1 — ... Converting to uppercase. Yields True for uppercase characters and False for lowercase ones.

_ — Reverse that list.

VV — And double-vectorize the following function over the two lists:

r — Convert to uppercase if the value is True (aka 1), else convert to lowercase.

This submission abuses the fact that r0 and r1 are the lowercase and uppercase functions in Pyth, and we use truth values (the values obtained by checking if each character is uppercase, reversed) yielding True for uppercase and False for lowercase. The fact that booleans are subclasses of integers in Python is very handy for the approach this answer is using. Porting Dennis and Jonathan's Jelly approaches both resulted in more than 18 bytes, so I am quite happy with the Pyth-specific tricks used here.

MATL, 11 bytes
kG91<P32*-c

Try it online! Or verify all test cases.
Explanation
k      % Implicit input: 2-row char matrix. Convert to lower-case
G      % Push input again
91<    % Less than 91?, element-wise. Gives 1 for upper-case
P      % Flip vertically
32*    % Multiply by 32, element-wise
-      % Subtract, element-wise
c      % Convert to char. Implicit display

Haskell, 78 bytes
import Data.Char
c x|isUpper x=toUpper|1<2=toLower
(!)=zipWith c
x#y=(y!x,x!y)

Try it online!

isUpper x can be x<'a'.

x86-64 machine code, 14 bytes
Callable from C (x86-64 SysV calling convention) with this prototype:
void casexchg(char *rdi, char *rsi);  // modify both strings in place

An explicit-length version with length in rcx is the same size.  void casexchg(char *rdi, char *rsi, int dummy, size_t len);

This uses the same bit-exchange algo as the C and Java answers: If both letters are the same case, neither needs to change.  If they're opposite case, they both need to change.
Use XOR to diff the case bit of the two strings.  mask = (a XOR b) AND 0x20 is 0 for same or 0x20 for differing.  a ^= mask; b ^= mask caseflip both letters iff they were opposite case.  (Because the ASCII letter codes for upper and lower differ only in bit 5.)
NASM listing (from nasm -felf64 -l/dev/stdout).  Use cut -b 26-  <casexchg.lst  >casexchg.lst to turn this back into something you can assemble.
   addr    machine
 6         code          global casexchg
 7         bytes         casexchg:
 8                       .loop:
 9 00000000 AC               lodsb                ; al=[rsi] ; rsi++
10 00000001 3207             xor   al, [rdi]
11 00000003 2420             and   al, 0x20       ; 0 if their cases were the same: no flipping needed
12
13 00000005 3007             xor   [rdi], al      ; caseflip both iff their cases were opposite
14 00000007 3046FF           xor   [rsi-1], al
15
16 0000000A AE               scasb                ; cmp al,[rdi] / inc rdi
17                           ; AL=0 or 0x20.
18                           ; At the terminating 0 in both strings, AL will be 0 so JNE will fall through.
19                           ; 0x20 is ASCII space, which isn't allowed, so AL=0x20 won't cause early exit
20 0000000B 75F3             jne  .loop
21                       ;    loop  .loop            ; caller passes explict length in RCX
22
23 0000000D C3               ret

  size = 0xe bytes = 14
24 0000000E 0E           db $ - casexchg_bitdiff

The slow loop instruction is also 2 bytes, same as a short jcc.  scasb is still the best way to increment rdi with a one-byte instruction.  I guess we could xor al, [rdi] / stosb.  That would be the same size but probably faster for the loop case (memory src + store is cheaper than memory dst + reload).  And would still set ZF appropriately for the implicit-length case!
Try it online! with a _start that calls it on argv[1], argv[2] and uses sys_write on the result

J, 36 31 27 bytes
-9 bytes thanks to FrownyFrog!
(XOR"$32*[:~:/97>])&.(3&u:)

Try it online!
The previous solution was:
J, 36 31 bytes
-5 bytes thanks to FrownyFrog!
|:@(XOR 32*0~:/@|:97>])&.(3&u:)

Try it online!
How it works:
                          (3&u:)  converts the strings to code points
   (                    )&.       then do the following and convert back to chars
                    97>]          check if they are uppercase letters
             0~:/@|:              transpose and check if the two values are different
          32*                     multiply by 32 (32 if different, 0 otherwise)
      XOR                         xor the code point values with 32 or 0
 |:@                              and transpose

The [: can be 0 and the (22 b.) can be XOR. &.(3&u:) saves 1 byte.

@FrownyFrog Very nice golfs, thank you! You are really good!

27

@FrownyFrog Wow! Can you explain the use of " and $? Thanks!

The input is done with ,:, there are 2 rows on the left side. We need "(1) but "$ works too, because it stands for  "1 _. $ b.0 gives the rank of $ (monadic, dyadic left, dyadic right).

I only know 3 useful ones, "$,"{,"#:. And &> for "0 0.

k, 14 bytes
{`c$l+|x-l:_x}

Try it online! Input/output is a list of two strings.

R, 118 94 75 72 bytes
m=sapply(scan(,""),utf8ToInt);w=m>96;apply(m-32*(w-w[,2:1]),2,intToUtf8)

Try it online!
There must be a much golfier way. -43 bytes thanks to Giuseppe who pointed me to the MATL solution by Luis Mendo.
TIO link contains a function solution for the same byte count.
m=sapply(a<-scan(,""),utf8ToInt)    # Turns input into a matrix of bytecode (2 columns)
w=m>96                              # Predicate : which chars are lower?
apply(m-32*(w-w[,2:1]),2,intToUtf8) # -32*w turns the string to UPPER
                                    # +32*w[,2:1] swaps capitalization
                                    # intToUtf8 turns bytecode to strings

Bonus: The output is a named vector whose names are the original input strings!

You should be able to drop a<- since you don't use a anywhere else.

@Giuseppe Were you reading my mind? ;)

Vyxal ṡ, 4 bytes
•??•

Try it Online!
Explanation:
•    # A with the capitalization of B
 ??  # Get both input strings (order ends up reversed)
   • # A with the capitalization of B
     # "ṡ" flag - Print entire stack, separated by spaces

Finally a use for A with the capitalization of B, huh?

@AlanBagel Yep, I've been waiting to use that one for a while. :)

Python 3, 83 bytes
lambda a,b:(g(a,b),g(b,a))
g=lambda*a:[chr(ord(x)&95|(y>'Z')<<5)for x,y in zip(*a)]

Try it online!
-3 bytes thanks to Mr. Xcoder
-3 bytes thanks to Chas Brown

83 bytes with a bit of bit-twiddling.

@ChasBrown Oh cool, nice. Thanks!

JavaScript, 77 74 73 bytes
W=>W.map((w,x)=>w.map((c,i)=>W[+!x][i][`to${c>{}?'Low':'Upp'}erCase`]()))

f=
W=>W.map((w,x)=>w.map((c,i)=>W[+!x][i][`to${c>{}?'Low':'Upp'}erCase`]()))

console.log(
    f([[...'CodeGolf'],[...'xxPPCGxx']])
)

Takes an array of char arrays, outputs an array of char arrays.
-1 byte (@Arnauld): c>'Z' → c>{}

You can save a byte with c>{}.

Haskell, 78 bytes
c!d=([c..'z']++[';'..])!!sum[32|(c>'Z')/=(d>'Z')]
(#)=zipWith(!)
s%t=(s#t,t#s)

Try it online!

QBasic, 133 bytes
INPUT a$,b$
FOR i=1TO LEN(a$)
c=ASC(MID$(a$,i,1))
d=ASC(MID$(b$,i,1))
s=32AND(c XOR d)
?CHR$(c XOR s);
r$=r$+CHR$(d XOR s)
NEXT
?
?r$

Takes the two strings comma-separated and outputs the results newline-separated. Uses the bit-fiddling algorithm from Dennis's Jelly answer. Other than that, the main golf trick here is that the first result string is printed directly, one character at a time, which is a little shorter than saving both result strings in variables and printing them outside the loop.

Jelly, 13 bytes
=Œu=/ị"Ɱż"Œs$

Try it online!
Also 13: =ŒuṚ×32ạŒlO$Ọ (or =ŒuṚæ«5ạŒlO$Ọ)

Python 3, 76 75 bytes
lambda a,b:''.join(chr(ord(x)&95|ord(y)&32)for x,y in zip(a+' '+b,b+'a'+a))

Try it online!
Outputs the result as one string with a single-character separator.
Thx to Jonathon Allan for 1 byte.

(y>'Z')*32 -> ord(y)&32

Retina, 75 bytes
^
¶
+`¶(([A-Z])|(.))(.*)¶(([A-Z])|(.))
$#6*$u$1$#7*$l$1¶$4$#2*$u$5$#3*$l$5¶

Try it online! Explanation: The newlines are used as markers to determine how much of the string has been processed. The regex tries to match against uppercase letters or failing that any characters. If an uppercase letter was matched then the other character is uppercased otherwise it is lowercased and vice versa, while the newlines are advanced to the next character.

Assembly (nasm, x64, Linux), 25 bytes (123 bytes source)
Hex bytes:
0x88, 0xE6, 0x30, 0xC6, 0x80, 0xE6, 0x20, 0x88
0xF2, 0x66, 0x31, 0xD0, 0x88, 0x26, 0xAA, 0xAC
0x8A, 0x26, 0x8A, 0x07, 0x08, 0xE4, 0x75, 0xE8, 0xC3

The function entry point is at a, with the strings passed in using RDI and RSI.
b:MOV DH,AH
XOR DH,AL
AND DH,32
MOV DL,DH
XOR AX,DX
MOV [RSI],AH
STOSB
LODSB
a:MOV AH,[RSI]
MOV AL,[RDI]
OR AH,AH
JNZ b
RET

Try it online!

I just realized you're golfing the asm source, not the machine-code size.  That's usually more fun, because it's occasionally useful in real life.  (All else being equal, smaller is typically better for the front-end and uop cache density.)  Tips for golfing in x86/x64 machine code.

@PeterCordes Thanks for the tip. I've added the hex bytes. My assembly is a little rusty (I last had to write a little device driver for DOS 3.3!) but I think I got most of the optimizations in.

Yeah, this looks pretty good.  Interesting partial-register hacks.  and al,32 is only 2 bytes, using the special AL,imm8 encoding that most ALU instructions have.  You could require the string length in RCX and use loop.  I was going to say you should test ah,ah because that's more efficient than or while being the same length, but it's longer in asm source so the crusty old idiom actually has merit for asm-source code golfing :P

Using memory-destination xor and a tighter loop structure, my version came in at 14 bytes of x86-64 machine code. Same for count implicit-length or explicit-length strings.  Its NASM source could probably be golfed down shorter than 123 bytes, too.  I'm not sure which would run faster on a modern CPU like Skylake or Ryzen (Ryzen wouldn't have any extra cost for merging DH when reading DX, but SKL would need an extra cycle to insert a merging uop.)

Crystal, 108 bytes
def f(a,b)r=s=""
a.zip(b){|x,y|r+="`"<x<"{"?y.downcase: y.upcase
s+="`"<y<"{"?x.downcase: x.upcase}
{s,r}end

Try it online!
How it works?
def f(a, b)                       # Strings as list of characters
r = s = ""                        # Strings buffers initialization
a.zip(b) do |x, y|                # Join two arrays to paired tuples and iterate
r+="`"<x<"{"?y.downcase: y.upcase # Check if character is downcase using triple
s+="`"<y<"{"?x.downcase: x.upcase # comparison and ascii table. Then apply it to
end                               # the other character using String methods
{s, r}                            # Return two new strings using a tuple
end                               # PS: Tuples are inmutable structures in Crystal

TI-Basic, 225 bytes
Prompt Str1,Str2
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ→Str3
"seq(inString(Str3,sub(Ans,I,1),I,1,length(Ans→u
Str1
u→F
Str2
augment(u,ʟF→S
augment(ʟF,Ans→F
".
For(I,1,dim(ʟS
Ans+sub(Str3,remainder(ʟF(I)-1,26)+1+26(ʟS(I)>26),1
End
Disp sub(Ans,2,length(Str1
sub(Ans,2+length(Str2),length(Str2

-1 byte if the i is replaced with the imaginary number i.+3 bytes by replacing remainder(ʟF(I)-1,26) with 26fPart((ʟF(I)-1)/26) if the calculator does not support remainder(.
Outputs are displayed, separated by a newline.

Charcoal, 17 bytes
Ｅθ⭆ι⎇№α§§θ¬κμ↥λ↧λ

Try it online! Link is to verbose version of code. Takes input as an array of two strings. Explanation:
 θ                  Input array
Ｅ                   Map over strings
   ι                Current string
  ⭆                 Map over characters
         θ          Input array
           κ        Outer loop index
          ¬         Logical Not
        §           Index into array
            μ       Inner loop index
       §            Index into array
      α             Uppercase characters
     №              Count number of matches
              λ λ   Current character
             ↥      Uppercase
               ↧    Lowercase
    ⎇               Ternary
                    Implicitly print

F#, 120 bytes
Bugger.
open System
let g=Seq.fold2(fun a x y->a+string(x|>if y>'Z'then Char.ToLower else Char.ToUpper))""
let b f s=g f s,g s f

Try it online!
The function g takes the two strings as parameters. Seq.fold2 applies a function with an accumulator (a) to each element (x and y) in the strings. Initially a is an empty string, and it adds the converted character to it in each iteration.
b is the main function. It first converts f with respect to s, and then converts s with respect to f. It then returns a tuple with both values.

Prolog (SWI), 121 bytes
[H|T]-[I|U]-[J|V]-[K|W]:-((H>96,I>96;H<92,I<92),J=H,K=I;H>96,J is H-32,K is I+32;J is H+32,K is I-32),T-U-V-W.
_-_-[]-[].

Try it online!

Stax, 10 bytes
▌Ö↑o╓→ì]yç

Run and debug it
Here's an ungolfed representation of the same program to show how it works.
        Example
        ["Ab", "cd"]
:)      [["Ab", "cd"], ["cd", "Ab"]]    Get all rotations of input
m       ["cd", "Ab"]                    For each, run the rest of program; print result
  M     ["cA", "db"]                    Transpose matrix
  {     "cA"                            Begin block for mapping to result
    B   "A" 99                          "Pop" first element from string array; leave the rest
    96> "A" 1                           Is the character code > 96?
    :c  "a"                             Set case of string; 0 -> upper,  1 -> lower
  m     "ab"                            Perform the map using the block

Run this one

Ruby, 74 69 bytes
->a,b{a.zip(b).map{|x|x.one?{|y|y>?_}?x.map(&:swapcase):x}.transpose}

Try it online!
Input and output are arrays of chars, so the footer does back and forth transformations from strings.
I'm not yet sure whether this is a good approach to the problem, but this challenge definitely looks like a nice use scenario for swapcase method.

PHP 4.1.2, 40 bytes
Replace the pair of quotation marks with byte A0 (in ISO-8859-1 or Windows-1252, this is NBSP) to get the byte count shown, then run from a web browser (or from the command line), providing the strings as the query string arguments (or environment variables) a and b.
<?=$a^$c=($a^$b)&str_pad("",2e5),_,$b^$c;

In this version of PHP, register_globals is on by default, so the strings will automatically be assigned to the variables $a and $b. Increase the value 2e5 (200000) if necessary.
PHP 7.1+, 58 bytes
Run on the command line, using php -r 'code here' string1 string2:
[,$a,$b]=$argv;echo("$b $a"^$a.=" $b")&str_pad("",3e5)^$a;

The value 3e5 (300000) is chosen to exceed (MAX_ARG_STRLEN * 2 + 1) on most Linux systems (specifically, x86 and other architectures for which PAGE_SIZE is 4096, and MAX_ARG_STRLEN is thus 131072), to avoid problems with any possible input string. Increase if necessary.
Try it online!


text:
Shortest Uniquely Identifying Substrings
Given a list of strings, replace each string by one of its non-empty substrings which is not a substring of any of the other strings in the list and as short as possible.
Example
Given the list ["hello","hallo","hola"], "hello" should be replaced by just "e" as this substring is not contained in "hallo" and "hola" and it is as short as possible. "hallo" could be replaced by either "ha" or "al" and "hola" by any of "ho", "ol" or "la".
Rules

You can assume that the strings will be non-empty and only contain alphabetical characters of the same case.
You can assume that such a substring exists for each string in the list, i.e. no string in the list will be a substring of any of the other strings.
Input and output can be in any reasonable format.
This is code-golf, so try to use as few bytes as possible in the language of your choice.

Test Cases
Only one possible output is given for most cases.
["ppcg"] -> ["p"] (or ["c"] or ["g"])
["hello","hallo","hola"] -> ["e","ha","ho"]
["abc","bca","bac"] -> ["ab","ca","ba"]
["abc","abd","dbc"] -> ["abc","bd","db"]
["lorem","ipsum","dolor","sit","amet"] -> ["re","p","d","si","a"]
["abc","acb","bac","bca","cab","cba"] -> ["abc","acb","bac","bca","cab","cba"]

Related: Shortest Identifying Substring - similar idea, but more involved rules and cumbersome format.

Why isnt "" (empty string) uniquely identifying for the single "ppcg" case?

@MooseBoys Given a list of strings, replace each string by one of it's non-empty substrings

Harder related challenge

Jelly,  12  9 bytes
Ẇ€ŒpẇþÞ⁸Ḣ

Try it online! Or see the test-suite (takes ~35s)

J, 30 29 25 bytes
1(|:(0{-.&,)"_1]\.)<\\.&>

Try it online!
                   <\\.&>        a 3-dimensional array of substrings
1 |:                             transpose each matrix to sort the substrings by length
1              ]\.               all choices where one word is missing
    (0{-.&,)"_1                  for every matrix, flatten, remove substrings
                                  that are present in the corresponding complement,
                                  pick first

Prolog (SWI), 175 163 bytes
S/L/R:-sub_string(S,_,L,_,R).
[H|T]+[I|R]:-string_length(H,L),between(1,L,X),H/X/I,T+R.
R+R.
L-R:-L+R,forall(member(E,L),findall(_,(member(F,R),\+ \+ E/_/F),[_])).

Try it online!
Most of the things here should be fairly obvious, but:
Explanation
Signatures: (+ = input, ? = optional, - = output, : = expression)

sub_string(+String, ?Before, ?Length, ?After, ?SubString)
string_length(+String, -Length)
member(?Elem, ?List)
between(+Low, +High, ?Value)
findall(+Template, :Goal, -Bag)
forall(:Cond, :Action)

\+ \+ is just not not (i.e. converts a match to boolean (in this case, prevents it from matching both ps in ppcg separately))

The right tool for the job :P except for the fact that it's mind-blowingly verbose

APL (Dyalog), 25 bytes
Thanks ngn for saving one byte
⊃¨1↓≢~⍨/(,⍨(,∘↑⍳∘≢,/¨⊂)¨)

Try it online!

Pyth, 12 bytes
mhf!ts}LTQ.:

Try it here!
How it works
Basicaly filters the substrings of each that only occur in one of the strings in the list (that is, it is unique to that string) and gets the first one.
mhf!ts}LTQ.:     Full program, Q=eval(stdin_input())
m         .:     Map over Q and obtain all the substrings of each.
  f              And filter-keep those that satisfy (var: T)...
      }LTQ       ... For each string in Q, yield 1 if it contains T, else 0.
   !ts           ... Sum the list, decrement and negate.
 h               Head. Yields the first valid substring, which is always the shortest.

Jelly, 10 bytes
Ẇ€ṙƬ1ḟ/Ḣ$€

Try it online!

Python 2, 116 bytes
def f(a):g=lambda s,S:s not in`set(a)-{S}`[3:]and min(s,g(s[1:],S),g(s[:-1],S),key=len)or S;return[g(s,s)for s in a]

Try it online!

JavaScript (ES6), 93 bytes
a=>a.map(s=>(L=s.length,g=n=>a.every(S=>S==s|!~S.search(u=s.substr(n%L,n/L+1)))?u:g(n+1))(0))

Try it online!
How?
For each string s of length L in the input array a[ ] and starting with n = 0, we use the recursive function g() to generate all substrings u of s with:
u = s.substr(n % L, n / L + 1)

For instance, with s = "abc" and L = 3:
 n | n%L | floor(n/L+1) | u
---+-----+--------------+-------
 0 |  0  |       1      | "a"
 1 |  1  |       1      | "b"
 2 |  2  |       1      | "c"
 3 |  0  |       2      | "ab"
 4 |  1  |       2      | "bc"
 5 |  2  |       2      | "c"
 6 |  0  |       3      | "abc"
 7 |  1  |       3      | "bc"
 8 |  2  |       3      | "c"

Some substrings are generated several times, but it doesn't matter. What's important is that all substrings of length N have been generated before any substring of length N+1.
We stop the process as soon as u cannot be found in any other string S in a[ ], which is guaranteed to happen when u == s in the worst case, as per challenge rule #2:

no string in the list will be a substring of any of the other strings

Therefore, in the above example, steps 7 and 8 will actually never be processed.

PowerShell, 107 bytes
($a=$args)|%{$(for($i=0;$i++-lt($g=($s=$_)|% Le*)){0..($g-$i)|%{$s|% s*g $_ $i}|?{!($a-match$_-ne$s)}})[0]}

Try it online!
Explanation
For each string supplied (and assign the whole array to $a):

Do a for loop over each substring length (1 based) of the string (assigning the string itself to $s and the length to $g)
For each length ($i):

Make an index loop, from 0 to to length - $i, then for each index:

Get the substring of the current string ($s) at position $_ (index) and of length $i
Pass that substring to Where-Object (?), and return it if:

The subset of array ($a) that does not contain the current string $s, does not have a match for the current substring $_

Back at the string level, we have all of the substrings of this string that were not found in the others, so take the first one [0] since we only need one of them, then continue with the next string.

C# (Visual C# Interactive Compiler), 149 bytes
a=>a.Select(s=>{var t=s;for(int j=0,k,l=s.Length;j++<l;)for(k=-1;j+k++<l;)if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any())j=k=l;return t;})

Try it online!
Less golfed...
// a is an input array of strings
a=>
  // iterate over input array
  a.Select(s=>{
    // t is the result string
    var t=s;
    // j is the substring length
    for(int j=0,k,l=s.Length;j++<l;)
      // k is the start index
      for(k=-1;j+k++<l;)
        // LINQ query to check if substring is valid
        // the tested string is collected in t
        if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any())
          // break loops
          j=k=l;
    // return result
    return t;
  })

source: Stack Exchange

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

sort: votes


text:
What surrounds my Minesweeper tile?
Minesweeper is a puzzle game where mines are hidden around a board of nondescript tiles with the goal of identifying the location of all mines. Clicking on a mine loses the game, but clicking on any other tile will reveal a number from 0-8 which signifies how many mines directly surround it.
Given a number, you must display a random* possible combination of empty tiles and mines surrounding it. This should be in the form of a 3x3 array. The center tile should be the number of mines taken as input.
*Must have a non-zero chance for all combinations to occur.

Examples
_ = blank square
X = mine

0

___
_0_
___

1

_X_
_1_
___

1

___
_1_
X__

___
_1_
__X

4

_X_
X4X
_X_

4

X_X
_4_
X_X

4

___
X4X
X_X

8

XXX
X8X
XXX

Input

The number of mines surrounding the center tile (0-8)

Output

Any reasonable form of output that displays the 3x3 array of tiles

Other rules

Each combination does not have to have an equal chance of happening. There just must be a non-zero chance of each combination to occur when executing your program.
Any 2 characters can be chosen for the mine and empty tile.
This is code golf, the program with fewest bytes wins.

"Any 2 characters can be chosen for the mine and empty tile" may we still use, say, 1 and 0?

@JonathanAllan I'll say yes, the 0/1 input cases might be a little bit confusing but I don't think it's a big deal.

is a flat, 9-element list a 'reasonable form of output'?

@ChasBrown no, a flat list is not really equivalent.

Jelly, 9 bytes
<Ɱ8Ẋs4js3

Try it online!
empty = 1
mine = 0
Note that 1 and 0 are integers.
Another note: this is somewhat similar to Jonathan Allan's 10-byte answer, but it's not really influenced by it in any way, and the mechanism, if you pay close attention, is actually more different than at first glance.

Ugh I missed a trick :)

@JonathanAllan Do you believe this is close enough to yours? The suffix is the same anyway...

It's slightly different. If I read a post and find a quick golf I comment; if I'm just trying to solve the challenge I post. I've posted identical code before independently.

@JonathanAllan My approach to that is a bit different, if I find out that my independent solution is actually almost the same as somebody else's but with a slightly different element which saves a byte or two (subjective opinion ensues), I comment, otherwise I outgolf. That's why I had asked, but you seem to prefer me posting it here, so...

APL (Dyalog Unicode), 28 15 bytes
-13 bytes thanks to ngn!
{3 3⍴5⌽⍵,⍵≥8?8}

Explanation:
{...} A direct function (D-Fn), ⍵ is its right argument.
8?8 deal 8 random numbers from the list 1..8:
      8?8
7 2 1 8 4 6 5 3

⍵≥ is the argument greater or equal to each of them?:
      5 ≥ 7 2 1 8 4 6 5 3
0 1 1 0 1 0 1 1

⍵, prepend the argument to the boolean list:
      5 , 0 1 1 0 1 0 1 1
5 0 1 1 0 1 0 1 1

5⌽ rotate the list 5 positions to the left, so that the argument is in the center:
      5 ⌽ 5 0 1 1 0 1 0 1 1
1 0 1 1 5 0 1 1 0

3 3⍴ reshape the list to a 3x3 matrix:
      3 3 ⍴ 1 0 1 1 5 0 1 1 0
1 0 1
1 5 0
1 1 0

Try it online!
J, 15 bytes
Also many bytes thanks to ngn!
3 3$5|.],]>8?8:

Try it online!

(8↑1⍴⍨⍵)[8?8] -> ⍵>8?8 (assuming ⎕io←0)

3 3⍴1↓,⍵,2 4⍴ -> 3 3⍴5⌽⍵,

@ngn Thanks! I feel ashamed by my verbose attempt...

no need for shame :) thank you - this answer gave me an opportunity to learn some J

that J answer is really lovely.

@Jonah The credit goes to ngn, I just applied his advice on the APL solution to the J solution.

@DLosc  I added an explanation of the APL solution; the J solution is analogous, just the list is 0-indexed.

JavaScript (ES6), 67 bytes
Shorter version suggested by @tsh
Empty slots are 0, mines are 1.
n=>`___
_${t=9,n}_
___`.replace(/_/g,_=>n-(n-=Math.random()<n/--t))

Try it online!

Original trial-and-error version, 78 bytes
Empty slots are _, mines are 7.
f=(n,o=`___
_${k=n}_
___`.replace(/_/g,c=>Math.random()<.5?--k|7:c))=>k?f(n):o

Try it online!
Commented
f = (                         // f = recursive function
  n,                          // n = input
  o = `___\n_${k = n}_\n___`  // o = minesweeper field / k = backup of n
    .replace(/_/g, c =>       // for each underscore character c in o:
      Math.random() < .5 ?    //   random action:
        --k | 7               //     either decrement k and yield 7
      :                       //   or:
        c                     //     let the underscore unchanged
    )                         // end of replace()
) =>                          //
  k ?                         // if k is not equal to 0:
    f(n)                      //   try again
  :                           // else:
    o                         //   stop recursion and return o

69 bytes (prettify)

Jelly,  13  10 bytes
8Ẉ>RẊs4js3

The returned list of lists has the displayed integer in the centre surrounded by 0s and 1s representing mines and blanks respectively.
Try it online! (footer pretty prints the array)
How?
8Ẉ>RẊs4js3 - Link: integer, n                   e.g.  3
8          - eight                                    8
 Ẉ         - length of each (implicit range of eight) [1,1,1,1,1,1,1,1]
   R       - range of n                               [1,2,3]
  >        - greater than? (vectorises)               [0,0,0,1,1,1,1,1]
    Ẋ      - shuffle                                  [1,1,1,0,0,1,1,0]
     s4    - split into chunks of 4                   [[1,1,1,0],[0,1,1,0]]
       j   - join (with n)                            [1,1,1,0,3,0,1,1,0]
        s3 - split into chunks of 3                   [[1,1,1],[0,3,0],[1,1,0]]

As a small note, ŒH also works in place of s4.

;ṙ4s3 also works

@dylnan I actually posted with a TIO having that same code at one point during my golfing (but quickly put it back so I didn't have to rewrite the explanation).

Pyth, 16 14 bytes
c3jQc2.S.[d8*N

Saved 2 bytes thanks to isaacg.
Uses spaces for safe spots and quotes for mines.
Try it here
Explanation
c3jQc2.S.[d8*N
            *NQ     Get (implicit) input number of quotes...
        .[d8        ... and pad to length 8 with spaces.
      .S            Shuffle.
  jQc2              Stick the input in the middle.
c3                  Split into three.

.[d8 instead of >8+*8d

Oracle 18 SQL, 230 bytes
Not a golfing language but...
WITH v(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1))SELECT v.v||b.v||c.v||'
'||d.v||n||e.v||'
'||f.v||g.v||h.v
FROM n,v,v b,v c,v d,v e,v f,v g,v h
WHERE v.v+b.v+c.v+d.v+e.v+f.v+g.v+h.v=n
ORDER BY DBMS_RANDOM.VALUE
FETCH NEXT ROW ONLY

The input value is in a table n with column n:
CREATE TABLE n(n) AS
SELECT 7 FROM DUAL;

Try it online - log onto https://livesql.oracle.com and paste it into a worksheet.
Output:
V.V||B.V||C.V||''||D.V||N||E.V||''||F.V||G.V||H.V
-------------------------------------------------
101
171
111

To get all possible combinations (183 Bytes):
WITH v(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1))SELECT v.v||b.v||c.v||'
'||d.v||n||e.v||'
'||f.v||g.v||h.v
FROM n,v,v b,v c,v d,v e,v f,v g,v h
WHERE v.v+b.v+c.v+d.v+e.v+f.v+g.v+h.v=n

Output:
V.V||B.V||C.V||''||D.V||N||E.V||''||F.V||G.V||H.V
-------------------------------------------------
111
171
110

111
171
101

111
171
011

111
170
111

111
071
111

110
171
111

101
171
111

011
171
111

Charcoal, 19 bytes
Ｗ¬⁼ΣＩＫＡ⁸«Ｅ³⭆³‽²↑↗↖θ

Try it online! Link is to verbose version of code. Uses 0 for a mine, 1 for an empty space. Explanation:
     ＫＡ             Peek the entire canvas
    Ｉ               Cast to integer
   Σ                Take the sum
       ⁸            Literal 8
  ⁼                 Equals
 ¬                  Logical Not
Ｗ       «           While
          ³ ³       Literal 3
         Ｅ          Map over implicit range
           ⭆        Map over implicit range and join
              ²     Literal 2
             ‽      Random element of implicit range
                    Implicitly print on separate lines
               ↑↗↖θ Print the original input in the middle

Peek returns an array of strings, which Sum simply concatenates, which is why we have to cast to integer first. (Sum(Sum(PeekAll())) also works.)
Sum returns None for an empty array (first loop), so the only safe comparison is Not(Equals(...)).
Nilary Random always returns 0, although its documentation says otherwise.

Alternative solution, was 19 bytes, now 17 bytes after a Charcoal bugfix:
θ←9Ｗ⁻ΣＩＫＡ⁸ＵＭＫＭＩ‽²

Try it online! Link is to verbose version of code. Uses 0 for a mine, 1 for an empty space. Explanation:
θ

Print the original input.
←9

Print a 9 leftwards. This moves the cursor back over the original input, and also forces at least one iteration of the while loop (otherwise an input of 8 would do nothing).
Ｗ⁻ΣＩＫＡ⁸

Repeat while the difference between the sum of all the digits on the canvas and 8 is nonzero:
ＵＭＫＭＩ‽²

Replace each of the surrounding characters randomly with 0 or 1.

Japt, 13 bytes
çÊú8 öÊi4U ò3

Try it

Explanation
                   :Implicit input of integer U
 Ê                 :"l"
ç                  :Repeat U times
  ú8               :Pad right to length 8
    öÊ             :Random permutation
       i4U         :Insert U at index 4
            ò3     :Split at every 3rd character

R, 67 63 62 59 bytes
matrix(c(sample(rep(1:0,c(n<-scan(),8-n))),n),6,5)[2:4,1:3]

Try it online!
Uses 1 and 0. Build a n* 1 +(8-n)* 0 vector, shuffles it, appends n, builds the bigger matrix shown below(where a...i stand for the elements of the original vector) and extracts the proper sub-matrix shown in uppercase:
     [,1] [,2] [,3] [,4] [,5]
[1,] "a"  "g"  "d"  "a"  "g"
[2,] "B"  "H"  "E"  "b"  "h"
[3,] "C"  "I"  "F"  "c"  "i"
[4,] "D"  "A"  "G"  "d"  "a"
[5,] "e"  "b"  "h"  "e"  "b"
[6,] "f"  "c"  "i"  "f"  "c"

One byte shorter: matrix((c(sample(rep(1:0,c(n<-scan(),8-n))),n))[c(1:4,9:5)],3)

@Gregor you're right an array is probably a reasonable form of output to display an array :)

QBasic 1.1, 206 186 bytes
RANDOMIZE TIMER
INPUT N
O=N
Z=8-N
FOR I=0TO 7
IF O*Z THEN
R=RND<.5
O=O+R
Z=Z-1-R
A(I)=-R
ELSEIF O THEN
O=O-1
A(I)=1
ELSE
Z=Z-1
A(I)=0
ENDIF
NEXT I
?A(0)A(1)A(2)
?A(3)N;A(4)
?A(5)A(6)A(7)

-20 thanks to DLosc (newly-posted golfing trick).
Empty = 0
Mine = 1
Note that 0 and 1 are integers, but I'm using STDOUT anyway, so...
Output appears like this:
 A  B  C
 D  x  E
 F  G  H

Where A-H are 0/1 and x is the input.

Nice trick, working with QBasic's wonky number output by using numbers for the mine & empty tile!

Python 2, 93 bytes
from random import*
def f(n):a=[1]*n+[0]*(8-n);shuffle(a);a[4:4]=[n];return zip(*[iter(a)]*3)

Try it online!
0 for empty; 1 for a mine; and n for one's self.

The use of iter is smart!

@Jonathan Allan: xnor showed me that just the other day.

Attache, 51 bytes
{[3,3]&Rotate[Sample[{Sum@_=_2}&_\BinBelow@8]'_,4]}

Try it online!
Explanation
Similar to Galen's J/APL answer, the basic technique is to generate an array of 1s and 0s with the correct number of mines, inserting the input by appending it to the end, rotating the array such that the input lies in the center, then reshaping into a 3x3 matrix.
Part 1: generating the binary array
There are many ways to go about doing this, but I mainly happened across two types: brute force and selection.
The primary brute force method looks like this:
NestWhile[{Random[8&2]},0,{Sum@_/=_2}&_]

This generates random arrays of 8 binary digits (Random[8&2]) while their sums do not equal the input {Sum@_/=_2}&_. This is a bit verbose, as the following emphasized portions of the code are there "just to make it work":
NestWhile[{Random[8&2]},0,{Sum@_/=_2}&_]
          ^           ^^^^^        ^^^^

And I discarded the idea.
Selection is more interesting. The main concept is to use the BaseBelow[b, n] builtin, which generates a list of all base-b integers of width n (as digit arrays), from 0 to b^n-1. For example, BaseBelow[3, 2] generates all ternary integers of width 2:
A> BaseBelow[3, 2]
 0 0
 0 1
 0 2
 1 0
 1 1
 1 2
 2 0
 2 1
 2 2

We specifically use BaseBelow[2, 8] for all binary integers of width 8. These represent all possible minefields of all lengths. This is the first step.
The second step is selecting all such arrays with only N 1s, where N is the input. My first idea was to translate this English statement directly into Attache:
Chunk[SortBy[Sum,BaseBelow[2,8]],Sum]@N@1

However, not only did this come out to be 1 byte longer than the aforementioned approach, it's also highly repetitive—and it isn't even randomized yet!. Sure, I could probably save 1 byte by reorganizing how BaseBelow is called, but it simply isn't worth using the approach.
So I decided to kill two birds with one stone and use a Shuffle based approach. The following gives all valid minefields of length N in random order:
{Sum@_=_2}&N\Shuffle[BaseBelow&8!2]

Then, all that needs to be done is to select the first. But I can do better—surely it'd be better to simply Sample the filtered array? This approach comes out to be something like this:
Sample[{Sum@_=_2}&_\BaseBelow[2,8]]

I had to revert the BaseBelow&8!2 golf because \s precedence is too high. Otherwise satisfied, I proceeded to chop a byte off of that:
Sample[{Sum@_=_2}&_\2&BaseBelow@8]

(I discovered another way to succinctly call a dyadic function here: x&f@y is a high-precedence expression which evaluates to f[x, y].)
However, despite this, I remembered that, all along, an alias for 2&BaseBelow existed: BinBelow. So I used that:
Sample[{Sum@_=_2}&_\BinBelow@8]

This generates the desired minefield. I'm convinced this is near optimal.
Part 2: Forming the array
As said earlier, the forming technique I used is similar to the J/APL answer, so I won't go into too much detail. Suppose MINEFIELD is the result from the last section. The function then becomes:
{[3,3]&Rotate[MINEFIELD'_,4]}

MINEFIELD'_ concatenates the minefield with the original input _, giving us something like this:
[1, 0, 0, 0, 1, 0, 0, 1, 3]

Then, Rotate[MINEFIELD'_,4] rotates this list 4 times to the left, placing the center:
[1, 0, 0, 1, 3, 1, 0, 0, 0]

The last step is using [3,3]& to reshape the list into a 3x3 matrix:
 1 0 0
 1 3 1
 0 0 0

Java 10, 165 157 141 bytes
n->{var r="___\n_"+n+"_\n___";for(int i;n>0;r=r.charAt(i*=Math.random())>58?r.substring(0*n--,i)+(i>9?0:0+r.substring(i+1)):r)i=11;return r;}

Empty tiles are _ (any character with a unicode value above 58 is fine) and mines are 0.
Try it online.
Explanation:
n->{                           // Method with integer parameter and String return-type
  var r="___\n_"+n+"_\n___";   //  Result-String, starting at:
                               //   "___
                               //    _n_
                               //    ___"
  for(int i;n>0                //  Loop as long as `n` isn't 0 yet:
      ;                        //    After every iteration:
       r=r.charAt(i*=Math.random())
                               //     Select a random integer in the range [0,11)
         >58?                  //     And if the character at this random index is a '_':
          r.substring(0*n--,i) //      Set `r` to the first part excluding character `i`,
                               //      (and decrease `n` by 1 in the process)
          +(i>9?0:0+           //      appended with a '0',
           r.substring(i+1))   //      appended with the second part
         :                     //     Else:
          r)                   //      Leave `r` unchanged
     i=11;                     //   Set `i` to 11 so a new random integer can be chosen
  return r;}                   //  Return the result

PowerShell, 77 bytes
param($n)-join(0..7|random -c 8|%{'X_'[$_-ge$n]
$n[++$i-ne4]
'
'*($i-in3,5)})

Try it online!

PHP, 135 134 123 117 122 121 bytes
Looping over str to print instead saves 1 byte
str_split and implode to insert the centre number saves 11 bytes
Don't need to assign the string to $s anymore saving 6 bytes
Yes you do. Otherwise the string is shuffled after every echo...
Removing whitespace after echo saves 1 byte
Replacing "\n" with an ctual line break saves 1 byte
$n=$argv[1];$s=implode($n,str_split(str_shuffle(str_pad(str_repeat(m,$n),8,n)),4));for(;$i<9;)echo$s[$i].(++$i%3?"":"
");

Try it online!

Alice, 24 bytes
a8E/be?SZ!@
~E-\ita*.o/a

Try it online!
Empty slots are 9, and mines are 0.
I also made a 27-byte program with 1 for mines and 0 for empty slots:
a8Ea8/be?SZ!@
-E-9:\ita*.o/

Try it online!

C (gcc), 81 bytes
f(n,i,j,k){for(j=i=8,k=n;--i+5;putchar(i%4?i-2?rand()%j--<k?k--,88:95:48+n:10));}

Try it online!

PowerShell, 91 86 bytes
-5 bytes thanks to mazzy

param($n)$x=,'X'*$n+,'_'*(8-$n)|random -c 8
-join$x[0..2]
$x[3,4]-join$n
-join$x[5..7]

Try it online!
Shuffles a generated string ranging from ________ to XXXXXXXX (replacing from the left). It then slices through it multiple times, inserting $n in the middle, to build the output string. This last part can probably be greatly optimized because each index costs a minimum of 5 bytes.

nice. 86 bytes

Perl 5 -pa, 105 101 bytes
@o=grep!/^....1/&&y/1//=="@F",map{sprintf"%09b",$_}0..2**9-1;$_=$o[rand@o];s/....\K./@F/;s/...\K/\n/g

Try it online!

Ruby, 59 bytes
Returns a list of strings (one for each line).
->n{a=([0]*(8-n)+[1]*n).shuffle;a[4,0]=n;a.join.scan /.../}

Try it online!

05AB1E, 12 bytes
$×8j.r2äIý3ô

Uses 0 for mines, spaces for blank squares. Outputs a list of lines, which is pretty printed in the TIOs below by joining with newline delimiter (»).
Try it online or verify a few more test cases at once.
Explanation:
$             # Push 0 and the input-digit
 ×            # Repeat the 0 the input-digit amount of times as string
              #  i.e. 4 → "0000"
  8j          # Prepend spaces to make the size 8
              #  → "    0000"
    .r        # Randomly shuffle the characters in this string
              #  i.e. "    0000" → " 00 0  0"
      2ä      # Split it into two equal halves (of 4 characters)
              #  → [" 00 ","0  0"]
        Iý    # Join it with the input-digit
              #  → " 00 40  0"
          3ô  # And then split it into (three) parts of 3 characters
              #  → [" 00"," 40","  0"]
              # (which is output implicitly as result)

12 bytes alternative:
8L@.rIš5._3ô

Uses 1 for mines, 0 for blank squares. Outputs a matrix of digits, which is pretty printed in the TIOs below by joining each row, and then these rows with newline delimiter (J»).
Try it online or verify a few more test cases at once.
Explanation:
8L            # Push the list [1,2,3,4,5,6,7,8]
  @           # Check for each if the (implicit) input-integer is >= it
              # (1 if truthy; 0 if falsey)
              #  i.e. 4 → [1,1,1,1,0,0,0,0]
   .r         # Randomly shuffle this list
              #  i.e. [1,1,1,1,0,0,0,0] → [0,1,1,0,1,0,0,1]
     Iš       # Prepend the input-digit to the list
              #  → [4,0,1,1,0,1,0,0,1]
       5._    # Rotate the list five times towards the left
              #  → [1,0,0,1,4,0,1,1,0]
          3ô  # And then split it into (three) parts of 3 digits each
              #  → [[1,0,0],[1,4,0],[1,1,0]]
              # (which is output implicitly as result)

Vyxal j, 53 bitsv2, 6.625 bytes
IṅÞ℅½j²

Try it Online!
Bitstring:
01011100001000000101111111001100101100100000000011001

Spaces for mines, 0 for empty spaces
IṅÞ℅½j²
I        # Push n spaces
 ṅ       # pad with zeros to the nearest multiple of 8
  Þ℅     # shuffle
    ½j   # split in half and join by the input
      ²  # shape as a square
# j flag joins on newlines

Created with the help of Luminespire.

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


text:
Get the sequence steps
Challenge
Given a sequence of numbers, create a function which returns the sequence steps.

Assume a sequence will be N >= 3
Sequence will repeat it steps at least once
Sequence will only contain natural numbers
Your function or program should return the shortest possible sequence of steps

Example:
Input: [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]
Output: [1, 1, 2]
Explanation: The initial sequence goes from 1 => 2 (1 step), 2 => 3 (1 step), 3 => 5 (2 steps). Then it repeats. The output then is [1 step, 1 step, 2 steps] => [1, 1, 2]
Another example:
Input: [2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]
Output: [3, 1, 1, 1]
[2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]
 \  /\ /\ /\ /
  3   1  1  1  Then it repeats...

Test Cases
Input: [1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28] => Output: [3,4,1,1]
Input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41] => Output: [5,2]
Input: [2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47] => Output: [4,4,3,4]
Input: [5, 6, 7] => Output: [1]

Clarifications

The input length - 1 is divisible by the output length
Assume sequence will always going to be increasing

This is code-golf, so the shortest answer in bytes win.

Related challenge.

@LuisfelipeDejesusMunoz Ah, I hadn't read natural in the challenge, sorry. Another question then: do natural numbers include 0? They usually don't

I've seen a few challenges you've posted recently with a lot of clarifying comments, and a couple closed as "unclear", and subsequently re-opened after you've made the appropriate edits. Have you considered posting these in the sandbox for a few days/a week? I've enjoyed your challenges since they're quite approachable, but all challenges, no matter how simple or by whom they're posted, can use refinement.

@Giuseppe Thanks for your suggestions. I have posted some other challenges in the sand box (usually if i don't get the right way to create a challenge with it i delete it). For these challenges I thought they were clear enough and that's why I posted immediately but I will start posting them in the sandbox first. Thanks

May I output negative deltas? Like [-1, -1, -2]

@LuisMendo Heretic! 0 is a natural number! Billy Joel even had a whole album dedicated to the Peano Man!

@ngm I had it coming... the Billy-Joel-meets-number-theory reference actually made me giggle :-D

@AdmBorkBork, this is more related by virtue of dealing with arbitrary-length operation lists.

Jelly, 9 7 bytes
IsJEƇḢḢ

Try it online!
How it works
IsJEƇḢḢ  Main link. Argument: A (array)

I        Increment; compute D, the array of A's forward differences.
  J      Indices; yield [1, ..., len(A)].
 s       Split D into chunks of length k, for each k in [1, ..., len(A)].
   EƇ    Comb equal; keep only partitions of identical chunks.
     Ḣ   Head; extract the first matching parititon.
      Ḣ  Head; extract the first chunk.

JavaScript (ES6), 58 bytes
Outputs a comma-separated string (with a leading comma).
a=>(a.map(p=x=>-(p-(p=x)))+'').match(/N((,\d+)*?)\1*$/)[1]

Try it online!
Or 56 bytes if we use ,- as the separator and we assume that the sequence is always strictly increasing.
How?
We first convert the input array a[ ] to a list of consecutive differences with:
a.map(p = x => -(p - (p = x)))

Because p is initially set to a non-numeric value (the callback function of map()), the first iteration yields NaN.
Example:
[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
[ NaN, 5, 2, 5, 2, 5, 2, 5, 2, 5, 2 ]

We then coerce the result to a string:
"NaN,5,2,5,2,5,2,5,2,5,2"

Finally, we look for the shortest1 pattern of comma-separated integers (,\d+) starting right after "NaN" and repeating till the end of the string:
match(/N((,\d+)*?)\1*$/)

1: using the non-greedy *?

I'm posting a solution based on the same regex idea, but very different in implementation. Of course I did not look at other solutions before developing mine, and it seems different enough, And maybe it's the first time ever I manage to score better than you here.

53 bytes: /(,.+?)\1*$/.

Brachylog, 11 bytes
s₂ᶠ-ᵐṅᵐ~j₍t

Try it online!
Would be 5 bytes if there was a built-in for consecutive differences.
Explanation
Example input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]

s₂ᶠ             Find all substrings of length 2: [[6,11],[11,13],…,[34,39],[39,41]]
   -ᵐ           Map subtraction: [-5,-2,-5,-2,-5,-2,-5,-2,-5,-2]
     ṅᵐ         Map negate: [5,2,5,2,5,2,5,2,5,2]
       ~j₍      Anti-juxtapose the list of differences; the shortest repeated list is found
                  first, with the biggest number of repetitions: [5,[5,2]]
            t   Tail: [5,2]

Can you negate after the tail, to save a byte?

@Rod I would still need to map it, so it would be the same length. Negate is a predicate between two numbers, it doesn't vectorize automatically to lists like other languages (otherwise it would not work well with unknown inputs/outputs which are common in declarative programs)

Japt, 14 12 bytes
äa
¯@eUéX}aÄ

Try it

Explanation
              :Implicit input of array U
äa            :Consecutive absolute differences
\n            :Reassign to U
 @    }aÄ     :Return the first positive integer X that returns true
   UéX        :  Rotate U right X times
  e           :  Check equality with U
¯             :Slice U to that element

Original
äa
@eUîX}a@¯XÄ

Try it

Pyth, 11 bytes
<J.+Qf.<IJT

Try it here
Explanation
<J.+Qf.<IJT
 J.+Q          Call the sequence of differences in the input J.
     f         Find the first positive integer T...
      .<IJT    ... where rotating J by T doesn't change it.
<J             Take that many elements of J.

R, 49 46 bytes
Full program:
d=diff(scan());while(any((s=d[1:T])-d))T=T+1;s

Try it online!
R, 72 58 54 bytes
Original function submission with all test cases in one place:
function(a,d=diff(a)){while(any((s=d[1:T])-d))T=T+1;s}

Try it online!
Thanks to JayCe for suggesting the full program route and -4 bytes on the function, and to Giuseppe for further -3.

-9 bytes by abusing a built-in and making it a full program The challenge allows a full program.

@JayCe don't need a<- here either

J, 22 19 bytes
3 bytes saved thanks to FrownyFrog!
0{"1[:~./:|."{}.-}:

Try it online!
[Try it online!][TIO-ji2uiwla]
How?
                 -      find the successive differences by subtracting
                  }:    the list with last element dropped
               }.       from the list with the first element dropped
           |."{         rotate the list of differences
         /:             0..length-1 times (the input graded up)
     [:~.               remove duplicating rows
 0{"1                   take the first element of each row

If you /: instead of #\, you can 0{"1[:~. to save 1 byte.

And "0 1 is "{

@FrownyFrog Thanks, once again!

this is gorgeous.

@Jonah Yes, thanks to FrownyFrog!

05AB1E, 8 bytes
Saved 3 bytes thanks to Kevin Cruijssen.
¥.œʒË}нн

Try it online!

05AB1E, 11 bytes
āεI¥ô}ʒË}нн

Try it online!

āεI¥ô}ʒË}нн   Full program.
ā             Length range. Push [1 ... len(inp)].
 ε   }        For each...
  I¥ô         ... Chop the deltas into pieces of the corresponding size
      ʒË}     Keep only those that have all their elements equal.
         нн   And first retrieve the first element of the first one.

13 bytes
A cute alternative, IMO:
¥©ηʒDg®ôÙ˜Q}н

Try it online!
¥©ηʒDg®ôÙ˜Q}н   Full program.
¥               Push the deltas.
 ©              Copy them to the register.
  ηʒ       }    And filter the prefixes by...
    D     Q     ... Is the prefix itself equal to...
     g®ô        ... The deltas, split into chunks of its length...
        Ù˜      ... Deduplicated and flattened?
            н   Head.

8 bytes by using .œ.

Javascript, 49 56 bytes
Edit 7 bytes saved thanks (guess who?) Arnauld
Same regex idea as Arnauld, but curiously so different in implementation ...
Returning a string with steps comma separated (and a leading comma)
p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]

Test

var F=
p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]

;[[1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]
,[1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28]
,[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
,[2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47]
,[5, 6, 7]]
.forEach(x=>console.log(x + ' -> ' + F(x)))

Using match was a poor decision of mine. You can outgolf me some more. :-)

MATL, 14 13 12 bytes
dt5YLFTF#Xu)

Try it online!
Just discovered that MATL does have a circulant function!
Explanation
d - Get the differences between successive terms, as an array
t5YL - duplicate that, then call the YL ('gallery') function with 5 ('circulant') option. Creates a matrix with the given vector as first row, then successive rows are the same vector shifted circularly, until it wraps around.
FTF#Xu - Check for unique rows and get their row numbers (not sure if there's a shorter way of doing this). When sequence steps repeat, the circularly shifted row will be the same as the first row, and the subsequent rows will be repeats. So this gets the indices of the first run of sequence steps before they start repeating.
) - index using that into the original differences array, to get the answer.

Older:
d`tt@YS-a}@:)

Try it online!
(-1 byte thanks to Giuseppe)
Explanation:
d   % Get the differences between successive terms, as an array
`   % Start do-while loop
  tt  % duplicate the difference array twice
  @   % push the current loop index value
  YS  % circularly shift the difference array by that amount
  -   % subtract the shifted diffs from the original diffs
  a   % see if the subtraction resulted in any non-zeros
    % if it did, shifted differences were not equal to original differences, so continue loop
}@ % if it didn't, then get loop index
:) % get the differences upto the loop index, before they started repeating
   % implicit loop end

Java 10, 104 100 bytes
a->{var t="";for(int i=a.length;i-->1;t+=a[i]-a[i-1]+" ");return t.replaceAll("( ?.+?)\\1*$","$1");}

Regex ( ?.+?)\1*$ for shortest repeating substring from @Neil's comment on @Arnauld's JavaScript (ES6) answer.
Try it online.
Explanation:
a->{                        // Method with integer-array parameter and String return-type
  var t="";                 //  Temp-String, starting empty
  for(int i=a.length;i-->1; //  Loop backward over the input-array, skipping the first item
    t+=a[i]-a[i-1]          //   Calculate the difference between two adjacent items
       +" ");               //   And append this with a space to the temp-String
  return t.replaceAll("( ?.+?)\\1*$",
                            //  Find the shortest repeating substring
                     "$1");}//  And only keep one such substring

Ruby, 62 bytes
Relies on Regex logic adapted from Arnauld's answer.
->a{i=-2;a.map{|x|(i+=1)>=0?x-a[i]:0}*?,=~/((,\d+)*?)\1*$/;$1}

Try it online!
Alternative determination of step differences, also 62 bytes:
->a{[0,*a.each_cons(2).map{|x,y|y-x}]*?,=~/((,\d+)*?)\1*$/;$1}

Try it online!

Python 2, 101 bytes
def f(l):d=[y-x for x,y in zip(l,l[1:])];g=len(l);print[d[:k]for k in range(1,g+1)if g/k*d[:k]==d][0]

Try it online!
First generates the deltas d, then finds the first prefix p of d that when repeated ⌊len(L) / len(p)⌋ times yields L, where L is the input list.

Retina 0.8.2, 42 bytes
\d+
$*
(?<=(1+),)\1

1+(.+?)\1*$
$1
1+
$.&

Try it online! Link includes test cases. Output includes leading comma. Explanation:
\d+
$*

Convert to unary.
(?<=(1+),)\1

Compute forward differences, except for the first number, which gets left behind.
1+(.+?)\1*$
$1

Match repeating differences.
1+
$.&

Convert to decimal.

05AB1E, 14 13 bytes
¥DηvÐNƒÁ}QD—#

Try it online or verify all test cases.
I know there are already two shorter 05AB1E answers posted by @Mr.Xcoder, but I wanted to try this alternative approach using rotation and equality check.
Might be able to golf it down a few bytes without dropping Á.
-1 byte after a tip of @Emigna to remove the global_variable registers (© and 2x ®) and use a Duplicate (D) and a Triplicate (Ð) instead.
Explanation:
¥             # Calculate the deltas of the input-array
              #  i.e. [1,2,3,5,6,7,9] → [1,1,2,1,1,2]
 D            # Duplicate it
  η           # Push all its prefixes
              #  [1,1,2,1,1,2] → [[1],[1,1],[1,1,2],[1,1,2,1],[1,1,2,1,1],[1,1,2,1,1,2]]
v             # For-each over these prefixes
 Ð            #  Triplicate the (duplicated) deltas-list
  NƒÁ}        #  Rotate the deltas-list N+1 amount of times,
              #  where N is the prefix index (== prefix_length-1)
              #   i.e. [1,1,2] and [1,1,2,1,1,2] (rotate 3 times) → [1,1,2,1,1,2]
      Q       #  If the rotated deltas and initial deltas are equal
              #   [1,1,2,1,1,2] and [1,1,2,1,1,2] → 1
       D—#    #  Print the current prefix-list, and stop the for-each loop

Here's a 9 (separate answer since it's a very different algo, though it does share the ¥η).

@Grimy Are you going through all my 05AB1E answers and golf each of them, haha? ;p Nice answer though (yet again), +1 from me.

Not all of them, I'm just going through those linked in this post.

@Grimy Ah ok, that makes sense. :)

Haskell, 107 bytes
let i=map(uncurry(-))$zip(tail x)(init x)in head$filter(\s->take(length i)(concat$repeat s)==i)(tail$inits i)

x is the input array.

Welcome to PPCG and Haskell golfing in particular! You cannot assume the input to be present in a certain variable, though this is easily fixed by prepending f x=. Also the use of inits requires import Data.List, as it is not part of Prelude: Try it online!

However you can save quite a few bytes: (init x) can just be x because zip truncates automatically if one of the lists is longer than the other one. And for map(uncurry(-))$zip exists an build-in: zipWith(-). Instead of f x=let i=...in you can use a pattern guard: f x|i<-...=.

Furthermore you can use a list comprehension instead of filter, !!0 instead of head and cycle instead of concat$repeat: Try it online!

@Laikoni Thanks a lot for your improvements!
You are right, my code needs a function declaration and an import for Data.List.inits. But I was wondering, should that be added to the length of the code? I'm asking because some of the other code samples rely on some extra code as well.

Yes, it is general consensus that those bytes are included in the score. We have a guide to golfing rules in Haskell which covers most of these cases.

Sometimes it can be frustrating that imports are counted, but on the other hand they often allow to find different approaches which don't need the import and end up being shorter. That's also the case here, I have a 79 byte version which does not need the import. I'll leave it as a challenge for now if you don't mind.

APL+WIN, 39 bytes
Prompt for input.
(↑((⍴v)=+/¨(⊂v)=(⍳⍴v)⌽¨⊂v)/⍳⍴v)↑v←-2-/⎕

Try it online! Courtesy of Dyalog Classic
Explanation:
v←-2-/⎕ Prompt for input and take successive differences

(⍳⍴v)⌽¨⊂v create a nested vector ans sequentially rotate by one to length of v

+/¨(⊂v)= compare to original v and sum positions where there is match

(⍴v)= identify where all elements match

(↑(....) identify number of rotations giving a first complete match

(↑(...)↑v take first number of elements from above from v as repeated sequence

Python 2, 86 85 bytes
def f(a,n=1):d=[y-x for x,y in zip(a,a[1:])];return d[:-n]==d[n:]and d[:n]or f(a,n+1)

Try it online!
Construct the differences as d; if d repeats with unit size n then d[n:]==d[:-n]; else recurse.

Stax, 8 6 bytes
░»F\☺»

Run and debug it
Here's an unpacked annotated version to show how it works.
:-  pairwise differences
:(  all leftward rotations of array
u   keep only unique rotations
mh  output the first element from each unique rotation

Run this one

Perl 6, 57 bytes
{~(.rotor(2=>-1).map:{.[1]-.[0]})~~/^(.+?){}" $0"+$/;~$0}

Test it
Output is space separated ("1 1 2")
Expanded:
{      # bare block lambda with implicit parameter $_

  ~(   # stringify (space separated)

    .rotor( 2 => -1 )     # from the input take 2 backup 1, repeat
    .map: { .[1] - .[0] } # subtract each pair to find the differences
  )

  ~~   # smartmatch

  /    # regex

    ^  # beginning of string

    ( .+? ) # match at least one character, but as few as possible
    {}      # make sure $0 is set (probably a compiler bug)
    " $0"+  # match $0 one or more times (with a leading space)

    $  # end of string
  /;

  ~$0  # return the stringified $0
}

The whole first part can be ~(.skip Z-$_)

05AB1E, 9 bytes
¥©η.ΔÞ®Å?

Explanation:
          # take input implicitly
¥         # deltas, eg [4, 5, 7, 8, 10] -> [1, 2, 1, 2]
 ©        # save this to the global register
  η       # prefixes, eg [1, 2, 1, 2] -> [[1], [1, 2], ...]
   .Δ     # find the first one such that
     Þ    # cycled infinitely, eg [1, 2] -> [1, 2, 1, 2, ...]
       Å? # starts with
      ®   # the global register
          # and implicitly print the found element

Alternative 9-byte:
¥η.ΔÞ.¥-Ë

Same algo, but instead of comparing to the list of deltas (which needs to be saved/restored), this uses .¥ (undelta) then compares to the (implicit) input.
Try it online!

Perl 5 -p, 55 bytes
s/\d+ (?=(\d+))/($1-$&).$"/ge;s/\d+$//;s/^(.+?)\1*$/$1/

Try it online!
Numbers are input as a space separated list.  Output is the same format.

Wolfram Language (Mathematica), 26 23 bytes
FindRepeat@*Differences

Try it online!

Husk, 12 bytes
←ḟΛ=Um`CẊ≠⁰N

Try it online! or Verify all test cases

K4, 30 bytes
Solution:
(*&d~/:c#'(!c:#d)#\:d)#d:1_-':

Examples:
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20
3 1 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17
1 1 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28
3 4 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41
5 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47
4 4 3 4
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':5 6 7
,1

Explanation:
Seems hefty for what we're trying to solve. Get the deltas of the input and then build sequences and determine the shortest one that matches it.
(*&d~/:c#'(!c:#d)#\:d)#d:1_-': / the solution
                           -': / deltas
                         1_    / drop first
                       d:      / save as d
                      #        / take (#) from
(                    )         / do this together
                 #\:d          / take (#) each-left (\:) from d
          (     )              / do this together
              #d               / count length of d
            c:                 / save as c
           !                   / range 0..c-1
       c#'                     / take c copies of each
   d~/:                        / d equal (~) to each right (/:)
  &                            / where true
 *                             / first one


text:
count ones in range
Challenge :
Count the number of ones 1 in the binary representation of all number between a range.

Input :
Two non-decimal positive integers

Output :
The sum of all the 1s in the range between the two numbers.

Example :
4 , 7        ---> 8
4  = 100 (adds one)   = 1
5  = 101 (adds two)   = 3
6  = 110 (adds two)   = 5
7  = 111 (adds three) = 8

10 , 20     ---> 27
100 , 200   ---> 419
1 , 3       ---> 4
1 , 2       ---> 2
1000, 2000  ---> 5938

I have only explained the first example otherwise it would have taken up a huge amount of space if I tried to explain for all of them.

Note :

Numbers can be apart by over a 1000
All input will be valid.
The minimum output will be one.
You can accept number as an array of two elements.
You can choose how the numbers are ordered.

Winning criteria :
This is code-golf so shortest code in bytes for each language wins.

OEIS A000788

May we take the input as some kind of range type (IntRange in Kotlin, Range in Ruby)?

Fun fact: case 1000 - 2000 yields 5938, but lower the case by 1000, the result also drops by 1000: 0-1000 = 4938. Proof

@steenbergh Consider 0-2000 + 1000. For 0<=i<1000, pair i with (2i,2i+1), then <0-2000,1000> is 2 times <0-1000> plus 1000 extra 1's. Removing a 0-1000 is, 1000-2000 is <0-1000> + 1000

JavaScript (ES6), 38 bytes
Takes input in currying syntax (a)(b).
a=>b=>(g=c=>a>b?0:1+g(c^c&-c||++a))(a)

Try it online!
Commented
a => b => (         // given the input values a and b
  g = c =>          // g = recursive function taking c = current value
    a > b ?         // if a is greater than b:
      0             //   stop recursion and return 0
    :               // else:
      1 +           //   add 1 to the final result
      g(            //   and do a recursive call to g() with:
        c ^ c & -c  //     the current value with the least significant bit thrown away
        || ++a      //     or the next value in the range if the above result is 0
      )             //   end of recursive call
)(a)                // initial call to g() with c = a

Python 2, 47 bytes
f=lambda x,y:y/x and bin(x).count('1')+f(x+1,y)

Try it online!

Clever trick to avoid >=...

Jelly, 4 bytes
rBFS

Try it online!
Explanation

rBFS – Full program. Takes the two inputs from the commands line arguments.
r    – Range.
 B   – For each, convert to binary.
  FS – Flatten and sum.

O_o , that was fast ?

@MuhammadSalman Well, the challenge is also kind of trivial IMO.

It may be, but an answer a minute after posting.

@MuhammadSalman Yes, that's not really that fast for trivial challenges like this one; knowledge of Jelly also ensues. The real effort goes in e.g. the language of this month, QBasic. ;-)

@EriktheOutgolfer : Can you answer this in QBasic / BrainF**k ?

05AB1E, 4 bytes
ŸbSO

Try it online!

Exactly the solution I got :). +1.

Java (JDK 10), 55 bytes
a->b->{int c=0;for(;a<=b;)c+=a.bitCount(b--);return c;}

Try it online!

IntStream.range(a,b+1).map(Integer::bitCount).sum()

@saka1029 The imports are mandatory. So it's actually a->b->java.util.stream.IntStream.range(a,b+1).map(Integer::bitCount).sum(), for a whole 74 bytes. Even if the the import wasn't mandatory, the parameters are, so we'd have to write a->b->IntStream.range(a,b+1).map(Integer::bitCount).sum(), which counts as 57 bytes

You could also have a->b->IntStream.range(a,b+1).map(Long::bitCount).sum() for a 1 byte improvement. Marginal, but still one.

@NotBaal As mentioned by Olivier in the comment above, imports are mandatory, so it should be a->b->java.util.stream.IntStream.range(a,b+1).map(Long::bitCount).sum() (71 bytes).

Python 2, 45 bytes
lambda x,y:`map(bin,range(x,y+1))`.count('1')

Try it online!

Pyth, 8 7 bytes
1 byte thanks to Mr. Xcoder.
ssjR2}F

Try it online!

MATL, 5 4 bytes
&:Bz

Try it online!
Thanks to Luis Mendo for saving a byte!
(implicit input a and b, a<b)
&:                              % two-element input range, construct [a..b]
  B                             % convert to Binary as a logical vector (matrix)
   z                            % number of nonzero entries
(implicit output of the result)

R, 41 34 bytes
function(a,b)sum(intToBits(a:b)>0)

Try it online!
Heavily inspired by the other R solution by ngm. This uses a different approach after the conversion to bits. Huge thanks to Giuseppe for hinting at a possible 34 bytes solution.

34 bytes is possible! I forget where I saw the trick (I know I didn't come up with it) but there's a trickier conversion to a summable vector -- I'll post if you/ngm can't find it.

@Giuseppe Indeed!

I got it down to 37 bytes using a technique that might otherwise be useful. Also discovered that sd and var coerce anything they can to double.

You can use pryr::f to save 4 bytes: https://tio.run/##K/qfZvu/oKiyyMoqTaO4NFcjM68kJN8ps6RYI9EqSdPOQFPzf5qGiY65JleahqGBjpEBhAFiQZg6xhDKSPM/AA

@pajonk good point! But I'm trying to stick to the base R packages rather than R+pryr. I'm going to search on meta what can be considered "pure R".

Python 3, 56 54 52 bytes

This can be golfed more imo.
-2 Bytes thanks to Mr.Xcoder
-2 More bytes thanks to M. I. Wright
lambda a,b:''.join(map(bin,range(a,b+1))).count('1')

Try it online!

You can in fact use str() instead of ''.join(), because all the extra characters don't change the .count('1')

Ruby, 38 bytes
->a,b{("%b"*(b-a+1)%[*a..b]).count ?1}

Try it online!

APL (Dyalog Unicode), 16 bytes
{≢⍸(⍵⍴2)⊤⍺↓0,⍳⍵}

Try it online!
-1 thanks to H.PWiz.
Left argument = min
Right argument = max

Octave with Communication toolbox, 21 bytes
@(a,b)nnz(de2bi(a:b))

Try it online!
The code should be fairly obvious. Number of nonzero elements in the binary representation of each of the numbers in the range.
This would be @(a,b)nnz(dec2bin(a:b)-48) without the communication toolbox.

Vyxal d, 2 bytes
ṡb

Try it online or see a four byte flagless version.
Gets the range between the two inputs, converts each to a list of 1s and 0s, then deep flattens and sums with the d flag.

Brachylog, 8 bytes
⟦₂ḃᵐcọht

Try it online!
Explanation
⟦₂         Ascending range between the two elements in the input
  ḃᵐ       Map to base 2
    c      Concatenate
     ọ     Occurrences of each element
      h    Head: take the list [1, <number of occurrences of 1>]
       t   Tail: the number of occurrences of 1

R, 44 40 37 bytes
function(a,b)sum(c(0,intToBits(a:b)))

Try it online!
Previously:
function(a,b)sum(strtoi(intToBits(a:b)))
function(a,b)sum(as.integer(intToBits(a:b)))

Stax, 6 bytes
çy╠Æ¼☻

Run and debug it

APL+WIN, 33 26 bytes
Prompts for vector of integers:
+/,((↑v)⍴2)⊤(1↓v)+0,⍳-/v←⎕

Try it online! Courtesy of Dalog Classic
Explanation:
v←⎕ prompt for input of a vector of two integers max first

(v←1↓v)+0,⍳-/ create a vector of integers from min to max

(↑v)⍴2 set max power of 2 to max

⊤ convert integers to a matrix of binaries

+/, convert matrix to a vector and sum

PowerShell, 72 bytes
param($x,$y)$x..$y|%{$o+=([convert]::ToString($_,2)-replace0).length};$o

Try it online!
Long because of the conversion to binary [convert]::ToString($_,2) and getting rid of the zeros -replace0. Otherwise we just take the input numbers, make a range $x..$y and for each number in the range convert it to binary, remove the zeros, take the .length thereof (i.e., the number of ones remaining), and add it to our $output.

try to use count instead length :)

@mazzy count will always be 1 because we're counting the length of a string, not an array.

string! you are right. thanks. -replace0 is smart.

Bash + common utilities, 50
jot -w%o - $@|tr 247356 1132|fold -1|paste -sd+|bc

Try it online!
Converting integers to binary strings is always a bit of pain in bash.  The approach here is slightly different - convert the integers to octal, then replace each octal digit with the number of binary 1s it contains.  Then we can just sum all converted digits

Forth (gforth), 69 bytes
: f 1+ 0 -rot swap do i begin 2 /mod -rot + swap ?dup 0= until loop ;

Try it online!
Explanation
The basic algorithm is to loop over every number in range, and sum the binary digits (divide by two, add remainder to sum, repeat until number is 0)
Code Explanation
1+                   \ add one to the higher number to make it inclusive
0 -rot swap          \ create a sum value of 0 and put loop parameters in high low order
do                   \ start a loop over the range provided
  i                  \ place the index on the stack
  begin              \ start an indefinite loop
    2 /mod           \ get the quotient and remainder of dividing by 2
    -rot             \ move the quotient to the back
    + swap           \ add the remainder to the sum and move it down the stack
    ?dup             \ duplicate the quotient unless it equals 0
    0=               \ check if it equals 0
  until              \ if it does equal 0, end the inner loop
loop                 \ end the outer loop

QBasic, 95 93 83 82 bytes
@DLosc saved me some a lot of bytes!
Saved another byte using this technique!
INPUT a,b
FOR i=a TO b
k=i
FOR j=i TO 0STEP-1
x=k>=2^j
s=s-x
k=k+x*2^j
NEXT j,i
?s

Language of the Month FTW!
Explanation
INPUT a,b           Ask user for lower and upper bound
FOR i=a TO b        Loop through that range
k=i                 we need a copy of i to not break the FOR loop
FOR j=i TO 0STEP-1  We're gonna loop through exponents of 2 from high to low.
                    Setting the first test up for 4 to 2^4 (etc) we know we're overshooting, but that 's OK
x=k>=2^j            Test if the current power of 2 is equal to or smaller than k
                    (yields 0 for false and -1 for true)
s=s-x               If k is bigger than 2^j, we found a 1, so add 1 to our running total s
                    (or sub -1 from the total s...)
k=k+x*2^j           Lower k by that factor of 2 if the test is true, else by 0
NEXT                Test the next exponent of 2
NEXT                process the next number in range
?s                  print the total

Last testcase of 1000 to 2000 actually works, in QBasic 4.5 running on Dosbox:

Husk, 4 bytes
Σṁḋ…

Try it online!
Explanation
Σṁḋ…
   …     Get the (inclusive) range.
 ṁḋ      Convert each to binary and concatenate.
Σ        Get the sum.

Pari/GP, 31 bytes
Saved one byte thanks to Mr. Xcoder.
a->b->sum(i=a,b,sumdigits(i,2))

Try it online!

Japt -x, 10 8 7 bytes
òV ®¤è1

Try it online!

8 bytes: òV m¤¬è1

Proton, 40 37 bytes
x=>y=>str(map(bin,x..y+1)).count("1")

Try it online!

Japt -x, 8 7 bytes
Takes input as an array of 2 integers.
rõ ®¤¬x

Try it

Explanation
rõ          :Reduce by inclusive range
   ®        :Map
    ¤       :  Convert to binary string
     ¬      :  Split
      x     :  Reduce by addition
            :Implicitly reduce by addition and output

PHP, 97 Bytes
(sure this can be shortened, but wanted to use the functions)
Try it online
Code
<?=substr_count(implode(array_map(function($v){return decbin($v);},
 range($argv[0],$argv[1]))),1);

Explanation
<?=
 substr_count(   //Implode the array and count every "1"
  implode(
    array_map(function($v){return decbin($v);}, //Transform every decimal to bin
          range($argv[0],$argv[1])   //generate a range between the arguments
     )
),1);   //count "1"'s

it seems you can just do this

For a second i absolutely forgot that you can set php function's name directly as a parameter :-(

$argv[0] is the program name or "-"; You should work with $argv[1] and $argv[2]. And you can use join instead of implode, shortening this to 68 bytes: <?=substr_count(join(array_map(decbin,range($argv[1],$argv[2]))),1);

K (ngn/k), 19 13 bytes
{+//2\x_!1+y}

Try it online!
{ } is a function with arguments x and y
!1+y is the list 0 1 ... y
x_ drops the first x elements
2\ encodes each int as a list of binary digits of the same length (this is specific to ngn/k)
+/ sum
+// sum until convergence; in this case sum of the sum of all binary digit lists

Haskell, 42 bytes
import Data.Bits
a%b=sum$popCount<$>[a..b]

Try it online!

Pip, 10 bytes
$+JTB:a\,b

Try it online!
Explanation
            a and b are command-line args (implicit)
      a\,b  Inclusive range from a to b
   TB:      Convert to binary (: forces TB's precedence down)
  J         Join into a single string of 1's and 0's
$+          Sum (fold on +)

J, 16, 15 14 bytes
1 byte saved thanks to FrownyFrog!
+/@,@#:@}.i.,]

Try it online!
Explanation:
A dyadic verb, the left argument is the lower bound m of the range, the right one - the upper n.
            ,    append
             ]   n to the
          i.     list 0..n-1
         }.      drop m elements from the beginning of that list
      #:@        and convert each element to binary
    ,@           and flatten the table
 +/@             and find the sum

Can you make it 14?

@FrownyFrog I'll try later today (apparently it's possible, since you are asking :) )

@FrownyFrog 15 for now, I'm still trying...

14

@FrownyFrog Aah, so easy! I was thinking about }. but always in a fork and not in a hook. Thanks!

Perl 6, 32 30 bytes
-1 bytes thanks to Brad Gillbert
{[…](@_)>>.base(2).comb.sum}

Try it online!
Explanation:
[…](@_)    #Range of parameter 1 to parameter 2
       >>    #Map each number to
                      .sum  #The sum of
                 .comb      #The string of
         .base(2)    #The binary form of the number

You can reduce it by one byte if you use [...](@_) instead of ($^a..$^b)

Charcoal, 10 bytes
ＩΣ⭆…·ＮＮ⍘ι²

Try it online! Link is to verbose version of code. Explanation:
     ＮＮ     Input numbers
   …·       Inclusive range
  ⭆         Map over range and join
        ι   Current value
         ²  Literal 2
       ⍘    Convert to base as string
 Σ          Sum of digits
Ｉ           Cast to string
            Implicitly print

Bash + coreutils, 38 32 bytes
seq -f2o%.fn $*|dc|tr -d 0|wc -c

Thanks to @Cowsquack for golfing off 6 bytes!
Try it online!

Nice approach, you can use dc to shave 6 bytes, seq -f2o%fp $*|dc|tr -cd 1|wc -c

Perl 5 -p, 39 bytes
map$\+=(sprintf'%b',$_)=~y/1//,$_..<>}{

Try it online!

APL (Dyalog Extended), 6 bytesSBCS
≢⍤⍸⍤⊤…

Try it online!
 ≢ tally
⍤ of
 ⍸ where true
⍤ in
 ⊤ the binary representation of
… the range

… and it looks cute too

PHP, 68 bytes
The mapping variant already has been posted (though not yet in it´s mostly golfed version), so here is a looping solution:
for($i=$argv[2];$i>=$argv[1];)for($n=$i--;$n;$n>>=1)$s+=$n&1;echo$s;

Run with -nr or try it online.

6510 machine code, 29 28 bytes
sub routine;
takes input from A (lower bound) and X (upper bound) registers;
returns result in A (MSB) and Y (LSB)
machine code:
85 02 A0 00 84 FC E8 CA
E4 02 30 OD 8A F0 F8 46
90 FB E8 90 F8 E6 FC D0
F4 A5 FC 60

source code:
        STA $02     store lower bound in $02
        LDY #0      init result to 0 (Y = LSB, $FC=MSB)
        STY $FC
        INX         increment upper bound
LOOP1:  DEX         decrement upper bound
        CPX $02     compare to lower bound
        BMI :FINISH if smaller, return
        TXA         copy X to A
LOOP2:  BEQ :LOOP1  if 0, next outer loop
        LSR         shift right
        BCC :LOOP2  if carry is clear, next inner loop
        INY         else increment result
        BCC :LOOP2
        INC $FC
        BNE :LOOP2  next inner loop
FINISH: LDA $FC
        RTS

notes

With only 8 bit input possible, the maximum number of set bits is 1024; so incrementing the MSB (INC $FC) always has a non-zero result; hence BNE :LOOP always branches.
BEQ following that BNE never branches, even not if the accumulator is zero (so I could actually add two to the BEQ parameter and save one cycle); but that doesn´t matter: LSR will clear the carry and set the zero flag, BCC will hop to LOOP2 and the BEQ to LOOP1.
I´m not completely sure (it´s been so long I actually coded on the C64), but it may fail if the range is larger than 127: CPX $02 is actually a substraction; if the result is >127, the negative flag may be set, so BMI would end the routine.
I hope I got the branching parameters correct - I assembled the machine code manually.

Scala, 45 44 bytes
_.to(_)flatMap(_.toBinaryString)count(49==)

Try it in Scastie

Thunno 2 S, 4 bytes
I2Bʂ

Attempt This Online!
Explanation
I2Bʂ  # Implicit input
I     # Inclusive range
 2B   # Convert each to binary
   ʂ  # Sum each inner list
      # Implicit output of sum

Rust, 54 50 btyes
Try it online!
|l:u32,h:u32|(l..=h).fold(0,|c,x|c+x.count_ones())

count_ones does the heavy lifting of counting the number of ones in each number here.
Used fold to avoid turbofish from sum.
Ungolfed:
|low: u32, high: u32| (low..=high).fold(0, |total, x| total + x.count_ones())

J-uby, 26 bytes
:!~|:sum+(~:digits&2|:sum)

Attempt This Online!

Retina 0.8.2, 43 bytes
\d+
$*
M!&`(?<=^(1+),.*)\1.*
+`(1+)\1
$1x
1

Try it online!

42 bytes

RProgN 2, 10 bytes
R²2Br.`0-L

Try it online!

C (GCC), 49 bytes
This function takes lower (a) and upper (b) bounds. Output is either through global c or by return value (if your ABI uses the same register from accumulating and function return).
c;f(a,b){for(c=b-a?f(a+1,b):0;a;a/=2)c+=a&1;a=c;}

Try It Online (output by return value)
Acknowledgments

-5 bytes thanks to GPS
-1 byte thanks to ceilingcat

50 bytes: c;f(a,b){c=b-a?f(a+1,b):0;for(;a;a/=2)c+=a&1;a=c;}

Javascript ES6, 78 bytes
With currying syntax
x=>y=>[...Array(y-x+1)].map((e,i)=>(i+x).toString`2`).join``.split`1`.length-1

Red, 82 bytes
func[a b][s: 0 until[n: a until[if n % 2 = 1[s: s + 1]1 > n: n / 2]b < a: a + 1]s]

Try it online!

F#, 80 bytes
let c s e=Seq.sumBy(fun x->seq{for i=0 to 31 do yield x>>>i&&&1}|>Seq.sum){s..e}

Try it online!
For each number x in the range, shift the number by i bytes, AND it with 1, and add that to the sum for that number. Finally add all the shifting results for each number and return it.
It does the shift 32 times, since the starting and ending numbers are of type int32.

Tcl, 80 bytes
proc P a\ b {while \$a<=$b {incr c [regexp -all 1 [format %b $a]]
incr a}
set c}

Try it online!

Julia 0.6, 28 bytes
(a,b)->sum(count_ones.(a:b))

Try it online!

If input can be sent in in the form of a range (i.e. c(4:7) instead of c(4,7)), that saves 6 bytes:
Julia 0.6, 22 bytes
r->sum(count_ones.(r))

Try it online!

sed 4.2.2, 59
:
s/\b(1+) (11\1)/\1 1\1 \2/
t
:a
s/(1+)\1/\10/
ta
s/0| //g

Try it online!
Input and output as unary.  Input is two space-separated unary integers.
The TIO has a footer line to convert to decimal, as a convenience.
The 1000, 2000 testcase takes too long - TIO times out after 1 minute.

Powershell, 59 58 bytes
param($n,$m)$n..$m|%{for(;$_){$s+=$_-band1;$_=$_-shr1}};$s

Test script:
$f = {
param($n,$m)$n..$m|%{for(;$_){$s+=$_-band1;$_=$_-shr1}};$s
}

@(
,(4,7,8)
,(10,20,27)
,(100,200,419)
,(1,3,4)
,(1,2,2)
,(1000,2000,5938)
) | % {
    $n,$m,$e=$_
    $r = &$f $n $m
    $c = $r -eq $e

    "$c : $n , $m ---> $e = $r"
}

Output:
True : 4 , 7 ---> 8 = 8
True : 10 , 20 ---> 27 = 27
True : 100 , 200 ---> 419 = 419
True : 1 , 3 ---> 4 = 4
True : 1 , 2 ---> 2 = 2
True : 1000 , 2000 ---> 5938 = 5938

Pyt, 3 bytes
Input is the larger number then the smaller number
ŘĦƩ

Explanation:
      Implicitly get the two numbers x and y (x<y)
Ř     Push [x,x+1,...,y]
Ħ     Get the Hamming weight of each element of the array
Ʃ     Sum the list of Hamming weights
      Implicit output

Try it online!

C# (.NET Core) with LINQ, 82 bytes
(a,b)=>{int c=0;for(;a<=b;a++)c+=Convert.ToString(a,2).Count(x=>x=='1');return c;}

Try it online!
Ungolfed:
(a, b) => {                     // takes in two integer inputs, separated by a comma
    int c = 0;                  // initialize the sum variable
    for(; a <= b; a++)          // from a (inclusive) to b (exclusive)
        c +=                            // add to c:
            Convert.ToString(a, 2)          // convert a to binary
                .Count(x => x == '1');      // count the number of ones in the binary form
    return c;                   // print c after the loop
}

x86 machine code, 14 bytes
00000000: 31c0 f30f b8d9 01d8 4139 d17e f5c3       1.......A9.~..

Takes bottom of range in ecx, and top of range in ebx. Returns in eax.
Assembly (NASM syntax):
section .text
	global func
func:
					;1st arg = ecx, 2nd arg = edx
	xor eax, eax			;reset total
	loop:
		popcnt ebx, ecx		;get number of binary 1's in current number and store in ebx
		add eax, ebx		;add ebx to total (eax)
		inc ecx			;increase the current number (ecx) in range
		cmp ecx, edx
		jle loop		;repeat while current number (ecx) >= range max (edx)
	ret				;return the register eax

Try it online!
C code equivalent:
/*
ecx=range_start
edx=range_end
eax=total
ebx=ones_count
*/

int ones_in_range(int range_start, int range_end){
	int total = 0;
	do {
		int ones_count = __builtin_popcount(range_start);
		total += ones_count;
		range_start++;
	} while(range_start <= range_end);
	return total;
}

APL(NARS), 15 chars, 30 bytes
{+/∊(⍵⍴2)⊤⍺..⍵}

test
  f←{+/∊(⍵⍴2)⊤⍺..⍵}
  1000 f 2000
5938

This seems ok even in the case 0 f 0 because +/⍬ is 0.

Burlesque - 12 bytes
per@b2\['1CN

pe             Parse eval
  r@           range
    b2         convert to base2
      \[       concat
        '1CN   count the `1`.

Try it online.

x86-16 machine code, 16 bytes
Binary:
00000000: 33c0 8bd1 d1e2 7301 4075 f93b cbe0 f3c3  3.....s.@u.;....

Listing:
33 C0       XOR  AX, AX         ; clear 1's counter in AX
        INTLOOP:
8B D1       MOV  DX, CX         ; current number into DX
        BITLOOP:
D1 E2       SHL  DX, 1          ; MSb into CF, ZF = ( DX == 0 )
73 01       JNC  BITZERO        ; if a zero, check ZF
40          INC  AX             ; increment counter
        BITZERO:
75 F9       JNZ  BITLOOP        ; if DX > 0 keep looping
3B CB       CMP  CX, BX         ; is CX < BX?
E0 F3       LOOPNZ INTLOOP      ; if not, decrement CX and loop
C3          RET                 ; return to caller

Callable function, low range number in BX, high number in CX.  Result in AX.
Note: There is another IA machine code submission which uses the POPCNT instruction introduced with SSE4 requiring an Intel Core or later architecture.  This one will run on any 8086 or later CPU.
Test program:

Wolfram Language (Mathematica), 28 bytes
Tr@DigitCount[Range@##,2,1]&

Try it online!

Prolog (SWI), 43 bytes
A*B*O:-A>B,O=0;- \A*B*S,O is S+popcount(A).

Try it online!

Aya, 15 bytes
[2|,10 2.&].FW

Apparently there's no to binary built-in, so it needs to be done manually. Takes inputs on the stack.
Example Session
Given that there's no try it online, I figured I'd provide an example console session, placing the program in a function for convenience. It would work outside the function and without the variable names, as taking input from the stack is an allowed default for stack languages.
aya> {a b, a b[2|,10 2.&].FW} :f
{a b, a b [2|, 10 2 .&] .F W}
aya> 4 7 f
8
aya> 10 20 f
27
aya> 100 200 f
419
aya> 1 3 f
4
aya> 1 2 f
2
aya> 1000 2000 f
5938

Explained
[2|,10 2.&].FW
[2|,      ]     # Over each number in a range from the first input to the second
        .&      #   Convert the number
    10          #   From base 10
       2        #   To base 2
           .F   # Flatten the resulting list
             W  # And summate

Created with the help of Luminespire.

MathGolf, 7 bytes
╒k(≥mâΣ

Takes two loose inputs in reversed order.
Try it online.
Explanation:
Unfortunately, MathGolf lacks a ranged-list builtin, so 4 bytes are used for that..
╒k(≥     # Push a list in the range [secondInput,firstInput]:
╒        #  Push a list in the range [1, (first) implicit input-integer]
 k       #  Push the second input-integer
  (      #  Decrease it by 1
   ≥     #  Remove that many leading items from the ranged-list
    m    # Map over each integer in this list:
     â   #  Convert it to a binary-list
      Σ  # Take the flattened sum of this list of lists of bits
         # (after which the entire stack is output implicitly as result)

Swift 5.9, 54 bytes
let f={($0+0...$1+0).reduce(0){$0+$1.nonzeroBitCount}}

f(_:_:) takes a lower bound and an upper bound.
There aren't really any fancy tricks here, just a simple call to reduce(_:_:) and some hints for the type checker in the form of +0s.