text:
Determine if a Graph is Toroidal
A simple graph is toroidal if it can be drawn on the surface of a torus without any edges intersecting.  Your task is to take a simple undirected graph via any reasonable method (adjacency matrix, edge vertex sets, etc.) and decide whether or not it is a toroidal graph.  You should output one of two distinct values for each of the two decisions.  You may choose what these values are.
This is code-golf so answers will be scored in bytes with less bytes being better.
Test Cases
Here Kn is the complete graph with n vertices and Kn,m is the complete bipartite graph.
Toroidal

K3
K7
K3,3
The Peterson graph
The Möbius Cantor graph

Not Toroidal

K8

Actual test cases would be helpful, for instance a few adjacency matrices. People are probably able to convert it to another appropriate format if they have to.

@StewieGriffin I'm not going to crowd the question with hundreds of lines of test-cases that are going to have to be converted by every user that wants to use them.

http://web.math.ucsb.edu/~padraic/ucsb_2013_14/math137b_s2014/math137b_s2014_lecture4.pdf the theorem at the end states: "If G is toroidal, then the Euler characteristic of G is 0"

What are K₃, K₇, K₃,₃ and K₈?

@EriktheOutgolfer K_n is the complete graph with n nodes.  K_n,m is the complete bipartite graph with partitions n and m.

Wikipedia links: complete graph, complete bipartite graph.

@Giuseppe, but can we go the other way? What is a face of a graph with no embedding yet defined?

Looks like the general purpose algorithm for this is quite extensive and probably beyond the scope of PPCG. See the Yu (2011) paper mentioned at: https://mathoverflow.net/questions/119493/toroidality-testing.  If "maybe" is a suitable answer I've got a short 1-liner :)

@KellyLowder This is not meant to be an easy question.  I don't really think there is a scope of difficulty on PPCG, after all we have the implement tetris in GoL question.

@Wheat Wizard. Fair enough. Kudos to anyone that comes up with a good solution.

This may work (just try all possible adjacency matrix and check how many faces it have, if the genus is 0 or 1 then done -- there must be no vertices without any edges attached)

So why can't we just calculate the Euler characteristic? I don't see why that is not a clear test of toroidality. This challenge already does that.

@dylnan I don't know that Euler characteristic can be used as a test of toroidality.  I do know that every toroidal graph must have Euler characteristic zero, but I don't know if the converse is true.  If you can prove this is the case or find a source proving it you are welcome to use that algorithm for an answer.

I realized I was confused before you responded so I deleted the comment. Is a graph embedded on a klein bottle considered a torus when embedded in 3 space?

@dylnan I don't believe so.

You say that edges musnt intersect? but then they appear to for some test case examples, unless the 2d they do but don't on Taurus?

Cause I'd like to make sure I understand toroidal correctly, cause $k_7$ is toroidal while $k_8$ isn't and it's not easy to picture either on the torus? So my question is, $k_2$ on torus would have 3 edges instead of just 1?

@marshalcraft $K_7$ is toroidal and $K_8$ is not.  $K_2$ has the same number of edges no matter on what surface you write it.  An easier way to picture it:  "A graph is toroidal if you can draw it on a piece of paper without crossings allowing you to jump from one side to the same place on the other side."

Yeah that clears up nothing for me, sorry. I can read clearly that from the question about 7 or 8 so no new information there. My point are the graphs have like how many edges? and so like i said, it not most feasible thing to think about as an example. Again as I said it would seem to me as though some of the toroidal examples, certainly must have interescting edges on the 2 dimensional flat plane. So I assume that the torus some how this isn't necessary, jsut as it seems to me a simple undirected graph can have up to 4 non trivial edges for 2 nodes, different then in R^2.

Also I look at wikipedia toroidal graph page and it seems that indeed, 2 nodes with 4 edges is a simple graph on a torus. Wish I could say your comments were useful @Post Left Ghost Hunter but they weren't. No wonder there isn't an answer after a year. None of you even know what your talking about.

So basically valid edges are gonna be geodesics. which i would think if the torus was parameterized by angle about major/minor axis (I'm not a torus expert so forgive me if my terminology is wrong), then you have lines similar to 2d, like y=mx+b but where y and x are the angles.

So you have in general, all the combination of nodes, the equations of lines connecting them, there are 4 each. So 4*number of combinations if there exists coeficients such that there are no simultaneous solutions to the large list of equations they do not intersect and thus are toroidal.

Also I read from most searches on google, the literature on torus is concerned with embedding's in eucludian space which is really more related to differential geometry. For purposes here, which so far seem completely independent of diff. geometry what is concerened is intrinsic to the genus 1 (the torus). Thus it's a matter of system of equations not having solutions and cases for all the combinations, thus not having intersections. Seems an application for this is say some kind of network of nodes needing to be connected but constraint that connections can't take up the same space.

Some how using genus 1 and higher is a method of solving some kind of problem.

Mathematically the most general form of this question would be given a set of nodes and minimum edges, what is the minimum genus so that they do not interesect.

@marshalcraft Amusingly, that's the problem I solved in my answer.

Rust, 1210 1200 bytes
use std::collections::HashMap as H;type I=i64;type E=Vec<(I,I)>;fn d(g:&E)->bool{let mut s:Vec<(E,Vec<I>)>=vec![];for e in g{let(v,w)=e;let f=(*v,*w);let z=|x|s.iter().position(|p|p.1.contains(x));match(z(v),z(w)){(Some(i),Some(j))=>{if i!=j{let mut p=s.remove(i);let q=s.remove(j-(i<j)as usize);p.0.extend(q.0);p.1.extend(q.1);s.push(p)}else{s[i].0.push(f)}}(Some(i),_)=>{s[i].0.push(f);s[i].1.push(*w)}(_,Some(j))=>{s[j].0.push(f);s[j].1.push(*v)}_=>{s.push((vec![f], vec![*v, *w]))}}}s.iter().map(|h|{let mut p=H::new();let mut r=H::new();let mut i=0;for e in&h.0{let(v,w)=e;i+=2;p.insert(i-1,i);p.insert(i,i-1);r.entry(v).or_insert(vec![]).push(i-1);r.entry(w).or_insert(vec![]).push(i)}let mut r:Vec<Vec<I>>=r.values().cloned().collect();r.sort();let mut x=0;let m=r.iter().flat_map(|v|1..v.len()).fold(1,|p,n|p*n);for mut w in 0..m{let mut t=H::new();for u in&r{let mut v=u.clone();let s=v.pop().unwrap();let mut f=s;while v.len()>0{let o=v.remove(w%v.len());w/=v.len()+1;t.insert(f,o);f=o}t.insert(f,s);}let mut f=vec![];let mut n=0;for s in p.keys(){if!f.contains(s){n+=1;let mut c=s;loop{f.push(*c);c=&t[&p[c]];if c==s{break}}}}x=x.max(n)}1-(r.len()as I-g.len()as I+x as I)/2}).sum::<I>()<2}

A toroidal example:
Try it online!
That's this toroidal graph:
A non-toroidal example: Try it online!
That's this non-toroidal graph:
The original code I wrote, before golfing, was the following. It has printouts so you can see what's happening:
use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct Vertex(u64);
type Edge = (Vertex, Vertex);
type Graph = Vec<Edge>;

fn full_genus(graph: &Graph) -> usize {
    componets(graph).iter().map(|g| genus(g)).sum()
}
fn genus(graph: &Graph) -> usize {
    #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, PartialOrd, Ord)]
    struct HalfEdge(usize);
    let mut edge_pairing: HashMap<HalfEdge, HalfEdge> = HashMap::new();
    let mut vertex_groups: HashMap<&Vertex, Vec<HalfEdge>> = HashMap::new();
    let mut i = 0;
    for edge in graph {
        let (vert1, vert2) = edge;
        let half1 = HalfEdge(i);
        i += 1;
        let half2 = HalfEdge(i);
        i += 1;
        edge_pairing.insert(half1, half2);
        edge_pairing.insert(half2, half1);
        vertex_groups.entry(vert1).or_insert(vec![]).push(half1);
        vertex_groups.entry(vert2).or_insert(vec![]).push(half2);
    }
    let mut vertex_groups: Vec<Vec<HalfEdge>> = vertex_groups.values().cloned().collect();
    vertex_groups.sort();
    println!("{:?}", edge_pairing);
    println!("{:?}", vertex_groups);

    let mut max_faces = 0;
    let num_rotations = vertex_groups
        .iter()
        .map(|v| v.len() - 1)
        .map(|n| {
            let mut prod = 1;
            for i in 0..n {
                prod *= i + 1;
            }
            prod
        })
        .fold(1, |p, n| p * n);
    println!("\nNum rotations: {}\n", num_rotations);
    for rotation_index in 0..num_rotations {
        let mut working_index = rotation_index;
        let mut rotation: HashMap<HalfEdge, HalfEdge> = HashMap::new();
        let mut pretty_rotation: Vec<Vec<HalfEdge>> = vec![];
        for group in &vertex_groups {
            let mut removal_group = group.clone();
            let start = removal_group.pop().unwrap();
            let mut from = start;
            let mut pretty_group = vec![from];
            while !removal_group.is_empty() {
                let index = working_index % removal_group.len();
                working_index /= removal_group.len();
                let to = removal_group.swap_remove(index);
                rotation.insert(from, to);
                pretty_group.push(to);
                from = to;
            }
            rotation.insert(from, start);
            pretty_rotation.push(pretty_group);
        }
        let mut seen_on_face: Vec<HalfEdge> = Vec::new();
        let mut num_faces = 0;
        for start_halfedge in edge_pairing.keys() {
            if !seen_on_face.contains(start_halfedge) {
                num_faces += 1;
                let mut current_halfedge = start_halfedge;
                loop {
                    seen_on_face.push(*current_halfedge);
                    let pair_halfedge = &edge_pairing[current_halfedge];
                    current_halfedge = &rotation[pair_halfedge];
                    if current_halfedge == start_halfedge {
                        break;
                    }
                }
            }
        }
        if num_faces > max_faces {
            max_faces = num_faces;
            let euler_characteristic: isize =
                vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
            let genus_num: isize = 1 - euler_characteristic / 2;
            println!(
                "Faces: {}, Genus <= {} on rotation {}",
                max_faces, genus_num, rotation_index
            );
            println!("{:?}\n", pretty_rotation);
        }
        if rotation_index % 1e7 as usize == 0 {
            println!("Faces: {} <= {} on rotation {}", num_faces, max_faces, rotation_index);
        }
    }
    let euler_characteristic: isize =
        vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
    let genus_num: isize = 1 - euler_characteristic / 2;
    assert!(genus_num >= 0);
    genus_num as usize
}

fn componets(graph: &Graph) -> Vec<Graph> {
    let mut graphs: Vec<(Graph, Vec<Vertex>)> = vec![];
    for edge in graph {
        let (vert1, vert2) = edge;
        let g_index1 = graphs.iter().position(|(_g, h)| h.contains(&vert1));
        let g_index2 = graphs.iter().position(|(_g, h)| h.contains(&vert2));
        match (g_index1, g_index2) {
            (Some(i1), Some(i2)) => {
                if i1 != i2 {
                    let (mut graph1, mut vs1) = graphs.remove(i1);
                    let new_i2 = if i1 < i2 { i2 - 1 } else { i2 };
                    let (graph2, vs2) = graphs.remove(new_i2);
                    graph1.extend(graph2);
                    vs1.extend(vs2);
                    graphs.push((graph1, vs1));
                } else {
                    graphs[i1].0.push(edge.clone());
                }
            }
            (Some(i1), None) => {
                graphs[i1].0.push(edge.clone());
                graphs[i1].1.push(vert2.clone());
            }
            (None, Some(i2)) => {
                graphs[i2].0.push(edge.clone());
                graphs[i2].1.push(vert1.clone());
            }
            (None, None) => {
                let edges = vec![edge.clone()];
                let vs = vec!(vert1.clone(), vert2.clone());
                graphs.push((edges, vs));
            }
        }
    }
    graphs.into_iter().map(|(g, _h)| g).collect()
}

fn main() {
    let graph = vec![
        (Vertex(0), Vertex(1)),
        (Vertex(0), Vertex(2)),
        (Vertex(0), Vertex(3)),
        (Vertex(0), Vertex(4)),
        (Vertex(0), Vertex(5)),
        (Vertex(1), Vertex(2)),
        (Vertex(1), Vertex(3)),
        (Vertex(1), Vertex(4)),
        (Vertex(1), Vertex(5)),
        (Vertex(2), Vertex(3)),
        (Vertex(2), Vertex(4)),
        (Vertex(2), Vertex(5)),
        (Vertex(3), Vertex(4)),
        (Vertex(3), Vertex(5)),
    ];
    let result = full_genus(&graph);
    println!("Result: {}", result);
}

This program finds the minimum genus surface that the given graph can be embedded in. A graph is toroidal if that genus is at most 1, the genus of the torus.
The code works by separating the graph into its connected components, finding their genii separately, and adding up the results.
To find the genus of a connected graph, I brute force search over all possible rotation systems of the graph, and figure out which one has the most faces. A rotation system is simply an ordering on the edges emerging from each vertex, saying what order those edges are in going around the vertex. Each rotation system has a straightforward minimum genus it can be embedded in, and having more faces directly corresponds to having lower genus. Since every possible embedding corresponds to some rotation system, if there is a toroidal embedding, my program will find the corresponding rotation system and declare that the graph is toroidal, and vice versa.
This program is very slow, because it searches through a number of rotation systems equal to the product over all degrees d of the vertices of (d-1)!. However, it can search through a little over 10 million such rotation systems per minute, so it can verify the toroidality or non-toroidality of simple graphs like the ones shown above.

You do know that your main function is still called is_toroidal right? Changing that to say t saves 10 bytes

@cairdcoinheringaahing Thanks, I feel silly for missing that

Hi. When I change the graph to:  graph = vec![
(0, 1), (0, 2),  (0, 3),   (0, 4),  (0, 5),  (0, 6),
(1, 2),  (1, 3),   (1, 4),  (1, 5),   (1, 7),   (2, 3),
(2, 4), (2, 6),    (2, 7),   (3, 5),  (3, 6),   (3, 7),
(4, 5),   (4, 6),    (4, 8),   (4, 9), (4, 10),  (5, 7),    (5, 8),(5, 9),   (5, 11),  (6, 7),  (6, 8),    (6, 10),   (6, 11),   (7, 9),    (7, 10),   (7, 11),  (8, 9),(8, 10),  (8, 11),   (9, 10), (9, 11),  (10, 11), ]; why does Rust give  a wrong? See https://stackoverflow.com/questions/75685787/why-does-changing-the-graph-in-the-main-function-result-in-an-error


text:
Blind binary adder
Imagine you have two boxes B(x) and B(y), each containing an unknown bit - 0 or 1, and a machine F that can X-ray them and produce a third box for B(x^y) (xor). F can also compute B(x*y) (and). In fact, those are just special cases of the the single operation the machine can perform - inner product each, denoted with F() below.
For two same-length arrays
[B(x[0]), B(x[1]), ..., B(x[n-1])]
[B(y[0]), B(y[1]), ..., B(y[n-1])]

inner product is defined as
B(x[0]*y[0] ^ x[1]*y[1] ^ ... ^ x[n-1]*y[n-1])

"Each" means F() can process multiple pairs of x[], y[] in one go. The x[] and y[] from one pair must be of the same length; x[]-s and y[]-s from different pairs don't necessarily need to.
Boxes are represented by unique integer ids.
An implementation of inner product each in JavaScript might look like
var H=[0,1];          // hidden values, indexed by boxId
function B(x) {       // seal x in a new box and return the box id
  return H.push(x)-1;
}
function F(pairs) {   // "inner product each"
  return pairs.map(function (pair) {
    var r = 0, x = pair[0], y = pair[1];
    for (var i = 0; i < x.length; i++) r ^= H[x[i]] * H[y[i]];
    return B(r);
  })
}

(Please translate the above to your language of choice.)
Given access to an F() implementation as appropriate for your language (but no access to H or B()) and given two arrays of box ids constituting the 16-bit binary representations of two integers a and b, your task is to produce box ids for the 16-bit binary representation of a+b (discarding
overflow) with the minimum number of F() calls.
The solution that calls F() the fewest times wins.
Ties will be broken by counting the total number of x[],y[] pairs F() was
called with - fewer is better.
If still tied, the size of your code (excluding the implementation of F() and its helpers) determines the winner in the traditional code golf way.
Please use a title like "MyLang, 123 calls, 456 pairs, 789 bytes" for your answer.
Write a function or a complete program.
Input/output/arguments/result is int arrays in any reasonable format.
Binary representation may be little- or big-endian - choose one.

Appendix 1: To make the challenge slightly easier, you can assume that boxes with ids 0 and 1 contain the values 0 and 1. This gives you constants, useful e.g. for negation (x^1 is "not"). There were ways around the lack of constants, of course, but the rest of the challenge is hard enough anyway, so let's eliminate this distraction.

Appendix 2: To win the bounty, you must do one of the following:

post your score (calls,pairs,bytes) and your code before the deadline
post your score and a sha256 hash of your code before the deadline; then post the actual code within 23 hours after the deadline

If I translated this into my language of choice (Haskell), I could use value recursion and call F only once. That would surely be cheating, but I'm not sure if it would be good cheating or bad cheating.

I know global state isn't welcome in Haskell, but let me ask this as a thought experiment: if I incremented a global counter in the implementation of F, by how much would have it grown at the end? - that is my understanding of "number of calls".

I could do exactly that, and it would say 1. But it could not be translated back to JavaScript using your code. Essentially I'd say y=f(x) and let x depend on y.

I'm afraid I don't understand how that would work. Could you show sample code, please? My Haskell is poor, but I'm sure I can figure it out if I can play with the code.

Perhaps we can use the following types to model this problem?
data Box = B Int   deriving (Show); f :: [[[Box]]] -> [Box]
I'll need more time to figure out how to implement f (Haskell forces lowercase here) - I'll give it a try tomorrow.

I think this should work: data Box=B Int deriving(Show);add(B x)(B y)=B(x+y);iprd[][]=B 0;iprd(B x:xs)(B y:ys)=add(B$x*y)(iprd xs ys);f[]=[];f([x,y]:ps)=(iprd x y):f ps;main=do print$f[[[B 2,B 3],[B 4,B 5]],[[B 6],[B 7]]] Of course, on condition you never peek behind the tag B :) Sorry about my horrible un-Haskell-like coding style.

I really... don't understand what is being asked. in your example code for F, pairs is a list of tuples of.. what? it seems like they are box ids (aka, index in H) but your H is mostly empty. Am I supposed to hide a and b inside my H before calling F(pairs) in brilliant ways to get a+b? so then the challenge is about using the results of "inner product each" to do addition

@JoshRagem "pairs is a list of tuples of.. what?" - ..of arrays of box ids. "but your H is mostly empty" - In the JS version B() appends to H and returns its old length as a box id. In Haskell it may be better to have B as a data constructor and not have H at all, like in my previous comment (by the way, I realised I've made a mistake there - addition should be mod 2). Or you may come up with some clever construct that does it in a better way.

Python 3, 5 calls, 92 pairs, 922 bytes
Python 3, 5 calls, 134 pairs, 3120 bytes
Python 3, 6 calls, 106 pairs, 2405 bytes
[JavaScript (Node.js)], 9 calls, 91 pairs, 1405 bytes
JavaScript (Node.js), 16 calls, 31 pairs, 378 bytes
def add(F,a,b):r=[];p=lambda x:(x,x);q=lambda u,v,t:([u,v]+t[0],[u,v]+t[1]);s=lambda c,k,n:([e[j][n]for j in range(k,-1,-1)]+[f[n]],[c]+f[n-k:n+1]);t=lambda c,k,n:q(a[n],b[n],s(c,k,n-1));z=F([p([a[i],b[i]])for i in range(16)]+[([a[i]],[b[i]])for i in range(16)]);e=[z[0:16]];f=z[16:32];r+=[e[0][0]];c=f[0];z=F([p([a[1],b[1],c]),([e[0][1],f[1]],[c,f[1]])]+[([e[0][i]],[e[0][i-1]])for i in range(3,16)]);r+=[z[0]];c=z[1];e+=[[0]*3+z[2:15]];z=F([p([a[2],b[2],c]),t(c,0,3),s(c,1,3)]+[([e[j][i]],[e[1][i-j-1]])for j in range(2)for i in range(6+j,16)]);r+=z[0:2];c=z[2];e+=u(2,4,z[3:]);z=F([p([a[4],b[4],c])]+[t(c,i,i+5)for i in range(0,3)]+[s(c,3,7)]+[([e[j][i]],[e[3][i-j-1]])for j in range(4)for i in range(12+j,16)]);r+=z[0:4];c=z[4];e+=u(4,8,z[5:]);z=F([p([a[8],b[8],c])]+[t(c,i,i+9) for i in range(0,7)]);return r+z
def u(b,e,z):
	j=0;w=[0]*(e-b)
	for i in range(b,e):w[i-b]=[0]*(i+e)+z[j:j+16-(i+e)];j+=16-(i+e)
	return w

Try it online!
FIRST VERSION
Okay that's not golfed. It's just an adaptation of @ngn's code.
The only idea here is that you don't need to compute the last carry since you discard overflow. Also, the calls of F are grouped by two. Maybe they may be grouped in another way, but I doubt you can reduce significantly the number of pairs, due to the nature of the basic addition algorithm.
EDIT: Still not golfed. The number of pairs could certainly be reduced, and probably the number of calls too. See https://gist.github.com/jferard/864f4be6e4b63979da176bff380e6c62 for a "proof" with sympy.
EDIT 2 Switched to Python because it's more readable for me. Now I have got the general formula, I think I may reach the limit of 5 (maybe 4) calls.
EDIT 3
Here are the basic bricks:
alpha[i] = a[i] ^ b[i]
beta[i] = a[i] * b[i]
c[0] = beta[0]
r[0] = alpha[0]

The general formula is:
c[i] = alpha[i]*c[i-1] ^ beta[i]
r[i] = a[i] ^ b[i] ^ c[i-1]

The expanded version is:
c[0] = beta[0]
c[1] = alpha[1]*beta[0] ^ beta[1]
c[2] = alpha[2]*alpha[1]*beta[0] ^ alpha[2]*beta[1] ^ beta[2]
c[3] = alpha[3]*alpha[2]*alpha[1]*beta[0] ^ alpha[3]*alpha[2]*beta[1] ^ alpha[3]*beta[2] ^ beta[3]
...
c[i] = alpha[i]*...*alpha[1]*beta[0] ^ alpha[i]*...*alpha[2]*beta[1] ^ .... ^ alpha[i]*beta[i-1] ^ beta[i]

5 calls seems the limit for me. Now I have a little work to remove pairs and golf it!
EDIT 4 I golfed this one.
Ungolfed version:

def add(F, a, b):
    r=[]
    # p is a convenient way to express x1^x2^...x^n
    p = lambda x:(x,x)
    # q is a convenient way to express a[i]^b[i]^carry[i-1]
    q = lambda u,v,t:([u,v]+t[0],[u,v]+t[1])

    # step1: the basic bricks
    z=F([p([a[i],b[i]]) for i in range(16)]+[([a[i]],[b[i]]) for i in range(16)])
    alpha=z[0:16];beta=z[16:32]
    r.append(alpha[0])
    c = beta[0]

    # step 2
    z=F([
        p([a[1],b[1],c]),
        ([alpha[1],beta[1]],[c,beta[1]])
        ]+[([alpha[i]],[alpha[i-1]]) for i in range(3,16)])
    r.append(z[0])
    c = z[1] # c[1]
    alpha2=[0]*3+z[2:15]
    assert len(z)==15, len(z)

    # step 3
    t0=([alpha[2],beta[2]],[c,beta[2]])
    t1=([alpha2[3],alpha[3],beta[3]],[c,beta[2],beta[3]])
    z=F([
        p([a[2],b[2],c]),
        q(a[3],b[3],t0),
        t1]+
        [([alpha[i]],[alpha2[i-1]]) for i in range(6,16)]+
        [([alpha2[i]],[alpha2[i-2]]) for i in range(7,16)])
    r.extend(z[0:2])
    c = z[2] # c[3]
    alpha3=[0]*6+z[3:13]
    alpha4=[0]*7+z[13:22]
    assert len(z)==22, len(z)

    # step 4
    t0=([alpha[4],beta[4]],[c,beta[4]])
    t1=([alpha2[5],alpha[5],beta[5]],[c,beta[4],beta[5]])
    t2=([alpha3[6],alpha2[6],alpha[6],beta[6]],[c,beta[4],beta[5],beta[6]])
    t3=([alpha4[7],alpha3[7],alpha2[7],alpha[7],beta[7]],[c,beta[4],beta[5],beta[6],beta[7]])
    z=F([
        p([a[4],b[4],c]),
        q(a[5],b[5],t0),
        q(a[6],b[6],t1),
        q(a[7],b[7],t2),
        t3]+
        [([alpha[i]],[alpha4[i-1]]) for i in range(12,16)]+
        [([alpha2[i]],[alpha4[i-2]]) for i in range(13,16)]+
        [([alpha3[i]],[alpha4[i-3]]) for i in range(14,16)]+
        [([alpha4[i]],[alpha4[i-4]]) for i in range(15,16)])
    r.extend(z[0:4])
    c = z[4] # c[7]
    alpha5 = [0]*12+z[5:9]
    alpha6 = [0]*13+z[9:12]
    alpha7 = [0]*14+z[12:14]
    alpha8 = [0]*15+z[14:15]
    assert len(z) == 15, len(z)

    # step 5
    t0=([alpha[8],beta[8]],[c,beta[8]])
    t1=([alpha2[9],alpha[9],beta[9]],[c,beta[8],beta[9]])
    t2=([alpha3[10],alpha2[10],alpha[10],beta[10]],[c,beta[8],beta[9],beta[10]])
    t3=([alpha4[11],alpha3[11],alpha2[11],alpha[11],beta[11]],[c,beta[8],beta[9],beta[10],beta[11]])
    t4=([alpha5[12],alpha4[12],alpha3[12],alpha2[12],alpha[12],beta[12]],[c,beta[8],beta[9],beta[10],beta[11],beta[12]])
    t5=([alpha6[13],alpha5[13],alpha4[13],alpha3[13],alpha2[13],alpha[13],beta[13]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13]])
    t6=([alpha7[14],alpha6[14],alpha5[14],alpha4[14],alpha3[14],alpha2[14],alpha[14],beta[14]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13],beta[14]])
    t7=([alpha8[15],alpha7[15],alpha6[15],alpha5[15],alpha4[15],alpha3[15],alpha2[15],alpha[15],beta[15]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13],beta[14],beta[15]])

    z=F([
        p([a[8],b[8],c]),
        q(a[9],b[9],t0),
        q(a[10],b[10],t1),
        q(a[11],b[11],t2),
        q(a[12],b[12],t3),
        q(a[13],b[13],t4),
        q(a[14],b[14],t5),
        q(a[15],b[15],t6)
    ])
    r.extend(z)
    return r

Try it online!

Very good :) You found the two easy optimisations I left out on purpose. "I doubt you can reduce significantly the number of pairs" - note that the first criterion for winning is the number of calls to F(). I guarantee there is a way to reduce those significantly (that's the hardest part of this challenge), and then there will be room for optimising the number of pairs, and finally of course golfing the code (but that's the least important criterion).

Ok I got it! Sooner or later, you got something like that: ... + x * y * z + .... We can't use F to evaluate it, but if we have computed x * y with the previous F call, we just have to do: ... + (x * y) * z + ... (it matches the format of F). Playing with sympy, I managed to spare a call (step1: compute r0,c0,r1; step2: compute c1 and some aux values; step3: compute r2,c2,r3,c3), and I'm now loooking for a general solution.

Yep, in other words: the output bits are polynomials of degree higher than 2 in the input bits. Inner product can combine an m-degree and n-degree polynomial into an (m+n)-degree polynomial, at most. Don't rush - in a few hours I'll be able to set up a bounty :)

You might want to consider taking advantage of Appendix 2 above. Or else: if someone copies your code, removes a space, and reposts it, technically I'll have to award the bonus to them.

@ngn I'm here for fun and I like this challenge. If I were interested in bonuses, I would work for the financial world! Having said that, I think there is a general consensus on this: you post an answer only if you have a significantly different solution. Obviously, "significantly different" depends on the challenge. But never mind if I'm wrong...

For the record, it is impossible to use fewer than five calls, since the solution requires a degree 32 polynomial.  (The polynomial corresponding to any function of the input bits is unique.)

@jferard Fair enough. You're right to assume that people most of the time treat others' work with respect - and yours has been brilliant so far. For me making up good rules that don't require too much trust is part of the fun :)

Haskell, 1 call (cheating???), 32 pairs (could be improved), 283 bytes (same)
Please don't be angry with me, I don't want to win with this, but I was encouraged in the remarks to the challenge to explain what I was talking about.
I tried to use the state monad to handle adding boxes and counting calls and pairs, and that worked, but I didn't manage to make my solution working in that setting. So I did what was also suggested in the comments: just hide the data behind a data constructor and don't peek. (The clean way would be to use a seperate module and not export the constructor.) This version has the advantage of being much simpler.
Since we are talking about boxes of bits, I put Bool values into them.
I define zero as the given box with the zero bit - a one is not needed.
import Debug.Trace

data B = B { unB :: Bool }

zero :: B
zero = B False

f :: [([B],[B])] -> [B]
f pairs =  trace ("f was called with " ++ show (length pairs) ++ " pairs") $
           let (B i) &&& (B j) = i && j
           in map (\(x,y) ->  B ( foldl1 (/=) (zipWith (&&&) x y))) pairs

We're using the debugging function trace to see how often f was called, and with how many pairs. &&& looks into the boxes by pattern matching, the inequality /=  used on Bool values is xor.
bits :: Int -> [Bool]
bits n = bitsh n 16
  where bitsh _ 0 = []
        bitsh n k = odd n : bitsh (n `div` 2) (k-1)

test :: ( [B] -> [B] -> [B] ) -> Int -> Int -> Bool
test bba n m = let x = map B (bits n)
                   y = map B (bits m)
                   r = bba x y
                   res = map unB r
               in res==bits(n+m)

The test function takes a blind binary adder as first argument, and then two numbers for which addition is tested. It returns a Bool indicating whether the test was successful. First the input boxes are created, then the adder is called, the result unboxed (with unB) and compared with the expected result.
I implemented two adders, the sample solution simple, so that we can see that the debug output works correctly, and my solution using value recursion valrec.
simple a b = let [r0] = f [([a!!0,b!!0],[a!!0,b!!0])]
                 [c]  = f [([a!!0],[b!!0])]
             in loop 1 [r0] c
             where loop 16 rs _ = rs
                   loop i  rs c = let [ri] = f [([a!!i,b!!i,c],[a!!i,b!!i,c])]
                                      [c'] = f [([a!!i,b!!i,c],[b!!i,c,a!!i])]
                                  in loop (i+1) (rs++[ri]) c'

valrec a b =
    let res = f (pairs res a b)
    in [ res!!i | i<-[0,2..30] ]
  where pairs res a b =
           let ts = zipWith3 (\x y z -> [x,y,z])
                             a b (zero : [ res!!i | i<-[1,3..29] ]) in
           [ p | t@(h:r) <- ts, p <- [ (t,t), (t,r++[h]) ] ]

See how I'm defining res in terms of itself? That is also known as tying the knot.
Now we can see how f is only called once:
*Main> test valrec 123 456
f was called with 32 pairs
True

Or replace valrec by simple to see f being called 32 times.
Try it online! (the tracing output appears under "Debug")

No anger here :) So, if I understand correctly, the argument to f is a lazy, potentially infinite list that materialises as you iterate through it? I'm afraid that's against the spirit of the challenge - it lets you to defer the decision about what to pass as the i+1-st argument til after you've obtained the result corresponding to the i-th. It's much more interesting to find out how many calls to f you'll need with fully materialised, immutable arguments :)

I agree. @jferard has done amazing work that shouldn't be invalidated by such a trick. While f could take infinite input (add infinite bit streams,yay!), that is not the point. Oh, and actually the trace message ensures that the length is finite and known at the beginning. Also, I wouldn't say that there is a deferred decision: everything was planned ahead of time, as demanded I am just blindly shuffling boxes. And note it's not about order of arguments: I could change it so that res contains first the result and then the carry bits.

"I am just blindly shuffling boxes" - Suppose you've obtained a box from calling f; do you feed back that box as another argument in the same call to f?

Yes, I do. That is what value recursion is all about. You had that right: it's using lazyness and the fact that I can use arguments that are not fully materialized (I like that description). Given the obvious spirit of the challenge, that's - as announced - clearly cheating. If one thinks it's inventive or noteworthy, one may argue that it's good cheating.

It's certainly of the good kind - obviously you have no intention to deceive here. Laziness in functional programming is a beautiful concept and it has its valid uses. When I tried to learn some Haskell a few years ago, I remember being very impressed with a one-liner that "ties the knot" for the Fibonacci numbers.

Now I also have a working version using the state monad.

Just a reminder: per Appendix 2 above, you can prevent your algorithm from being stolen.

@ChristianSievers Please try this The trace appears only once for two calls. I will ask a SO question about that. Is Haskell that much lazy?

The SO question: https://stackoverflow.com/q/45967186/6914441

@jferard Are the answers on SO enough? Doubts about trace like this are why I also have simple where you can see that multiple calls to f are reported. And now I have the monadic version which confirms that my adder only calls f once.

@ngn The state monad version is also cheating, so there is no reason to make it official and unstealable. It's the program I wanted to write from the beginning, that really counts how often f gets called, without the need to trust dubious output from trace. I just wanted to confirm that doing that is indeed possible.

@ChristianSievers Ok, let's try to follow lazily what's happening. f is basically a map, thus I need only (pairs res a b)!!i to evaluate res!!i = f (pairs res a b)!!i. Let's take i=2: res!!2 evaluates to (<the function f maps on the pairs>)([a!!2,b!!2,res!!1],[a!!2,b!!2,res!!1]). Where does res!!1 come from? from the same call? It's difficult to say, since valrec computes res!!1 using f and then immediately puts it again in the list of the arguments of f.

An interesting experience:

add deriving (Show) after the definition of B
make the call to f show the pairs instead of the length: trace ("f was called with " ++ (show pairs) ++ " pairs")
It gives a <<loop>> error.

JavaScript, 32 calls, 32 pairs, 388 bytes
Dyalog APL, 32 calls, 32 pairs, 270 bytes
This is a naïve sample solution that can serve as a template.
Note that the byte count must include only the section surrounded with "BEGIN/END SOLUTION".
Explanation:
I chose little-endian bit order (x[0] is the least significant bit).
Observe that single-bit addition mod 2 can be realised as F([[[x,y],[x,y]]]) (that is: x*x ^ y*y - multiplication mod 2 is idempotent) and binary multiplication as F([[[x],[y]]]).
We traverse the bits from least significant to most significant and at each step compute a result bit and a carry.
#!/usr/bin/env node
'use strict'
let H=[0,1]
,B=x=>H.push(x)-1
,nCalls=0
,nPairs=0
,F=pairs=>{
  nCalls++;nPairs+=pairs.length
  return pairs.map(([x,y])=>{let s=0;for(let i=0;i<x.length;i++)s^=H[x[i]]*H[y[i]];return B(s)})
}

// -----BEGIN SOLUTION-----
var f=(a,b)=>{
  var r=[], c // r:result bits (as box ids), c:carry (as a box id)
  r[0]=F([[[a[0],b[0]],[a[0],b[0]]]])          // r0 = a0 ^ b0
  c=F([[[a[0]],[b[0]]]])                       // c = a0*b0
  for(var i=1;i<16;i++){
    r.push(F([[[a[i],b[i],c],[a[i],b[i],c]]])) // ri = ai ^ bi ^ c
    c=F([[[a[i],b[i],c],[b[i],c,a[i]]]])       // c = ai*bi ^ bi*c ^ c*ai
  }
  return r
}
// -----END SOLUTION-----

// tests
let bits=x=>{let r=[];for(let i=0;i<16;i++){r.push(x&1);x>>=1}return r}
,test=(a,b)=>{
  console.info(bits(a))
  console.info(bits(b))
  nCalls=nPairs=0
  let r=f(bits(a).map(B),bits(b).map(B))
  console.info(r.map(x=>H[x]))
  console.info('calls:'+nCalls+',pairs:'+nPairs)
  console.assert(bits(a+b).every((x,i)=>x===H[r[i]]))
}

test(12345,6789)
test(12,3)
test(35342,36789)

The same in Dyalog APL (but using randomised box ids):
⎕io←0⋄K←(V←⍳2),2+?⍨1e6⋄B←{(V,←⍵)⊢K[≢V]}⋄S←0⋄F←{S+←1,≢⍵⋄B¨2|+/×/V[K⍳↑⍉∘↑¨⍵]}
⍝ -----BEGIN SOLUTION-----
f←{
  r←F,⊂2⍴⊂⊃¨⍺⍵        ⍝ r0 = a0 ^ b0
  c←⊃F,⊂,¨⊃¨⍺⍵        ⍝ c = a0*b0
  r,⊃{
    ri←⊃F,⊂2⍴⊂⍺⍵c     ⍝ ri = ai ^ bi ^ c
    c⊢←⊃F,⊂(⍺⍵c)(⍵c⍺) ⍝ c = ai*bi ^ bi*c ^ c*ai
    ri
  }¨/1↓¨⍺⍵
}
⍝ -----END SOLUTION-----
bits←{⌽(16⍴2)⊤⍵}
test←{S⊢←0⋄r←⊃f/B¨¨bits¨⍺⍵
      ⎕←(↑bits¨⍺⍵)⍪V[K⍳r]⋄⎕←'calls:' 'pairs:',¨S
      (bits⍺+⍵)≢V[K⍳r]:⎕←'wrong!'}
test/¨(12345 6789)(12 3)(35342 36789)

source: Stack Exchange

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

sort: votes


text:
How hard can I crush my array?
Lets define the process of crushing an array of numbers.  In a crush we read the array left to right.  If at a point we encounter two of the same element in a row we remove the first one and double the second one.  For example here is the process of crushing the following array
[5,2,2,3]
 ^
[5,2,2,3]
   ^
[5,2,2,3]
     ^
[5,4,3]
   ^
[5,4,3]
     ^

The same element can be collapsed multiple times, for example [1,1,2] becomes [4] when crushed.
We will call an array uncrushable when the process of crushing that array does not change it.  For example [1,2,3] is still [1,2,3] after being crushed.
Your task is to take an array and determine the number of crushes required to make it uncrushable.  You need only support integers on the range of 0 to 232-1
This is code-golf so answers will be scored in bytes with less bytes being better.
Test Cases
[1] -> 0
[1,1] -> 1
[2,1,1] -> 2
[4,2,1,1] -> 3
[2,2,2,1,1] -> 3
[0,0,0,0] -> 1
[4,0,0,0,4] -> 1
[4,0,0,0,0,4] -> 1
[] -> 0

What's the maximum input size we must support?

Should [1,1,2,4,8] return 1 or 4?

@MooseBoys It is 1.

If you tried to crush [1 1 1 2] you would end up with [2 1 2] if you follow the spec exactly as written, but you could end up with [1 4] if you do it more intelligently. What should [1 1 1 2] result in?

@latias1290. "In a crush we read the array left to right."

@ThePirateBay TFW you "reject irrelevant information" then realize how relevant it truly is.

x86 assembly (64-bit), 66 65 bytes
31 c0 57 59 56 51 56 5f 4d 31 c0 48 83 c6 08 48
83 e9 01 76 1b fc f2 48 a7 75 15 48 d1 67 f8 51
56 57 f3 48 a5 5f 5e 59 fd 48 a7 49 ff c0 eb e5
59 5e 4c 29 c1 48 ff c2 4d 85 c0 75 c7 48 ff c8
c3

String instructions were helpful. Having to correct for off-by-one errors in a 64-bit environment was not.
Fully commentated source code:
.globl crush
crush:
/* return value */
xor %eax, %eax
/* save our length in rcx */
push %rdi
pop %rcx
pass:
/* save the start of the string and the length */
push %rsi
push %rcx
/* this is the loop */
/* first copy source to dest */
push %rsi
pop %rdi
/* and zero a variable to record the number of squashes we make this pass */
xor %r8, %r8
/* increment source, and decrement ecx */
add $8,%rsi
sub $1,%rcx
/* if ecx is zero or -1, we're done (we can't depend on the code to take care of this
automatically since dec will leave the zero flag set and cmpsq won't change it) */
jbe endpass
compare:
/* make sure we're going forward */
cld
/* compare our two values until we find two that are the same */
repne cmpsq
/* if we reach here, we either found the end of the string, or
we found two values that are the same. check the zero flag to
find out which */
jne endpass
/* okay, so we found two values that are the same. what we need
to do is double the previous value of the destination, and then
shift everything leftwards once */
shlq $1, -8(%rdi)
/* easiest way to shift leftwards is rep movsq, especially since
our ecx is already right. we just need to save it and the rsi/rdi */
push %rcx
push %rsi
push %rdi
rep movsq
pop %rdi
pop %rsi
pop %rcx
/* problem: edi and esi are now one farther than they should be,
since we can squash this dest with a different source. consequently
we need to put them back where they were. */
std
cmpsq
/* we don't need to put ecx back since the list is now one shorter
than it was. */
/* finally, mark that we made a squash */
inc %r8
/* okay, once we've reached this point, we should have:
 edi and esi: next two values to compare
 ecx: number of comparisons left
so we just jump back to our comparison operation */
jmp compare
endpass:
/* we reached the end of the string. retrieve our old ecx and esi */
pop %rcx
pop %rsi
/* rsi is accurate, but rcx is not. we need to subtract the number of squashes
that we made this pass. */
sub %r8, %rcx
/* record that we performed a pass */
inc %rax
/* if we did make any squashes, we need to perform another pass */
test %r8, %r8
jnz pass
/* we reached the end; we've made as many passes as we can.
decrement our pass counter since we counted one too many */
dec %rax
/* and finally return it */
ret

I may try doing this in 32-bit, if only for fun, since those REX prefixes really killed me.
Edit: shaved one byte off by replacing lodsq with add, %rdx with %rax, and collapsing two cld's into one.

Pyth, 22 bytes
tl.uu?&GqeGH+PGyH+GHN[

Verify all testcases.

Jeebus! Do you first use a transpiler and then hand-edit it, or do you actually write Pyth from the beginning?

@oligofren the latter.

Haskell, 66 bytes
f(a:b:x)|a==b=f$a+a:x|1>0=a:f(b:x)
f x=x
g x|f x==x=0|1>0=1+g(f x)

Try it online!
Explanation
f is a function that crushes a list.  It performs the crush as desribed in the question.  g is a function that counts the number of crushes.  If f x==x, g x=0 otherwise g x=1+g(f x).

Shave off a byte by changing g(f x) to g$f x

@ApproachingDarknessFish That doesn't work because + has higher precedence than $

Ah, my bad. Funny that I've never run into that error before.

Paradoc (v0.2.10), 16 bytes (CP-1252)
{—1\ε=k+x}]»}IL(

Try it online! / with header/footer that check all test cases
Takes a list on the stack, and results in a number on the stack.
Pretty straightforward implementation, to be quite honest. Crushes a list by starting with a sentinel -1, looping through the list, pushing each element and adding it to the element beneath it iff they're equal. At the end we cut off the -1. We only crush equal numbers together and all the problem's numbers are nonnegative, so the -1 sentinel won't affect the crushing process. With crushing implemented, it's only a matter of counting iterations to its fixed point.
Explanation:
{            }I  .. Iterate this block: repeatedly apply it until a fixed
                 .. point is reached, and collect all intermediate results
 —1              ..   Push -1 (note that that's an em dash)
   \             ..   Swap it under the current list of numbers
    ε    }       ..   Execute this block for each element in the list:
     =           ..     Check if it's equal to the next element on the stack...
      k          ..       ... while keeping (i.e. not popping either of) them
       +         ..     Add the top two elements of the stack...
        x        ..       ... that many times (so, do add them if they were
                 ..       equal, and don't add them if they weren't)
          ]      ..   Collect all elements pushed inside the block that
                 ..     we're iterating into a list
           »     ..   Tail: take all but the first element (gets rid of the -1)
              L  .. Compute the length of the number of intermediate results
               ( .. Subtract 1

If we could assume the input were nonempty, we wouldn't need the sentinel and could shave 2 bytes: {(\ε=k+x}]}IL(
Another fun fact: we only lose 2 bytes if we force ourselves to only use ASCII: {1m\{=k+x}e]1>}IL(

JavaScript (ES6), 86 bytes
f=a=>a.length>eval("for(i=0;a[i]>-1;)a[i]==a[++i]&&a.splice(--i,2,a[i]*2);i")?1+f(a):0

Ungolfed and Explained
f=a=>                           // function taking array a
    a.length > eval("           // if a.length > the result of the following...
        for(i=0; a[i]>-1;)      //   loop from 0 until the current value is undefined (which is not > -1)
            a[i] == a[++i] &&   //     if the current value equals the next one...
                a.splice(--i,   //       splice the array at the first index of the pair...
                    2,          //       by replacing 2 items...
                    a[i]*2);    //       with the current item * 2
                                //       this also decrements the counter, which means the current value is now the next
    i")                         //   return the counter, which is new a.length
        ? 1+f(a)                // if that was true, the array was crushed. add 1 and recur with the new array
        : 0                     // otherwise just return 0

Tests

f=a=>a.length>eval("for(i=0;a[i]>-1;)a[i]==a[++i]&&a.splice(--i,2,a[i]*2);i")?1+f(a):0

;[ [1], [1,1], [2,1,1], [4,2,1,1], [2,2,2,1,1], [0,0,0,0], [4,0,0,0,4], [4,0,0,0,0,4], []
].forEach(x=>console.log( JSON.stringify(x) + " -> " + f(x) ))
.as-console-wrapper{max-height:100%!important}

a.length>n is the same as a[n]!=[]._. In this case (since all items in the array are numbers larger than -1), it is the same as a[n]>-1. Also, a[i]==a[++i]&&x is the same as a[i]-a[++i]||x.

I think 1/a[i] also works to save another byte.

JavaScript, 67 bytes
f=a=>a.map(a=>k[k[d-1]!=a?d++:(a*=z=2,d-1)]=a,k=d=[z=0])&&z&&f(k)+1

Try it online!

Nice!  I thought I had golfed this as low as possible.

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

Try it online!
Explanation
([])                                                                 Push stack height (starts main loop if list nonempty)
     {                                                       }       Do while the last iteration involved at least one crush:
      <{}>                                                           Remove crush indicator
           <(...)>                                                   Do a crush iteration
                  {()(<{}>)}                                         Evaluate to 1 if list was changed
                            {}{}                                     Remove zeroes
                                <>                        <>         On other stack:
                                  <([]){{}        ([])}>{}           Do while stack is nonempty:
                                          ({}<>)<>                   Move to first stack
          (                                                 )        Push 1 if crush worked, 0 otherwise
    (                                                         <>)    Push sum of results on other stack and implicitly print

The crush function evaluates to the number of pairs of items that were crushed together:
([][()]){[{}]                                                            ([][()])}    Do while stack height isn't 1:
              ({}[({})]      )                                                        Calculate difference between top two elements
                       <(())>                                                         Push a 1 below difference
                              {                    }                                  If difference was nonzero (don't crush this pair)
                               ({}    ({})<>)                                         Reconstruct top element and place on other stack
                                  <{}>       ((<>))                                   Push zeros to exit this conditional and skip next
             <                                      >{}                               Evaluate as zero
                                                       {              }{}             If difference was zero (crush this pair):
                                                        {}                            Evaluate as previously pushed 1
                                                          (<(({}){})>)                Double top of stack

Java 8, 120 bytes
A lambda from List<Long> to Integer. Input list must implement remove(int) (e.g. ArrayList). Assign to Function<List<Long>, Integer>.
l->{int c=-1,i,f=1;for(;f>0;c++)for(f=i=0;++i<l.size();)if(l.get(i)-l.get(i-1)==0)l.set(i-=f=1,2*l.remove(i));return c;}

Try It Online
Ungolfed lambda
l -> {
    int
        c = -1,
        i,
        f = 1
    ;
    for (; f > 0; c++)
        for (f = i = 0; ++i < l.size(); )
            if (l.get(i) - l.get(i - 1) == 0)
                l.set(i -= f = 1, 2 * l.remove(i));
    return c;
}

c counts the number of crushes so far, i is the index into the list, and f indicates whether to continue crushing the list when an iteration finishes. Inside the loops, each adjacent pair is compared. i is incremented unconditionally, so if an element is removed by crushing, i is decremented first to cancel out the increment. The former element is removed from the list.
Acknowledgments

Bugfix thanks to Olivier Grégoire: boxed equality test

Doesn't work when the longs don't hit the valueOf cache. Example: {128L, 128L}. That's because of l.get(i)==l.get(i-1), which should be replaced by l.get(i).equals(l.get(i-1)).

Wow, embarassing...luckily l.get(i)-l.get(i-1)==0 will work. Thanks!

Python 2, 112 110 108 107 105 100 bytes
Edit: saved 2 bytes by removing or in return statement
Edit: saved 2 bytes by having i as the index of the second of the two elements to be accessed
Edit: saved 1 byte thanks to @Mr.Xcoder
Edit: saved 7 bytes thanks to @jferard
def f(x):
 i=e=1
 while x[i:]:
	if x[~-i]==x[i]:del x[i];i-=1;x[i]*=2;e=2
	i+=1
 return~-e and-~f(x)

Try it online!

JavaScript (ES6), 83 bytes
f=([x,y,...a],b=[],c)=>1/x?x==y?f([x+y,...a],b,1):f([y,...a],[...b,x],c):c?1+f(b):0

Explanation: The elements are recursively extracted from the original array and unique values are appended to b while c is a flag to indicate whether the array had been successfully crushed.

JavaScript (ES6), 70 bytes
f=(a,j=m=0,t=[])=>a.map(e=>t[e==t[j-1]?(e*=m=2,j-1):j++]=e)&&m&&1+f(t)

Explanation:
f=(
  a,                  //the input
  j=m=0,              //j is the index into t; m starts out falsey
  t=[]                //t will hold the crushed array
)=>
  a.map(e=>           //for each element in the array
    t[e==t[j-1] ?     //if the element repeats:
      (e*=m=2,        //... multiply it by two, set m to truthy,
       j-1) :         //... and index the previous element of t.
      j++             //else append to t, and increment its index.
    ]=e               //set this index of t to the current value of e
  ) &&                //map is always truthy
  m &&                //if m is falsey, return 0
  1+f(t)              //else return 1 plus the recurse on t

Test Cases:

f=(a,j=m=0,t=[])=>a.map(e=>t[e==t[j-1]?(e*=m=2,j-1):j++]=e)&&m&&1+f(t)

console.log(f([1])) // 0
console.log(f([1,1])) // 1
console.log(f([2,1,1])) // 2
console.log(f([4,2,1,1])) // 3
console.log(f([2,2,2,1,1])) // 3
console.log(f([0,0,0,0])) // 1
console.log(f([4,0,0,0,4])) // 1
console.log(f([4,0,0,0,0,4])) // 1
console.log(f([])) // 0

Hm.. It seems that we came up with the pretty much same idea :). After golfing mine answer I realized it is very similar to yours.

Perl 5, 96 bytes
94 code, 2 for -pa
do{$\++;$l=@F;for($i=0;++$i<@F;){$F[$i]==$F[$i-1]&&splice@F,$i,2,$F[$i--]*2}}while$l!=@F}{$\--

Try it online!

J, 54 bytes
[:<:@#[:".@":@(,`(+:@[,}.@])@.({.@]=[))/^:a:@".@":_,|.

Try it online!
Not my best golf by any means. Surely there has to be a better way of converting a list with one item to an atom.
Explanation
crush =. ,`(+:@[ , }.@])@.({.@] = [)/
times =. <:@# [: ".@":@crush^:a:@".@": _ , |.

crush
This crushes an array once. It needs to be given the array in reverse since J's insert works right-to-left (something I learned today). This doesn't particularly matter, since all we need to output is the number of times we can crush the array.
,`(+:@[ , }.@])@.({.@] = [)/
                           /  Fold/reduce from the right
                  {.@] = [    Head of the running array equals the left argument?
   +:@[ ,                     If so, prepend double the argument to
          }.@]                the array minus its head
,                             Else, prepend the left argument.

times
This is fairly straightforward: apply crush to the array until our result converges, but there are a few issues I had to deal with that result in much more code than I anticipated.
First, when crushing reduces to a single element, that element is actually in a one item list (i.e. it is nonatomic), so the function is applied again resulting in overcounting. To fix this, I used a hack I came up with to reduce a single element list to an atom which is ".@": (convert to string and then evaluate).
Second, crush errors on the empty list. I think you can define how a function should behave on receiving empty input with insert (/), but I couldn't find anything after a cursory look, so I'm using another workaround. This workaround is to prepend _ (infinity) to the list since it will never affect the number of times the array is crushed (_ > 2^64). However, this results in a single element list consisting of _ when given the empty list, so we need to convert to an atom again before crushing.
<:@# [: ".@":@crush^:a:@".@": _ , |.
                                  |.  Reverse input
                              _ ,     Prepend infinity
                        ".@":         Convert single-element list to atom
              crush                   Crush the list and after
        ".@":                         Convert single-element list to atom
                   ^:a:               until it converges, storing each
                                      iteration in an array
<:@#                                  Length of the resulting list minus 1

Jelly, 21 bytes
ṪḤ,⁼?⁹⁸;µ/Ḋ$¹L’$?ÐĿL’

Try it online!

R, 142 75 bytes
function(l){while(any(z<-which(!diff(l)))){l[z]=l[z]*2
l=l[-z-1]
F=F+1}
+F}

Try it online!

Would be cool to see a more clever way.

@Razetime wish granted. After 3 years of golfing in R, it's clear I've learned quite a lot.

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:
Code 3k to Codee k
Write some code...
Write a program that takes no input and outputs an integer n which is a multiple of 3. So n=3k, where k is a positive integer.
Double the last character of your code.
Your code should then output k.
Examples
Here is my program hui#2(21+4)//lm, which outputs 81.
Because of that, hui#2(21+4)//lmm should output 27.
or
If p8$w2*8 outputs 9, p8$w2*88 should output 3.
Rules
This is code-golf, shortest answer in bytes wins!

Can it output 9.0 and 3.0? (Taking square roots, so it automatically turns into a float. :P)

This is a less interesting version of double the source, double the output.  And that wasn't terribly interesting to begin with.

I've downvoted this as, even by my standards, this is far too trivial, solvable with basic subtraction or square rooting, as illustrated by a lot of the solutions so far.

@Shaggy then use your imagination! be creative instead of downvoting.Many people here gave some great answers.

@BillSteihn You don't understand - this is code golf. The goal is to find the shortest answer, not to be creative. The answer that Shaggy provided is a trivial way of achieving your answer, and will be the shortest way to solve this challenge in most languages.

@Qwerp-Derp you don't understand what I am really saying... Since this is code-golf only a very clever and creative answer can win! just look at the answers!

@BillSteihn But with a challenge this straightforward (at least, for languages with 1-byte builtins for mathematical functions), this is the approach that a lot of the answers here take, which is what Shaggy noted.

As @QwerpDerp said, this is code golf; creativity is, for the most part, not conducive to a healthy byte count.

Are we allowed to use a function instead of a program for verbose languages like Java or .NET C#?

Mathematica, 2 bytes
4!

4! returns 24
4!! returns 8

This one is really cute :)

Many languages, 4 bytes
16-1

Outputs 15.
16-11

Outputs 5.
This is a CW answer for many languages it works for. Edit to add to the list:

APL
bc
Dyvil
Haskell
I
J
Japt
Javascript REPL
Java REPL
Julia REPL
Mathematica
Python REPL
R REPL
Ruby REPL
Scala REPL
Swift REPL
TI-83/84 Basic

JavaScript (console only). But I'm not sure if it would be valid.

@ThePirateBay I think REPL answers are valid. This should work for Python too, in a REPL environment, right?

@IsmaelMiguel Yes, though they count as separate languages. i added both.

I suspect your list is going to get quite long for this one! Works in Japt (although you could replace 16 with a constant to save a byte).

Sage as well. :)

JShell 9 should also work

k too :)

Lost, 52, 18 bytes
\(@>>>
\>>%?
\(13$

Try it online!
\(@>>>
\>>%?
\(13$$

Try it online!
Explanation
Lost is a language in which the start location and direction of the pointer are entirely random.  Thus making a deterministic program can be tough.
The code we want to execute is either 13$(@ or 13$$(@.

31 pushes 3 and 1 to the stack
$ will swap them
$ will swap them back if present
( will pop the top element
@ will halt and output

We want to insert the $ at the end so we have to split this
\(@
v
\31$

The rest of this is a careful orchestration to make sure that every possible pointer executes this code and only this code.

Operation Flashpoint scripting language, 19 bytes
a="3";aa="1";hint a

Outputs:

a="3";aa="1";hint aa

Outputs:

Wow, just wow :D Anyway, can't you just hint a,aa?

@KeyWeeUsr You mean to output both at the same time? hint format["%1\n%2", a, aa] would do that (or hint (a+"\n"+aa) because they are strings), but I think outputting them separately illustrates the solution better here.

The screenshots are always entertaining now, you sniping a tank, eh?

@MagicOctopusUrn Just observing it and the surroundings with my binoculars. It's way out of range for any anti-tank weapons I'd might be carrying, so I need to get closer, but first I must check that there's no enemy infantry around preventing me from doing so.

@Steadybox obviously you'd recommend this game, eh? Is it a steam game?

@MagicOctopusUrn It's my favourite game. However, its old and might not be for everybody, and most of the fun with it is modding it and making your own scenarios (or playing around with existing mods). You can find it on Steam with its re-release name "ARMA: Cold War Assault".

@Steadybox THIS IS ARMA?! I've heard such good things! I'll look into it.

@MagicOctopusUrn The ARMA series are sequels of this game. They (and the re-release of this game) are named differently, because the developer (Bohemia Interactive Studios) didn't own the name "Operation Flashpoint". That name is owned by the original publisher (Codemasters).

You should crop those images...

Jelly, 2 bytes
3ȷ

Try it online!
Outputs 3000. 3ȷ is a numeric literal for 3000.
3ȷȷ outputs 1000: 3ȷ is 3000, which is thrown away and replaced by ȷ, 1000.
This is the only two-byte solution, and it is optimal; I found it by trying every possible program.

Actually, 2 bytes
5¬

Try it online!
Repeating the last character: 5¬¬.
Explanation:
5¬
5   push 5
 ¬  subtract 2

Adding another ¬ causes 2 to be subtracted from 3, yielding 1.

Paradoc version: 5«, 5«« I hope you find this symbol choice more mnemonic — it was supposed to be one of its comparative strengths :)

Python 2, 9 bytes
print 3&3

Try it online! Prints 3.
print 3&33

Try it online! Prints 1.

Also works with 3&7, 6&6, 7&3, 7&6, or 8^1

Shave off 6 bytes by using REPL

CJam, 4 bytes
2_5+

Outputs 27. Try it online!
2_5++

Outputs 9. Try it online!

Pyke, 2 bytes
This prints 3 and 6ee prints 1.
6e

Try it here!
6ee

Try it here!
6  - Push 6.
 e - Floor halve.
   - Print Implicitly.

How?
Not much to explain. The whole point of this solution is that:

Cubix, 6 bytes
Works by changing the path based on cubes with different edge sizes.  None of that tricky math stuff.  The starting numbers could be also 1 3 or 2 6
39O@W@

Cubified
  3
9 O @ W
  @

Try it online!
Only executes 9O@ which is Push 9, Output as number, Halt.
39O@W@

Cubified
    3 9
    O @
W @ @ . . . . .
. . . . . . . .
    . .
    . .

This now executes W3O@, which is Left shift, Push 3, Output as number, Halt.
Try it online!

Jelly, 3 bytes
81½

Try it online!
Outputs 9.
81½½

Try it online!
Outputs 3.

Is ½ really square root? I can't figure which is worse, the ½ or Actually's ¬

Haskell, 8 bytes
gcd 3 21

Outputs 3, and gcd 3 211 outputs 1.

05AB1E, 3 bytes
3Xr

Outputs 3.
Try it online!
3Xrr

Outputs 1.
Try it online!

5Í, maybe? :P

тg too ;)...?

Mathematica, 13 bytes
PrimeOmega@27

Not the shortest solution but y'know...

C, 60 45 bytes
Thanks to @nwellnhof for saving 15 bytes!
#define AA"5");}
#define A"1"AA
main(){puts(A

Outputs 15
#define AA"5");}
#define A"1"AA
main(){puts(AA

Outputs 5

#define AA"5");} #define A"1"AA main(){puts(A

@nwellnhof Thanks!

Polyglot, 05AB1E / 2sable, 3 bytes
This one prints 9. 81tt prints 3.
81t

Try it online!
Try it online!
81tt

Try it online! Try it online!

Befunge-98, 6 bytes
<q%5b'

Try it online!
Outputs via exit code.
Explanation: On program start the IP is immediately sent leftwards, so it wraps to the right end and executes commands from right to left. So, in this program, it encounters 'b5%, which pushes 98, the value of the character b, and then computes the remainder of 98 when divided by 5, which is 3. Finally, with q, it quits with this exit code.
With the last character doubled, it encounters ''b5%, which pushes the value of the character ' but then immediately pushes b, which is 11. It then computes the remainder of 11 when divided by 5, which is 1, and quits with this exit code.

"It then computes the remainder of 12 when divided by 5, which is 1, and quits with this exit code." - I think you mean 11...

You're right, fixed

Pyth, 4 bytes
This prints 9. x8 11 prints 3.
x8 1

Try it online!
x8 11

Try it online!

How?

x8 1  - Full program.

x     - Bitwise XOR.
 8 1  - Of 8 and 1.
      - Implicitly print.

Befunge-98 (PyFunge), 5 bytes
[q/3g

Try it online!
Outputs via exit code.
Explanation
First, the IP hits the "turn left" instruction ([) twice, which wraps it back around to the back of the code, going right.
The "get" instruction (g) takes the first 2 values and pushes the ASCII value of the character at that x and y position. The first time it is executed, there are only zeros on the stack, meaning we get the value 91. If we don't double the g, we divide 91 by 3, with integer division, truncating it to 30, which is returned.
If we do duplicate the g, it gets the ASCII value at (0, 91), which isn't anywhere near the code. Because the grid is initialized to be filled with spaces, this returns the value 32. if we integer divide by 3, we get 10, one third of 30.

Python 2, 16 bytes
a=3;aa=1;print a

outputs 3
a=3;aa=1;print aa

outputs 1

V, 5 bytes
é52ñ

Try it online!
Outputs 3
é52ñ

Try it online!
Outputs 1

Ly, 6 bytes
3>1<<>

Try it online!
Outputs 3.
With the second character duplicated:
3>1<<>>

Try it online!
Outputs 1.

Recursiva, 5 bytes
+16-1

Try it online!

Ripped off from Many languages solution, only a byte more since Recursiva is prefix and - sign and subtract operator are the same. This is actually adding 16 and -1.

Other solution:
Recursiva, 10 bytes
Y_+B5A3IH1

Try it online!

Jelly, 5 bytes
This one outputs 3. By doubling the last character, you get 1.
HḞ
6Ç

Try it online!
HḞ
6ÇÇ

Try it online!

Japt, 3 bytes
Still on the hunt for a 2 byte solution.
#Q is 81 and ¬ is square root, which gives 9. Adding another ¬ at the end gives 3
#Q¬

Try it
#Q¬¬

Try it

><>, 6 bytes
",n;c!

Try it online!
",n;c!!

Try it online!
Explanation
",n;c!  : Put each character onto the stack;
          [110, 59, 99, 33]
 ,n;    : Divide the top two stack items, print as a number and end.
          99/33 = 3

",n;c!! : Put each chat onto the stack;
          [110, 59, 99, 33, 33]
 ,n;    : Divide the top two stack items, print as a number and end.
          99/33 = 3

This ports to Runic and doesn't feel worth posting as its own answer.

Pyt, 2 bytes
9₃

Returns 9/3
Try it online!

9₃₃

Returns (9/3)/3
Try it online!

Alternatively, also 2 bytes:
6₂

This works due to Python 2's integer division

Ruby, 5 bytes
3/0b1

Division by one or three, written in binary.

This appears to be a code snippet and not a function or full program.

Pyth, 5 bytes
-16 1

Try it online!

Yet another rip from many languages answer

Charcoal, 6 bytes
This one prints 15. The other version prints 5.
Ｉ⁻¹⁶¦¹

Try it online!
Ｉ⁻¹⁶¦¹¹

Try it online!

Neim, 2 bytes
ηᚠ

Outputs 3. Doubled, outputs 1.
Try it online!
Doubled

RProgN 2, 2 bytes
6›

6› takes 6 and shifts it right. 110 -> 11 which gives 3. 6›› shifts 6 twice, which gives 110 -> 1, or 1.
Try it online!

Forth (gforth), 10 bytes
Feels cheap to just overwrite the 33 numeric literal, but it's the shortest way I know of to make this work in forth

: 33 1 ; 3

Try it online!
outputs 3
: 33 1 ; 33

Try it online!
outputs 1
Explanation
: 33 1 ;  \ defines a new word 33 that puts a 1 on the stack.
          \ In forth explicit word definitions are parsed before numeric literals

This is in the wrong direction. You should output 3 for the first program and 1 for the second.

@WeijunZhou Good catch, thanks for pointing that out

Klein 0X0, 8 bytes
Works in 000 (torus) and 010 (Klein bottle)
\(@
\13$

Try it online!
\(@
\13$$

Try it online!
1XX,  9 bytes
Works in 100, 101, 110 and 111
\>(@
\13$

Try it online!
\>(@
\13$$

Try it online!


text:
Find out how Abstractly Capacious™ someone is!
At the Code-Golf™ Psychological Society, you are delighted to present a new method of measuring mental age: Abstract Capacity™.
To get the Abstract Capacity of a person, you take their actual age divided by 4, take their IQ divided by 9, then add the two values together. Then, round this sum down to find the Abstract Capacity.
Challenge
Write a program, given an actual age A and an IQ of I, produces the Abstract Capacity using those values. The program should also print how older (age) or how smarter (IQ) someone should be in order to raise their Abstract Capacity by 1.
An input will always look something like

A I

and an output will always look something like

AC A' I'

where AC, A' and I' respectively denote the Abstract Capacity, how older someone has to be to raise their Abstract Capacity, and how smarter someone has to be to raise their Abstract Capacity.
Examples
Input
13 43

Output
8 4 9

Input
92 5

Output
23 2 4

Input
40 17

Output
11 1 1

Rules
Your code must be able to find the Abstract Capacity for any given A and I when 1 < A,I < 400.
This is code-golf. Shortest answer in bytes wins!

You can only use one of the languages commonly pre-installed on Mac such as C, C++, Java, PhP, Perl, Python (2 or 3), Ruby, and Swift. - I strongly suggest allowing any language to compete.

Also, some more test cases would be helpful in order to test our submissions.

If I am not wrong, by increasing 43 by 7, you get 14/4+50/9 which is higher than 9 (i.e. 9.0(5)). If the expected result is always int(a/4+i/9 + 1), then the whole answer would be [int(a/4+i/9),4,9] for all cases.

@Mr.Xcoder You put 14/4 instead of 13/4. I can confirm that 13/4+50/9>9. Also, I've edited the question in line with your previous suggestions.

Now that you have removed the restriction, I upvoted this challenge

Can we choose the order of the output or does it have to be AC, A', I'?

@Emigna You'll have to use that order, to make it fair on everyone else.

I wasn't suggesting that only I would get to choose the output order of course. I just felt it was worth asking as that would have saved me a byte and maybe would have helped someone else as well. Thanks for the answer.

@Emigna Oh yeah, I understand. just answered in a way that I felt would justify my choice, not pointing fingers at you in any shape or form. Apologies.

Python 2, 61 bytes
def f(a,i):r=a*9+i*4;print r/36,(r+44-i*4)/9-a,(r+39-a*9)/4-i

Try it online!

Python 2, 50 bytes
-1 byte thanks to Mr. Xcoder (print instead of return).
def f(a,i):x=a*9+i*4;m=x%36;print x/36,4-m/9,9-m/4

Try it online!

Switch to print to save 1 byte?

Oh yeah - I always assumed we could only print the result if it is a full program, while a function must actually yield the result. Do you know if there is a consensus?

I have used it many times without problems. I don't know if there is any consensus.

Here's the consensus.

Ah cool, thanks @totallyhuman!

MATL, 25 22 bytes
K9hGy/sktQ3M1YS-b*XkG-

-3 bytes thanks to @LuisMendo
Try it online!

[4 9] can be shortened to K9h, and tGw to Gy: K9hGy/sktQ3M1YS-b*XkG-

@LuisMendo Thanks!

05AB1E, 21 19 18 bytes
94S©*O36‰RĆÁ®÷®RαÁ

Try it online!
Explanation
Example for input = [92, 5]
94                   # push the number 94
  S©                 # split to a list of digits and store a copy in register
                     # STACK: [9,4]
    *                # element-wise multiplication with input
                     # STACK: [828, 20]
     O               # sum
                     # STACK: 848
      36‰            # divmod 36
                     # STACK: [23, 20]
         R           # reverse
          Ć          # append the head (the mod result)
           Á         # rotate right
                     # STACK: [20, 20, 23]
            ®÷       # element-wise integer division with the register
                     # STACK: [2, 5, 23]
              ®Rα    # absolute difference with the register reversed
                     # STACK: [2, 4, 23]
                 Á   # rotate right

JavaScript (ES6), 67 50 bytes

f=
(a,i,r=a*9+i*4)=>[r/36|0,4-(r%36/9|0),9-(r%36>>2)]

Age: <input type=number id=a>
IQ: <input type=number id=i>
Abstract Capacity:
Extra age needed:
Extra IQ needed:

Edit: Although originally I was trying to verify @Mr.Xcoder's comment I ended up verifying @JonathanAllan's answer instead.

61 bytes: (a,i,r=(a*9+i*4))=>[r/36|0,(r+44-i*4)/9-a|0,(r+39-a*9)/4-i|0]. Not 100% sure it is correct, but I believe it is

Pyth, 26 bytes
/K+*9Q*4E36-4/J%K36 9-9/J4

Try it here!

Excel, 89 bytes
=INT(A2/4+B2/9)&" "&ROUNDUP(4-MOD(A2*9+B2*4,36)/9,0)&" "&ROUNDUP(9-MOD(A2*9+B2*4,36)/4,0)

Using @Jonathan Allan's approach.

Java 8, 77 67 bytes
Nicked from @JonathanAllan
a->i->System.out.printf("%d %d %d",(i=a*9+i*4)/36,4-i/9%4,9-i/4%9);

67 bytes: a->i->System.out.printf("%d %d %d",(i=a*9+i*4)/36,4-i/9%4,9-i/4%9);.


text:
Braille graphics
Cut a boolean matrix in 4x2 blocks and render them as Braille characters U+2800...U+28FF.
[[0,1,0,0,1,0],
 [1,0,0,0,0,0],
 [1,0,0,0,1,0],
 [1,1,1,1,0,0]]

⣎⣀⠅

Pad with 0-s if dimensions are not multiples of 4 and 2.
[[0,1,0],
 [1,0,0],
 [1,1,1]]

⠮⠄

Usual golfing rules apply, flexible on input format. Output should either have the structure of a matrix or look like a matrix, e.g. list of strings; single string with newlines.
Hint: chr(0x2800 + 128*b7 + 64*b6 + 32*b5 + 16*b4 + 8*b3 + 4*b2 + 2*b1 + b0) is the dot pattern
b0 b3
b1 b4
b2 b5
b6 b7

Larger test:
[[0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0],
 [0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1],
 [0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1],
 [1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1],
 [1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0],
 [1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0],
 [1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0],
 [1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1],
 [1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0],
 [1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0],
 [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0],
 [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0],
 [0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0],
 [0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0],
 [0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0]]

⣰⠟⠻⣦⠀⠠⠾⡇⢠⡞⢛⡆
⣿⢠⣬⣥⠄⣀⠀⡇⢈⣻⣈⡀
⣿⠘⢹⡇⡞⠙⡇⣧⡉⢹⡏
⠘⠷⠟⠁⠳⠾⠃⠘⠇⠾⠧

Congrats on second challenge.

Better description: you have a 2D array of Boolean values whose rows represents the horizontal raster lines of a black-and-white (1 bit per pixel) frame buffer or graphics canvas. Encode all of the 4x2 rectangular blocks of this canvas into Unicode Braille characters.  To handle fractional blocks at the edges, pad the canvas's width to a multiple of 2, and height to a multiple of four, with zeros (or otherwise ensure the equivalent output, treating the data as if it were so padded).

@Kaz I don't know, I personally really appreciate how concise this post is. IMO, not a lot of clarity would be added by writing any more (besides a few small clarifications like noting that the height should be a mult of 4 and the width of 2); your suggestion is harder for me to read than the current post.

Jelly,  31  30 bytes
sz0Z
ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY

Try it online!
How?
sz0Z - Link 1, split & right-pad with zeros: list, items; number, chunkSize
s    - split items into chunks of length chunkSize
 z0  - transpose with filler zero
   Z - transpose

ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY - Main link: list of lists of numbers (1s & 0s), M
ç€2                       - call the last link (1) as a dyad for €ach (left=M, right=2)
                          -  ((left,right) bits read left-right then top-bottom)
   Z                      - transpose the resulting list of lists of lists
                          -  ((left, right) bits read top-bottom then left-right)
    F€                    - flatten €ach
      ç€8                 - call the last link (1) as a dyad for €ach (left=^, right=8)
         Z                - transpose the resulting list of lists of lists
                          -  ("blocks" each and all read left-right top-to bottom)
               -36        - literal -36
             €€           - for €ach (block-wise row) for €ach (block)
          œ?@             -   lexicographical permutation with reversed arguments
                          -    (get the permutation at index -36 (modular) in a list of
                          -     all permutations of the indexes sorted lexicographically.
                          -     That is the 8!-36 = 40284th - equivalently the values at
                          -     indexes [8,7,6,4,2,5,3,1])
                  Ḅ       - convert from binary list to integer (vectorises)
                    ⁽$ṁ   - base 250 literal = 10240
                   +      - add
                       Ọ  - cast to character (vectorises)
                        Y - join with newlines
                          - implicit print

Does Ḅ support "digits" greater than 1? Instead of adding 10240 (0x2800 - two bytes) to the result, you could prepend 40 (0x28 - one byte) to the vector of binary digits. I don't know much about Jelly, so I'm not sure if this would really work.

Ḅ would indeed convert a leading digit of 40 as you suggest, but we'd need to prepend it to each such list (at a depth of 2) which, I think, would require more bytes of code (;@€€40Ḅ).

Mathematica, 126 110 97 90
FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]&

This solution takes advantage of ListCorrelate to convolve a (reversed) kernel over a matrix, which is essentially a sliding matrix multiplication (or dot product). See a visual explanation here. Padding is done by using 0 as the fourth argument. In the following example, we expect the result to match the hint above:
ListCorrelate[
  2^{{0, 3}, {1, 4}, {2, 5}, {6, 7}},
  {{b0, b3}, {b1, b4}, {b2, b5}, {b6, b7}}
]

(* returns {{b0 + 2 b1 + 4 b2 + 8 b3 + 16 b4 + 32 b5 + 64 b6 + 128 b7}} *)

Note that ListConvolve is not any shorter, since the third argument would be -1.
Since this applies the kernel at every position of the matrix, we just need to extract the elements in every fourth row and second column. We use shorthands for Span and Part: [[;;;;4,;;;;2]].
Helpfully, FromCharacterCode can take a matrix of character codes and return a list of strings.

This solution returns a list of strings, which is one of the allowed output formats. Simply prepend Column@ for the output to “look like a matrix.”

You can play around with this in a free online Mathematica notebook. Go here, click Create a New Notebook, wait a moment, paste in this code, then press shift+enter.
m1={{0,1,0,0,1,0},{1,0,0,0,0,0},{1,0,0,0,1,0},{1,1,1,1,0,0}};
m2={{0,1,0},{1,0,0},{1,1,1}};
m3={{0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0},{0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1},{0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1},{1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0},{1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0},{1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0},{1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1},{1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0},{1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0},{0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0},{0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0},{0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0}};

MatrixToBraille := Column@
  FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]&

MatrixToBraille/@{m1,m2,m3}

Then you should see this:

(recently Wolfram cloud requires user sign in, but that code works on TIO as well; however I didn't figure out how to get it to print Unicode characters)

JavaScript ES7 210 207 201 200 198 194 185 183 bytes
a=>eval('for(y=0,c="";A=a[y];y+=4,c+=`\n`)for(x=0;A[x]+1;x+=2)c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(X,Y=3)=>(a[Y+y]||0)[X+x]|0)(k>2,k%3)*2**k")|g(0)+g(1)*2<<6)')

4 bytes saved thanks to ngn
3 bytes saved thanks to Luke
How it works
I'm going to split the code up into parts and speak about them separately:
for(y=x=0, c=""; a[y]; x+=2)
    !((a[y] || [])[x]+1) && (y+=4,x=0,c+=`\n`)

This is where every variable gets declared. x and y is the position of the "cursor" (the upper left edge of the current braille character). The x coordinate increases by 2 every iteration, and it stops, when there's no row with the index y (a[x] returns undefined if it doesn't exist, which gets converted to false).
There are multiple tricks in the second row. (a[y] || [])[x] ensures that looking up the value at the (x, y) position doesn't throw an error. The && is the usual and operator, and it only checks the right side of the expression, if the left was true. This can be translated to
if (!((a[y] || [])[x] + 1))
    y+=4,x=0,c+=`\n`

The next part:
c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k,N")+g(x,y+3)*64+g(x+1,y+3)*128)

String.fromCharCode simply converts the passed number to a unicode character with the same character code. The expression in the parentheses calculates the index of the Braille character:
for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k

Goes through the position in the
1 4
2 5
3 6

order, multiplies the values at those positions with 2i, where i is the index and adds them together. The
g=(x,y)=>(a[y]||[])[x]||0

part declares a lambda function called g, which given an x and y coordinate returns either the value at the (x, y) position or 0 if the position lies outside the bounds of the array.
+g(x,y+3)*64+g(x+1,y+3)*128

This part adds up the last two positions with the correct weights using the function defined a bit earlier.
Last but not least, the
a=>eval('...')

part has 2 functions. It defines an anonymous lambda and ensures, that the for loop doesn't cause any problems (a single line lambda such as this one can't contain a single for loop only, an evaluation circumvents this).

a few simple suggestions: ||0 -> |0; ~~(k/3) -> (k>2); *128 -> <<7 (replacing +-s with |-s)

Why not submit the ES7 version as your primary solution?

@Shaggy Not everyone can run ES7 yet, so it's a backup

That's irrelevant 'round these parts ;) As long as there is one, single interpreter (browser) that can run your code properly, it's considered to be valid here.

@ngn Thanks for the first two, but bit shifting has a lower precedence than basically anything, so that won't work

@Shaggy I started with ES6, but then realized I could save a couple of bytes with a technique and I could utilize ES7 there, but here you go, removed

Sorry, shaky hands on a touchscreen posted my last comment before I could add: Submit the ES7 one as your main solution and, if you feel it's worth it, the ES6 one as the backup.

@JonathanAllan Thanks, forgot to add the next one

I saved 10 bytes: a=>eval('for(y=x=0,c="";A=a[y]||[];A[x+=2]<0||(y+=4,x=0,c+="\n"))c+=String.fromCharCode(10240+eval("for(N=k=0;++k<6;)N+=(g=(X,Y=3)=>(a[Y+y]||[])[X+x]|0)(k>2,k%3)*2**k")+g(0)*64+g(1)*128)')

@Bálint as I mentioned in brackets, for <<7 you'd have to replace some +-s with |-s: ...+g(0,3)*64+g(1,3)*128... -> ...|g(0,3)*64|g(1,3)<<7...; shifting has higher precedence than bitwise or - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

@Luke that doesn't really work. If you insert ||[] after A=a[y], then the loop won't stop. Thanks for the Y=3 one though

@ngn Right, fixed

Dyalog APL, 133 122 114 112 101 100 98 95 94 93 90 88 86 bytes
Assumes ⎕IO←0
{C⍴{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨(,b)/,⍳⍴b←{0 0≡A|⍵}¨⍳⍴S←⍵↑⍨A×C←⌈(⍴⍵)÷A←4 2}

-8 9 12 bytes thanks to @Adám in chat
-2 bytes thanks to @ngn
Try it online!
How (input is ⍵)?

A←4 2, store the vector 4 2 in variable A
(⍴⍵)÷, the dimensions of ⍵ divided by A
⌈, ceiling
C←, stored in C
A×, multiplied by A
⍵↑⍨, fit ⍵ to those dimensions
S←, stored in S
⍳⍴, indexes of S
{0 0≡A|⍵}¨, 1 where the top left of a cell is, 0 everywhere else
(,b)/,⍳⍴b←, truthy indexes
{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨, turn each element into braille
C⍴, reshape the dimensions to C

consider +/(2*0 3 1,A,4+⍳3)×something → 2⊥something[⍎¨⍕76524130]

WOuld that still work now that I changed it to ⎕IO←0?

Actually, it would only work in ⎕IO←0 :)

I tried that, am I doing something wrong? https://tio.run/##RU87CsJAEO33FFsmuOLko9YhELCyCKIgFopgI2grmlaiuKKFWFsI6VXSx5vMReKLwcjA7vvMm9kdL@f16Wo8X8zynI@XTpe3JxKij8uVLdZPUpYiVZ4loor/9bLAxQBJRzpV8pdGCSECuGsf5hrLen4oLbJdqtm8vxsc70M@pKwT1q8a60eWeOaQ9TGDcGm3mrZrOTSKssRQE7Oh0IFBk2IiSeLdzdsgGBXdhRHCAOftGRO999Uv@CE2YEE236n3/aMdCTwFMJD9Cg3y/AM

Sorry, I forgot about this stupid thing (⎕IO) in APL. For ⎕IO←1, of course you'd have to add 1 to each digit of 76524130.

Are those something's different?

It seems something is fine, but the permutation (76524130) must be different.

it should work with 76531420

Python 2 + drawille, 141 125 120 116 bytes
Saved 16 bytes thanks to ngn and L3viathan
Saved 5 bytes thanks to L3viathan
Saved 4 bytes thanks to ngn
from drawille import*
def a(d,c=Canvas(),e=enumerate):[c.set(j,i)for i,x in e(d)for j,y in e(x)if y];print c.frame()

Try it online!
tio does not have drawille installed so it does not work

Python and its batteries! :) Doesn't fail to surprise me. You can shrink this to under 120 bytes if you use enumerate() and a list comprehension.

Save a couple of bytes by making the function a one-liner: def b(d,c=l.Canvas()):print([c.set(j,i)for i,x in enumerate(d)for j,y in enumerate(x)if y]and c).frame()

Got it to 120 bytes

you don't need the and c trick - the comprehension could be a statement on its own followed by ;print c.frame()

JavaScript, 136 bytes
a=>(b=a.map(x=>[]),a.map((l,i)=>l.map((c,j)=>b[i>>2][j>>1]|=c<<'01263457'[i%4+j*4%8])),b.map(l=>l.map(c=>String.fromCharCode(10240+c))))

Thanks to ngn, using bit shifts save 4 bytes.

you can use bit shifts like i/4|0 -> i>>2

c*2** is a bit shift, too :)

APL (Dyalog), 57 54 bytes*
-3 thanks to OP. Prompts for Boolean matrix. Prints character matrix.
1↓⎕UCS{2⊥40,⌽(,⍉3↑⍵),⊢⌿⍵}⌺(2 2⍴4 2)⊢0⍪⍣3⍪∘0⍣3⊢⎕,0

Try it online!
⎕,0 append a zero on right (ignored if even number of columns)
⊢ yield that (to separate 3 and ⎕)
⍪∘0⍣3 append zeros on bottom thrice (because ⌺ drops partial windows)
0⍪⍣3 stack zeros on top thrice (because ⌺ starts in the top left corner)
⊢ yield that (separates the parenthesis and the 0)
{…}⌺(2 2⍴4 2) on each 4-row 2-column window, with 4-row vertical and 2 row horizontal step:
 ⊢⌿⍵ last row (lit. vertical right reduction); [b6,b7]
 (…), prepend:
  3↑ take three rows; [[b0,b3],[b1,b4],[b2,b5]]
  ⍉ transpose; [[b0,b1,b2],[b3,b4,b5]]
  , ravel; [b0,b1,b2,b3,b4,b5]
 now we have [b0,b1,b2,b3,b4,b5,b6,b7]
 ⌽ reverse; [b7,b6,b5,b4,b3,b2,b1,b0]
 40, prepend 40 (for 40×29 = 10240); [40,b7,b6,b5,b4,b3,b2,b1,b0]
 2⊥ evaluate as base-2 (binary)
⎕UCS convert to character
1↓ drop the first row (all-zero because of ⌺'s padding)

* In Classic, counting ⌺ as ⎕U233A.

There's an easy way to save a few bytes, see my comment under the Jelly solution.

There must be a mistake - the TIO link doesn't match the code you posted here.

it's the zero-padding code near the end: 0⍪⍣3⍪∘0⍣3⊢⎕,0 vs 0⍪∘0⍣3⊢⎕,0

@ngn Fixed, but I have a feeling that ⍪∘0⍣3 and ,0 are only needed due to a bug in ⌺, and the first one isn't needed for your test cases.

My test cases aren't exhaustive - the solution should, of course, work for any valid input. You can shorten 0⍪⍣3⍪∘0⍣3⊢⍵,0 to 0(⊖⍪)⍣6⊢⍵,0.

Haskell, 145 bytes
(a!b)c=take b$c++repeat a
r([]:_)=[]
r l=['⠀'..]!!(sum.zipWith(*)[1,8,2,16,4,32,64,128]$l>>=0!2):r(drop 2<$>l)
b[]=[]
b s=r(([]!4)s):b(drop 4s)

Try it online!

Python 3, 168 165 161 bytes
def f(m):
 while m:
  r,m,s=[*zip(*m)],m[4:],''
  while r:s+=chr(10240+sum(q<<int(w)for(q,w)in zip((r[0]+(0,)*3)[:4]+(r+[()])[1],'01263457')));r=r[2:]
  print(s)

Try it online!

Nicely golfed! You can save three bytes with [*zip(*m[:4])] instead of calling list.

Python 3, 169 bytes
a=[]
y=0
for l in eval(input()):
 y-=1;a+=y%4//3*[-~len(l)//2*[10240]];x=0
 for v in l:a[-1][x//2]|=v<<(6429374>>y%4*6+x%2*3&7);x+=1
for l in a:print(*map(chr,l),sep='')

Try it online!

You can rewrite if y%4<1:a+=-~len(l)//2*[10240], as a+=(y%4<1)*[-~len(l)//2*[10240]] and fit x=0;y+=1 on the same line. I think it saves a byte.

@ngn saved a few more bytes from there on out, thank you!

APL (Dyalog), 53 bytes
4 2∘{⎕ucs 2⊥40⍪(⍎¨⍕76531420)∘.⊃,¨⍺∘↑¨↓∘⍵¨⍺∘×¨⍳⌈⍺÷⍨⍴⍵}

Try it online!

Perl 5, 164 bytes
163 bytes of code + 1 flag -p
@a=eval}{for(;$r<@a;$r+=4){for($c=0;$c<@{$a[0]};$c+=2){$n="0b";map$n.=0|$a[$r+3][$c+$_],1,0;for$y(1,0){map$n.=0|$a[$r+$_][$c+$y],2,1,0}$\.=chr 0x2800+oct$n}$\.=$/}

Try it online!
Takes each row comma separated on one line.


text:
Circularly moving sum
Inspired by a question at Stack Overflow.
Given a non-empty array of integers x and a positive integer n, compute the sum of each sliding block of length n along the array x, circularly filling the missing values at the left with values from the right as follows:

the first block contains the first entry of x, preceded by n-1 circularly shifted entries;
the second block has the first and second entries of x, preceded by n-2 circularly shifted entries; and so on.

The output array y has the same size as x. It is possible for n to exceed the length of x, and then the values of x are circularly reused several times.
Examples
Example 1 (values are reused only once)
x = [2, 4, -3, 0, -4]
n = 3

give as output
y = [-2, 2, 3, 1, -7]

where

-2 is the sum of the block [0, -4, 2] (the first two values come from the circular shifting)
2 is the sum of [-4, 2, 4] (the first value comes from the circular shifting)
3 is the sum of [2, 4, -3] (no circular shifting necessary anymore)
1 is the sum of [4, -3, 0]
-7 is the sum of [-3, 0, -4].

Example 2 (values are reused several times)
x = [1, 2]
n = 5

give
y = [7, 8]

where

7 is the sum of the block [1, 2, 1, 2, 1] (the first four values have been circularly reused)
8 is the sum of the block [2, 1, 2, 1, 2] (the first three values have been circularly reused)

Additional rules

The algorithm should work for arrays of arbitrary size and for arbitrary integer values. It is acceptable if the program is limited by data type or memory restrictions; but positive as well as negative integer values must be handled.
Input/output can be taken/produced by any reasonable means.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.

Test cases
x, n, -> y

[2, 4, -3, 0, -4], 3          ->  [-2, 2, 3, 1, -7]
[1, 2], 5                     ->  [7, 8]
[2], 7                        ->  [14]
[-5, 4, 0, 1, 0, -10, -4], 4  ->  [-19, -15, -5, 0, 5, -9, -13]
[-5, 4, 0, 1, 0, -10, -4], 1  ->  [-5, 4, 0, 1, 0, -10, -4]
[-2, -1, 0, 1, 2, 3], 5       ->  [4, 3, 2, 1, 0, 5]
[-10, 0, 10], 4               ->  [-10, 0, 10]

Bah, why did you have to use preceding entries?

Jelly, 5 bytes
ṙC€}S

Try it online!
How it works
ṙC€}S  Main link. Arguments: A (array), n (positive integer)

   }   Apply the link to the left to the right argument (n).
 C€      Complement each; map (z -> 1-z) over [1, ..., n], yielding [0, ..., 1-n].
ṙ      Rotate A 0, ..., 1-n units to the left (i.e., 0, ..., n-1 units to the
       right), yielding a 2D array.
    S  Take the sum of the rows.

MATL, 11 10 9 7 bytes
3 Bytes saved thanks to @Luis!
:gyn&Z+

The first input is the size of the window and the second input is the array
Try it at MATL Online
Explanation
       % Implicitly grab the first input (n)
       %     STACK: { 3 }
:      % Create the array [1...n]
       %     STACK: { [1, 2, 3] }
g      % Convert it to a logical array, yielding an array of 1's of length n
       %     STACK: { [1, 1, 1] }
y      % Implicitly grab the second input and duplicate it
       %     STACK: { [2, 4, -3, 0, -4], [1, 1, 1], [2, 4, -3, 0, -4]}
n      % Determine the length of the array
       %     STACK: { [2, 4, -3, 0, -4], [1, 1, 1], 5}
&Z+    % Perform circular convolution
       %     STACK: { [-2, 2, 3, 1, -7] }
       % Implicitly display the result

Mathematica, 29 bytes
RotateLeft[#,1-n]~Sum~{n,#2}&

Or the same length:
ListConvolve[1~Table~#2,#,1]&

CJam (16 bytes)
{_2$*ew1fb\,~)>}

Online test suite. This is an anonymous block (function) which takes the array and the length on the stack and leaves an array on the stack.
Dissection
{       e# Declare a block
  _2$*  e#   Repeat the array n times: this guarantees having enough windows even
        e#   if x is only a single element
  ew    e#   Take each window of n elements
  1fb   e#   Sum each of the windows
  \,~)  e#   Compute -n
  >     e#   Take the last n elements of the array of sums
}

Haskell, 57 bytes
a#n|l<-length a=[sum[a!!mod j l|j<-[i-n..i-1]]|i<-[1..l]]

Try it online!
Just some index looping and accessing the input list at indices modulo the length of the list.

Haskell, 69 65 64 bytes
r=reverse
s#n=r$init[sum$take n$x++cycle(r s)|x<-scanr(:)[]$r s]

Try it online! Example usage: [2, 4, -3, 0, -4] # 3.

Using n succeeding instead of preceding entries could be 50 46 bytes (getting rid of the reverse at the beginning and the end):
s#n=init[sum$take n$x++cycle s|x<-scanr(:)[]s]

Try it online!

05AB1E, 10 bytes
.×ŒùOR¹g£R

Try it online!
Explanation
.×           # repeat input_1 input_2 times
  Œù         # push all sublists of size input_2
    O        # sum each
     R       # reverse the list
      ¹g£    # take the first len(input_1) items
         R   # reverse the list

Pyth, 18 16 bytes
Saved 2 bytes thanks to @FryAmTheEggman!
JEms<.>*JQ-JhdJl

Try it here or Verify all the test cases.
Fixed all the flaws at a cost of -6 bytes! Thanks a lot to Luis for making me understand the task in chat.

Explanation (to be updated)
KEms<>_*QhK-lQhdKU - Full program.

KE                 - Assign the second input to a variable K.
  m              U - Map over the range [0...len(first input)).
       *QhK        - First input * (Second input + 1).
      _            - Reverse.
     >     -lQhd   - All the elements of the above after len(x)-current element-1
    <          K   - Up until the second input.
   s               - Sum.

Might be a better way before reversing, trying to golf soon.

Got 16 bytes but I feel like there should still be something shorter.

@FryAmTheEggman Thanks. I feel it should be shorter but I cannot figure out how

Japt, 12 bytes
ËVo rÈ+UgE-Z

Try it online!
TIO doesn't support the Ë, so the TIO link won't work. Instead, try it here.

Kotlin, 141 140 138 bytes
Just a first go
Submission
fun c(a:List<Int>,n:Int):List<Int>{
return (0..(a.size-1)).map{var t=0
for (o in 0..(n-1)){var i=it-o
while(i<0) {i+=a.size};t+=a[i]}
t}}

Beautified
fun c(a: List<Int>, n: Int): List<Int> {
    return (0..(a.size - 1)).map {    // Iterate over the items
        var t = 0                     // Start the total at 0
        for (o in 0..(n - 1)) {       // Start at the item, go over the window backwards
            var i = it - o            // -------------------------
            while (i < 0) {           //  Make the index in range
                i += a.size           //
            }                         // -------------------------
            t += a[i]                 // Add the item to the total
        }
        t                             // Return the total
    }
}

TryItOnline
Edits

Removed newline on before last closing bracket

Java 8, 102 bytes
Lambda (curried) from int[] to lambda from Integer to int[]. Assign to Function<int[], Function<Integer, int[]>>.
a->n->{int l=a.length,o[]=new int[l],i=0,j;for(;i<l;i++)for(j=i-n;j++<i;)o[i]+=a[(j%l+l)%l];return o;}

Try It Online
Ungolfed lambda
a ->
    n -> {
        int
            l = a.length,
            o[] = new int[l],
            i = 0,
            j
        ;
        for (; i < l; i++)
            for (j = i - n; j++ < i; )
                o[i] += a[(j % l + l) % l];
        return o;
    }

(j % l + l) % l computes a nonnegative remainder for any j. Taken from here.

C, 91 bytes
i,j,k,s;f(a,l,n)int*a;{for(i=0;i<l;printf("%d ",s))for(j=n*l+i++,k=n,s=0;k--;)s+=a[j--%l];}

Try it online!

Octave, 53 bytes
@(x,n)shift(imfilter(x,+!!(1:n),'circular'),fix(n/2))

Try it online!

The imfilter function with option circular computes the circular convolution at the center of window so the result should be shifted.

Perl 6, 42 39 bytes
{@^a;[«+»] map {@a.rotate(-$_)},^$^b}

Try it online!
My first Perl 6 entry. Can probably be improved.

Note that you can sometimes reduce the length by using a pointy block with sigilless variables rather than a block with placeholder parameters ->\a,\b{[«+»] map {a.rotate(-$_)},^b} Note that it doesn't in this case but it would if there was another instance of $b in the code.

Perl 5, 66 + 1 (-a) = 67 bytes
$n=pop@F;$,=$";say map{$q=$c++;$t=0;$t+=$F[$q--%@F]for 1..$n;$t}@F

Try it online!

R, 101 93 89 bytes
function(x,n,w=sum(x|1)){for(j in 1:w)F=c(F,sum(c(tail(rep(x,n),n-1),x)[1:n+j-1]))
F[-1]}

Try it online!

Python 2, 69 61 bytes
- 8 bytes Thanks a lot @muru
lambda x,n:[sum((x[-n+1:]+x*n)[i:i+n])for i in range(len(x))]

Try it online!
Explanation:
First we need to ensure there is enough numbers on the left of the original list, this is acheived by the x*n+x part.
For, example: [2,4,-3,0,4],5:
                   ,2,4,-3,0,-4
 ....-4,2,4,-3,0,-4,2,4,-3,0,-4

Then we shall reverse the list:
 <original->
 -4,0,-3,4,2, -4,0,-3, 4........
           <-2's block->

Next we obtain corresponding blocks for each element by [len(x)+~i:][:n]. The slice will be reverse i.e. 2 will gain a block: [2,-4,0,-3,4] which is reverse of the expected [4,-3,0,-4,2], but we need the sum after all. So, this works. :)

Not sure why you have to reverse first? Can't you modify the slices later on in the reverse direction instead?

@Mr.Xcoder I do think there is a way but this way was less tedious so I sticked with this... :D

I think x[-n+1:]+x*n should give you the list with sufficient padding on either side, without having to reverse (lambda x,n:[sum((x[-n+1:]+x*n)[i:i+n])for i in range(len(x))])

@muru Did you just edit it? Now, it works. Thanks a lot!

JavaScript ES6 80 78 bytes
x=>n=>x.map((_,i)=>eval('for(L=x.length,N=0,j=++i-n;j<i;j++)N+=x[(j%L+L)%L]'))

2 bytes saved thanks to Neil
Usage:
f=x=>n=>x.map((_,i)=>eval('for(L=x.length,N=0,j=++i-n;j<i;j++)N+=x[(j%L+L)%L]'))

f([2, 4, -3, 0, -4])(3)

The ,N looks unnecessary to me...

@Neil You're right, thanks

Röda, 52 bytes
f a,n{(a*n)|slide n|tail#a*n|{head n|sum}while open}

Try it online!
Explanation:
f a,n{
  (a*n)|    /* Push the items in a n times to the stream */
  slide n|  /* Create a sliding block of length n */
  tail#a*n| /* Push the last n*len(a) values in the stream to the stream */
  {         /* While there are elements in the stream (stream is open): */
    head n| /*   Pull n values from the stream */
    sum     /*   Sum them and push the sum to the stream */
  } while open
}

K (oK), 18 bytes
Solution:
{+/+y':(1-y+#x)#x}

Try it online!
Examples:
{+/+y':(1-y+#x)#x}[1 2;5]
7 8
{+/+y':(1-y+#x)#x}[-5 4 0 1 0 -10 -4;4]
-19 -15 -5 0 5 -9 -13
{+/+y':(1-y+#x)#x}[-10 0 10;4]
-10 0 10

Explanation:
Was about to post a 31 byte solution then I remembered that oK has a built-in for sliding windows...
{+/+y':(1-y+#x)#x} / the solution
{                } / lambda with implicit x and y parameters
               #x  / take (#) from list x
       (    #x)    / length of x
          y+       / add y (window size)
        1-         / subtract from 1 to give a negative
    y':            / sliding window of size y
   +               / flip
 +/                / sum

Bonus:
The 31 byte solution that also works in K4:
q)k){+/+x#y#'|+(:':\|(1-y+x:#x)#x)}[2 4 -3 0 -4;3]
-2 2 3 1 -7

Japt, 8 bytes
£gVonY)x

Try it
£gVonY)x     :Implicit input of array U=x & integer V=n
£            :Map each 0-based index Y in U
 g           :  Get the elements in U at 0-based indices
  Vo         :    Range [0,V)
    nY       :    Subtract each from Y
      )      :  End indexing
       x     :  Reduce by addition