text:
Tips for golfing in Swift
What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications?
Please post one tip per answer.

You can count on us--if it's meant to be safe, it will be made d̶a̶n̶g̶e̶r̶o̶u̶s̶ golfy!

Hopefully some good tips come in swiftly.

Swift golfing? I thought golf was supposed to be a slow-paced, calm game...

Ranges
One thing that is really helpful is creating ranges using the ... or ..< operators
For example
array[0..<n] //first n elements of array
array[k..<n] //kth through nth elements of array
array[k...n] //kth through n-1 elements of array

So, to get the 2nd through 4th values of an array
let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"]
print(myArray[1..<4]) //["cd", "ef", "gh"]

Practical Use
let a = [3, 1, 4, 1, 5, 9]

Using
for v in a[0...3]{print(v)}

Is 8 bytes shorter than
for n in 0...3{let v=a[n];print(v)}

…is for n in 0...3{print(a[n])} not valid?

You can also use unbound ranges like ...3 and 3.... For that example you can use a[...3].map{print($0)}.

Closures:
The use of variables the hold a function vs. using a function itself can help:
65 bytes:
var r:(String,Int)->String={return String(repeating:$0,count:$1)}

66 bytes:
func r(s:String,i:Int)->String{return String(repeating:s,count:i)}

Small difference here, but it'll show more in some puzzles.
Shortening Functions:
Looking at the previous example reminds me of something. Sometimes, if you will be using a function enough times, it is worth the space to rename it:
This:
String(repeating:$0,count:$1)

To this:
var r:(String,Int)->String={return String(repeating:$0,count:$1)}

Or, actually, this is better:
var r=String.init(repeating:count:)

That way you just call r("Hello World",8) instead of String(repeating:"Hello World",count:8)
Leaving Out Type Declarations:
I once created a closure without setting the argument type, thus creating a shorter answer:
var f={(i)->Int in i-1+i%2*2}

The compiler inferred that i is in Int.
Create Arrays the Fast Way:
If you need an array of Ints, use a Range to create it:
Array(0...5)

This does the same thing as:
[0,1,2,3,4,5]

Arrays Instead of If or Switch:
Instead of doing this:
if n==0{return "a"}else if n==1{return "b"}else{return "c"}

You can probably do this:
return ["a","b","c"][n]

Shorten Types:
If you are using type conversion a lot, you might want to create a type alias:
typealias f=Float

Map:
Remember that you often don't need to use the return keyword in the map function.
Running Swift Online:
Although Try It Online does not support Swift It does now!

Thanks for the post. Helped me a lot. https://tio.run/nexus now works with swift :)

Getting Rid of Argument Labels
Argument labels eat up a lot of characters:
String(repeating:"-",count:81)

g.joined(separator:"")

But function types in Swift have no argument labels, so if we use the function type instead of the initializer/method directly, we don't need argument labels. The shortest way I know is to put the initializer/method in a closure, then call the closure, and immediately call the resulting function:
{String.init}()("-",81)

{g.joined}()("")

This works for overloaded methods as well, as long as the compiler can infer the method to call from the parameter types.

In case anybody is curious, argument labels come from Objective-C, which borrowed the from Smalltalk. In those languages, the function "name" and the first label were combined.

try
In Swift 2.x and above, functions that traditionally handled errors by passing a pointer to an NSError object as a function parameter now throw their error.
This means that this:
var regex = NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: nil, error: nil)

now looks like:
do {
    let regex = try NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])
} catch {
    print(error)
}

This can be shortened by using try? or try!.  try? will evaluate the expression to nil if an error is thrown.  try! will crash your program if an error is thrown, and should be only used in cases where there will never be an error thrown.
let regex = try! NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])

try? and try! save at least 13 bytes from the do-try-catch loop.  Note that you also save at least one more byte by passing in an empty array ([]) for options instead of nil as well.

Reducing Arrays
Iterating with for-in loops through an array to get a single value such as the sum of the elements inside, or the product of its elements may be too long for how simple it actually is. You can just use the reduce() method. Some examples:
var array = [1,2,3,4,5,6,7]

Adding up the elements in an array with for-in loops:
var sum = 0

for item in array{
    sum += item
}
print(sum)

can be simplified to:
print(array.reduce(0, +))

And getting the product of the elements inside of the array with for-in loops:
var multiplier = 1
for item in array{
    multiplier *= item
}
print(multiplier)

can also be reduced to:
print(array.reduce(1, *))

Don't you lose more bytes by declaring the ** function than you would by just calling pow manually?

@JAL yes, but if you call pow 10 times, it saves a small amount of bytes. Not really the best golfing technique, but it's just another potential help. It was not meant for pow specifically, but for other operations such as searching for prime numbers, if you do that 3 times, it saves a huge amount of bytes

Substring
Sometimes, you can save bytes by falling back onto Foundation types instead of using pure Swift types.  Compare accessing a substring of an NSString vs a Swift String type:
let x:NSString = "hello world"
x.substringToIndex(5) // "hello"

let y = "hello world"
y.substringToIndex(y.startIndex.advancedBy(5)) // "hello"

Even with the 9 characters lost by declaring x as an NSString, you save 25 more by using the Foundation type, since substringToIndex takes an Int as a parameter for NSString, vs an Index struct (String.CharacterView.Index) for Swift String types.
I should note that the availability of Foundation types may differ across multiple platforms (OS X, Linux, etc).  Most Foundation classes are NSUnimplemented in the open-source version of Swift.

Enumeration
You can chain forEach from enumerated() on a collection type to get a reference to the object (or value type) in a collection, as well as its index:
[1,2,3,4,5].enumerated().forEach{print($0,$1)}

or
for (c,i) in [1,2,3,4,5].enumerated(){print(c,i)}

or (even shorter CountableClosedRange syntax)
(1...5).enumerated().forEach{print($0,$1)}

Prints:
0 1
1 2
2 3
3 4
4 5

.map()
Combining .map() with trailing closure syntax can tighten up for-loops. We can put the things we want to iterate over into an array, then use .map() to perform some action on each element.
For example, we can use .map() to write that old chestnut, Fizzbuzz, in one line.
var d: [Int] = Array(1...100)

d.map{$0%15 == 0 ? print("Fizzbuzz") : $0%3 == 0 ? print("Fizz") : $0%5 == 0 ? print("Buzz") : print($0)}

Outside of golf, .map() can help cut down on repetition. For example, suppose you have a view you need to position programmatically. You can put the anchors for the view into an anonymous array and run .map() over it to set each constraint's .isActive to true, like so:
_ = [
        view.topAnchor.constraint(equalTo: view.topAnchor, constant: 40),
        view.widthAnchor.constraint(equalTo: view.widthAnchor),
        view.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ].map { $0.isActive = true }

Isn't it better to use forEach in your second example?  map should really be used for transforming the contents of an array, and not as an iteration shortcut.  In this case, you're discarding the result.

Golfing variable assignments in control flow structures using tuples
Consider you want to use a while loop, and you want to use the same thing in both the condition and the block to follow. Then, an inline assignment in a tuple would most likely help. The longer your attribute, the better! Consider this (3 bytes shorter):
func f(s:[Int]){var k=s,i=0;while(i=k.count,i>0).1{print(i,i+k[i-1]);k.removeLast();}}

over this:
func g(s:[Int]){var k=s,i=0;while k.count>0{i=k.count;print(i,i+k[i-1]);k.removeLast();}}

Notice the (i=k.count,i>0).1 part, which is quite interesting.

Inspired by one of Herman Lauenstein's answers.

Import
You can replace import Foundation with import UIKit for 5 bytes shorter, as UIKit does import Foundation already.

Swift's ternary operator is very terse: condition ? action : otheraction
If the condition is true, do one thing, if not, do something else.
textColor = bgIsBlack ? .white : .black

This makes the textColor white if the background is black, or black if the background is any other color.
The nil coalescing operator is even terser: a ?? b
Let's say you're checking JSON for a certain key so you can present the key's value as title text. If the key isn't present (i.e value is nil), we want to give the title default text.
title = keysValue ?? "Not Available"

Repeating Strings
Unfortunately, Swift does not support String multiplication with *, likewise Python. A good method you can use instead is String(repeating:count:), but unfortunately that's not really golfy. Compare these two approaches:
var a=String(repeating:"abc",count:3)

and
var a="";for _ in 0..<3{a+="abc"}

The second one is a couple of bytes shorter, but that cannot be used in a closure... Better yet, and it also works in closures:
(0..<3).map{_ in"abc"}.joined()

And what if I do it multiple times? Well, you can use String.init(). Now, this may save lots of bytes. For example (68 bytes):
let k=String.init(repeating:count:)
print(k("abcd",9)+k("XYZxyz",9))

instead of (74 bytes):
print(String(repeating:"abcd",count:9)+String(repeating:"XYZxyz",count:9))

or (70 bytes):
var f={String(repeating:$0,count:$1)}
print(f("abcd",9)+f("XYZxyz",9))

But make sure your String is long enough. If you are using String(repeating:"abc",3), it is much better to use "abcabcabc" instead.

+1 because I had no idea variables could be initializers like that.

Type Inference
Swift's type checker is very good at inferring types — a blessing like no other when golfing — but sometimes it needs a little help. Consider this code (borrowed from one of my own answers):
let function = { (decoy: String, target: String) in
  let array = ([decoy] + { [String].init }()(target, 511)).shuffled()
  // ...
}

(For context, this creates a 512-element array where all but one of the elements are identical.)
Thanks to closure tricks, this is already pretty golfy once whitespace is removed and names are shortened:
let f={(d:String,t:String)in let a=([d]+{[String].init}()(t,511)).shuffled()
/* ... */}

But there are three words that stick out like sore thumbs, and they all start with an S and end with a tring. Thankfully, we can get rid of all three by combining two more tricks.
Type Placeholders (Swift 5.6 and newer)
If the type checker can't infer an entire type on its own, but it can infer some of its type parameters (i.e. things like the T in SomeType<T>), then you can replace those parameters with an underscore to tell the type checker to figure them out for you. For instance, Array<String> can become Array<_> (as long as something else makes it clear that the type parameter is a String).

Of course, this also applies to the syntactic sugar versions of Array<Element>, Dictionary<Key, Value>, and Optional<Wrapped>, as well as tuple types, function types, and anything else that counts as a type. So [String] can be replaced with [_] in much the same manner.

Taking advantage of this, we can save 5 bytes in our example:
let f={(d:String,t:String)in let a=([d]+{[_].init}()(t,511)).shuffled()
/* ... */}

Now we've got the other two to deal with. We can't use the type placeholder trick with these, since the type checker will then struggle with just about everything. So we've got to hint at these types another way...
Appending Literals
Let's start with an absolutely horrible example that still illustrates the point well:
let p={(n:Int)in print(n)}

Let's say you want to get rid of the bulky Int type signature. You can't just outright remove it, because then the type checker won't have any way of knowing that n is an Int. So you need to give it some other, shorter way of figuring the type out.
One way to do this is by doing something with the value that doesn't affect how the program runs, but still makes it clear what the type is. In this instance, you can simply add 0 to n:
let p={n in print(n+0)}

Since we no longer have to declare any explicit types, we can do away with the closure header altogether and use implicit closure parameters instead:
let p={print($0+0)}

Note, however, that this only saves bytes if you only use each parameter once or twice, and that implicit parameters can't be used inside of other closures.

Here's a table of literals you can use in this manner:

Type
Type Hint

Array
$0+[]

Dictionary
$0+[:]

String
$0+""

Int
$0+0

Double
$0+0.0

Using these, our first example can be reduced to:
let f={d,t in let a=([d+""]+{[_].init}()(t,511)).shuffled()
/* ... */}

t can be inferred on its own without a problem here, so we don't need to append an empty literal to it.

With implicit closure parameters, we can make this even smaller:
let f={let a=([$0+""]+{[_].init}()($1,511)).shuffled()
/* ... */}

Conversion to string
When possible, it is shorter to use string interpolation than to use the String method for converting to a string.
String(a)

vs
"\(a)"

Boolean Literals
Instead of using Boolean literals, which take up 4 or 5 bytes, use a 3-byte comparison instead.

Literal
Comparison
Bytes Saved

true
0<1
1

false
0>1
2


text:
Minimize Those Ones
Your task is to build a natural number using the fewest number of ones and only the operators + or -. For example, the number seven can be written 1+1+1+1+1+1+1=7, but it can also be written as 11-1-1-1-1=7. The first one uses 7 ones, while the latter only uses 6. Your task is to return the minimum number of ones that can be used given the input of some natural number, n.
This is code golf, so the shortest valid code in bytes wins.
Test cases
Input => Output
0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21

Nice first challenge. I'd suggest including more test cases. Is "VALID OUTPUTS" a mistake, given that there's a single output? Also, is 0 a valid input, and if so, what should be output?

This is an interesting challenge. You may want to add an explanation for the outputs, change VALID OUTPUTS. It's your choice, but generally people like bold or italics instead of CAPITAL LETTERS (they make it look like shouting instead of emphasis). Bold is **bold text**, and italics is *italics text*. You could also use ### Text for bold-er text. Anyway, welcome to PPCG!

You should make a computer-readable table or list of test cases that people can run their code on. See this tip.

I'm voting to close this question because this question is of a duplicate of the current (active!!) golfing challenge over at https://codefights.com/challenges. Even if the OP is also the author of the original challenge on codefights (which I doubt), the question should be closed until the challenge on codefights isn't active any more.

@Jakube the direct link could've been helpful, but I agree. I will vote to close.

Is it gone yet?

JavaScript (ES6), 127 126 87 bytes

f=(n,z=2,m=n*9+'',r=m.replace(/./g,1))=>n?m.length+(m<'55'?f(n- --r/10,0)-1:f(r-n,0)):z
Input: <input type="number" oninput="result.textContent=f(this.value)"> Result:

Should work to about 101415 at which point you start running into JavaScript's integer limits. Explanation:
f=(                             Recursive function
 n,                             Parameter
 z=2,                           Zero workaround
 m=n*9+'',                      Magic
 r=m.replace(/./g,1)            Find repunit not less than than n
)=>n?                           Nothing to do if n is zero
 m.length+                      Assume subtracting from repunit
 (m<'55'?                       Should we subtract from repunit?
  f(n- --r/10,0)                No, so subtract previous repuint
   -1:                          Which is one 1 shorter
  f(r-n,0)):                    Subtract from repunit
 z                              Return special case if n is zero

This uses the n*9 magic twice; firstly, it gives me the length of the next repunit, secondly, if the first two digits of n*9 are 55 or higher, then we need to subtract n from that next repunit, otherwise we need to subtract the previous repunit (which is calculated by subtracting 1 and dividing by 10). This should work up to 1015.

Pyth, 19 16 bytes
ffqQvs+R1Y^c3"+-

Test suite
Brute force algorithm. The necessary strings are generated by taking all lists whose elements are ['+', '-', ''] of length equal to the number of 1s being tested, appending a 1 to each, and concatenating to a single string. These strings are then evaluated and compared with the input. This is repeated until a successful string is found.
Some strings with a leading + or - are tested, but this isn't a problem. It would be if the input was negative though.
It can run up to length 9 before it becomes too slow.
Explanation:
ffqQvs+R1Y^c3"+-
ffqQvs+R1Y^c3"+-"T    Implicit variable introduction
                      Q = eval(input())
f                     Starting with T = 1 and counting upwards, repeat until true.
                      The value of T where the result is first true is output.
           c3"+-"     Chop "+-" into thirds, giving ['+', '-', '']
          ^      T    Form every list with those elements of length T.
 f                    Filter over those lists, lambda var Y.
      +R1Y            Append a 1 to each element of the list.
     s                Concatenate.
    v                 Eval.
  qQ                  Compare for equality with the input.
                      The inner filter will let through the successful cases.
                      The outer filter will stop when there is a successful case.

JavaScript (ES6), 92 bytes

f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1
n = <input type="number" oninput="R.textContent=f(this.value)" />

Explanation
Recursive function. This generates all possible permutations of 1s separated by either +, - or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit 0 to -, 1 to + and 2 to an empty string, then joining them together with 1s. The resulting string is evald as a JavaScript statement which returns the result of the equation.
Because the operators are joined with 1s in between (like +1+1+1+), there are length - 1 1s. The first operator is ignored (because +1 = 1, <nothing>1 = 1 and it's a number so there will never be a leading 0 for -) and the final operator is also ignored (by appending .0 to the equation).
Higher Output Version, 96 bytes
The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.
n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')

This sounds overcomplicated, I like it.

source: Stack Exchange

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

sort: votes


text:
Reconstruct a missing RGB channel
Look at these photographs of natural scenes, with one of the RGB channels taken out of them:

Source (with red): https://en.wikipedia.org/wiki/File:Altja_j%C3%B5gi_Lahemaal.jpg

Source (with green): https://commons.wikimedia.org/wiki/File:2007_mather-lake_hg.jpg

Source (with blue): https://commons.wikimedia.org/wiki/File:Fox_01.jpg
Even without one of the channels, you can probably make out what colours certain things are supposed to be, or at least have a good idea if a reconstruction of the missing channel is accurate.
For example, here is the first picture with a red channel added back onto it which is just random noise:

This image clearly isn't an accurate reconstruction of the red channel. This is because nature photos generally don't use the entire RGB spectrum, but only a subset of "natural-looking colours". Also, the shades of red will follow certain gradients that correlate with the others.

Your task is to build a program that will take a photograph that's had one channel removed and attempt to approximate the original image as closely as possible by reconstructing what it believes is the missing channel.
Your program will be scored on how closely the missing channel matches with the channel of the original image, by counting the percentage of pixels whose values of that channel are within ±15 (inclusive) of the actual value in the original image (where the values range from 0 to 255 as in a standard 8-bit colour channel).
The test cases that your program will be scored on can be found here (9.04 MB zip file, 6 images). Currently it only contains the three example images above and their originals, but I'll add a few more later to make the full suite once I've done them.
Each image is scaled down and cropped to 1024 x 768, so they will have the same weight in your score. The program that can predict the most pixels within the given tolerance wins.

Could you write a scoring program, e.g. in Python?

I'll get to that tomorrow. Right now I need to go to bed.

Is there a limit to runtime of the program?

@Lause The limit is your patience for the program to actually produce output.

Python 3 + scikit-image
Simply sets the color of the missing channel to the average of the other two.
import sys
from skimage import io, color

im = io.imread(sys.argv[1])
h, w, c = im.shape

removed_channel_options = {0, 1, 2}
for y in range(h):
    for x in range(w):
        if len(removed_channel_options) == 1: break
        removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()

for y in range(h):
    for x in range(w):
        p = [float(c) / 255 for c in im[y][x][:3]]
        p = [sum(p)/2 if i == removed_channel else p[i]
             for i in range(3)]
        im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)

io.imsave(sys.argv[2], im)

And the restored images:

average of the other two - apparently a lot more accurate (subjectively) than I would have guessed.  +1.

They are reminiscent of hand tinted daguerreotypes of long ago. Very nice. +1

Lua, Love2D
Just sets the missing channel to the smaller of the two remaining channels.
local inp = love.image.newImageData(arg[2])

local channels = {1, 2, 3}
local removed = nil
local removed_options = {true,true,true}

inp:mapPixel(function(x,y,r,g,b)
    local o = {r,g,b}
    for k,v in pairs(o) do
        if v > 0 then
            removed_options[k] = false
        end
    end
    return r,g,b
end)

for k,v in pairs(removed_options) do
    if v then
        removed = k
        break
    end
end
inp:mapPixel(function(x,y,r,g,b)
    local o = {r,g,b}
    o[removed] = math.min(o[removed%3+1], o[(removed+1)%3 + 1])
    return unpack(o)
end)

inp:encode('png', IMAGE:gsub("%.png", "2.png"))

Takes a filename as an argument on the command line.

Bonus
I tried setting the missing channel to 255-(a+b), clamping the value. As to "fill in the gap". The results are useless but glorious.

And with 255-(a+b)/2

The images look even more realistic than the other answer. Great job! Out of curiousity, what happens if you do 255-(a+b)/2 instead (no need for clamping)?

Results are a less saturated version of the ones posted above. I'll add them to the answer for the giggles.

I did, in fact, giggle.  Thank you.

A little late to the party but I created a ControlNet - Channels RGB machine learning model which was trained on 400K RGB images where each of them have one channel missing in order to restore a missing channel from an image. It uses Stable Diffusion 1.5 generative image AI to infer an image. You can either use the inference as is, or only use the missing channel from the inference (which doesn't look to good unfortunately). I also created an accompanying space which lets you replace the channel from an inference image. Original post is here: https://github.com/lllyasviel/ControlNet/discussions/567 . There are some disadvantages however:

it changes the image content a bit,
Stable Diffusion 1 works best on images with 512 x n*64.
you have to create a prompt for the image, and
you have to cherry-pick one of the generations.

Results
first is inference only, second is recomposing the missing channel from inference, the image on the right is ground truth with a missing channel
Forest

Glacier

Fox

Welcome to Code Golf, and nice answer!

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

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


text:
Probability of something happening at least n out of m times
Write a program or function, that given a success probability p, a number n and a number of trials m returns the chance of at least n successes out of m trials.
Your answer must be precise to at least 5 digits after the decimal.
Test cases:
 0.1, 10, 100 -> 0.54871
 0.2, 10, 100 -> 0.99767
 0.5, 13,  20 -> 0.13159
 0.5,  4,   4 -> 0.06250
0.45, 50, 100 -> 0.18273
 0.4, 50, 100 -> 0.02710
   1,  1,   2 -> 1.00000
   1,  2,   1 -> 0.00000
   0,  0,   1 -> 1.00000
   0,  0,   0 -> 1.00000
   0,  1,   1 -> 0.00000
   1,  1,   0 -> 0.00000

Would you care to include a formula to those of us who haven't studied binomial distribution?

@KennyLau Sorry, that is part of the challenge.

Jelly, 15 14 bytes
2ṗ’S<¥ÐḟCạ⁵P€S

Reads m, n and p (in that order) as command-line arguments. Try it online!
Note that this approach requires O(2m) time and memory, so it isn't quite efficient enough for the test cases where m = 100. On my machine, the test case (m, n, p) = (20, 13, 0.5) takes roughly 100 seconds. It requires too much memory for the online interpreter.
How it works
2ṗ              Cartesian product; yield all vectors of {1, 2}^n.
  ’             Decrement, yielding all vectors of {0, 1}^n.
      Ðḟ        Filter; keep elements for which the link to the left yields False.
     ¥          Combine the two links to the left into a dyadic chain.
   S              Sum, counting the number of ones.
    <             Compare the count with n.
        C       Complement; map z to 1 - z.
         ạ⁵     Compute the absolute difference with p.
           P€   Compute the product of each list.
             S  Compute the sum of all products.

Mathematica, 29 bytes
BetaRegularized[#3,#,1+#2-#]&

Takes input in the order n,m,p. Mathematica is so good, it even golfs your code for you:

BetaRegularized is the regularised incomplete beta function.

R, 32 31 bytes
function(p,n,m)pbeta(p,m,1+n-m)

edit - 1 byte switching to beta distribution (along the lines of @Sp3000 Mathematica Answer)

Haskell, 73 bytes
g x=product[1..x];f p n m=sum[g m/g k/g(m-k)*p**k*(1-p)**(m-k)|k<-[n..m]]

MATLAB, 78 71 bytes
Saved 7 bytes thanks to Luis Mendo!
@(m,k,p)sum(arrayfun(@(t)prod((1:m)./[1:t 1:m-t])*p^t*(1-p)^(m-t),k:m))

ans(100,10,0.1)
0.5487

The arrayfun function is no fun, but I haven't found a way to get rid of it...

Python, 57 bytes
f=lambda p,n,m:m and(1-p)*f(p,n,m-1)+p*f(p,n-1,m-1)or n<1

The recursive formula for binomial coefficients, except the base case m==0 indicates whether the remaining number of required successes n is nonnegative, with True/False for 1/0. Because of its exponential recursion tree, this stalls on large inputs.

To test out this answer for large cases, add caching using from functools import lru_cache; f = lru_cache(None)(f).

@orlp Thanks, I confirmed the large test cases.

Pyth, 26 bytes
AQJEsm**.cHd^Jd^-1J-HdrGhH

Try it online!
Uses standard cumulative binomial distribution.

Pyth, 20 bytes
JEKEcsmgsm<O0QKJCGCG

Try it online!
Note: CG is a very large number which the interpreter cannot handle. Therefore, the number of trials have been lowered to ^T3 which is one thousand. Therefore, the link produces an inaccurate result.
Uses pure probabilistic approach.

I don't think a probabilistic approach would be valid for this question, but we'd have to ask @orlp

You need on the order of 1/c^2 trials to get within accuracy c with high probability, so that would be ~10^10 for five decimal places.

CG is a very large number. In fact, it is the string "abc...z" converted from base-256 to decimal.

^TT would be 10^10, and ^T11 would be 10^11.

@Sp3000 I am not sure if that would ping @orlp

@Sp3000 If you can guarantee 5 decimals of precision somehow through probabilistic means, go ahead.

@KennyLau It didn't, but I'm lurking.

I can guarantee 5 decimal places.

If "probabilstic" means random, you can't guarante an accurate value, no matter how many realizations you average. In fact, the result is different every time.

It is highly improbable that it is not accurate to 5 decimal places.

There is always a nonzero probability that the result is not accurate to 5 decimal places. Therefore it doesn't fulfill the requirement Your answer must be precise to at least 5 digits

In science, highly improbable is equivalent to impossible.

But this is not science, this is maths :-)

Let the poster judge.

JavaScript (ES7), 82 bytes
(p,n,m)=>[...Array(++m)].reduce((r,_,i)=>r+(b=!i||b*m/i)*p**i*(1-p)**--m*(i>=n),0)

Saved 1 byte by using reduce! Explanation:
(p,n,m)=>               Parameters
 [...Array(++m)].       m+1 terms
  reduce((r,_,i)=>r+    Sum
   (b=!i||b*m/i)*       Binomial coefficient
   p**i*(1-p)**--m*     Probability
   (i>=n),              Ignore first n terms
   0)

MATL, 23 bytes
y2$:Xni5M^1IG-lG7M-^**s

Inputs are in the order m, n, p.
Try it online!
This does a direct computation summing the terms from n to m of the binomial probability (mass) function.

Octave, 26 bytes
@(p,n,m)1-binocdf(n-1,m,p)

This is an anonymous function. To use it, assign it to a variable.
Try it here.

Jelly, 18 17 bytes
⁵C*ạ×⁵*¥×c@
R’çSC

Reads n, m and p (in that order) as command-line arguments. Try it online!

TI-Basic, 17 bytes
Precise to 10 decimals, could be adjusted anywhere from 0-14 decimals with more code.
Prompt P,N,M:1-binomcdf(M,P,N-1

Haskell, 54 bytes
(p%n)m|m<1=sum[1|n<1]|d<-m-1=(1-p)*(p%n)d+p*(p%(n-1))d

Defines a function (%). Call it like (%) 0.4 2 3.

n<1 instead of n<=0.

Mathematica, 48 bytes
Sum[s^k(1-s)^(#3-k)#3~Binomial~k,{k,##2}]/.s->#&

Uses the binomial distribution probability formula to calculate the chance of k successes for k from n to m. Handles the edge cases by using a symbolic sum where s is a symbolic variable for the probability that is later replaced with the actual value p. (Since s0 = 1 but 00 is indeterminate.)


text:
Polygonal numbers
A polygonal number is the number of dots in a k-gon of size n.
You will be given n and k, and your task is to write a program/function that outputs/prints the corresponding number.
Scoring
This is code-golf. Shortest solution in bytes wins.
Example

The 3rd hexagon number (k=6, n=3) is 28 because there are 28 dots above.
Testcases
Can be generated from this Pyth test suite.
Usage: two lines per testcase, n above, k below.
n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000

Further information

In Wikipedia: https://en.wikipedia.org/wiki/Polygonal_number
In Wolfram Mathworld: http://mathworld.wolfram.com/PolygonalNumber.html
In OEIS Wiki: http://oeis.org/wiki/Polygonal_numbers
OEIS sequences for n-gonal numbers for various n: 3 (A000217), 4 (A000290), 5 (A000326), 6 (A000384), 7 (A000566), 8 (A000567), 9 (A001106), 10 (A001107), 11 (A051682), 12 (A051624), 13 (A051865), 14 (A051866), 15 (A051867), 16 (A051868), 17 (A051869), 18 (A051870), 19 (A051871), 20 (A051872), 21 (A051873), 22 (A051874), 23 (A051875), 24 (A051876)

Isn't that the 4th hexagonal number in the picture?

@Neil We count from zero.

You really are going on a question posting spree, aren't you?

The example might be off. If you put n=3 and k=6 into your test suite, you get 15. If you put in n=4 and k=6, you get 28.

Jelly, 7 bytes
’;’;PH+

This uses the formula

to compute the nth s-gonal number.
Try it online!
How it works
’;’;PH+  Main link. Arguments: s, n

’        Decrement; yield s - 1.
 ;       Concatenate; yield [s - 1, n].
  ’      Decrement; yield [s - 2, n - 1].
   ;     Concatenate; yield [s - 2, n - 1, n].
    P    Product; yield (s - 2)(n - 1)n.
     H   Halve; yield (s - 2)(n - 1)n ÷ 2.
      +  Add; yield (s - 2)(n - 1)n ÷ 2 + n.

Hexagony, 25 bytes
?(({"+!@/"*'+{/?('*})/2':

Unfolded:
   ? ( ( {
  " + ! @ /
 " * ' + { /
? ( ' * } ) /
 2 ' : . . .
  . . . . .
   . . . .

Reads k first and n second (using any separator).
Try it online!
Explanation
The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:

The paths are executed in the order grey, dark blue, red, light blue, dark green, pink. As you can see, the three / only act to redirect the flow. Also, the . are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:
?(({?('*})"*'+{2':"+!@

This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:

Here's how this is done:
?    Read integer input s into edge A.
((   Decrement twice to get (s-2).
{    Move the MP forwards onto edge B.
?    Read integer input n into edge B.
(    Decrement to get (n-1).
'    Move the MP backwards onto edge C.
*    Multiply edges A and B to store the result (s-2)(n-1) in edge C.
}    Move the MP forwards onto edge B.
)    Increment to restore the value n.
"    Move the MP backwards onto edge A.
*    Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
'    Move the MP backwards onto edge D.
+    Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{    Move the MP forwards onto edge E.
2    Set the memory edge to value 2.
'    Move the MP backwards onto edge A.
:    Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
"    Move the MP backwards onto edge C.
+    Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
!    Print as integer.
@    Terminate the program.

Such a simple formula... requires 25 bytes?!

@KennyLau This is Hexagony after all...

Hexagony meta question

05AB1E, 8 bytes
Code:
D<LOIÍ*+

Explanation:
D         # Duplicate the input
 <LO      # Compute n × (n - 1) / 2
    IÍ    # Compute k - 2
      *   # Multiply, resulting into (k - 2)(n - 1)(n) / 2
       +  # Add, resulting into n + (k - 2)(n - 1)(n) / 2

Uses CP-1252 encoding. Try it online!.

Labyrinth, 13 bytes
?::(*?((*#/+!

Try it online!
Explanation
Due to its single-character commands (which are merely a necessity of the 2D-ness of the language), Labyrinth can be surprisingly golfy for linear programs.
This uses the same formula as several other answers:

Op  Explanation                 Stack
?   Read n.                     [n]
::  Make two copies.            [n n n]
(   Decrement.                  [n n (n-1)]
*   Multiply.                   [n (n*(n-1))]
?   Read s.                     [n (n*(n-1)) s]
((  Decrement twice.            [n (n*(n-1)) (s-2)]
*   Multiply.                   [n (n*(n-1)*(s-2))]
#   Push stack depth, 2.        [n (n*(n-1)*(s-2)) 2]
/   Divide.                     [n (n*(n-1)*(s-2))/2]
+   Add.                        [(n+(n*(n-1)*(s-2))/2)]
!   Print.                      []

At this point, the instruction pointer hits a dead end and turns around. Now + is executed again, which is a no-op (since the bottom of the stack is implicitly filled with an infinite amount of zeros), and then / attempts a division-by-zero which terminates the program with an error.

JavaScript (ES6), 24 22 bytes
(k,n)=>n+n*--n*(k-2)/2

Explanation: Each n-gon can be considered to be n points along one side plus k-2 triangles of size n-1, i.e. n+n(n-1)(k-2)/2.

k--*n--+2-n haven't tested though

@KennyLau Sorry, but (k,n)=>n*(--k*--n-n+2)/2 is still 24 bytes.

@KennyLau In fact I overlooked the obvious use of --n for (n-1). D'oh!

@NeiI Well, nice.

You can save a bye with currying: k=>n=>n+n*--n*(k-2)/2

@Dennis I'm too lazy to curry any of my answers.

CJam, 13 bytes
q~__(*2/@2-*+

Try it online

APL (Dyalog Extended), 11 bytesSBCS
Thanks to Adám for his help for suggesting this alternate version.
⊢+-∘2⍤⊣×2!⊢

Try it online!
Explanation
⊢+-∘2⍤⊣×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

        2!⊢  Binomial(n, 2) == n*(n-1)/2.
  -∘2⍤⊣×     Multiply (×) with by getLeftArgument (⊢) with (⍤) minus 2 (-∘2) called on it.
             In short, multiply binomial(n,2) with (s-2).
⊢+           Add n.

APL (Dyalog Unicode), 12 11 bytesSBCS
Thanks to Adám for his help in golfing this.
Edit: -1 byte from ngn.
⊢+{⍺-2}×2!⊢

Try it online!
Ungolfing
⊢+{⍺-2}×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

        2!⊢  Binomial(n, 2) == n*(n-1)/2.
  {⍺-2}×     Multiply it by s-2.
⊢+           Add n.

Actually, 12 bytes
3@n(¬@D3╟π½+

Try it online!
Explanation:
3@n(¬@D3╟π½+
3@n           push 3 copies of n (stack: [n, n, n, k])
   (¬         bring k to front and subtract 2 ([k-2, n, n, n])
     @D       bring an n to front and subtract 1 ([n-1, k-2, n, n])
       3╟π    product of top 3 elements ([n*(n-1)*(k-2), n])
          ½   divide by 2 ([n*(n-1)*(k-2)/2, n])
           +  add ([n*(n-1)*(k-2)/2 + n])

dc, 14 bytes
?dd1-*2/?2-*+p

Try it online!
Explanation
This makes use of the following formula
(note that Tn = n*(n-1)/2):

                # inputs              | N S                  | 10 5
?dd             # push N three times  | N, N, N              | 10, 10, 10
   1-           # subtract 1          | (N-1), N, N          | 9, 10, 10
     *          # multiply            | (N-1)*N, N           | 90, 10
      2/        # divide by two       | (N-1)*N/2, N         | 45, 10
        ?       # push S              | S, (N-1)*N/2, N      | 5, 45, 10
         2-     # subtract 2          | (S-2), (N-1)*N/2, N  | 3, 45, 10
           *    # multiply            | (S-2)*(N-1)*N/2, N   | 135, 10
            +   # add                 | (S-2)*(N-1)*N/2 + N  | 145
             p  # print to stdout

Aceto, 18 15 bytes
Port of the Bruce Forte's dc answer:
riddD*2/ri2-*+p

Saved 3 bytes by realizing that any "pure" (no combined commands) Aceto program can be written linearly.

MathGolf, 8 bytes
_┐*½?⌡*+

Try it online!
Explanation (with \$n = 10, k = 5\$
_          duplicate first implicit input, stack is [10, 10]
 ┐         push TOS-1 without popping, stack is [10, 10, 9]
  *        multiply, stack is [10, 90]
   ½       halve TOS, stack is [10, 45]
    ?      rotate top 3 stack elements, popping k to the top: [10, 45, 5]
     ⌡     decrement TOS twice: [10, 45, 3]
      *    multiply: [10, 135]
       +   add: [145]

An alternative 8-byter is ┼┐*½\⌡*+, which takes the input in reversed order.

><>, 13 bytes
::1-*2,{2-*+n

Try it online!

Mathematica, 17 bytes
(#2-2)#(#-1)/2+#&

Straight-forward application of the formula.
Usage
  f = (#2-2)#(#-1)/2+#&
  f[10, 3]
55
  f[10, 5]
145
  f[100, 3]
5050
  f[1000, 24]
10990000

J, 14 bytes
]++/@i.@]*[-2:

Based on the formula.
P(k, n) = (k - 2) * T(n - 1) + n where T(n) = n * (n + 1) / 2
        = (k - 2) * n * (n - 1) / 2 + n

Usage
   f =: ]++/@i.@]*[-2:
   3 f 10
55
   5 f 10
145
   3 f 100
5050
   24 f 1000
10990000

Explanation
]++/@i.@]*[-2:
            2:  The constant function 2
          [     Get k
           -    Subtract to get k-2
        ]       Get n
     i.@        Make a range from 0 to n-1
  +/@           Sum the range to get the (n-1) Triangle number = n*(n-1)/2
                The nth Triangle number is also the sum of the first n numbers
         *      Multiply n*(n-1)/2 with (k-2)
]               Get n
 +              Add n to (k-2)*n*(n-1)/2

How long would it be, using my approach?

TI-Basic, 20 bytes
Prompt K,N:(K-2)N(N-1)/2+N

GameMaker Language, 44 bytes
n=argument1;return (argument0-2)*n*(n-1)/2+n

Is the space required?

Python 3, 31 30 28 bytes
The straight up equation from this wiki article
lambda s,n:(s-2)*(n-1)*n/2+n

Thanks to @Mego for saving a byte!

You can remove the space between the colon and the parenthesis.

Japt, 14 12 10 bytes
-[U½UÉVÍ]×

Try it

Fourier, 18 bytes
I-2~SI~Nv*N/2*S+No

Try it on FourIDE!
Takes k as first input and n as second input. Uses the formula:

Explanation Pseudocode:
S = Input - 2
N = Input
Print (N - 1) * N / 2 *S + N

Excel,  22 bytes
Calculates the A1th B1-gonal number.
=(B1-2)*A1*(A1-1)/2+A1

Java 8, 21 bytes
All individual answers of equal byte-length:
k->n->n+n*~-n*(k-2)/2
k->n->n+n*--n*(k-2)/2
k->n->n+n*~-n*~-~-k/2
k->n->n+n*--n*~-~-k/2

Explanation:
Try it here.
k->n->            // Method with two integer parameters and integer return-type
  n+              //  Return `n` plus
    n*            //   `n` multiplied by
      ~-n         //   `n-1`
         *(k-2)   //   Multiplied by `k-2`
               /2 //   Divided by 2
                  // End of method (implicit / single-line return-statement)

Husk, 9 bytes
S+~*-2(Σ←

Try it online!
Explanation
Using the same formula as in my dc answer:

            -- implicit inputs S, N                     | 5, 10
S+          -- compute N + the result of the following  | 10 +
  ~*        --   multiply these two together            |      (   ) *
    -2      --     S-2                                  |       S-2
      (Σ←)  --     triangle number of (N-1)             |              tri(N-1)

APL(NARS), 16 char, 32 bytes
{⍵+(⍺-2)×+/⍳⍵-1}

It is based from the fact that seems n×(n-1)/2=sum(1..n-1) test:
  f←{⍵+(⍺-2)×+/⍳⍵-1}
  10 f 3
27
  3 f 10
55
  5 f 19
532
  3 f 10
55
  5 f 10
145
  3 f 100
5050
  24 f 1000
10990000

Rockstar, 67 bytes
listen to N
listen to K
cast N
let K be-2
let K be*N-1
say K*.5*N+N

Try it here (Code will need to be pasted in, with each input integer on an individual line)

x86-16 machine code, 14 bytes
00000000: 4949 8bc3 48f7 e3f7 e1d1 e803 c3c3       II..H.........

Listing:
49          DEC  CX         ; k = k - 2
49          DEC  CX
8B C3       MOV  AX, BX     ; AX = n
48          DEC  AX         ; AX = n - 1
F7 E3       MUL  BX         ; AX = n * n - 1
F7 E1       MUL  CX         ; AX = ( k - 2 ) * n * ( n - 1 )
D1 E8       SHR  AX, 1      ; AX = ( k - 2 ) * n * ( n - 1 ) / 2
03 C3       ADD  AX, BX     ; AX = ( ( k - 2 ) * n * ( n - 1 ) / 2 ) + n
C3          RET             ; return to caller

Callable function, input n in BX, k in CX, result in AX.


text:
Random word-sentence-story generator
This question got me nostalgic: Build a word generator!
In the '80s I wrote a simple word generator in under 42kB (code and working memory) that would take a collection of strings and use them to create new words and phrases.
Your task is to recreate this program in as few bytes as possible, with a few minor updates.
Your program will take the input and ensure that there are two spaces after each sentence. Each sentence should end with a full-stop (.). There must not be three consecutive spaces anywhere in the text. Line breaks should be replaced by a single space. There should only be two spaces after a sentence and nowhere else.
Record the number of times each character triplet appears. If you're using regex to break up the text /\X/ is a good way to match a Unicode glyph (could be multiple codepoints, not necessarily a single codepoint). For the purposes of counting, assume that there are two spaces at the start of the text and two spaces at the end.
Hopefully, you now have some good data to work with! Randomly select a triplet where the first two characters are both spaces. For example, if the only two matching triplets are [' ', ' ', 'I'] => 3 and [' ', ' ', 'A'] => 7 there should be a 30% chance of selecting I and a 70% chance of selecting A. Shift the characters along and randomly select one of the next triplets. If A was the first character selected the next triplets might be [' ', 'A', 'n'] => 2, [' ', 'A', 't'] => 2 and [' ', 'A', 's'] => 3. Randomly select one using the correct weightings and so on. Repeat until the last two characters are both spaces, then output the string generated if it's 100 characters or longer. If the output is less than 100 characters, repeat the process again, adding to the existing string until it is at least 100 characters long.
You should end up with output something like below, which looks almost like the input language. As my test input I used the first chapter of Charles Dickens' A Tale of Two Cities but you can use any text you feel like. Please provide a link to your input text (preferably not copyrighted) and a sample of the output.

In harithe dir, in hadede Fards fouses, by we aws, mand by nouse St. Merty exce, he th at ing ithe inceir farce, a Capir bod day, one defor ond rodmane of the ce witsethe after seas a pleark parison a prion to eves hund Parglairty the beere tielaires, and wrece to ente comses itic plaw andozene hich tat andiver, a he pent wer thneople, the werseved froads se sebron theire mands inge Woodmage larestown ther Ligh, sed and was the withaved broce pers. Brity-fired of bust a din humakings th, incre pas of the amonoblis the a kne Chrooteres, to offle ound lies yeargland this thing by on the goil ituarivesdozen, moolurd instive the whe only a king was thelfe one divery. Und the intren a king thiging ors, and he tow, afty out pas musears, thot he in aces, it it Fran, tho the blets be anglaters ouseticiodmand whimeng was by the primed tord a ce a dirience.

TL;DR
Build sentences from test input by analysing the frequency of the character triplets, and using those frequencies to randomly select each character in sequence.
You can pre-format your text to make sure it matches the input requirements. It doesn't have to contribute to your byte-count.
If your language can't cope with Unicode at all, limit the input to ASCII characters. Ideally, your program should be able to cope with combining marks (accents and the like) if they are encoded separately but it doesn't have to. It shouldn't affect the output much, although it's possible you might get weird output in rare cases. e.g. if é is encoded as two codepoints, e+combining acute accent, it SHOULD (but doesn't HAVE to) treat it as a single glyph.

Could you include a TL;DR?

@KennyLau I could run the description through my program if that would help?

I'll try to understand the question xd

Could you not include characters spanning multiple bytes?

@KennyLau é could be one codepoint or two: an e with a combining acute accent. Ideally your program should keep the accent with the letter, if it happens to be encoded separately. That's what /\X/ does. For example in Sinhala ක is 1 codepoint, and ක් and කො are both 2 but /\X/ will match each of them as a single glyph. You probably won't get weird glyphs if your program treats them separately.

I mean, could we assume that the input will only have U+0020 - U+007F ?

It's quite chameleon otherwise.

@KennyLau Ah! I see! That's tricky. The languages that can easily cope with that are a bit more verbose. Limiting it to just ASCII significantly changes which languages would be competitive. It's pretty much an either/or proposition.

Why would limiting it to ASCII change which languages would be competitive?

Let us continue this discussion in chat.

"Your program will take the input and ensure that there are two spaces after each sentence." (And the following sentences.) Do you mean it will check that that's the case (and exit otherwise), or that it will change the text (if necessary) so that that's the case?

I think this is also referred to as a Markov text generator, if I'm not incorrect

Ruby, 88 bytes
Port from the Python answer by @Blue with a few modifications because it's still the shortest way to do things in Ruby as well...
->s{o=e='  ';(s[x=rand(s.size-2),2]==o[-2,2]?o+=s[x+2]:0)while o.size<100||o[-2,2]!=e;o}

Alternate version using selection and sampling, 99 bytes
->s{o=e='  ';o+=s[(0..s.size-2).select{|i|s[i,2]==o[-2,2]}.sample+2]while o.size<100||o[-2,2]!=e;o}

I love your version with selection and sampling. “The mank becard of the spely, brick, fact, his lially whis thes, days leters thimplets lery and mosich at homeening, toon com feenthe hise alke loster towl acuse momessiome hed forbecafrood mad man’s retimplats give I’ven, exculy, of thaps hinfuld hime sted of therver parreters.” made my day. Next time I meet an English learner, he is going to have an amazing bedtime story in the strongest London accent possible. Or maybe one should make a video “How English language sounds to the rest of the world” for English speakers.

Python 2.7, 156 149 135 131 bytes
Screw efficiency, as long as it's short.
Saved 7 bytes thanks to @TuukkaX on the import statement
Saved 14 bytes thanks to @KevinLau-notKenny for negative list indice trick and if statement.
Saved 4 bytes by changing the randint
Notice that the second level uses tabs, but SE renders as 4 spaces.
from random import*
def r(i):
 o='  '
 while len(o)<100or o[-2:]!='  ':
    x=randint(2,len(i))
    if i[x-2:x]==o[-2:]:o+=i[x]
 return o

Why are you importing randint from the random? You can just use import random and then call random.randint. Am I missing something?

@TuukkaX You're right, I should be just doing import* so I don't have to say random twice

o[-2:] grabs the last two characters you need from the output string, saving bytes over o[l(o)-2:l(o)]. Also, the spec says you can stop when you have 100+ characters and the last two characters are spaces, which can cut down on your while condition to l(o)<100||o[-2]!='  '

@KevinLau-notKenny order of operations says bitwise or won't work, but the rest will, thanks!

Erm, I typoed... the while check needs to be o[-2:]=='  ', since the end condition is for the last two characters to both be spaces. whoops. (Also, SE is rendering the two spaces as one for some reason)

I think you can save two chars by using randint(0,len(i)); if i ends up being too large, the if condition won't be satisfied anyway.

@NikitaBorisov no, then it would potentially throw an error. But you did give me an idea.

It won't throw an error, it just returns a truncated string, but your solution is nicer.

PowerShell, 141 bytes
param($d)$o='  '
while($o.Length-lt100-or$o.EndsWith('  ')){if(($s=$d[($x=Get-Random $d.Length)-2]+$d[$x-1])-eq$o[-2]+$o[-1]){$o+=$d[$x]}}$o

It's a port of @Blue's answer as well. Assuming pre-formatted text, as mentioned in the question.
e.g.
PS U:\posh> .\New-RandomStory.ps1 @'
  It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct
the other way--in short, the period was so far like the present
period, that some of its noisiest authorities insisted on its
being received, for good or for evil, in the superlative degree
of comparison only.
'@

  It wincres the befor evil, its the all going redulight, fort, the of it we best waso forst waso fo


text:
Am I happy or sad?
You are trying to guess my emotion.
I will give you an adjective, as the input to the function/program.
Your task is to output my emotion, either :) for happy, or :( for sad.
Details
For these adjectives, you must output the happy face :)
contented
delighted
merry
overjoyed
pleased
blessed
chipper
content
convivial
gleeful
gratified
intoxicated
jolly
light
peppy
perky
playful
sparkling
sunny

For these adjectives, you must output the sad face :(
melancholy
bitter
somber
dismal
mournful
blue
dejected
despairing
despondent
disconsolate
distressed
down
downcast
gloomy
glum
heavyhearted
lugubrious
morbid
morose
troubled
bereaved

Other adjectives are undefined. You may output whatever you want for other adjectives.
Specs

All in lowercase. All matches regex ^[a-z]+$.

Scoring
This is code-golf. Shortest solution in bytes wins.
Tips
There is a trick.

This isn't very interesting, basically is input in this set.

@EᴀsᴛᴇʀʟʏIʀᴋ Well, input.length % 2 is even less interesting...

The problem with this type of question is that once the bag, you have a completely different challenge.

melancholy is not an adjective

@LuisMendo Come on.

@LuisMendo turning it to melancholiac can still keep the rule going, besides i think it is an adj

Melancholy is an adjective.

CJam, 9 bytes
':q,"()"=

The "trick" is the parity of the word lengths.
Test it here.
Explanation
':     e# Push character ':'.
q,     e# Get length of input.
"()"=  e# Using length as cyclic index into "()", giving '(' for even lengths
       e# and ')' for odd lengths.

Could you share with us how you discovered the trick?

@KennyLau By looking at the inputs I guess. It's fairly obvious (visually) that your word lengths are always taking steps in multiples of 2.

@MartinBüttner speak for yourself, I would never notice that.

@Bálint Well I wouldn't have either if I hadn't been looking for it, due to Kenny's hint.

me too i wudnt notice, was wastin my time finding connection between ascii patterns

Retina, 21 18 14 bytes
(..)+
:(
\(.
)

3 bytes saved thanks to Martin Büttner. Another 4 saved thanks to Kenny Lau.
Try it online! (The first line is just to make it run for all test cases).
Uses the same approach as Martins answer.

Brainfuck, 71 bytes
+[--------->+<]>+.>,+[[-]>[->+<]+>[<->-]<<,+]>[<<+>>-]<+++[<------>-]<.

Assumes that EOF = -1.
Explaination:
The first part, +[--------->+<]>+., prints : and stores its ascii value (58) in cell #2.
The second part, >,+[[-]>[->+<]+>[<->-]<<,+], is a bit more complicated. For each character in the input, it moves the value in cell #4 into cell #5, it adds one to cell #4, and sets cell #4 = cell #4 - cell #5. Basically, what this does is it changes cell #4 into 1 - cell #4. When every character has been read, cell #4 is length of input % 2.
The third part, >[<<+>>-] adds the value of cell #4 to cell #2.
The last part, >,+[[-]>[->+<]+>[<->-]<<,+] subtracts 18, which is the difference in the ascii table from the colon and the left parentesens  from cell #2 and prints it.

MATL,  11 10 bytes
58')('jn)h

1 byte saved thanks to @Luis's tip to just rely upon modular indexing rather than an explicit modulus.
Try it Online!
Explanation
58      % Number literal (ASCII for ':')
')('    % String literal
j       % Explicitly grab input as string
n       % Compute the length of the input string
)       % Index into ')(' using modular indexing
h       % Horizontally concatenate ':' with the result
        % Implicitly display resulting string

58')('jn)h saves 1 byte using modular indexing

@LuisMendo Modular indexing gets me every time! Thanks!

J, 15 bytes
':',"0'()'{~2|#

':',"0 concats ':' with the 0-cells of the string '()', making an array of :( and :). {~ is get with switched argument order, 2| is the parity of the length # of the RHS.
  p =: ':',"0'()'{~2|#
  p 'happy'
:)
  p 'somber'
:(

Use (>;p)"0 to test a list of words and compare their output.

What does prozac mean?

@KennyLau Bad pun. prozac is a depression medicine :P

Hahaha, made me laugh for a bit :p

@Adnan Yeah, but I guess it's not the apt place :P

Reng v.3.3, 12 bytes
":("k2,+roo~

This puts 58, 40 on the stack, gets the length of the input stack, 2, modulos by 2, + adds it to the (, r reverses, oo outputs two characters, and ~ terminates the program. Try it here! Input is like "somber". I don't think we need a GIF for this ;)

05AB1E, 10 bytes
Code:
':žuâ`¹gÉ@

Dammit, also 10 bytes: gÉ40+ç':sJ.
Uses CP-1252 encoding. Try it online!.

Jelly, 8 bytes
Code:
”:³Lị“)(

Explanation:
”:         # The ":" character
  ³L       # Get the length of the input
    ị“)(   # Find the index of the length in the ")(" string.
           # Uses cyclic indexing for indices exceeding the length of the string.

Uses the Jelly-encoding.
Try it online!.

Fuzzy Octo Guacamole, 22 bytes
^!_2rm{':('0}i{':)'1}_

Gets input, finds length%2, prints :) vs :( for on a remainder of 1 or 0.

Lua, 35 34 30 bytes
print(#(...)%2>0 and":)"or":(")

Use <1 instead of ==0 to save a byte :)

use (...) instead of io.read() to save 3 bytes :)

print(#(...)%2 and":)"or":(") just skip the <1 already

But (...) doesn't take input :(

But it's allowed.

Javascript 30 bytes
a=>alert(a.length%2?":)":":(")

Javascript return version 23 bytes
a=>a.length%2?":)":":("

Try it out:

b=a=>a.length%2?":)":":("
alert(b(prompt("Please enter how you feel!")));

Since it's a function, I think you can just return the result.

@CᴏɴᴏʀO'Bʀɪᴇɴ You need to output it.

See my javascript answer for what I'm talking about.

Jolf, 12 11 bytes
+':."()"mρl

I might (might) be was able to golf it down a byte by joining the faces. Try it here!
Explanation
+':."()"mρl
+':          ":" +
   ."()"     the member from "()"
        mρl  that is the parity of the length of the implicit input

Labyrinth, 14 bytes
4
1
#$
;,98..@

Try it online!
Explanation
Labyrinth primer:

Labyrinth has two stacks of arbitrary-precision integers, main and aux(iliary), which are initially filled with an (implicit) infinite amount of zeros.
The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.
Digits are processed by multiplying the top of the main stack by 10 and then adding the digit. If the top of the stack is negative, the digit is subtracted instead.

The code starts in the top left corner, with the IP moving south. The 41 simply turns the top 0 on the main stack into 41, the character code of ).
We now enter a 2x2 (clockwise) loop which reads one character at a time, and toggles the top of the stack between 40 (() and 41 ()):
#   Push the stack depth, which is 1.
$   XOR the top two values on the stack, toggling between 40 and 41.
,   Read a character (positive value) or -1 at EOF. At EOF, we exit the loop.
;   Discard the character.

At the end of the loop, the main stack has the correct character code for either ( or ) and a -1 on top of that. The rest of the code is linear.
98  Turn the -1 on top of the stack into -198.
.   Print the top of the stack, modulo 256. -198 % 256 == 58, the character
    code of ':'.
.   Print the top of the stack, i.e. the mouth of the emoticon.
@   Terminate the program.

Magic, magic numbers.

@KennyLau )'s char code is 41, so I bet it has something to with that.

https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code

JavaScript ES6, 23 bytes
x=>":"+"()"[x.length%2]

Simple anonymous function.
Test

f = x => ":" + "()" [x.length % 2];
makeRow = (x, y) => t.innerHTML += `<tr><td>${x}</td><td>${y}</td></tr>`;
`contented
delighted
merry
overjoyed
pleased
blessed
chipper
content
convivial
gleeful
gratified
intoxicated
jolly
light
peppy
perky
playful
sparkling
sunny`.split(`\n`).forEach(e => makeRow(e, f(e)));

t.innerHTML += "
Sad cases
";

`melancholy
bitter
somber
dismal
mournful
blue
dejected
despairing
despondent
disconsolate
distressed
down
downcast
gloomy
glum
heavyhearted
lugubrious
morbid
morose
troubled
bereaved`.split(`\n`).forEach(e => makeRow(e, f(e)));
html {
  font-family: Consolas, monospace;
}
table {
  border-collapse: collapse;
}
td,
th {
  padding: 10px;
  border: 1px solid;
}

    Word
    Output

    Happy cases

what is the type of x?

@KennyLau x is a string.

javascript does not require x.length()?

@KennyLau Nope, .length is a method that changes with the object.

It's shorter to just use ":(" or  ":)"

@Bálint No, they're the same length last i checked.

It's 23 bytes if I can count correctly. That's why I felt it strange. They should be the same length, but mine was a byte shorter.

@Bálint You can count correctly. I had the wrong score up >_>


text:
Automatic house-builder
Automatic house building nanobots have been fabricated, and it's your job to code them.
Here is the house created by input 7 4 2
  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/

The input is a string containing the house's dimensions.
7 is the width.
|_____|

---7---

4 is the height.
|
|
|
|

2 is the depth
 /
/

Given this input, can you create the house?
Your code must be as small as possible so that it can fit in the robots.
Notes
The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.
Testcases
3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/

Related.

It is not a cube, so I think my question is separate enough. Could change chars though.

I didn't say duplicate.

More testcases please?

Also, this is a nice question. I don't think we have one yet.

What would the output be for 3 2 10?

@Downgoat Expected output in question

trailing spaces allowed on lines?

Why don't the bottom-right perspective edge of each prism go all the way back? It seems like they stop 1 before the end, when they can indeed go all the way like this.

Also, regarding what I said in my previous comment, it seems like, as a result, the heights in the very back of the prisms are 1 less than they should be. For instance, in your first example, you can clearly see that on the front it has a height of 4. However in the back, it seems as if it has a height of 3, which very much contradicts what is said to be the height of the "house". There are not many answers (yet), so you may still have time to fix this issue.

@R.Kap No, this was how I wanted them to be designed.

But, the height in the back is 1 less than it should be. However, if that's how you want them, then thats how you want them. I was just giving a suggestion.

@R.Kap Though I still don't really understand you. Could you propose an edit?

Here is a link to plain text file containing what I am proposing. I will also propose an edit.

Okay, I have proposed the edit, but I had to add the hello to the very bottom since the edit was less than 6 characters. So just remove that if you approve of my edit.

Much better! :)

Python 2, 128 bytes
w,h,d=input();i=d
while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1

Prints row by row. The row indices i count down from d to -h+1.

You can trim 3 bytes by replacing ' '*min(d-i,h-1,w+1,h-1+i) with (' '*d)[max(0,i):h-1+i]

Python 224 301 297 Bytes
(Now Works for all boxes including 1x1x1)
l,w,h=input()
s,r,d,v,R,x=" "," - ","/","|",range,(l*3-1)
print s*(w+1)+r*l
for n in R(w):
    if n<h:e,c=v,n
    else:e,c=d,h
    print s*(w-n)+d+s*x+d+s*c+e
if h-w>=1:e,c=v,w
elif w>h:e,c=d,h
else:e,c=d,w
print s+r*l+s*c+e
for n in R(h):
    if h>w+n:e,c=v,w
    else:e,c=d,h-n-1
    print v+s*x+v+s*c+e
print r*l

Explanation:
Takes in three constants: l (length), h(height), w(width).
If we look at a couple sample boxes we can find patterns in the spacing.
For a 3 x 4 x 3 box, we will use numbers to represent spacing between sections.
1234 -  -  -
123/12345678/|
12/12345678/1|
1/12345678/12|
1 -  -  - 123|
|12345678|123/
|       8|12/
|       8|1/
|       8|/
 -  -  -

The top row has 4 spaces or which is w + 1.
The Next three lines have w - (1 * x). X being the line.
These are patterns that continue throughout all lines in all boxes.
Therefore, we can easily program this line by line, multiplying the number of spaces to fit the pattern.
Here is a sample for a 5 x 5 x2 box.
 123 -  -  -  -  -
 12/12345678912345/|
 1/              /1|
 1 -  -  -  -  - 12|
 |              |12|
 |              |12|
 |              |12|
 |              |1/
 |12345678912345|/
  -  -  -  -  -

You should probably keep golfing.

Also, you need to either assign w,h,l=input() or make this a function.

Welcome to Programming Puzzles & Code Golf! We require all submissions to be either full programs that read from STDIN and write to STDOUT or functions that accept arguments and return values. We also require submissions to be serious contenders for winning at the time of posting, which means we don't allow ungolfed or partially ungolfed solutions for code golf.

When I run this code here, there are extra spaces in the output.

@DrGreenEggsandHamDJ Fixed It! It didn't account for a certain pattern of h, w, and l so I added some if statements.

JavaScript (ES6), 169 bytes
(w,h,d)=>[...Array(d+h--)].map((_,i)=>` `[r=`repeat`](i<d&&d-i)+(c=`|/`[+(i<d)])+` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+c+` `[r]((i<d?i:d)-(i>h&&i-h))+`|/`[+(i>h)]).join`\n`

Where \n represents a literal newline character. Explanation:
(w,h,d,)=>                          Parameters
[...Array(d+h--)].map((_,i)=>       Loop over total height = d + h
 ` `[r=`repeat`](i<d&&d-i)+         Space before roof (if applicable)
 (c=`|/`[+(i<d)])+                  Left wall/roof edge
 ` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+ Space, floor or eaves between walls
 c+                                 Right wall/roof edge (same as left)
 ` `[r]((i<d?i:d)-(i>h&&i-h))+      Right wall
 `|/`[+(i>h)]                       Back wall/floor edge
).join`                             Join everything together
`

Edit: Saved 2 bytes thanks to @jrich.

Try removing the ,r='repeat' from the front and replace the first [r] with [r='repeat']

@jrich Thanks, I originally had ,r=(n,c=\ `)=>c.repeat(n)` and when I changed tack I overlooked the possibility for the rearrangement.

Ruby, 145 bytes
Returns a list of strings. Each element in the list corresponds to a line. If a multiline string must be returned, add 3 bytes to add *$/ right before the last bracket.
->w,h,d{s=' ';(0..m=d+h-1).map{|i|(i<d ?s*(d-i)+?/:?|)+(i<1||i==d ??-:i==m ??_ :s)*(w-2)+(i<d ? ?/:?|)+(i<h ?s*[i,d].min+?|:s*[m-i,h-1].min+?/)}}

Python 3.5, 328 326 313 305 295 248 bytes
(Thanks to Kevin Lau for the tip about reducing the size of the ternary statements!)
def s(w,h,d):R,M=range,max;S,V,L=' |/';O=w-2;D=d-M(0,d-h);Q=h-M(0,h-d);print('\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]))

Takes input as 3 integers in the order of width, height, depth. Will golf more over time wherever I can.
Try it online! (Ideone)
Explanation:
For the purposes of this explanation, assume the function was executed with the arguments (3,2,3) where 3 is the width (w), 2 is the height (h), and 3 is the depth (d). That being said, let me begin by showing the main part of the entire function:
'\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)])

Here, the two lists that make up the entire "house" are created and then joined together by literal new lines (\n). Let's call them list a and list b respectively, and analyze each one of them:

Here is where list a is created:
[S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]

This list contains the first d lines of the house. Here, i is each number in the range 0=>(d-(d-h))+d-h where d-h=0 if negative or zero. To start, d-i spaces are added to the list, followed by a / and then whatever is returned by a compressed conditional statement. In this conditional statement, w-2 number of spaces are returned if i>1. Otherwise the same number of - are returned. Then, these are followed up by another /, and then spaces, where the number of spaces now depends on whether or not i<=d-(d-h)-1. If it is, then i spaces are added. Otherwise, h-1 spaces are added. Finally, this is all topped off by either a / or a |, where | is added if i<=d-(d-h)-1, otherwise a / is added. In this case of a 3x2x3 prism, this would be returned by list a:
      /-/|
     / / |
    / / /

Here is where list b is created:
[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]`

This lists contains the rest of the lines of the prism. In this list, i is each integer in the range (h-(h-d))+h-d=>0 where h-d=0 if negative or zero. To start this list off, firstly a | is added since these lines always start with a |. Then, either a space, -, or _ is added depending on whether or not i=h or i<2. If i<2, then a _ is added. Otherwise, a - is added if i=h, or a space is added if i>h or i<h or i>2. After this decision has been made, then w-2 number of the chosen character is added. After this, another | is added, and then either i-1 or d number of spaces are added. If i>h-(h-d), then a d number of spaces are added. Otherwise, i-1 number of spaces are added. Finally, this is all topped off with either a | or a /, in which a | is added if i>h-(h-d), or a / is added if i<=h-(h-d). In the case of a 3x2x3 prism, list b returns:
    |-| /
    |_|/

After the 2 lists have been created, they are finally joined with literal new lines (\n) using '\n'.join(). This is your completed prism, and in this case, would come to look like this:
       /-/|
      / / |
     / / /
    |-| /
    |_|/

Python booleans evaluate to integers, which means most of your ternaries can be compressed to things like '-_'[f<2]. Finally, R=range;S,V,L=' |/' works for assigning your initial variables since strings will gladly unpack themselves for you in that situation.

Never mind, I forgot that operator doesn't exist in Python... But the rest should work!

@KevinLau-notKenny Wow, thanks for the tips! :) I did not know that ternary expressions could be expressed in that way!

You can use that trick for ternaries so long as you aren't modifying variables inside it. For example, a=1 if b<9 else c=5 can't be expressed as [a=1,c=5][b<9] because you'll end up modifying both a and c. Here is the PPCG Python golfing tips page: http://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python

You still have one ternary that's still there, '_'if f<2else' -'[f==h]. Remember booleans evaluate as integers, so you could "chain" this ternary to the other one you fixed to get [' -'[f==h],'_'][f<2]. Also, you haven't used my tip with S,V,L=' |/' yet.

@KevinLau-notKenny Yeah, I was in a bit of a hurry. I must have forgotten to do that last one. Thanks again for the tips! :)

@KevinLau-notKenny It's fixed now.


text:
Smallest groups in an array
Introduction
Let's observe the following array:
[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

A group consists of the same digits next to each other. In the above array, there are 5 different groups:
[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1

The smallest group of these is [2, 2], so we output [2, 2].
Let's take another example:
[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4

You can see that there are multiple groups with the same length. The smallest groups are:
[3, 3], [4, 4], [4, 4] and [5, 5].

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.
The Task
Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.
Test cases
Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]

This is code-golf, so the submission with the least amount of bytes wins!

Related.

can the input be a string?

@downrep_nation Hmm, how would you want to do that then? If you can do it with multidigit integers, than it's fine.

ints are very limited by size and strings are not. thats why im asking

@downrep_nation Okay, so how do you want to provide the input then for the last test case? 11101010100100 doesn't seem correct for input :p.

@Adnan i didn't even think of that, logical fallacy.

In an x86 asm answer, I'm thinking of a function that takes input and output pointers to arrays of 32bit integers.  I'm not sure how to delimit groups in the output.  Would a -1 element or something be acceptable?

Would a string of space-separated integers be acceptable?

@PeterCordes I'd say that a pointer to an array of array pointers is the proper way to represent the output.

@PeterCordes Can you give an example of how you want to provide the input?

@Mego Yes, that is acceptable.

@Adnan: The input is a single flat array.  So I was thinking of a function signature like int smallest_groups(int *dst, int *src, int len_of_src).  The caller allocates a dst as large as the src... oh wait, with group separator sentinel elements added in, dst can take more space than src.  Caller allocates twice as much space as src?  Or what if I write(2) each group to stdout with a separate system call for each group?  A reader on the other end of a pipe would in theory have read return separate buffers for each group.

Pyth, 14 12 11
mM_MmhbrQ8

Test Suite
2 bytes thanks to Jakube! And 1 byte thanks to isaacg!
Unfortunately, run length decoding doesn't quite do what we want it to do, but it will work with a minor workaround, but that makes it slightly longer than the manual implementation:
mr]d9.mhbrQ8

Credit to Jakube for finding this out.

Btw, rld works, but you have to provide a list of pairs: mr]d9.mhbrQ8

More about run length decoding: Run length decoding expects a list of pairs, such as what run length encoding returns, not an individual pair.

.bmYN == mM_M

@isaacg Ah, right that makes sense, I guess I wasn't thinking through that enough. Also that map trick is neat, thanks!

Mathematica, 24 bytes
MinimalBy[Length]@*Split

This is a composition of two functions that can be applied to a list. Split takes all groups of consecutive numbers, and MinimalBy[Length] selects those with minimal length.

Damn, just fired up Mathematica to test this... +1 :)

Now I'm wondering if I haven't made this too trivial :/.

Haskell, 38 bytes
import Data.Lists
argmins length.group

Usage example: argmins length.group $ [3,3,3,4,4,4,4,5,5,4,4,3,3,4,4] -> [[4,4],[3,3],[4,4],[5,5]].
Build groups of equal elements and find those with minimal length.

Where’s the documentation for Data.Lists?

@Lynn: Data.Lists. See also the links to the re-exported modules on this page. argmins for example is from Data.List.Extras.Agrmax.

Python 2, 120 bytes
import re
r=[x.group().split()for x in re.finditer(r'(\d+ )\1*',input())]
print[x for x in r if len(x)==min(map(len,r))]

Takes input as a string of space-separated integers with a trailing space, and outputs a list of lists of strings. The strategy is to find groups using the regex (\d+ )\1* (which matches one or more space-separated integers, with a trailing space), then split them on spaces into lists of integers, and print those groups whose length is equal to the minimum group length.
Try it online

C#, 204 bytes
void f(string o){var r=Regex.Matches(o,@"([0-9])\1{0,}").Cast<Match>().OrderBy(x=>x.Groups[0].Value.Length);foreach(var s in r){foreach(var z in r)if(s.Length>z.Length)return;Console.WriteLine(s.Value);}}

I don't know if using a string is fair considering all the golfing esolangs get their input in the same way but he requested array input.

ungolfed:
    public static void f(string inp)
    {

        var r = Regex.Matches(inp, @"([0-9])\1{0,}").Cast<Match>().OrderBy(x => x.Groups[0].Value.Length);

        foreach (Match s in r)
        {
            foreach (Match z in r)
                if (s.Length > z.Length)
                    return;

        Console.WriteLine(s.Value);
        }

    }

I need a way to get the smallest matches for the match array, most of my bytes are wasted there, help appreciated. I'm trying to get into LINQ and lambda stuff.

Technically a string is an array.

Python 2.x, 303 bytes
x=input()
r=[q[2]for q in filter(lambda l:(len(l[2])>0)&((l[0]<1)or(x[l[0]-1]!=x[l[0]]))&((l[1]>len(x)-1)or(x[l[1]]!=x[l[1]-1]))&(len(filter(lambda k:k==l[2][0],l[2]))==len(l[2])),[(a,b,x[a:b])for a in range(0,len(x))for b in range(0,len(x)+1)])]
print filter(lambda k:len(k)==min([len(s)for s in r]),r)

Ugliest. Code. Ever.
Input: An array in the format r'\[(\d,)*(\d,?)?\]'
In other words, a python array of numbers
Output: An array of arrays (the smallest groups), in the order that they appear in the input array
Additional Coincidental Features (Features that I did not intend to make):

The input can be an empty array; the output will be an empty array.
By changing min to max, it will return an array of the largest groups.
If you just do print r, it will print all of the groups in order.

Retina, 91 85 80 79 77 76 75 74 bytes
M!`\b(\d+)(,\1\b)*
(,()|.)+
$#2:$&
O#`.+
s`^(.*\b(.+:).*)¶(?!\2).+
$1
.+:
<empty-line>

Try it online!
Explanation
The input is 1,1,10,10,10,100,100.
The first line matches groups with same terms:
M!`\b(\d+)(,\1\b)*

The input becomes:
1,1
10,10,10
100,100

The following two lines prepend the number of commas to the line:
(,()|.)+
$#2:$&

The input becomes:
1:1,1
2:10,10,10
1:100,100

Then they are sorted by this line, which looks for the first number as index:
O#`.+

The input becomes:
1:1,1
1:100,100
2:10,10,10

Then these two lines find the place where the length is different, and remove everything onwards:
s`^(.*\b(.+:).*)¶(?!\2).+
$1

The input becomes:
1:1,1
1:100,100

Then the numbers are removed by these two lines:
.+:
<empty-line>

Where the input becomes:
1,1
100,100

R, 70 65 bytes
Edit: -5 bytes thanks to Giuseppe
function(x)(y=split(x,diffinv(!!diff(x))))[min(l<-lengths(y))==l]

Try it online!
This feels rather clunky, so I won't be surprised if there's a much slicker R way to do this...  Edit: there is...
function(x)             # x is vector of values;
(y=                     # define y as
  split(x,              # groups of values of x that share the same
          cumsum(       # cumulative sum of
          x!=c(0,x))))  # 1 if different to the next element;
[                       # now, get element(s) of y
 (l=lengths(y))         # whose length(s)
        ==min(l[l>0])]  # equal the smallest non-zero lengths of y

Would rle be handy here?

this is 58

@Giuseppe - Nice!  And 56 bytes by including the variable defs into the function def.  Post it.  I thought about rle, but didn't try it because it seemed to me that it would be too verbose to 'rebuild' the groups.  Obviously I was wrong...

Done! And as a bonus 65 bytes tweaking your approach.

Jelly, 22 17 16 bytes
I0;œṗ¹L=¥ÐfL€Ṃ$$

Try it online!
I0;œṗ¹L=¥ÐfL€Ṃ$$     Main link. List: z = [a,b,c,...]

I                    Compute [b-a, c-b, d-c, ...]
 0;                  Concatenate 0 in front: [0, b-a, c-b, d-c, ...]
   œṗ                Split z where the corresponding item in the above array is not zero.
      L=¥Ðf          Filter sublists whose length equal:
           L€Ṃ$      the minimum length throughout the list.

     ¹         $     (grammar stuffs)

MATL, 15 bytes
Y'tX<tb=bw)wTX"

Try it online
Input is a vector, like [1 2 3 4], and output is a matrix where each column is one of the smallest groups, e.g.:
1 100
1 100

for the third test case.
Explanation:
Y'    %// Run length encoding, gives 2 vectors of group-lengths and values
t     %// Duplicate group lengths
X<    %// Minimum group length
tb    %// Duplicate and get vector of group lengths to the top
=     %// Find which group lengths are equal to the minimum
bw)   %// And get the values of those groups
wTX"  %// Repeats the matrix of minimum-length-group values by the minimum group length

JavaScript (ES6), 106
a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))

Test

f=a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))

console.log=x=>O.textContent+=x+'\n'

;[[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
, [3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]
, [1, 1, 2, 2, 3, 3, 4]
, [1]
, [1, 1, 10, 10, 10, 100, 100]]
.forEach(t=>console.log(t+' -> '+f(t).join` `))

Does h.map(length) not work?

@KennyLau no, for it to work length should be a function with the string as argument, not a method of string

@edc65 Actually, a property of String. Not a method.

JavaScript (ES6), 113 bytes
a=>a.map(n=>n==c[0]?c.push(n):b.push(c=[n]),c=b=[])&&b.sort((a,b)=>a[l]-b[l],l='length').filter(e=>e[l]==b[0][l])

APL, 25 chars
{z/⍨(⊢=⌊/)≢¨z←(1,2≠/⍵)⊂⍵}

In English:

put in z the argument split where a number is different than the one preceding;
compute the length of each subarray
compare the minimum with each of the lengths producing a boolean...
... that is used to reduce z

Commute. Commute. Commute! ⍵⊂⍨1,2≠/⍵

J, 31 bytes
[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]

Input is an array of values. Output is an array of boxed arrays.
Usage
   f =: [:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
   f 1 1 2 2 3 3 4
┌─┐
│4│
└─┘
   f 3 3 3 4 4 4 4 5 5 4 4 3 3 4 4
┌───┬───┬───┬───┐
│5 5│4 4│3 3│4 4│
└───┴───┴───┴───┘

Explanation
[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]  Input: s
                              ]  Identity function, get s
                         2       The constant 2
                             \   Operate on each overlapping sublist of size 2
                          ~:/      Check if each pair is unequal, 1 if true else 0
                       1,        Prepend a 1 to that list
                 ]               Identity function, get s
                  <;.1~          Using the list above, chop s at each true index
[:(             )                Operate on the sublists
             #@>                 Get the length of each sublist
     [:(    )                    Operate on the length of each sublist
         <./                     Get the minimum length
        =                        Mark each index as 1 if equal to the min length else 0
   #~                            Copy only the sublists with min length and return

Clojure, 65 bytes
#(let[G(group-by count(partition-by + %))](G(apply min(keys G))))

Uses + as identity function as (+ 5) is 5 :) The rest should be obvious, G is a hash-map used as a function and given a key it returns the corresponding value.

Brachylog, 6 bytes
ḅlᵒlᵍh

Try it online!
Input through the input variable and output through the output variable.
ḅ         The list of runs of consecutive equal elements of
          the input
 lᵒ       sorted by length
   lᵍ     and grouped by length
          has the output variable
     h    as its first element.

Although, unlike ḅ, ᵍ groups non-consecutive equal elements, the lᵒ is still necessary to find the group with the shortest lengths, and it works because the order of groups in the output from ᵍ is determined by the position of the first element of each group, so that ᵍhᵐ could function as sort of a deduplicate by pseudo-metapredicate.

Perl 5 -MList::Util=pairkeys,min -a, 69 bytes
map$r{y/ //}.="[ $_]",pairkeys"@F "=~/((\d+ )\2*)/g;say$r{min keys%r}

Try it online!

Husk, 4 bytes
←kLg

Try it online!

Jelly, 5 bytes
ŒgLÐṂ

Try it online!

05AB1E, 5 bytes
γé¬gù

Try it online!
Commented:
γ      # split into chunks of equal adjacent elements
 é     # sort the chunks by length
  ¬    # get the shortest (first) chunk without popping the list
   g   # take the length of that chunk
    ù  # keep all chunks with this length

Try it with step-by-step output!

Japt -g, 4 bytes
Outputs a 2D-array.
òÎüÊ

Try it
òÎüÊ     :Implicit input of array
ò        :Partition between elements where
 Î       :  The sign of their difference is truthy (not 0)
  ü      :Group and sort by
   Ê     :  Length
         :Implicit output of first element

R, 56 bytes
function(x,r=rle(x),l=min(r$l))lapply(r$v[r$l==l],rep,l)

Try it online!
-2 bytes thanks to Dominic van Essen. Uses rle and rep to collapse and reconstruct the array.

K (ngn/k), 24 bytes
{{x=&/x:#'x}#(&~=':x)_x}

Try it online!

(&~=':x)_x split the input on indices where the values change
{x=&/x:#'x}# filter down to items of the minimum length

Factor + grouping.extras, 36 bytes
[ [ ] group-by values all-shortest ]

Try it online!

[ ] group-by values Split a sequence into groups of contiguous equal elements.
all-shortest Take all the shortest groups.

[ stable-slices all-shortest ] would work except it doesn't have the right behavior for 1-element inputs.

JavaScript (Node.js), 97 bytes
x=>eval(`[[${x}]]`.replace(/\b(\d+),(?!\1\b)/g,'$1],[')).filter((t,_,x)=>!x.some(y=>t[y.length]))

Try it online!

Not sure if this works

Nekomata, 2 bytes
ĉş

Attempt This Online!
ĉ       Split the input into chunks of equal elements
 ş      Find the shortest chunk

PowerShell for Windows, 88 bytes
$h=@{}
$args|%{$i+=$p-ne$_;$h.+$i+=,$p=$_}
($g=@($h|% v*|sort c*))|? c*t -eq $g[0].count

Try it online!
The script uses the Powershell alias sort that should be sort-object with Linux.
Less golfed:
$hashTable=@{}
$args|foreach-object{
    $i += ($prev -ne $_)
    $prev = $_
    $hashTable.+$i += ,$prev
}
$groups=@($hashTable|foreach-object Values|sort-object Count)
$groups|where-object count -eq $groups[0].count

Arturo, 46 bytes
$=>[c:chunk&=>[&]select c=>[=size&size min c]]

Try it


text:
Are my eyes open or closed?
You are trying to guess my emotion.
I will give you an adjective, as the input to the function/program.
Your task is to output the state of my eyes, either O_O for open, or ._. for closed.
Details
For these adjectives, you must output open eyes O_O
animated
breezy
brisk
driving
enterprising
fresh
indefatigable
industrious
snappy
spirited
sprightly
spry
stalwart
strenuous
strong
sturdy
unflagging
untiring

For these adjectives, you must output closed eyes ._.
beat
bored
collapsing
consumed
distressed
empty
fagged
faint
fatigued
finished
jaded
wasted
worn

Other adjectives are undefined. You may output whatever you want for other adjectives.
Specs

All in lowercase. All matches regex ^[a-z]+$.

Scoring
This is code-golf. Shortest solution in bytes wins.
Tips
There is a trick. The adjectives that correspond to closed eyes are all related to "tired". The adjectives that correspond to open eyes are all related to "active".

Why did you post 2 of pretty much the same challenges?

That one was too easy xd

Closed eyes would probably be better as -_-.

@KennyLau repeating the same idea in several challenges doesnt sound exciting from the second bit, try to use them as puzzles.

Possible duplicate of Minecraft Mirrored

@Mego Ummm... How?

@ericw31415 Its essentially identical to the other challenge OP just posted, which is itself a duplicate of the linked challenge.

@Mego The other one was only a duplicate because of the line length parity aspect

Empty doesn't follow the pattern.

CJam, 17 bytes
q1=1^'n>".O"='_1$

Second letters. This would have been much more fun without any "tricks" in the test cases :/
Try it online.

JavaScript, 151 123 113 54 50 47 45 bytes

a=>["beat","bored","collapsing","consumed","distressed","empty","fagged","faint","fatigued","finished","jaded","wasted","worn"].includes(a)?"._.":"O_O"

Long, but it's a good start.

a=>/(beat|bored|collapsing|consumed|distressed|empty|fagged|faint|fatigued|finished|jaded|wasted|worn)/.test(a)?"._.":"O_O"

Still pretty long.

a=>(/beat|(bor|consum|distress|finish|jad|wast)ed|collapsing|empty|fa(gged|int|tigued)|worn/).test(a)?"._.":"O_O"

Eliminated some redundancy.

a=>/^(be|bo|c|di|en|fa|fi|j|w)\w+/.test(a)?"._.":"O_O"

Shorter.

a=>/^(a|br|dr|en|fr|i|s|u)\w+/.test(a)?"O_O":"._."

Switched to the other(even shorter) regex for open eyes, instead of closed ones.

a=>/^(a|br|dr|en|fr|i|s|u)/.test(a)?"O_O":"._."

Better.
a=>/^(a|[bdf]r|en|i|s|u)/.test(a)?"O_O":"._."

Python (2.x), 95 94 bytes
import re
print('O_O','._.')[len(re.findall('^a|(br)|(dr)|(en)|(fr)|i|s|u.*',raw_input()))==0]

Regex! If it starts with:
a
br
dr
en
fr
i
s
u
then it is on the eyes-open list.
EDIT: Removed 1 byte because I didn't know how wc worked on bash. :P

Don't you mean em instead of en?

@ericw31415 No; "enterprising".

TI-Basic, 34 bytes
"._.
If inString("nrpt",sub(Ans,2,1:"O-O
Ans

39-byte oneliner:
sub("._.O-O",1+3inString("nrpt",sub(Ans,2,1)),3

MATL, 22 16 bytes
2)2\?'._.'}'O_O'

Try it online
22 byte version, 2)'ntpr'=a?'O_O'}'._.'.

rs, 45 bytes
^(.*[^t]ed|[cbwef](?![rn]).*)$/._.
[^_.]+/0_0

Live demo.

you need four spaces to make this a code block (I can't edit because SE is bad)

@ven I made an edit; I just put an empty div tag at the end so I edited enough chars.

@AlexL. I...uhh...edited your edit. You ended up putting the whole script on one line, but it actually is two.

@kirbyfan64sos Whoops. Okay, thanks; I don't know anything about RS. Thanks though!

GameMaker Language, 72 bytes
a="._."if string_count(string_copy(argument0,2,1),"nrpt")a="O_O"return a


text:
Drilling For Oil
Congratulations!
You have just been hired by a Fortune 499 company specializing in oil drilling.
Your job is to write a program to determine the optimum placement of OilRUs' drill (represented by a single alphabetical character of your choice, I use a capital "O" in the examples), given a length of piping, and a two-dimensional Ground Composition Analysis(Henceforth, "GCA") of the area.
However, due to the limited amounts of fossil fuels in the region, copious amounts of bureaucracy, and a recent influx of environmentalists, you must write your program in the fewest bytes possible.
Your program is expected to return the GCA with an Oil drill and piping in the optimal position, as defined below.

Rules:

Input will be composed of an integer, followed by a new-line-separated GCA.
The GCA will be composed exclusively of the following characters, representing the surface, dirt, and oil respectively:

=
.
~

The first line of the GCA will always contain exclusively surface tiles, and all layers below that will contain a mixture exclusively of dirt and oil.
The GCA will be at least 4 lines of 3 characters, but will not exceed 64 lines of 256 characters each. Every input will contain at least one oil tile.
Multiple, adjacent oil tiles on the same row create a 'pool', where all tiles are collected if a pipe tile replaces any of them.
Every GCA will have at least one valid solution. See Clarification section for examples.

For GCAs with multiple equivalent solutions, the solution closest to the surface wins.
For GCAs with multiple equivalent solutions at the same depth, the one closest to the left-hand side wins.
A single, larger pool with the same volume as multiple smaller ones are viewed as equivalent. For example, two pools of four tiles are equivalent to a single pool of eight tiles.
Volume of oil retrieved outweighs the above three points. If a superior solution exists at a deeper level, or further rightward, that solution is to be the one returned by the program.

You may not use any purpose-created built-ins for finding oil reserves, whether they're supplied by OilRUs, WeDrill4U, or any third parties.
Your program must complete its execution within a reasonable time frame (~30 minutes or less).
Standard Loopholes apply.

Clarification:

The integer portion of the input represents the maximum number of pipes available. They do not all need to be used.
Optimum position is defined in this challenge as the first valid place the drill can be set that intersects the largest amount of oil tiles/pools.
Oil tiles replaced by pipe tiles are still collected, even though they don't show up in the output.

Rule 6 Examples:
   Equal (assuming you were given 3+ pipes)
=====  =====
..~..  .....
..~..  .....
..~..  ..~~~

But:
Loses  Wins
=====  =====
.....  .....
.....  .~~~. ** Solution closer to the surface. (Rule 6.1)
.~...  .....
.~...  .....
.~...  .....

Also:
 Wins     Loses
=====     =====
.....     .....
..~~.     ...~~ ** Solutions are at the same depth,
..~~.     ...~~ ** but one is further left. (Rule 6.2)
.....     .....

Test Cases
Note: The text shown (denoted by the preceding two asterisks and continuing to the end of that line) in some of the test case outputs below is there for illustrative purposes only. Your program is not expected to print anything apart from OilRUs' drill, pipe, and the GCA.
Input:
4
===============================
..~~....~~.....................
~~........~~~...~~~~~~.........
.....~~~~.....~~~..~~..........
..............~~~...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........

Output:
================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........

Input:
2
===============
..~~~.~~.......
..~.....~~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.

Output:
========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~... ** Leftmost tile in pool (Rule 6.2)
..~~~..~~..~~~.
.~~...~~~....~.

Input:
5
===
~.~
...
~.~

Output:
O==
|.~
|.. ** Leftmost solution wins (Rule 6.2)
|.~

Input:
55
============
............
............
...~.~~..~..
..~~......~.
.....~~~....
..~~~...~~..
...~~~~~~~..

Output:
===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..

Input:
6
============
............
............
..~~........
...~..~~~~..
............
...~........

Output:
======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~.. ** Even though there is a solution closer to the left,
............ ** the solution highlighted here takes priority because it is
...~........ ** closer to the surface. (Rule 6.1)

So what should be returned if all solutions are equivalent?

@r.kap: The solution furthest left, and nearest to the surface. Rule 6.

Java, 287 bytes
void a(int d,char[][]a){int b=a.length-1,c=0,e=d=b>d?d:b,f=0,i=0,j,k,g,h,l,m=a[0].length;for(;i<m;i++){g=0;h=0;for(j=1;j<=d;j++){l=0;for(k=0;k<m;k++)if(a[j][k]!=46)l++;else if(k<i)l=0;else break;g+=k==i?0:l;h=l>0?j:h;}if(g>c||g==c&&h<e){c=g;e=h;f=i;}}for(j=0;j<=e;a[j][f]=j++>0?'|':79);}

Ungolfed
void gcaAnalysis(int pipes, char[][] soil) {
    int soilDepth = soil.length - 1, bestCount = 0, bestDepth = pipes = soilDepth > pipes ? pipes : soilDepth, bestX = 0, x = 0, y, k, curCount, curDepth, curLayerCount, width = soil[0].length;
    for (; x < width; x++) {
        curCount = 0;
        curDepth = 0;
        for (y = 1; y <= pipes; y++) {
            curLayerCount = 0;
            for (k = 0; k < width; k++)
                if (soil[y][k] != 46) curLayerCount++;
                else if (k < x) curLayerCount = 0;
                else break;
            curCount += k == x ? 0 : curLayerCount;
            curDepth = curLayerCount > 0 ? y : curDepth;
        }
        if (curCount > bestCount || curCount == bestCount && curDepth < bestDepth) {
            bestCount = curCount;
            bestDepth = curDepth;
            bestX = x;
        }
    }
    for (y = 0; y <= bestDepth; soil[y][bestX] = y++ > 0 ? '|' : 79);
}

Note

Well... this took half an alphabet of variable names, but it works i guess...
Results are written back into a (aka soil in the ungolfed code).

Output
================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........

========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.

O==
|.~
|..
|.~

===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..

======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~..
............
...~........