diff --git a/README.md b/README.md index ff3e97a..2f292bf 100644 --- a/README.md +++ b/README.md @@ -48,3 +48,20 @@ Implemented are the following Encoders and Decoders: * [bose_chaudhuri_hocquenghem_encoder.hh](bose_chaudhuri_hocquenghem_encoder.hh) * [bose_chaudhuri_hocquenghem_decoder.hh](bose_chaudhuri_hocquenghem_decoder.hh) +### [exclusive_reduce.hh](exclusive_reduce.hh) + +Reduce N times while excluding ith input element + +It computes the following, but having only O(N) complexity and using O(1) extra storage: + +``` + output[0] = input[1]; + output[1] = input[0]; + for (int i = 2; i < N; ++i) + output[i] = op(input[0], input[1]); + for (int i = 0; i < N; ++i) + for (int j = 2; j < N; ++j) + if (i != j) + output[i] = op(output[i], input[j]); +``` + diff --git a/exclusive_reduce.hh b/exclusive_reduce.hh new file mode 100644 index 0000000..cfb7151 --- /dev/null +++ b/exclusive_reduce.hh @@ -0,0 +1,32 @@ +/* +Reduce N times while excluding ith input element + +Copyright 2018 Ahmet Inan +*/ + +#ifndef EXCLUSIVE_REDUCE_HH +#define EXCLUSIVE_REDUCE_HH + +namespace CODE { + +template +void exclusive_reduce(const TYPE *in, TYPE *out, int N, OPERATOR op) +{ + TYPE pre = in[0]; + for (int i = 1; i < N-1; ++i) { + out[i] = pre; + pre = op(pre, in[i]); + } + out[N-1] = pre; + TYPE suf = in[N-1]; + for (int i = N-2; i > 0; --i) { + out[i] = op(out[i], suf); + suf = op(suf, in[i]); + } + out[0] = suf; +} + +} + +#endif +