text:
Fruit bagging factory
Your mission is to build an algorithm (program or function) that can optimize packing fruit from a conveyor belt into bags to be sent off to retailers, optimizing for a largest number of bags.
Each bag has to weight at least a certain amount, but any excess is lost profit since that weight could be used to fill another bag. Your bagging machine has always a lookahead of n fruits from the queue and may only choose to add any of these n fruits to the (single) bag that is being processed. It cannot look beyond the n first elements in the queue. The program always knows exactly how much weight there already is in the bag.
Another way to visualize this is having a conveyor belt with a loading area of size n at the end, from where a fruit has to be taken before a new fruit arrives. Any leftover fruit and a non-full bag at the end are discarded.

Inputs

List/array of weights of fruits in queue (positive integers)
Minimum total weight for bags (positive integer)
Lookahead n (positive integer)

Output
Your algorithm should return for all bags the weights of the fruits in them, by whatever means is convenient for you and your language, be that stdin or a return value or something else. You should be able to run the program and calculate your score in one minute on your computer.
Example
Total weight 1000, lookahead of 3 and fruit queue:
[171,163,172,196,156,175,162,176,155,182,189,142,161,160,152,162,174,172,191,185]

One possible output (indented to show how the lookahead affects the bagging):
[171,163,172,    156,175,    176]
                        [162,    155,182,189,    161,160]
                                                        [152,162,174,172,191,185]

Scoring
Your algorithm will be tested on six runs on a batch of 10000 oranges I have prepared for you, on lookaheads ranging from 2 to 7, inclusive on both ends. You shall pack them into bags weighing at least 1000 units. The oranges are normally distributed with a mean weight of 170 and a standard deviation of 13, if that is of any help.
Your score will be the sum of number of bags from the six runs. The highest score wins. Standard loopholes are disallowed.
Simple example implementation and test suite boilerplate in Haskell

Come on people, I think there are still some low hanging fruit algorithms still waiting to be picked…

Can programs hardcode the mean weight / distribution? (assume that it works equally well on similar batches, of course hardcoding everything is invalid as it destroys the purpose of limited lookahead)

@user202729: Yes they can.

And hardcoding everything is a forbidden standard loophole anyway.

I can't see what lookhead is

Also, if no time limit, no length limit, and question is clear, everyone write brute-force for best solution

@l4m2 since optimizing for the given test case is forbidden, brute-forcing a best solution is impossible. Basically this means it should work as well / properly if the test set is shuffled. The algorithm can only act on the first n items in the queue.

@Angs Suggest a reasonable time requirement as it's not default

@l4m2 there are only 10000 test cases with always at most seven items to choose from - I can't imagine how it could take more than a few seconds but let's say a minute to be safe.

A bounty is maybe too soon?

Now I'm more confused. What exactly is limited to 256 bits? How exactly are we supposed to return if the return value doesn't fit in memory?

@user202729: You have a bag that weights b. You have to fill the bag up to t. You have n items with known weight and more coming. Which of the n items to choose next? That's the problem.

So the algorithm can only process one bag at a time?

@user202729 yes, I'll add that clarification

I think this problem would be more interesting with a lookahead of 10 or 20.

@qwr There are tradeoffs I suppose. My reasoning was that since a bag usually holds just six items, there are diminishing returns with larger lookaheads and being a model of a physical process, larger values require more space and are more error-prone. The smaller ones put on emphasis on how to guess what's coming, whereas larger lookaheads would probably favor brute-forcing all combinations (to a point of course, as it's exponential). At that point it becomes more about time constraints than the algorithm.

Or in other words: work smarter, not harder.

Anyway it is a fun problem and there's many interesting variations: 2 fruits with different distributions, k such fruits, ability to recycle some of wasted fruit into juice, etc.

Python 3, 9964 9981 bags
The idea of this solution is similar to those of Jonathan, JayCe and fortraan, but with a scoring function =)
This solution appends the best subsets of the lookahead area accoring to the score.
score provides an order over the subsets using the following scheme:

A subset completing a bag is better than one that's not
One subset completing a bag is better than another if it has less excess weight
One subset not completing a bag is better than another if its mean is closer to what's expected to be in a bag

expected_mean tries to predict what the rest of the values should look like (assuming their choice is optimal).
UPD:
Here is another observation: you can place any oranges from the best subset into the bag without hurting the algorithm's performance. Moving any part of it still allows to move the rest afterwards, and the remainder should still be the best option (without new oranges) if the scoring is right. Moreover, this way there is a chance to dynamically improve the set of candidates to put into the bag by seeing more oranges before filling the bag. And you want to know as much information as possible, so there is no point in moving more than one orange to the bag at any given time.
import itertools as it
import math
from functools import partial
from collections import Counter

mean, std = 170, 13

def powerset(list_, max_items):
    return it.chain.from_iterable(it.combinations(list_, r) for r in range(1, max_items + 1))

def expected_mean(w):
    spread = std * 1
    return max(mean - spread, min(mean + spread, w / max(1, round(w / mean))))

def score(weight_needed, candidate):
    c_sum = sum(candidate)
    c_mean = c_sum / len(candidate)
    if c_sum >= weight_needed:
        return int(-2e9) + c_sum - weight_needed
    return abs(expected_mean(weight_needed) - c_mean)

def f(oranges, min_bag_weight, lookahead):
    check = Counter(oranges)

    oranges = oranges.copy()
    result = []
    bag = []

    while oranges:
        weight_needed = min_bag_weight - sum(bag)

        lookahead_area = oranges[:lookahead]
        tail = oranges[lookahead:]

        to_add = min(powerset(lookahead_area, lookahead),
                     key=partial(score, weight_needed))
        to_add = min(powerset(to_add, 1),
                     key=partial(score, weight_needed))

        bag.extend(to_add)
        for x in to_add:
            lookahead_area.remove(x)
        oranges = lookahead_area + tail

        if sum(bag) >= min_bag_weight:
            result.append(bag)
            bag = []

    assert check == Counter(oranges) + Counter(bag) + sum(map(Counter, result), Counter())

    return result

if __name__ == '__main__':
    with open('oranges') as file:
        oranges = list(map(int, file))
    res = [f(oranges, 1000, l) for l in range(2, 7+1)]
    print(sum(map(len, res)))

Try it!

Very nice! It gets 1672 with a lookahead of 7, never seen one that high.

(it looks like that the second argument to your powerset function is redundant in this case because it's equal to len(list_) anyway?)

@user I experimented with this parameter in the previous version. Will probably remove it later

Congratulations on discovering the powerful combination of best single element out of the best subset and also having the best score! The bounty is yours.

A simpler expected_mean(w) that gives as good results: return  (w+2) / max(1, round((w+2) / mean))

Python 3, 9796 bags
Building on Jonathan's answer:
import itertools as it

def powerset(iterable):
    s = list(iterable)
    return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))

def f(a,m,l):
 r=[];b=[]
 while a:
  c =  min(list(powerset(a[:l])),key=lambda w: abs(sum(b)+sum(w)-m))
  if sum(c)==0:
   c = a[:l]
  b+=[a.pop(a.index(min(c,key=lambda w: abs(sum(b)+w-m))))]
  if sum(b)>=m:r+=[b];b=[]
 return r

This relies on powerset from itertool's cookbook. First finds optimal subset of the buffer based on minimizing difference from target weight for all subsets, and then picks an element out of this subset based on same criterion. If no optimal subset selects from the whole buffer.

Welcome to PPCG!

@MartinEnder Thanks Martin for the welcoming upvote :)

Ah yes I missed a trick there... I have no problem with this as another answer!

@JonathanAllan Thanks Jonathan I've shortened my answer to credit you without all the apologies. This can be improved by using the fact that it's a normal(170,13) distribution - I'm sure the probability of getting a better fruit in the next run(s) can be used.

@JayCe sounds dangerously close to gambler's fallacy.

this new answer looks suspiciously like mine...

https://codegolf.stackexchange.com/revisions/162852/4

@qwr You are correct! Scrolling down I realize this was your 9947 answer. I reverted it.

I don't mind if you build off my answer, just some attribution would be nice.

C++17, 9961.58 (average over some random seeds)
(scroll down for explanation if you don't know C++)
#include<iostream>

#include<vector>
#include<random>

std::mt19937 engine(279); // random engine
// random distribution of the oranges
std::normal_distribution dist (170.,13.);

int constexpr N_NEW_ORANGES=7;

/** Input format: Current remaining weight of the bag (remain) and
the weight of the oranges (weights)
Output: the index of the orange to be pick.
*/
struct pick_orange{
    std::vector<int>weights,sum_postfix;int remain;

    /// returns {min excess, mask}, (index) is the LSB
    std::pair<int,int> backtrack(int index, int remain) {
        if(sum_postfix[index]<remain)return {1e9,0};
        int min_excess=1e9, good_mask=0;
        for(int next=index;next<N_NEW_ORANGES;++next){
            if(weights[next]==remain){
                return {0, 1<<(next-index)};
            }else if(weights[next]>remain){
                if(weights[next]-remain<min_excess){
                    min_excess=weights[next]-remain;
                    good_mask=1<<(next-index);
                }
            }else{
                auto[excess,mask]=backtrack(next+1,remain-weights[next]);
                if(excess<min_excess){
                    min_excess=excess;
                    good_mask=(mask<<1|1)<<(next-index);
                }
            }
        }
        return {min_excess,good_mask};
    }

    int ans;

    pick_orange(std::vector<int> weights_,int remain_)
        :weights(std::move(weights_)),remain(remain_){

        int old_size=weights.size();

        std::vector<int> count (N_NEW_ORANGES, 0);
        weights.resize(N_NEW_ORANGES, 0);

        sum_postfix.resize(N_NEW_ORANGES+1);
        sum_postfix.back()=0;

        for(int _=0; _<500; ++_){

            for(int i=old_size;i<N_NEW_ORANGES;++i)
                weights[i] = dist(engine);

            // prepare sum postfix
            for(int i=N_NEW_ORANGES;i-->0;)
                sum_postfix[i]=weights[i]+sum_postfix[i+1];

            // auto[excess,mask]=backtrack(0,remain);
            int mask = backtrack(0,remain).second;

            for(int i=0;

                mask
                // i < N_NEW_ORANGES

                ; mask>>=1, ++i){

                // if(mask&1)std::cout<<'(';
                // std::cout<<weights[i];
                // if(mask&1)std::cout<<')';
                // std::cout<<' ';

                count[i]+=mask&1;
            }

            // std::cout<<"| "<<remain<<" | "<<excess<<'\n';

        }

        std::vector<double> count_balanced(old_size, -1);
        for(int i=0;i<old_size;++i){
            if(count_balanced[i]>-1)continue;
            int sum=0,amount=0;
            for(int j=i;j<old_size;++j)
                if(weights[j]==weights[i]){sum+=count[j];++amount;}

            double avg=sum;avg/=amount;
            for(int j=i;j<old_size;++j)
                if(weights[j]==weights[i])count_balanced[j]=avg;
        }

        ans=old_size-1;
        for(int i=ans;i-->0;)
            if(count_balanced[i]>count_balanced[ans])ans=i;
        // Fun fact: originally I wrote `<` for `>` here and wonder
        // why the number of bags is even less than that of the
        // randomized algorithm
    }

    operator int()const{return ans;}
};

#include<iostream>
#include<fstream>
#include<algorithm>

int main(){
    // read input from the file "data"
    std::ifstream data ("data");
    std::vector<int> weights;
    int weight;while(data>>weight)weights.push_back(weight);

    int constexpr BAG_SIZE=1000;
    int total_n_bag=0;
    for(int lookahead=2;lookahead<=7;++lookahead){
        auto weights1=weights;
        std::reverse(weights1.begin(),weights1.end());

        int remain=BAG_SIZE,n_bag=0;
        std::vector<int> w;
        for(int _=lookahead;_--;){
            w.push_back(weights1.back());
            weights1.pop_back();
        }
        while(!weights1.empty()){
            int index=pick_orange(w,remain);

            remain-=w[index];
            if(remain<=0){
                ++n_bag;remain=BAG_SIZE;

                if(n_bag%100==0)
                    std::cout<<n_bag<<" bags so far..."<<std::endl;
            }
            w[index]=weights1.back();weights1.pop_back();
        }

        while(!w.empty()){
            int index=pick_orange(w,remain);
            remain-=w[index];
            if(remain<=0){++n_bag;remain=BAG_SIZE;}
            w.erase(w.begin()+index);
        }

        std::cout<<"lookahead = "<<lookahead<<", "
            "n_bag = "<<n_bag<<'\n';
        total_n_bag += n_bag;
    }

    std::cout<<"total_n_bag = "<<total_n_bag<<'\n';
}

// Fun fact: originally I wrote < for > here and wonder
  // why the number of bags is even less than that of the
  // randomized algorithm

(if < is used basically the algorithm tries to minimize the number of bags)
Inspired by this answer.
TIO link for 250 repetitions: Try it online!

Defines a function (actually it just looks like a function, it's a struct) pick_orange that, given a vector<int> weights the weight of the oranges and int remain the remaining weight of the bag, returns the index of the orange that should be picked.
Algorithm:
repeat 500 times {
generates random (fake) oranges (normal distribution with mean 170 and stddev 13) until there are N_NEW_ORANGES=7 oranges
pick any subset whose sum is smallest and not smaller than remain (the function backtrack does that)
mark all oranges in that subset as good
}
average out the number of times an oranges being marked as good of the (real) oranges with equal weight
return the best orange

There are 3 hardcoded constants in the program that cannot be inferred from the problem:

The random seed (this is not important)
N_NEW_ORANGES (the prediction length). Increasing this makes the program runs exponentially longer (because backtrack)
number of repetitions. Increasing this makes the program runs linearly longer.

Ok. Changing the seed to the one that gives the best answer seems like optimizing for the test case though, so you should take the average of a few, say 10, different seeds as your score. Could you post a TIO link to a version that does less repetitions to get the runtime down?

Finally got it to compile after getting a newer gcc. On 50 runs with random seeds it got an average of 9961.58. Very impressive still. Made me wonder though - your algorithm basically trains itself again on every bag, is there fixed set of best values that could be memorized?

@Angs I don't think there is a way that can use memorization to help in this case. Any idea?

My OS comes with gcc 5.4.0, it had some problems with invalid use of template-name ‘std::normal_distribution’. No problems with gcc 7.1.0.

Python 2, 9756 bags
Let's get the orange rolling...
def f(a,m,l):
 r=[];b=[]
 while a:
  b+=[a.pop(a.index(min(a[:l],key=lambda w:abs(sum(b)+w-m))))]
  if sum(b)>=m:r+=[b];b=[]
 return r

Try it online!
Always picks the fruit from the buffer which minimises the absolute difference of the new weight and the target weight.

Python 3, 9806 bags
Building on Jonathan and JayCe's answers:
import itertools as it

def powerset(iterable):
    s = list(iterable)
    return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))

def f(a,m,l):
 r=[];b=[]
 while a:
  c =  min(list(powerset(list(reversed(sorted(a[:l]))))),key=lambda w: abs((sum(b)+sum(w))-m))
  if sum(c)==0:
   c = a[:l]
  b+=[a.pop(a.index(min(c,key=lambda w: abs((sum(b)+w)-m))))]
  if sum(b)>=m:r+=[b];b=[]
 return r

Try it online!
How it works
Say that the bag has 900 units in it, and there are 2 fruit available: a 99 unit fruit and a 101 unit fruit. If the 99 unit fruit is closer to the beginning of the lookahead list, then min will select it instead of 101. If this happens, we would now need another fruit to fulfill the remaining 1 unit needed. I changed the program to favor the higher-valued fruit in these cases.
It does this by sorting and then reversing the lookahead list before powersetting.

PHP, 9975 bags

If possible go for 5 oranges
When starting bag pick extreme value, balance later
If possible fill bag immediately
Try to keep bag weight close to estimated curve (n*200 for 5bag, n*167 for 6bag, etc)

longest out of all submissions but should be readable

class Belt
{
    private $file;
    private $windowSize;
    private $buffer = [];

    public function __construct($filename, $windowSize) {
        $this->file = new \SplFileObject($filename);
        $this->windowSize = $windowSize;
        $this->loadBuffer();
    }

    public function reset($windowSize) {
        $this->file->seek(0);
        $this->windowSize = $windowSize;
        $this->buffer = [];
        $this->loadBuffer();
    }

    public function peekBuffer() {
        return $this->buffer;
    }

    public function pick($index) {
        if (!array_key_exists($index, $this->buffer)) {
            return null;
        }
        $value = $this->buffer[$index];
        unset($this->buffer[$index]);
        $this->buffer = \array_values($this->buffer);
        $this->loadBuffer();
        return $value;
    }

    private function loadBuffer() {
        for ($c = count($this->buffer); $c < $this->windowSize; $c++) {
            if ($this->file->eof()) {
                return;
            }
            $line = $this->file->fgets();
            if (false !== $line && "" !== $line) {
                $this->buffer[] = trim($line);
            }
        }
    }
}

class Packer
{

    const BAG_TARGET_WEIGHT = 1000;
    const MEAN_WEIGHT = 170;
    const MEAN_COUNT = 6; //ceil(self::BAG_WEIGHT/self::MEAN_WEIGHT);
    const MEAN_TARGET_WEIGHT = 167; //ceil(self::BAG_WEIGHT/self::MEAN_COUNT);

    public static function pack(Belt $belt, Picker $picker) {
        $bag = ["oranges" => [], "buffers" => []];
        $bags = [];
        while ($oranges = $belt->peekBuffer()) {

            $index = $picker->pick($oranges, \array_sum($bag["oranges"]));
            $orange = $belt->pick($index);
            $bag["oranges"][] = $orange;
            $bag["buffers"][] = $oranges;

            if (\array_sum($bag["oranges"]) >= self::BAG_TARGET_WEIGHT) {
                $bags[] = $bag;
                $bag = ["oranges" => [], "buffers" => []];
            }
        }
        return $bags;
    }
}

class Base
{
    public static function bestPermutation($elements, $weight = 0) {
        if (\array_sum($elements) < Packer::BAG_TARGET_WEIGHT - $weight) {
            return null;
        }
        $permute = function ($weight, $elements) use (&$permute) {
            if ($weight >= Packer::BAG_TARGET_WEIGHT) {
                return [];
            }
            $best = \PHP_INT_MAX;
            $bestElements = [];
            foreach ($elements as $key => $value) {
                $sum = $weight + $value;
                $els = [$value];
                if ($sum < Packer::BAG_TARGET_WEIGHT) {
                    $subSet = $elements;
                    unset($subSet[$key]);
                    $els = $permute($weight + $value, $subSet);
                    $els[] = $value;
                    $sum = $weight + \array_sum($els);
                }
                if ($sum >= Packer::BAG_TARGET_WEIGHT && $sum < $best) {
                    $best = $sum;
                    $bestElements = $els;
                }
            }
            return $bestElements;
        };
        $best = $permute($weight, $elements);

        return $best;
    }

    public function pickLightestOutOfHeavierThan($buffer, $targetWeight) {
        $b = -1;
        $bW = PHP_INT_MAX;
        foreach ($buffer as $key => $value) {
            if ($targetWeight <= $value && $value < $bW) {
                $b = $key;
                $bW = $value;
            }
        }
        return $b;
    }

    public function pickClosestTo($buffer, $targetWeight) {
        $b = -1;
        $bW = PHP_INT_MAX;
        foreach ($buffer as $key => $value) {
            $diff = \abs($targetWeight - $value);
            if ($diff < $bW) {
                $b = $key;
                $bW = $diff;
            }
        }
        return $b;
    }

    public function pickFurthestFrom($buffer, $targetWeight) {
        $b = -1;
        $bW = \PHP_INT_MIN;
        foreach ($buffer as $key => $value) {
            $diff = \abs($targetWeight - $value);
            if ($diff > $bW) {
                $b = $key;
                $bW = $diff;
            }
        }
        return $b;
    }

    public function findMax($buffer) {
        $i = -1;
        $m = 0;
        foreach ($buffer as $k => $v) {
            if ($v > $m) {
                $m = $v;
                $i = $k;
            }
        }
        return $i;
    }

    public function findMin($buffer) {
        $i = -1;
        $m = \PHP_INT_MAX;
        foreach ($buffer as $k => $v) {
            if ($v < $m) {
                $m = $v;
                $i = $k;
            }
        }
        return $i;
    }

    public function minimalOrangeCount($buffer, $weight) {
        $elementsToAdd = ceil((Packer::BAG_TARGET_WEIGHT - $weight) / Packer::MEAN_WEIGHT);
        $buffer = \array_merge($buffer,
            \array_fill(0, \floor($elementsToAdd / 2), Packer::MEAN_WEIGHT - 7),
            \array_fill(0, \floor($elementsToAdd / 2), Packer::MEAN_WEIGHT + 7),
            \array_fill(0, $elementsToAdd - \floor($elementsToAdd / 2) * 2, Packer::MEAN_WEIGHT)
        );
        \rsort($buffer);
        $orangeCount = 0;
        foreach ($buffer as $w) {
            $weight += $w;
            $orangeCount++;
            if ($weight >= Packer::BAG_TARGET_WEIGHT) {
                return $orangeCount;
            }
        }
        return $orangeCount + (Packer::BAG_TARGET_WEIGHT - $weight) / Packer::MEAN_WEIGHT;
    }
}

class Picker extends Base
{
    public function pick($buffer, $weight) {
        $weightNeeded = Packer::BAG_TARGET_WEIGHT - $weight;

        $minimalOrangeCount = $this->minimalOrangeCount($buffer, $weight);
        $orangeTargetWeight = ceil($weightNeeded / $minimalOrangeCount);

        if (0 === $weight) {
            $mean = \array_sum($buffer) / count($buffer);
            if ($mean > $orangeTargetWeight) {
                return $this->findMin($buffer);
            } elseif ($mean < $orangeTargetWeight) {
                return $this->findMax($buffer);
            }
            return $this->pickFurthestFrom($buffer, $orangeTargetWeight);
        }

        $i = $this->pickLightestOutOfHeavierThan($buffer, $weightNeeded);
        if (-1 !== $i) {
            return $i;
        }
        $i = $this->pickClosestTo($buffer, $orangeTargetWeight);
        return -1 !== $i ? $i : 0;
    }
}

$bagCount = 0;
$belt = new Belt(__DIR__ . "/oranges.txt", 0);
for ($l = 2; $l <= 7; $l++) {
    $belt->reset($l);
    $bags = Packer::pack($belt, new Picker());
    $bagCount += count($bags);
    printf("%d -> %d\n", $l, count($bags));
}
echo "Total: $bagCount\n";

2 -> 1645
  3 -> 1657
  4 -> 1663
  5 -> 1667
  6 -> 1671
  7 -> 1672
  Total: 9975

Try It

Nice! What's surprising for me is that it uses the current item count – I wonder if than can be factored out. After all, it doesn't matter if there are 3 items weighting 120 each or 3 items weighting 160 each.

@Angs probably it is possible. Current item count came out as a simple shortcut for idea "Hey, sometimes its possible to do 5 item bag" and I tunelled on getting 5 item bags working. With free time improvements will come :)

Python 3, 9855 9928 9947 9956 9964 bags
Based on Jonathan Allan's starter code, but ungolfed to be readable.
Idea: Since 1000/170 = 5.88, we try to select fruits close to 1000/6 (I fiddled with the magic constants). However, if the last fruit in the bag can minimize waste, we use that instead.
This solution has bag sum targets for each fruit added. I'll probably stop here. I used Nelder-Mead to find my targets array:
[  165.79534144   343.58443287   522.58081597   680.76516204   845.93431713 1063.17204861]

def f(a, m, l, targets):
    bags = []
    bag = []
    bag_sum = 0
    while a:
        buffer = a[:l]
        finishers = tuple(filter(lambda w: bag_sum + w >= m, buffer))
        if finishers:
            next_fruits = [min(finishers)]

        else:
            ind = len(bag)
            next_fruits = [min(buffer, key=lambda w: abs(targets[ind]-bag_sum-w))]

        for next_fruit in next_fruits:
            bag.append(a.pop(a.index(next_fruit)))
            bag_sum += bag[-1]

        if sum(bag) >= m:
            bags.append(bag)
            bag = []  # Reset bag
            bag_sum = 0

    return bags

9956 bags
from itertools import combinations

def f(a,m,l):
    bags = []
    bag = []
    while a:
        buffer = a[:l]
        next_fruit = None
        single_fruit = True

        finishers = [w for w in buffer if sum(bag) + w >= m ]
        if finishers: next_fruit = min(finishers)

        if not next_fruit:
            if len(buffer) >= 4 and sum(bag) < 600:
                next_fruits = min(combinations(buffer, 2), key=
                                  lambda ws: abs(2*169-sum(ws)))
                for fruit in next_fruits:
                    bag.append(a.pop(a.index(fruit)))

                single_fruit = False  # Skip adding single fruit

            else:
                next_fruit = min(buffer, key=lambda w: abs(171.5-w))

        if single_fruit:
            bag.append(a.pop(a.index(next_fruit)))

        if sum(bag)>=m:
            bags.append(bag)
            bag = []

    return bags

oranges = [int(x.strip()) for x in open("fruit.txt").readlines()]
bagLists = []
for lookahead in (2,3,4,5,6,7):
    bagLists.append(f(oranges[:], 1000, lookahead))

totalBagsOver1000 = sum(map(len, bagLists))
print('bags: ', (totalBagsOver1000))

The 9947 bags program is particularly simple:
def f(a,m,l):
    bags = []
    bag = []
    while a:
        buffer = a[:l]
        next_fruit = None

        finishers = [w for w in buffer if sum(bag) + w >= m ]
        if finishers: next_fruit = min(finishers)

        if not next_fruit:
            next_fruit = min(buffer, key=lambda w: abs(171.5-w))

        bag.append(a.pop(a.index(next_fruit)))

        if sum(bag)>=m:
            bags.append(bag)
            bag = []

    return bags

Good! Btw, just picking the last item so as to minimize waste is quite powerful by itself and gives 9862 bags.

How did you come up with those targets? Training on random data?

@Alex I stated so: Nelder-Mead method (with negative bags as loss function)

Ruby, 9967 bags
def pick a, n
  if a.sum < n
    #return a.max
    d = n % 170
    return a.min_by{|w|
      [(w - d).abs, (w - d - 170).abs].min
    }
  end

  subsets = (0..a.length).map do |i|
    a.combination(i).to_a
  end.flatten(1)

  subsets.select!{|s|s.sum >= n}
  least_overkill = subsets.min_by{|s|s.sum}
  #puts "best: #{least_overkill.sort}"
  return least_overkill.min
end

def run list, weight, n
  bags = 0
  in_bag = 0
  while list.size > 0
    x = pick(list[0...n], weight - in_bag)
    i = list.index(x)
    raise new Exeption("not a valid weight") if(!i || i >= n)
    list.delete_at i
    in_bag += x
    if in_bag >= weight
      #puts in_bag
      in_bag = 0
      bags += 1
    end
  end
  return bags
end

Try it online!
If you have enough weight to fill the bag, find the lightest subset that can fill the bag and use the lightest orange of that subset. Otherwise, get the remaining weight as close as possible to a multiple of 170.

Racket/Scheme, 9880 bags
To decide which piece of fruit to add to the bag, compare the optimal bag weight to the weight of the bag with the additional piece of fruit. If it's the optimal weight, use it. If it's overweight, minimize the excess amount.
If it's underweight, minimize the excess amount after trying to leave an optimal gap.
;; types

(define-struct bagger (fruit look tray bag bags)) ; fruit bagger

;; constants

(define MBW 1000) ; minimum bag weight
(define AFW 170) ; average piece-of-fruit weight
(define GAP (- MBW AFW)) ; targeted gap
(define FRUIT (file->list "fruit-supply.txt")) ; supplied fruit

;; utility functions

(define (weigh-it ls)
  (if (empty? ls)
      0
      (+ (car ls) (weigh-it (cdr ls)))))

(define (ref-to-car ls ref)
  (if (zero? ref)
      ls
      (let ((elem (list-ref ls ref)))
        (cons elem (remove elem ls)))))

;; predicates

(define (bag-empty? bgr) (empty? (bagger-bag bgr)))
(define (bag-full? bgr) (>= (weigh-it (bagger-bag bgr)) MBW))
(define (fruit-empty? bgr) (empty? (bagger-fruit bgr)))
(define (tray-empty? bgr) (empty? (bagger-tray bgr)))
(define (tray-full? bgr) (= (length (bagger-tray bgr)) (bagger-look bgr)))
(define (target-not-set? target value) (and (empty? target) (empty? value)))

;; pick best piece of fruit

(define (pf-rec tray bag i target value diff)
  (if (or (target-not-set? target value) (< diff value))
      (pick-fruit (cdr tray) bag (add1 i) i diff)
      (pick-fruit (cdr tray) bag (add1 i) target value)))

(define (pick-fruit tray bag i target value)
  (if (empty? tray)
      target
      (let ((weight (weigh-it (cons (car tray) bag))))
        (cond
          ((= weight MBW) i)
          ((> weight MBW) (pf-rec tray bag i target value (- weight MBW)))
          ((< weight MBW)
           (if (> weight GAP)
               (pf-rec tray bag i target value (- weight GAP))
               (pf-rec tray bag i target value (modulo (- MBW weight) AFW))))))))

;; load tray, bag, bags, etc.

(define (load-bag bgr)
  (let* ((tray (bagger-tray bgr))
         (bag (bagger-bag bgr))
         (weight (+ (weigh-it tray) (weigh-it bag))))
    (if (= weight MBW)
        (struct-copy bagger bgr
                     (tray empty)
                     (bag (append tray bag)))
        (let ((new-tray (ref-to-car tray (pick-fruit tray bag 0 empty empty))))
          (struct-copy bagger bgr
                       (tray (cdr new-tray))
                       (bag (cons (car new-tray) bag)))))))

(define (load-bags bgr)
  (struct-copy bagger bgr
               (bag empty)
               (bags (cons (bagger-bag bgr) (bagger-bags bgr)))))

(define (load-tray bgr)
  (struct-copy bagger bgr
               (fruit (cdr (bagger-fruit bgr)))
               (tray (cons (car (bagger-fruit bgr)) (bagger-tray bgr)))))

;; run the bagger factory

(define (run-bagger-aux bgr)
  (cond
    ((bag-full? bgr) (run-bagger-aux (load-bags bgr)))
    ((bag-empty? bgr)
     (cond
       ((tray-full? bgr) (run-bagger-aux (load-bag bgr)))
       ((tray-empty? bgr)
        (if (fruit-empty? bgr)
            (length (bagger-bags bgr))
            (run-bagger-aux (load-tray bgr))))
       (else
        (if (fruit-empty? bgr)
            (run-bagger-aux (load-bag bgr))
            (run-bagger-aux (load-tray bgr))))))
    (else
     (cond
       ((tray-full? bgr) (run-bagger-aux (load-bag bgr)))
       ((tray-empty? bgr)
        (if (fruit-empty? bgr)
            (run-bagger-aux (load-bags bgr))
            (run-bagger-aux (load-tray bgr))))
       (else
        (if (fruit-empty? bgr)
            (run-bagger-aux (load-bag bgr))
            (run-bagger-aux (load-tray bgr))))))))

(define (run-bagger fruit look)
  (run-bagger-aux (make-bagger fruit look empty empty empty)))

;; stackexchange problem run

(define (run-problem fruit looks)
  (if (empty? looks)
      0
      (+ (run-bagger fruit (car looks)) (run-problem fruit (cdr looks)))))

(run-problem FRUIT '(2 3 4 5 6 7)) ; result = 9880

Haskell, 9777 bags
This was my first attempt:

it greedily filled a bag with a batch when it could,
or flushed all oranges into the bag when it could not.

options[]=[(0,([],[]))]
options(first:rest)=[option|(sum,(now,later))<-options rest,
 option<-[(sum+first,(first:now,later)),(sum,(now,first:later))]]
bags _[_]_=[]
bags(w_sum,w_bag)(w_kilo:w_iyts)w_view=
 let(w_take,w_remd)=splitAt(w_view)w_iyts;
     w_fill=filter((>=(w_kilo-w_sum)).fst)(options w_take)
 in if null w_fill then bags(w_sum+sum w_take,w_bag++w_take)(w_kilo:w_remd)w_view
    else let(_,(w_now,w_later))=minimum w_fill in
         (w_bag++w_now):bags(0,[])(w_kilo:w_later++w_remd)w_view
main=print.sum$map(length.bags(0,[])(1000:batch))[2..7]

Try it online!

Haskell, 9981 bags
The Angs → Jonathan Allan → JayCe → fortraan → Alex → Roman Czyborra codegolf python could cyclize back to Haskell for some added mathematical purity along the same major train of thought

only one orange gets sacked before a new orange is added into consideration
bias prefers sufficing fruits ((<miss)==False<True)
bias prefers fruits close to the most likely integer fill
for that integer reverse the
(m-n)/sqrt(n)==(n+1-m)/sqrt(n+1) <==> n=sqrt(m^2-1/4)-1/2
from a https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables

seasoned with some unecessary pointlessnesses
subsets[]=[[]];subsets(f:t)=[r|s<-subsets t,r<-[s,f:s]]
mean=uncurry(div).(id***max 1).(sum&&&length)
bags[]_ _=[];bags batch(miss:have)n=let
 goal=div miss$ceiling(sqrt((fromIntegral miss/170)^2+1/4)-1/2)
 best=minimumBy.comparing.(((<miss)&&&(abs.(goal-))).); desk=take n batch
 pick=best id.best(if sum desk<miss then mean else sum).filter(>[]).subsets$desk
 in if pick < miss then bags(delete pick batch)(miss-pick:pick:have)n
       else (pick:have):bags(delete pick batch)[miss+sum have]n
main=print$id&&&sum$map(length.bags batch[1000])[2..7]

Try it online!
without yielding a different numeric gain atop the 9981 nets of oranges harvested afore while my 10k011 bags packer grabbing unfit oranges back out of unclosed bags was disqualified by user69850 in persona user202729 → Jo King → ovs hencefore the deserved bounty went to Alex

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


text:
Program my autodialer
Back in the day, telephone autodialers used punched cards with one column for each digit of the number to be dialed. Columns had seven rows. The first three rows represented the numbers (1,2,3), (4,5,6), and (7,8,9) respectively. The last three rows rotated this arrangement by 90°: (1,4,7), (2,5,8), and (3,6,9). The middle row was used for 0. Any digit 1-9 would have two holes punched - one in the first three rows, and one in the bottom three rows. Zero would only have the middle row punched. Let's visualize the punched column for the number 6 (. is unpunched, x is punched, guide on left is just to illustrate the encoding):
123 .
456 x
789 .
 0  .
147 .
258 .
369 x

We look for which row(s) contain the number we're trying to dial. For 6, this is the second row, and the ninth row. These two rows are punched, the remaining five rows are unpunched. Here are the punched patterns for all digits 0-9:
    0 1 2 3 4 5 6 7 8 9
123 . x x x . . . . . .
456 . . . . x x x . . .
789 . . . . . . . x x x
 0  x . . . . . . . . .
147 . x . . x . . x . .
258 . . x . . x . . x .
369 . . . x . . x . . x

Your goal is to (write a program or function to) punch these cards for me.
Input: A number, taken in any reasonable format (string, integer, list of integers, &c.), not to exceed 9999999999999.
Output: The grid of punched columns corresponding to the number input. You don't need the headers or extra spacing shown above, just the punched columns themselves. Leading/trailing newlines are ok, as is whitespace between rows/columns as long as it is consistent. Speaking of, as long as they are consistent, you may use any (non-whitespace) character for punched, and any other character for unpunched (while it should be obvious, please specify what characters you are using).
This is code-golf, so shortest code wins. Standard loopholes are disallowed.
Test cases (all use . for unpunched, x for punched):
In: 911
Out: .xx
     ...
     x..
     ...
     .xx
     ...
     x..

In: 8675309
Out: ....x..
     .x.x...
     x.x...x
     .....x.
     ..x....
     x..x...
     .x..x.x

In: 5553226
Out: ...xxx.
     xxx...x
     .......
     .......
     .......
     xxx.xx.
     ...x..x

Totally unnecessary for solving the question, but there's a neat little gallery of these cards/devices here.

you may use any character for punched, and any other character for unpunched you mean any non-whitespace characters?

Yes, I suppose that would be preferable since whitespace is allowed elsewhere. And for the sake of being able to see. Will edit in, thanks.

cool challenge...tempted to write a FORTRAN 77 answer, but idk how to golf it

@qwr Feel free to create a "Tips for golfing in Fortran" post.

Jelly, 13 bytes
9s3,Z$j0ċþDZY

Try it online!
1 = punctured, 0 = not punctured.

Pyth, 25 bytes
.tm?djNmX*3NkZ.Dtd3X*7N3Z

Uses 0 for punched and " for unpunched.
Try it here
Explanation
.tm?djNmX*3NkZ.Dtd3X*7N3Z
  m                      Q  For each number in the (implicit) input...
   ?d                       ... if the number is nonzero...
              .Dtd3         ... get (n - 1) divmod 3...
       mX*3NkZ              ... replace each position in `"""` with `0`...
     jN                     ... and stick them together with `"`. ...
                   X*7N3Z   ... Otherwise, `"""0"""`.
.t                          Transpose the result.

JavaScript (ES6), 60 54 bytes
Takes input as an array of integers. Returns a binary matrix, with 0 = unpunched / 1 = punched.
a=>[14,112,896,1,146,292,584].map(n=>a.map(i=>n>>i&1))

Try it online!

05AB1E, 16 15 bytes
Uses 0 and 1.
ε9ÝÀ3ôD¨ø«¢O}ø»

Try it online!
Explanation
ε           }     # apply to each digit in input
 9Ý               # push the range [0 ... 9]
   À              # rotate left
    3ô            # split into pieces of 3
      D¨          # duplicate and remove the last digit (0)
        ø         # transpose
         «        # append
          ¢O      # sum the counts of each in the current digit
             ø    # transpose
              »   # format output

SOGL V0.12, 23 bytes
,{r"ΧL→▓lφ℮o¤κ²‘7nwι}⁰H

Try it Here!
Compression.

Python 2, 84 bytes
lambda a:[''.join(`(ord('(1Aa2Bb4Dd'[int(n)])-32)>>k&1`for n in a)for k in range(7)]

Try it online!
0/1 is used for unpunched/punched.

Python 3, 84 80 bytes
def f(s):[print(*[int(i in[~-n//3,6--n%3-3*(n<1)])for n in s])for i in range(7)]

Try it online!

Something seems funky with your fifth and sixth rows (they seem to be flipped). [1,2,3] should form a diagonal line down, for instance.

@brhfl thanks for telling me, fixed it

J, 31 20 bytes
-11 bytes thanks to FrownyFrog!
(e."1],0,|:)1+i.@3 3

Try it online!
J, 31 bytes
1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~]

Try it online!
Takes the input as a list of digits
0 - unpunched, 1 - punched
Explanation:
   a=.1+i.3 3 - generates the matrix and stores it into a
1 2 3
4 5 6
7 8 9

   (a,0,|:a=.1+i.3 3) - generates the entire comparison table
1 2 3
4 5 6
7 8 9
0 0 0
1 4 7
2 5 8
3 6 9

   ]=/ - creates an equality table between the input and the comparison table

 ((a,0,|:a=.1+i.3 3)=/~]) 9 1 1
0 0 0
0 0 0
0 0 1
0 0 0
0 0 0
0 0 0
0 0 1

1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0

1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0

  1*@|:@:#. - adds the tables, transposes the resulting table and finds the magnitude

  (1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~])  9 1 1
0 1 1
0 0 0
1 0 0
0 0 0
0 1 1
0 0 0
1 0 0

@FrownyFrog Thank you! You are brilliant as always!

20

C (clang), 108 107 bytes
c,i;f(*q){char*r;for(i=~0;i++<6;puts(""))for(r=q;c=*r++;c-=48,putchar(".X"[(c--?16<<c%3|1<<c/3:8)>>i&1]));}

Try it online!
Takes input number as string. Prints output in . and X as in examples.
Credits
-1 byte thanks @ASCII-only

107, and removed header otherwise you'd need to include the header in the bytecount

Can you please point me to general consensus that header inclusions needs to be counted for byte count towards function solutions (not full programs)

1, 2, 3

Suggest putchar(".X"[(c--?16<<c%3|1<<c/3:8)>>i&1]))c-=48 instead of c-=48,putchar(".X"[(c--?16<<c%3|1<<c/3:8)>>i&1]))

Canvas, 27 25 bytes
｛９＋├３÷ｕ４％ ×#＋#¹╷３％５＋１╋］↶↕

Try it here!

Charcoal, 28 bytes
Ｅ⁴⭆θＩ⁼ι÷﹪⊖λχ³Ｅ³⭆θＩ∧Ｉλ¬﹪⁻⊖λι³

Try it online! Link is to verbose version of code. Uses 0/1, but can support arbitrary characters at a cost of 1 byte: Try it online!. Explanation:
Ｅ⁴              Loop from 0 to 3
  ⭆θ            Loop over input string and join
           λ     Current character
         ⊖      Cast to integer and decrement
        ﹪  χ    Modulo predefined variable 10 (changes -1 to 9)
       ÷    ³   Integer divide by literal 3
     ⁼ι         Compare to outer loop variable
    Ｉ           Cast to string
                Implicitly print each outer result on a separate line

Ｅ³              Loop from 0 to 2
  ⭆θ            Loop over input string and join
            λ   Current character
           ⊖    Cast to integer and decrement
          ⁻  ι  Subtract outer loop variable
         ﹪    ³ Modulo by literal 3
        ¬       Logical not
       λ        Inner loop character
      Ｉ         Cast to integer
     ∧          Logical and
    Ｉ           Cast to string
                Implicitly print each outer result on a separate line

Perl 5 -F, 52 bytes
for$i(123,456,789,0,147,258,369){say map$i=~$_|0,@F}

Try it online!
Uses 1 for punched and 0 for unpunched.

source: Stack Exchange

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

sort: votes


text:
Solve for N from input string
Challenge :
Your job is to find the given number N.

Input :
You will be given a string in the following form:
dN ± Y = X

Where:
d, N, X, Y are all numbers with d , X , Y being integers (not decimals).

Output :
Solve the equation and output the value of N rounded. Round up if decimal is greater than or equal to 0.5 and round down if less than 0.5

Examples :
Input                  Output
 N + 1 = 3        ---> 2
 N - 1 = 5        ---> 6
2N + 1 = 3        ---> 1
2N + 1 = 4        ---> 2

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

Notes :

Answer must be rounded it cannot be a float
Whitespace do not matter. You can have every element in the string separated by white space if you want or if you don't want leave it as it is.
You do not need to check for invalid input. i.e. All inputs will be strings in the given format.

Comments are not for extended discussion; this conversation has been moved to chat.

@Mego : I have (hopefully) made it more clear. Can you kindly take a look and open it?

@MuhammadSalman I'll leave both the original and add the alternative [-128,127] range answer then. (And I will delete some of my answers now, thanks for answering them.)

Can d , X , and Y be negative? what is the maximum value that needs to be handled?

@TaylorScott : If you want you can implement that.

Python 2, 88 74 70 bytes
-14 bytes thanks to Chas Brown.
-4 bytes thanks to Sunny Patel.
d,w,Y,_,X=input().split()
print round((int(X)-int(w+Y))/float(d[:-1]))

Try it online!

@ovs : He he broke it. If I remove even a single space bam. It blows up. This is whitespace sensitive.

@MuhammadSalman This was the case before. This solution requires at least one space between the different parts. If this is not allowed I will delete my answer.

@ovs: Na it is perfectly alright.

under the assumption (according to comments) that we deal only with digits
JavaScript (Node.js), 30 bytes
*thanks for @Rick Hitchcock for pointing out i can use 1 instead of space (reduces 13 bytes
x=>(x[3]+x[5]-x[9])/-x[0]+.5|0

Try it online!

Python 2, 64 63 bytes
Using eval
d,w,Y,_,X=input().split()
print-eval('('+w+Y+'-'+X+')/'+d[:-1])

Try it online!
Saved 1 byte thanks to Keyu Gan

Java 10, 111 94 (or 92) bytes
s->{var a=s.split("N|=");return(int)((new Float(a[2])-new Float(a[1]))/new Float(a[0])+.5);}

Input is in the format dN±Y=X (without any spaces) instead of dN ± Y = X.
Try it online.
2 more bytes could be saved if the numbers are never outside the [-128, 127] range, in which case the last and one of the two first Float can be changed to Byte.
Try it online.
Explanation:
s->{                             // Method with String parameter and integer return-type
  var a=s.split("N|=");          //  And split by "N" or "=" to a String-array
  return(int)((new Float(a[2])   //  Return the third number (after the equal sign),
               -new Float(a[1])) //   minus the second number (including leading +/-),
              /new Float(a[0])   //   divided by the first number
         +.5);}                  //  Rounded by using `(int)(R + 0.5)`

Japt v2.0a0, 20 bytes
q/N|=/ f
o!-Uo)r!÷ r

Try it
q/N|=/ f\no!-Uo)r!÷ r     :Implicit input of string U
                          : e.g. "2N+1=4"  "N+1=4"
q                         :Split on
 /N|=/                    :  "N" or "="
                          > ["2","+1","4"] ["","+1","4"]
       f                  :Filter (removes the first element if the string started with "N")
                          > ["2","+1","4"] ["+1","4"]
        \n                :Reassign to U
             Uo           :Pop last element (X)
                          > "4"            "4"
          o               :Modify last element (Y)
           !-             :X-Y
                          > ["2",3]        [3]
                r         :Reduce by
                 !÷       :  Inverse division
                          > 1.5            3
                    r     :Round
                          > 2              3

Wolfram Language (Mathematica), 54 46 bytes
Round[ToExpression[""<>(#/."="->"-")]~Root~1]&

Try it online!

JavaScript (Node.js), 44 bytes
x=>([m,a,r]=x.split(/N|=/),r-a)/(+m||1)+.5|0

Try it online!
Or, for only single-digit numbers:
JavaScript (Node.js), 36 bytes
([m,,o,a,,r])=>-(o+a-r)/(+m||1)+.5|0

Try it online!

Befunge-93 (FBBI), 34 26 bytes
&~$~90p0&X&-2*\/-:2%\2/+.@

Try it online!
If we didn’t need to bother with rounding correctly, it could be much smaller:
&~$~90p0&X&-\/-.@

Try it online!
-\/-

I think this fails to round, and instead truncates. For example, it returns 0 for 3N+1=3 when it should round 2/3 up to 1

Fixed

For rounding, you can double the numerator before dividing, add the quotient to itself mod 2, and then divide the sum of that by 2, instead of doing the multiply by 10 thing

np, always happy to help

C (clang), 133 bytes
N,d,y,x,a[9],o;f(*s){sscanf(s," %[0-9N] %c %d = %d",a,&o,&y,&x);d=!sscanf(a,"%d",&d)?1:d;N=(x-(o>43?-y:y))*2/d;printf("%d",N/2+N%2);}

Try it online!
This handles all spaces except between d and N.
[Removed wrong answer that rounds down]

some spaces can be removed

124 bytes

Yabasic, 142 bytes
An anonymous function that takes input as a string and outputs to the console.
Line Input""s$
dim n$(5)
k=token(s$,n$())
n$=n$(1)
If n$="N"n$=("1N")
?Int((Val(n$(5))-Val(n$(2)+"1")*Val(n$(3)))/Val(Left$(n$,Len(n$)-1))+.5)

Try it online!

Vyxal, 110 bits1, 13.75 bytes
‛Nx*\=/ƒ∆qh.1+ṙ

Try it Online!
Python rounding is a little goofy hence the .1+ṙ at the end.
Could be 9.125 bytes: ‛Nx*\=/ƒ∆q if it wasn't for rounding.
Explained
‛Nx*\=/ƒ∆qh.1+ṙ
‛Nx*            # Replace all N with x
    \=/         # split on equal sign
       ƒ∆q      # and solve the equation for x. Yes. There's a built in for it.
          h.1+  # add 0.1 to the result to account for the fact that python seems to round down if <= 0.5 instead of < 0.5
              ṙ # round the answer as required

Scala 3, 168 bytes
import java.lang._
import scala.util.chaining._
val c:String=>Int=_.split("N|=").pipe(a=>(new Float(a(2))-new Float(a(1)))/new Float(a(0))).pipe(x=>math.round(x).toInt)

Attempt This Online!

I thought scala._ and java.lang._ were imported by default

[Matlab],  91 bytes
this is the most resilient version.
assuming that s is the input string.
syms N;v=str2double(regexp(s,'(?<!\d)(\d)+(?!\d)','match'));round(solve(v(1)*N+v(2)==v(3)))

[Matlab],  74 bytes
syms N;round(solve(str2double(s(1))*N+str2double(s(4))==str2double(s(6))))

but doesnt really work if for example Y was 2 digits (ie 10). I'll try to improve it a bit.
[Matlab],  29 bytes
if the input was just the numbers and not a string
sym N;round(solve(d*N+Y==X))

Convex, 19 bytes
S-®-?\d+"ô:d~\-\/mo

Try it online!

PHP, 45 bytes
<?=round((($s=$argn)[3].$s[5]-$s[9])/-$s[0]);

Run with echo '<input>' | php -nF <filename> or Try it online.
This requires that d always be given, and that the string is the same length each time, e.g.:

N + 1 = 3 won't work, but 1N + 1 = 3 will work.
1N +1 =3 won't work, but 1N + 1 = 3 will work.

J, 26 Bytes
<.({.%~{:-1&{)".>0 2 4{cut

Note that the result for N is floored (not rounded), so for the last test case it returns 1 instead of 2. If this is unacceptable I will change the answer.
Input should be of the form 'd N +-Y = X'
Explanation:
   cut '10 N +2 = 23'  NB. Split on whitespace
┌──┬─┬──┬─┬──┐
│10│N│+2│=│23│
└──┴─┴──┴─┴──┘
   0 2 4{cut '10 N +2 = 23'  NB. Choose relevant portions
┌──┬──┬──┐
│10│+2│23│
└──┴──┴──┘
   ".>0 2 4{cut '10 N +2 = 23'  NB. Eval each
10 2 23
   ({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23'  NB. Compute (x-y)/d
2.1
   <.({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23'  NB. Floor
2

C# (149 Bytes)
s=>(int)Math.Round(((s=s.Replace(" ",""))[s.Length-1]-48-((s.Contains("-")?-1:1)*(s.Split(new[]{'+','-'})[1][0]-48)))/(decimal)(s[0]=='N'?1:s[0]-48))

Craptacular bloated C# solution. Guess I could've ported the Java solution but I try not to look at others' stuff before posting mine, so here we are.
Try it Online

Ruby, 66 bytes
->s{a,_,b,_,c=s.split.map &:to_f;((s[?+]?c-b:c+b)/(a+0**a)).round}

Try it online!

awk, 48 bytes
awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

Use cases:
echo "N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "N - 1 = 5" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "2N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "2N + 1 = 4" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

Extra case:
echo "3N + 1 = 11" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

Output: 3

PHP, 83 Bytes
Try it online
Try it online2
For some reason round does not round to the closest integer on tio run, on this version the solution has some extra bytes (87 Bytes)
Code
<?=round(($c=explode(" ",$argv))[4]-($c[1].$c[2]))/($c[0]==N?1:substr($c[0],0,-1));

Explanation
//ecuation structure xN sign c = m
//array structure like ["xN","sign", "c", "=", "m"]
round(                         //round the result
(                              //first element of the ecuation
   $c=explode(" ",$argv))[4]   //explode the string and get the 4th value
   -                           //substract, php accepts (1-(-1)) so,
                               //it can ve solved like this
   ($c[1].$c[2])               //concat the sign with c
)
/                              //divide by x
($c[0]==N?1:substr($c[0],0,-1) //if the first element xN it's N
                               //divide by 1, else remove N and divide
);

Question
About negative numbers, my code should work for an equation like -xN +- c = m, but when you are considering a x = -1, the input will be -N +- c = m or -1N +- c = m?

R, 90 bytes
-round(eval(parse(t=gsub("=","-",gsub("\\dN","",s<-scan(,"")))))/(gsub("N.*$","",s):1)[1])

Try it online!
Assumes d is present as per the spec.
Probably not the shortest option - I am sure there are better regex.

awk : safe division without branching ternary condition
echo 'N + 1 = 3' |

gawk '$__=sprintf("%.f",($5-($2$3))/(_+=$_)^!!_)'
mawk '{printf("%.f",($5-($2$3))/(_+=$_)^!!_)}'

2

echo '2N + 1 = 4' |

nawk '$!NF=sprintf("%.f",($5-($2$3))/(_+=$!_)^!!_)'

2

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:
Where are my pennies?
Given string S representing a dollar amount, make change for that amount of money use the least number of coins to make the change and record the amount of each coin in a list. Here are the coins available to use and their value.
Coin : Value
Dollar Coins : $1.00
Quarters: $0.25
Dimes: $0.10
Nickels: $0.05
Pennies: $0.01

Input
String S that contains the dollar symbol $ and the dollar amount.
Output
List of coin numbers separated by a space character " ". The list must be in this order: Dollar coins, quarters, dimes, nickels, pennies.
Constraints

$0.00 < S < $10.00
S is given to two decimal places.
make change for that amount of money use the least number of coins

Example Input
$4.58
$9.99
Output
4 2 0 1 3
9 3 2 0 4
Win Condition
shortest bytes win.

Do we have to get the $ sign in the input? I suggest allowing the number itself, either as a number or a string (optional).

It's essentially the same as this, but I personally think it's sufficiently different, since we don't need to output the strings.

Knapsack problem, possible duplicate of https://codegolf.stackexchange.com/questions/162158/knapsack-problem

@0x45 I'd upvote this if you remove the $-sign requirement in the input, and make the output format optional...

@StewieGriffin I like the tricky part about the $, since you have to format the input first. And in the detail the best golfer wins then.

Fair enough... You might want to read this.

I think the input format is interesting but the output being space-separated is just a chore.

On further thought, this input format isn't interesting either. Because the format is always $d.dd, the symbols give no information and so just need to be stripped away or ignored.

Possible duplicate of +- knapsack problem

This is OP's question, and the input format as a string is perfectly reasonable for this case.

@Xcali This is not a duplicate of the knapsack problem, because the list of item sizes is bounded. In fact the only tricky part is how many dimes and nickels to use, and after you divide the input by 5 pennies, this just goes in a cycle mod 5. Knapsack problem requires non-polynomial time. This question can be answered in constant time. This is not an outstanding question but it is not a duplicate of the cited question either.

What about languages that do not support string input?

@Xcali Nope, this one can be solved with greedy algorithm.

05AB1E, 24 17 bytes
¦'.¡25‰10‰5‰r5F?' ?}
¦'.¡`25‰`T‰`5‰`ðý

Try it online!
My first attempt at it. It's very verbose in my opinion and I'll look at further revising this answer. Maybe somebody better than me will figure it out.
Explanation
¦             # Remove '$' from input
'.¡           # Push '.' and split string on that. (dollar),(cents) is result
`25‰          # Push all items onto stack and mod top by 25
`T‰           # Push all items onto stack and mod top by 10
`5‰           # Push all items onto stack and mod top by 5
`r            # Push all items onto stack and reverse stack
ðý            # Loop through stack and print each element with space

-7 bytes thanks to Emigna

Some quick gains: Replace 10 with T and r5F?' ?} with ðý.

@Emigna How did you go about translating the r5F?' ?} to ðý if you don't mind so that I can know for future challenges.

ðý means join by space, which gives the same result as the print each with a space after that you were doing (except with a trailing newline instead of a trailing space)

@Emigna Oh! I see now. I thought i was some sort of weird encoding, but it is literally push space and b.join(a). I got it now. Thanks :)

Python 2, 79 72 71 bytes
s=input()
d=int(s[1]+s[3:])
for c in(100,25,10,5,1):print d/c,;d-=d/c*c

Try it online!
Saved 7 bytes thanks, in part, to Chas Brown
Saved a byte thanks to Jo King

Save 6 via s=input();d=int(s[1]+s[-2:]).

Thanks, I totally overlooked that the input was less than $10, though my previous was flexible. :$

What's the ~~ for?

@JoKing The ~ does a bitwise two's complement, and two of them reverses it, but essentially performs a Math.floor in many languages. And now I realize that the / operator does just that in  Python 2 in this case. Thanks for pointing that out! Saved a byte.

suggest d%=c instead of d-=d/c*c

Hexagony, 35 32 28 27 bytes
]{=?2'?!/@[1[5/P0;:!%'[01[5

Try it online!
There are no no-ops . now, so it must be optimal.

-1 byte. This way of using "functions" in Hexagony is very interesting

@JoKing Thanks! (originally I intend to use $ or > and throw it in a loop, but then figure out this way after trying to rotate the program to save some bytes)

One more. This one ends in a divide by zero error and prints an excess space though (also, what program are using to create the images? It doesn't look like the one I usually use)

@JoKing Hexagony Colorer (of course), but I have to remove the caps  (and I was too lazy to reimplement it) because of a Mono bug. (also with some change-font feature...)

Octave, 106 bytes
@(n)[k=(f=@fix)(x=str2num(n(2:5))),m=f(4*(x-k)),t=f(10*(s=x-k-.25*m)),p=f(20*(s-.1*t)),100*(s-.1*t-.05*p)]

Try it online!
16 bytes is used simply to get rid of $ and convert the string to a number. The rest is simply removing the as many coins as possible, one value at a time.

Stax, 18 17 bytes
ä┐¢6ⁿ≡♠₧ç7╦Δ╛XÄR│

Run and debug it

R, 81 bytes
x=as.double(substr(scan(,""),2,6));for(i in 1/c(1,4,10,20,100))x=x-i*print(x%/%i)

Try it online!
26 bytes ensuring the data are a double rather than a string, very nearly a third of the program! That's lame, to say the least.

Ruby, 74 bytes
->s{n=s.delete("$.").to_i;["%s"]*5*" "%[n/100,n/25%4,(m=n/5%5)/2,m%2,n%5]}

Try it online!
Converts input to an integer containing number of pennies, then applies formulas in the [] at the end.
5 bytes standard Ruby boilerplate ->s{}
34 bytes on solving the problem
35 bytes on formatting

Julia, 72 71 bytes
!s=(x=parse(Int,filter(>('.'),s));[100,25,10,5,1].|>u->(t=x÷u;x%=u;t))
Attempt This Online!

-1 byte: x=x%u -> x*=u - thanks to @MarcMush

Java 8, 138 bytes
s->{long p=new Long(s.replaceAll("\\D","")),c,i=100;for(s="";i>0;s+=c+" ",i=i>25?25:i>10?10:i>5?5:i>1?1:0)for(c=0;p>=i;p-=i)c++;return s;}

Explanation:
Try it online.
s->{              // Method with String as both parameter and return-type
  long p=new Long(s.replaceAll("\\D","")),
                  //  Remove all non-digits, and convert it to a number
       c,         //  Count-integer
       i=100;     //  Amount integer, starting at 100
  for(s="";       //  Set the input to an empty String, because we no longer need it
      i>0         //  Loop as long as `i` is not 0
      ;           //    After every iteration:
       s+=c+" ",  //     Append the count and a space to `s`
       i=i>25?    //     If `i` is 100:
          25      //      Change it to 25
         :i>10?   //     Else-if `i` is 25:
          10      //      Change it to 10
         :i>5?    //     Else-if `i` is 10:
          5       //      Change it to 5
         :i>1?    //     Else-if `i` is 5:
          1       //      Change it to 1
         :        //     Else (`i` is 1)
          0)      //      Change it to 0
    for(c=0;      //   Reset the count `c` to 0
        p>=i;     //   Inner loop as long as `p` is larger than or equal to `i`
        p-=i)     //     After every iteration: subtract `i` from `p`
      c++;        //    Increase the count `c` by 1
  return s;}      //  Return the result


text:
Interleaving Sequences
Interleaved sequences represent an arbitrary merging of some number of sequences.
An interleaved sequence can be made by appending elements to a list one by one from some number of lists, choosing the next element from some list each time. Therefore, an interleaved sequence will contain exactly the same elements of all the lists combined, in an order consistent with all lists.
The only interleaving of 1 list is that same list.
Challenge
Your challenge is to create a function/program that takes an arbitrary number of sequences and outputs all possible interleavings of those sequences.
Examples
Input: [1, 2], [3, 4]
Output:
    [1, 2, 3, 4]
    [1, 3, 2, 4]
    [1, 3, 4, 2]
    [3, 1, 2, 4]
    [3, 1, 4, 2]
    [3, 4, 1, 2]

Input: [1, 2, 3, 4, 5]
Output:
    [1, 2, 3, 4, 5]

Input: []
Output:
    []

Input: <nothing>
Output:
    []

(also acceptable)
Input: <nothing>
Output: <nothing>

Input: [1, 2, 3], [4, 5]
Output:
    [1, 2, 3, 4, 5]
    [1, 2, 4, 3, 5]
    [1, 2, 4, 5, 3]
    [1, 4, 2, 3, 5]
    [1, 4, 2, 5, 3]
    [1, 4, 5, 2, 3]
    [4, 1, 2, 3, 5]
    [4, 1, 2, 5, 3]
    [4, 1, 5, 2, 3]
    [4, 5, 1, 2, 3]

Input: [1, 2], [3, 4], [5, 6]
Output:
    [1, 2, 3, 4, 5, 6]
    [1, 2, 3, 5, 4, 6]
    [1, 2, 3, 5, 6, 4]
    [1, 2, 5, 3, 4, 6]
    [1, 2, 5, 3, 6, 4]
    [1, 2, 5, 6, 3, 4]
    [1, 3, 2, 4, 5, 6]
    [1, 3, 2, 5, 4, 6]
    [1, 3, 2, 5, 6, 4]
    [1, 3, 4, 2, 5, 6]
    [1, 3, 4, 5, 2, 6]
    [1, 3, 4, 5, 6, 2]
    [1, 3, 5, 2, 4, 6]
    [1, 3, 5, 2, 6, 4]
    [1, 3, 5, 4, 2, 6]
    [1, 3, 5, 4, 6, 2]
    [1, 3, 5, 6, 2, 4]
    [1, 3, 5, 6, 4, 2]
    [1, 5, 2, 3, 4, 6]
    [1, 5, 2, 3, 6, 4]
    [1, 5, 2, 6, 3, 4]
    [1, 5, 3, 2, 4, 6]
    [1, 5, 3, 2, 6, 4]
    [1, 5, 3, 4, 2, 6]
    [1, 5, 3, 4, 6, 2]
    [1, 5, 3, 6, 2, 4]
    [1, 5, 3, 6, 4, 2]
    [1, 5, 6, 2, 3, 4]
    [1, 5, 6, 3, 2, 4]
    [1, 5, 6, 3, 4, 2]
    [3, 1, 2, 4, 5, 6]
    [3, 1, 2, 5, 4, 6]
    [3, 1, 2, 5, 6, 4]
    [3, 1, 4, 2, 5, 6]
    [3, 1, 4, 5, 2, 6]
    [3, 1, 4, 5, 6, 2]
    [3, 1, 5, 2, 4, 6]
    [3, 1, 5, 2, 6, 4]
    [3, 1, 5, 4, 2, 6]
    [3, 1, 5, 4, 6, 2]
    [3, 1, 5, 6, 2, 4]
    [3, 1, 5, 6, 4, 2]
    [3, 4, 1, 2, 5, 6]
    [3, 4, 1, 5, 2, 6]
    [3, 4, 1, 5, 6, 2]
    [3, 4, 5, 1, 2, 6]
    [3, 4, 5, 1, 6, 2]
    [3, 4, 5, 6, 1, 2]
    [3, 5, 1, 2, 4, 6]
    [3, 5, 1, 2, 6, 4]
    [3, 5, 1, 4, 2, 6]
    [3, 5, 1, 4, 6, 2]
    [3, 5, 1, 6, 2, 4]
    [3, 5, 1, 6, 4, 2]
    [3, 5, 4, 1, 2, 6]
    [3, 5, 4, 1, 6, 2]
    [3, 5, 4, 6, 1, 2]
    [3, 5, 6, 1, 2, 4]
    [3, 5, 6, 1, 4, 2]
    [3, 5, 6, 4, 1, 2]
    [5, 1, 2, 3, 4, 6]
    [5, 1, 2, 3, 6, 4]
    [5, 1, 2, 6, 3, 4]
    [5, 1, 3, 2, 4, 6]
    [5, 1, 3, 2, 6, 4]
    [5, 1, 3, 4, 2, 6]
    [5, 1, 3, 4, 6, 2]
    [5, 1, 3, 6, 2, 4]
    [5, 1, 3, 6, 4, 2]
    [5, 1, 6, 2, 3, 4]
    [5, 1, 6, 3, 2, 4]
    [5, 1, 6, 3, 4, 2]
    [5, 3, 1, 2, 4, 6]
    [5, 3, 1, 2, 6, 4]
    [5, 3, 1, 4, 2, 6]
    [5, 3, 1, 4, 6, 2]
    [5, 3, 1, 6, 2, 4]
    [5, 3, 1, 6, 4, 2]
    [5, 3, 4, 1, 2, 6]
    [5, 3, 4, 1, 6, 2]
    [5, 3, 4, 6, 1, 2]
    [5, 3, 6, 1, 2, 4]
    [5, 3, 6, 1, 4, 2]
    [5, 3, 6, 4, 1, 2]
    [5, 6, 1, 2, 3, 4]
    [5, 6, 1, 3, 2, 4]
    [5, 6, 1, 3, 4, 2]
    [5, 6, 3, 1, 2, 4]
    [5, 6, 3, 1, 4, 2]
    [5, 6, 3, 4, 1, 2]

Rules

Standard loopholes forbidden (duh)
Input may be taken in any reasonable format, e.g. a list of lists, vararg list of lists, parameter lists, etc... as long as it is unambiguous where lists begin and end.
Output may be in any reasonable format, so long as it is clear where lists begin and end. Valid outputs include, but are not necessarily limited to:

stdout, with one list per line
A list of lists
An iterator over lists (can be implemented with a generator if your language has them)

The order of the yielded interleavings does not matter, however, there should not be any repeated interleavings.
To simplify repeat detection, you may assume that all elements across all input sequences are unique.
If given no lists as input, both the empty list and no output are valid outputs.
Types of the elements in the sequences is irrelevant. (e.g. they could all be one type or a mishmash of types, whichever is more convenient in your language)
Your program/function must be guaranteed to terminate in a finite amount of time.
This is code-golf, so the shortest code for each language wins.

The only interleaving of no lists is the empty list. Does that mean that we have to output [[]] instead of [] when we are given no lists as input?

Also, will the lists have equal length?

I suppose it would be mathematically sane to return no lists as output if no lists are given as input. I will allow both. All the output lists will be equal length. Input lists may vary in length.

Haskell, 84 77 76 bytes
foldl((.(!)).(>>=))[[]]
a#b=(b:)<$>a
x@(a:c)!y@(b:d)=x!d#b++c!y#a
a!b=[a++b]

Thanks to @Lynn for 7 bytes and @user9549915 for a byte!
Try it online!

76 bytes by getting rid of some parentheses

Python 2, 103 92 79 78 bytes
def f(A,c=[]):
 if not[f([b[b==x:]for b in A],c+x[:1])for x in A if x]:print c

Try it online!
Or:
Python 3, 73 bytes
def f(A,c=[]):[f([b[b==x:]for b in A],c+x[:1])for x in A if x]or print(c)

Try it online!
-1 by replacing [x[0]] with x[:1] as per xnor
-13 bytes by shamelessly stealing expanding upon [b[b==x:]for b in A] as suggested by Neil's answer instead of longer enumerate approach.
Takes a list of lists A as input. If all elements of A are empty, then the list evaluated in the if will be empty, so we have reached the end of the recursion and can print. Otherwise, we have a list of one or more None's; and we recurse.

[x[0]] is x[:1]

@xnor: of course! thx!

Jelly, 11 bytes
FŒ!fÐ€⁼ṛɗÐf

Try it online!
How it works
FŒ!fÐ€⁼ṛɗÐf  Main link. Argument: A (array of arrays)

F            Flatten A.
 Œ!          Take all permutations.
        ɗÐf  Filter by the chain to the left, keeping only permutations for which
             it returns a truthy value.
   fÐ€         Intersect the permutation with each array in A.
      ⁼ṛ       Test if the result is equal to A.

Ruby, 66 bytes
f=->a,*p{(a-=[[]])[0]?a.flat_map{|b|h,*t=b;f[a-[b]+[t],*p,h]}:[p]}

If there are no non-empty sequences, return an empty sequence. Otherwise, for each non-empty sequence, recurse with the first element removed then add it onto the beginning of each result. The implementation uses the assumption that elements are guaranteed to be globally unique, otherwise a-[b] could potentially remove more than 1 sequence from the recursive call. Although on reflection, maybe that'd actually be the right behavior to avoid duplicate output.
Example IO:
f[[[1,2],[3,4]]]
=> [[1, 3, 2, 4], [1, 3, 4, 2], [1, 2, 3, 4], [3, 1, 4, 2], [3, 1, 2, 4], [3, 4, 1, 2]]

Wolfram Language (Mathematica), 76 75 71 bytes
Cases[Permutations[Join@@#],x_/;And@@OrderedQ/@(x~Position~#&/@#&/@#)]&
(* or *)
Cases[Join/*Permutations@@#,x_/;And@@(x~Position~#&/@#&/*OrderedQ/@#)]&

Try it online!
Naive approach: find all permutations that are interleavings of the input.
Explanation
Permutations[Join@@#]

Flatten <input> and find all of its permutations.
Cases[ ... ,x_/; ...]

Find all elements x such that...
(x~Position~#&/@#&/@#)

Replace all of the items in depth-2 of <input> with their respective position in x.
And@@OrderedQ/@ ...

Check whether all depth-1 lists are ordered (i.e. in increasing order).
Actual implementation of interleaving, 117 bytes
Cases[{}~(f=ReplaceList[#2,{{a___,{b_,c___},d___}/;b>0:>#~Join~{b}~f~{a,{c},d},_:>#}]&)~#,{___},{Tr[1^(Join@@#)]+1}]&

Try it online!

Python 2, 87 84 bytes
f=lambda a:any(a)and[b[:1]+c for b in a if b for c in f([c[c==b:]for c in a])]or[[]]

Try it online! Port of my JavaScript answer. Edit: Saved 3 bytes thanks to @ChasBrown.

-3 by replacing sum(a,[]) with any(a).

@ChasBrown Thanks, I don't know Python that well.

Neil: Well enough, I think :). sum(a,[]) has nice use in some situations, though!

Haskell, 45 bytes
f l=max[[]][h:y|h:t<-l,y<-f$t:filter(/=h:t)l]

Try it online!
Adapted from Chas Brown's Python answer.
The max[[]] is a trick to give a base case of [[]] when the input only contains [] elements. In that case, the list used for empty, recursing is empty, and max[[]][] gives [[]].
When recursing, rather than selectively dropping the first element of the chosen list h:t, we make a new list with t at the front and h:t filtered out.

JavaScript (Firefox 30-57), 92 bytes
f=a=>a.some(b=>b+b)?[for(b of a)if(b+b)for(c of f(a.map(c=>c.slice(c==b))))[b[0],...c]]:[[]]

Japt -Q, 14 bytes
c á f@e_XfZ eZ
c              // Flatten the input into a single array
  á            // and find all permutations.
    f          // Then filter the results for items
     @e_       // where for each original input
        XfZ eZ // the ordering of the items is unchanged.

Takes input as an array of arrays. -Q makes the output preserve the array notation.
Try it here.

Scala: (not intended to be minimal, more a clear reference resource)
object Interleave {

  private def interleavePair[A](x: Seq[A], y: Seq[A]): Seq[Seq[A]] =
    (x, y) match {
      case (a +: c, b +: d) =>
        interleavePair(x, d).map(b +: _) ++ interleavePair(c, y).map(a +: _)
      case _ => Seq(x ++ y)
    }

  def interleave[A](ssa: Seq[Seq[A]]): Seq[Seq[A]] =
    ssa.foldLeft[Seq[Seq[A]]](Seq(Seq.empty)) {
      case (sssat, sa) => sssat.flatMap(interleavePair(sa, _))
    }
}

object Main extends App {

  import Interleave._

  println(interleave(Seq()))
  println(interleave(Seq(Seq(1, 2), Seq(3, 4))))
}

Try it online!

You should at least try to golf this code...


text:
Seidel Triangle
The Seidel Triangle is a mathematical construction similar to Pascal's Triangle, and is known for it's connection to the Bernoulli numbers.
The first few rows are:
      1
      1  1
   2  2  1
   2  4  5  5
16 16 14 10 5
16 32 46 56 61 61

Each row is generated as follows:
If the row number is even (1-indexed):

Bring down the first item of the previous row
Every next item is the sum of the previous item and the item above it
Duplicate the last item

If the row number is odd:

Bring down the last item of the previous row
Going backwards, each item is the sum of the previous item and the item above it
Duplicate what is now the first item.

Basically, we construct the triangle in a zig-zag pattern:
    1
    v
    1 > 1
        v
2 < 2 < 1
v
2 > 4 > 5 > 5

For more information, see the Wikipedia page on Bernoulli numbers.
The Challenge:
Given n, either as a function argument or from STDIN, print or return either the nth row of the Seidel triangle or the first n rows. You may use either 0 or 1 indexing.
You do not need to handle negative or non-integer input (nor 0, if 1-indexed). You do not have to handle outputs larger than 2147483647 = 2^31 - 1
As this is code-golf, do this in as few bytes as possible.
Examples:
In these examples the return value is the nth row, 0-indexed.
Input   ->  Output

0           1
1           1 1
2           2 2 1
6           272 272 256 224 178 122 61
13          22368256 44736512 66750976 88057856 108311296 127181312 144361456 159575936 172585936 183194912 191252686 196658216 199360981 199360981

"You do not have to handle outputs larger than your language's default int type" makes this trivial for languages with only 1-bit ints

Can the rows be outputted always sorted from small to large?

@ASCII-only Changed to match C++'s maximum int

@Angs No, the rows should be ordered as shown

@ASCII-only That's a default loophole (although IMO it's a bit poorly worded as it depends on what people would consider "reasonable")

@user202729 it's not a loophole if it's explicitly stated

@ASCII-only ... fine. OP can explicitly override loopholes. | Although this version is definitely better.

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

Try it online!
Row is 0-indexed.
# Push 1 (the contents of row 0) on other stack; use implicit zero as parity of current row
<>(())<>

# Do a number of times equal to input:
{({}[()]<

  # Subtract the row parity from 1
  (()[{}]<

    # For each entry in old row:
    <>{

      # Add to previous entry in new row and push twice
      (({}<>{}))<>

    }

  >)

>)}{}

# If row parity is odd:
{{}

  # Reverse stack for output
  <>{({}<>)<>}

# Switch stacks for output
}<>

JavaScript (SpiderMonkey), 67 bytes
This code abuses the sort() method and doesn't work on all engines.
Rows are 0-indexed.
f=(n,a=[1],r)=>n--?f(n,[...a.map(n=>k+=n,k=0),k].sort(_=>n|r),!r):a

Try it online!
How?
We conditionally reverse an array by using the sort() method with a callback function that ignores its parameters and returns either 0 or a positive integer. Don't try this at home! This only works reliably on SpiderMonkey.
let A = [1,2,3,4,5] and B = [1,2,3,4,5,6,7,8,9,10,11]

             | SpiderMonkey (Firefox)  | V8 (Chrome)             | Chakra (Edge)
-------------+-------------------------+-------------------------+------------------------
A.sort(_=>0) | 1,2,3,4,5               | 1,2,3,4,5               | 1,2,3,4,5
A.sort(_=>1) | 5,4,3,2,1               | 5,4,3,2,1               | 1,2,3,4,5
B.sort(_=>0) | 1,2,3,4,5,6,7,8,9,10,11 | 6,1,3,4,5,2,7,8,9,10,11 | 1,2,3,4,5,6,7,8,9,10,11
B.sort(_=>1) | 11,10,9,8,7,6,5,4,3,2,1 | 6,11,1,10,9,8,7,2,5,4,3 | 1,2,3,4,5,6,7,8,9,10,11

Note that V8 is probably using different sort algorithms depending on the length of the array (less or more than 10 elements).
Commented
f = (                     // f = recursive function taking:
  n,                      //   n   = row counter
  a = [1],                //   a[] = current row, initialized to [1]
  r                       //   r   = 'reverse' flag, initially undefined
) =>                      //
  n-- ?                   // decrement n; if it was not equal to zero:
    f(                    //   do a recursive call with:
      n,                  //     - the updated value of n
      [ ...a.map(n =>     //     - a new array:
          k += n, k = 0   //       - made of the cumulative sum of a[]
        ), k              //         with the last value appended twice
      ].sort(_ => n | r), //       - reversed if n is not equal to 0 or r is set
      !r                  //     - the updated flag r
    )                     //   end of recursive call
  :                       // else:
    a                     //   stop recursion and return a[]

What spider-monkey specific feature does this use?

@Downgoat It's taking advantage of the specific implementation of sort() in this engine. I've added an explanation.

Perl 6, 52 bytes
{(1,{[[\+] |.reverse,0]}...*)[$_].sort((-1)**$_*-*)}

Try it online!

Haskell, 89 87 82 bytes
(cycle[r,id]!!)<*>s
r=reverse
s 0=[1]
s n=let a=zipWith(+)(0:a)$(r.s$n-1)++[0]in a

Just s prints the lines in the zig-zag order, the anonymous function on the first row reverses half of the rows.
Thanks to @nimi for saving 5 bytes!
Try it online!

Jelly, 12 bytes
1;0SƤUƊ⁸¡U⁸¡

Try it online!

You could remove the first ⁸

Python 3, 98 91 bytes
from itertools import*
f=lambda n:n and[*accumulate(f(n-1)[::n&1or-1]+[0])][::n&1or-1]or[1]

Try it online!
Switching to 0-based row numbering saved 7 bytes.

Python 2, 103 97 bytes
f=lambda n,r=[1],k=2:n and f(n-1,[sum(r[-2::-1][:i],r[-1])for i in range(k)],k+1)or r[::-(-1)**k]

Try it online!
Non-recursive version (easier to read):
Python 2, 106 bytes
def f(n,r=[1],j=1):
 while n:
	a=r[-2::-1];r=r[-1:];n-=1;j=-j
	for x in a+[0]:r+=[r[-1]+x]
 return r[::-j]

Try it online!
Surely, better is possible!

Python 3, 91 bytes
from numpy import *
s=lambda n:n and cumsum(s(n-1)[::n%2*2-1]+[0]).tolist()[::n%2*2-1]or[1]

Try it online!

You can remove the space between import and *

Julia 0.6, 85 bytes
r(l,n=cumsum(l))=[n...,n[end]]
w=reverse
f(n)=n<2?[1]:n%2<1?r(f(n-1)):w(r(w(f(n-1))))

Try it online!
This is a recursive solution in Julia. Note that it has 1-based indexing. Hence the tests.
Ungolfed version, to understand the logic:
function new_row(last_row)
    new_row = cumsum(last_row)
    push!(new_row, new_row[end])
    return new_row
end

function triangle(n)
    if n == 1
        return [1]
    elseif mod(n,2) == 0
        return new_row(triangle(n-1))
    else
        return reverse(new_row(reverse(triangle(n-1))))
    end
end

Asa bonus, here's a non-recursive version, but this is longer:
w=reverse;c=cumsum
r(l,i)=i%2<1?c([l...,0]):w(c(w([0,l...])))
f(n,l=[1])=(for i=2:n l=r(l,i)end;l)

Husk, 16 bytes
!z*:1İ_¡ȯ↔S:→∫;1

Try it online!
There may be a better way for arriving at the rows in the correct order. To get the correct output, this program reverses every other row.
Explanation
!z*:1İ_¡ȯ↔S:→∫;1
              ;1 array [1]
       ¡ȯ        apply the following functions repeatedly on it, collecting results:
             ∫   cumulative sum
          S:→    repeat the last element
         ↔       reverse it
                 this generates all the required rows
 z*              zip multiply that with:
   :1İ_          [1,-1,1,-1,1,-1,...]
                 which reverses every other row
!                Get row at input index

Husk, 16 bytes
?I↔%2¹!¡ȯ↔S:→∫;1

Try it online!
Uses a ternary instead.

APL (Dyalog Unicode), 22 18 bytes
{⊖⍣⍵{⌽+\⍵,0}⍣⍵,1}

Try it online!
Same method as my Husk answer.
-4 bytes from coltim.
Explanation
{⊖⍣⍵{⌽(⊢,⊢/)+\⍵}⍣⍵,1} ⍵ ← input(n)
                  ,1  convert 1 to an array [1]
    {          }⍣⍵    apply the following n times:
            +\⍵       cumulative sum
      (⊢,⊢/)          duplicate the last element
     ⌽                reverse
 ⊖⍣⍵                  then reverse n times

Instead of duplicating the last element ((⊢,⊢/)+\⍵) could you instead do +\⍵,0 to save 4 bytes?

Haskell, 59 bytes
(k!!)<*>(iterate(r.scanr1(+).(0:))[1]!!)
r=reverse
k=r:id:k

Try it online!

k4, 17 bytes
{x|:/x{|+\x,0}/1}

Adapted from @razetime's APL answer.


text:
Overlapping Strings
Challenge
A simple challenge: given two or more strings, output all of the substrings that are in each string.
Rules

Input is always a comma separated list of strings
Strings should be outputted from longest to shortest length without duplicates
Strings should preserve whitespace

Examples
Input: aaa,aa
Output:
aa
a

Input: ababa,aba
Output:
aba
ab
ba
a
b

Input: Hello\, world!, Hello world!
Output:
 world!
world!
 world
 worl
world
orld!
Hello
orld
rld!
ello
 wor
Hell
worl
ell
rld
 wo
ld!
llo
wor
orl
Hel
d!
ll
 w
lo
rl
wo
or
He
el
ld
o
l
r
H
e
d
!
w

Based on your testcases it seems you mean contiguous substrings, not just substrings.

You do not have examples of more than two strings as input.

In addition why is the input format so strict?  The input format you require seems overly stringent.  If I were to solve this the majority of my code would be an input parser.

To pile on with What Wizard, \, is a pretty non-standard way of saying "don't split on this comma". Why not just take as input a list of strings?

Also - welcome to PPCG! I didn't notice that this is your first post, and didn't mean to bite your head off! :) You might want to check out the sandbox where people often post their questions first so they can get helpful feedback including the usual sorts of expectations that people have for questions/challenges.

Input is always a comma separated list of strings - does this mean you want to pass the strings as a single string, and then we have to split it into an array, or can we just take the input as a list?

@WhatWizard Substrings are contiguous by default. Subsequences are not.

Note that cumbersome I/O formats are discouraged. If you really want to enforce that, you should make it more explicit in the post (and the reason why you enforce it).

Welcome to PPCG! I like the challenge (and was about to post an answer), but it got closed as unclear. Reason for this is already stated above, but: 1. You state more than two strings is an acceptable input, so I would add some test cases for three or more input-strings. 2. "Input is always a comma separated list of strings". I would make the I/O flexible, so a list of strings is acceptable as both input and/or output. Splitting by comma distracts from the actual challenge.  3. In your ["Hello, world!", "Hello world!"] test case you don't have a space as output? Both contain a space..

Also, as mentioned by @ChasBrown, in the future use the Sandbox of proposed challenges to perfect your challenge based on feedback before posting it to main. Being new you of course didn't knew this, so no problem. If you fix the issues mentioned in the comments above it should be re-opened in no time. :) Enjoy your stay!

Also, which characters can appear in the input? Printable ASCII?

Oops, I posted this and completely forgot about it! I'll rewrite the question so that it is clearer tonight, thank you for the feedback everyone!

05AB1E, 9 bytes
€Œ.»ÃÙéR»

Try it online!
Explanation
€Œ         # get the substrings of each
  .»Ã      # reduce by intersection
     Ù     # remove duplicates
      é    # sort by length
       R   # reverse
        »  # join on newline

Jelly, 6 bytes
Ẇ€f/QṚ

Try it online!
Ẇ€f/QṚ  Main Link
 €      For each string
Ẇ       Get all substrings
   /    Reduce this list of lists by
  f     Filter (intersection)
    Q   Remove duplicates
     Ṛ  Reverse

Pyth, 8
_{@Fm.:d

Explanation
        Q  # Implicit input list of 2 strings
    m.:d   # get lists of all substrings of each input string
  @F       # intersection
 {         # deduplicate
_          # reverse

Online test.

The comment should probably read "Implicit input list of strings", since it can be more than two strings.