FAQ Database Discussion Community


How to directly map/expand object to stream?

java,dictionary,tree,java-8,reduce
Is it possible directly expand an object into a stream? My current approach is: private BigDecimal getNodeScore(Optional<Node> node) { return node.map(Node::getBranches) .orElseGet(Collections::emptySet) .stream() .filter(Branch::isValid) .flatMap(Branch::getLeafs) .map(Leaf::getScore) .reduce(BigDecimal::ZERO, BigDecimal::add); } It works quite well (yes, I know it's ugly.. for now) but is just hate using the orElseGet and steam to...

Javascript: Why array variable assignment is behaving differently inside and outside this function?

javascript,arrays,concat,reduce
For the life of me, I just can't figure out what I'm doing wrong here. I'm trying to use both the reduce and concat array methods to take all of the values of a 2d array and combine them into a single value (basically condense them into a single array...

d3 reduce method is returning NaN

javascript,arrays,date,d3.js,reduce
UPDATE: Added JSFIDDLE, and I updated the original values in this posting to match. The fiddle is not working because the csv is external. I tried this, but couldn't figure it out. But, at least you can see the code. On my machine the console logs at lines 52-54 show:...

Having trouble stepping through function that reduces an array of functions

javascript,functional-programming,reduce,higher-order-functions
When using the reduce method on an array of functions I am having difficulty tracing through how reduce works on the array exactly. comboFunc(num, functionsArr) { return functionsArr.reduce(function (last, current) { return current(last); }, input); } so with functionsArr = [add, multi] and the functions add and multi being function...

Does for..in loop keeps track of orders of its properties for Object?

javascript,arrays,object,functional-programming,reduce
I'm a beginner for programming in general, and JavaScript is my first language. While I was studying, I faced with this concern, and I'm not sure if my concern is appropriate. I thought for..in loop does not keep track of orders when we loop through an Object, because, unlike Arrays,...

Swift Array Running Total to x item

ios,arrays,swift,reduce,running-total
Swift has a great function .reduce that provides a running total for an entire array: let array = [1, 2, 3, 4, 5] let addResult = array.reduce(0) { $0 + $1 } // addResult is 15 let multiplyResult = array.reduce(1) { $0 * $1 } // multiplyResult is 120 But...

Nonassociative reductions with Java Streams

java,java-8,reduce,java-stream
As you may know, the Java Stream API handles reduction operations that are associative; this allows for the possibility that reduction may be performed in parallel through spliteration. However, do we have an analogue for reduction operations that are strictly sequential? Consider this: public interface ExpressionFactory { public Expression createExpression(Expression...

TypeError: Reduce() of empty sequence with no initial value

python,python-3.x,tuples,reduce
I'm currently trying to write a function that will give me a tuple whose 0 index is the amount of lines in that file, and whose 1 index is how many characters are in that file. So far, I have a list of tuples, which looks like this: mapped =...

Data Array Decimation

c,arrays,reduce
I have an array which is changing rapidly and has variable length -this could be 100 minimum and about 5k maximum-. And i'm going to use these values to encolouring a data column that i produce by drawing lines one by one. This will be something like scan graph. And...

Understanding reduce with enumerate for a list of lists

python,list,reduce,enumerate
I am trying to multiply the first number, 1, of the first list, the second number of the second list, 5, and so on for a list of lists. For example, for [[1, 2, 3], [4, 5, 6], [7, 8, 9]], I'd like to get 1*5*9. While there are many...

java 8 reduce accumulator return type

java,dictionary,lambda,java-8,reduce
I need to do a simple traversal over a list of elements, perform some kind of transformation over all of them, and them accumulate all the results in a list. Something like this: List<GraphEdge> edges = new LinkedList<GraphEdge>(); for (CrawlResult result : crawlResults) { edges.addAll(resultToEdges(result)); } This code takes 4...

Remove duplicates based on a key and referenced Objects in Mongodb?

mongodb,dictionary,mongoose,reduce
I have MongoDB models of Actor and Movies. The Mongoose schema of both the models is as following : var ActorsSchema = new Schema({ id : { type : Number }, known_for:[{ type: Schema.Types.ObjectId, ref: 'Movie' }] }) var MovieSchema = new Schema({ genres: [{ type: Schema.Types.ObjectId, ref: 'Genre' }],...

Underscore.js— the relationship between _.contains and _.reduce

javascript,underscore.js,reduce,contain
Can anyone explain how the _.reduce function works within _.contain function? Why is it "false" for the third parameter of the reduce function? _.contains = function(collection, target) { return _.reduce(collection, function(wasFound, item) { if (wasFound) { return true; } return item === target; }, false); };...

Using Reduce in Apache Spark

hadoop,apache-spark,reduce
I am trying to use Apache spark to load up a file, and distribute the file to several nodes in my cluster and then aggregate the results and obtain them. I don't quite understand how to do this. From my understanding the reduce action enables Spark to combine the results...

Grouping hashes together to concat a key's values

ruby,reduce
I have an array of hashes like the following: records = [ { id: "PU525", note: "Foo" }, { id: "PU525", note: "Bar" }, { id: "DT525", note: "Hello World" }, { id: "PU680", note: "Fubar" } ] The end result should be: result = [ { id: "PU525", note:...

How do I flatten nested lists of lists in python?

python,list,reduce,fold
I have created a function to split paths into lists of directories in python like so: splitAllPaths = lambda path: flatten([[splitAllPaths(start), end] if start else end for (start, end) in [os.path.split(path)]]) with this helper function: #these only work one directory deep def flatten(list_of_lists): return list(itertools.chain.from_iterable(list_of_lists)) The output from this function...

Reduce a nested list with varying length

r,list,reduce
Say i have a list: mylist=list(list(data.frame(a=3,b=2,c=4),data.frame(d=5,e=6,h=8),data.frame(k=2,e=3,b=5,m=5)), list(data.frame(a=32,b=22,c=42),data.frame(d=5,e=63,h=82),data.frame(k=2,e=33,b=5,m=5)), list(data.frame(a=33,b=21,k=41,c=41),data.frame(d=5,e=61,h=80),data.frame(k=22,e=3,b=5,m=5))) Then I try to get a new list by cbind each element of the list, for example cbind mylist[[1]][[1]]withmylist[[2]][[1]]andmylist[[3]][[1]] The function: newlist=lapply(seq_along(mylist[[1]]), function(x){...

I don't understand the function Reduce in R

r,reduce
I have a question about the Reduce function in R. I read its documentation, but I am still confused a bit. So, I have 5 vectors with genes name. For example: v1 <- c("geneA","geneB",""...) v2 <- c("geneA","geneC",""...) v3 <- c("geneD","geneE",""...) v4 <- c("geneA","geneE",""...) v5 <- c("geneB","geneC",""...) And I would like...

Why does post-increment fail in .Aggregate(…) but pre-increment succeeds?

c#,linq,aggregate,reduce
I was fiddling with one of my project euler answers to try and make it a bit shorter/cleaner/succinct. I came up with this: Sequences.FibonacciBig() // infinite fib sequence of type BigInteger .TakeWhile(f => f.ToString().Length < 1000) .Aggregate(1, (i, _) => i++); My test failed as the actual was 1, which...

Input of the reduce phase is not what I expect in Hadoop (Java)

java,hadoop,mapreduce,reduce,emit
I'm working on a very simple graph analysis tool in Hadoop using MapReduce. I have a graph that looks like the following (each row represents and edge - in fact, this is a triangle graph): 1 3 3 1 3 2 2 3 Now, I want to use MapReduce to...

Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?

python,list,python-2.7,python-3.x,reduce
I've achived these two things. Find all possible sublists of a list in given range (i ,j). A = [ 44, 55, 66, 77, 88, 99, 11, 22, 33 ] Let, i = 2 and j = 4 Then, Possible sublists of the list "A" in the given range (2,4)...

Error when using reduce() in Swift 2.0

function,swift,reduce,swift2
When I attempt to use the reduce function, I get an error saying: reduce is unavailable: call the 'reduce()' method on the sequence I already figured out how to do this with the enumerate() function but I cannot seem to solve this issue. Here is the line of code returning...

Why does reduce not work on Struct?

swift,struct,reduce
I have the following code struct Tab { var origin:CGFloat var width:CGFloat init(width:CGFloat) { origin = 0 self.width = width } } let subTabs = [Tab(width:1), Tab(width:2)] let w = reduce(subTabs, CGFloat(0), { $0.width + $1.width }) and would expect the reduce to sum up the widths in my struct....

Anonymous parameters working- but not explicit ones - for scala reduceLeft

scala,reduce
Given a simple sequence: scala> val a = Seq(1.0,2.0,3.0) res8: Seq[Double] = List(1.0, 2.0, 3.0) Let us add them up! scala> a.reduceLeft{_ + _} res6: Double = 6.0 But how to be explicit with the parameters? Here is my attempt: scala> a.reduceLeft{case(b,c) => b+c} Well .. no .. We have...

Swift: Reduce Function with a closure

swift,mapkit,reduce
Below is the code that I'm struggling to understand: let rectToDisplay = self.treasures.reduce(MKMapRectNull) { //1 (mapRect: MKMapRect, treasure: Treasure) -> MKMapRect in //2 let treasurePointRect = MKMapRect(origin: treasure.location.mapPoint, size: MKMapSize(width: 0, height: 0)) //3 return MKMapRectUnion(mapRect, treasurePointRect) } My understanding of reduce function is: var people [] // an array...

Results of tbb::parallel_reduce and std::accumulate differ

c++,c++11,reduce,tbb
I am learning Intel's TBB library. When summing all values in a std::vector the result of tbb::parallel_reduce differs from std::accumulate in the case of more than 16.777.220 elements in the vector (errors experienced at 16.777.320 elements). Here is my minimum-working-example: #include <iostream> #include <vector> #include <numeric> #include <limits> #include "tbb/tbb.h"...

How to reduce given list by using Lambda expression .reduce() method

java,filter,lambda,java-8,reduce
List<Integer> integers = Arrays.asList(1, 2, 3, 5, 6, 8, 9, 10); integers.stream().filter((integer) -> integer % 2 == 0).collect(Collectors.toList()); As shown above integers is a List, from which we need to filter only even numbers. I can achieve by using .filter() method. But, is there any possibility to achieve the same...

Reduce, manipulating the initial value

arrays,swift,reduce
I want to create an array or dictionary with reduce() using another array. Normally I would use: class Foo { var number: Int init(number: Int) { self.number = number } } let array1 = [Foo(number: 1), Foo(number: 1), Foo(number: 2)] let array2: [Int] = array1.reduce([]) { $0 + [$1.number] }...

Spark RDD repeated reduce operations yielding inconsistent results

scala,mapreduce,apache-spark,reduce,rdd
Consider the following code in Spark that should return the sum of the sqrt's of a sequence of integers: // Create an RDD of a sequence of integers val data = sc.parallelize(Range(0,100)) // Transform RDD to sequence of Doubles val x = data.map(_.toDouble) // Reduce the sequence as the sum...

How to handle initial nil value for reduce functions

swift,functional-programming,reduce
I would like to learn and use more functional programming in Swift. So, I've been trying various things in playground. I don't understand Reduce, though. The basic textbook examples work, but I can't get my head around this problem. I have an array of strings called "toDoItems". I would like...

Swift: Reduce with closure

swift,reduce
Code: var treasures: [Treasure] = [] treasures = [treasureA, treasureB, treasureC, treasureD, treasureE] let rectToDisplay = self.treasures.reduce(MKMapRectNull) { (mapRect: MKMapRect, treasure: Treasure) -> MKMapRect in // 2 let treasurePointRect = MKMapRect(origin: treasure.location.mapPoint, size: MKMapSize(width: 0, height: 0)) // 3 return MKMapRectUnion(mapRect, treasurePointRect) } In the code above, we are running...

How to resovle rename exception in Pymongo map reduce

python,mongodb,dictionary,reduce
I have a map reduce that runs every hour on my server as a cronjob. I come across an error that prevents the map reduce from completing. This typically happens when I run the map reduce script locally it collides at the same time with the map reduce on the...

How to extension HalfOpenInterval with reduce method

swift,reduce
I hope to extension HalfOpenInterval with reduce method so can easy use some quick code snippet for example: var a = [3,4,9,7] var mini = (0..<a.count).reduce(0, combine: { a[$0] > a[$1] ? $0 : $1 }) I notice that HalfOpenInterval fit IntervalType protocol, but not sure how to iterative each...

Using the reduce method to eliminate any duplicated numbers

javascript,reduce,higher-order-functions
I am trying to use the reduce method as follows to eliminate duplicates however, it is not quite working: var unique = function(array) { array = array.sort(function(a,b) {return a-b;}); var noDup = [array[0]]; array.reduce(function(c,d) { if(c!==d) { noDup.push(d); return d; } }); return noDup; }; var x = [9,2,1,5,9,1,1,4,2,9];//==>[1, 1,...

iOS Swift - Reduce function

ios,swift,reduce
I have a piece of code in SWIFT that I don't understand: var peers: [String:NSSet] = [:] for s in squares { var ps = reduce(units[s]!, NSMutableSet()) { set, u in set.addObjectsFromArray(u) return set } ps.removeObject(s) peers[s] = ps } squares is an array of String. So far I have...

How to average elements in several data frames with unequal size?

r,average,dataframes,reduce
I have a series of text files (100 files) with same structure (same number of columns) that need to be averaged for each element in all files. What I use is this code: my.list<-list() for(j in 1:100){ my.list[[j]]<-read.table(paste('file_',j,'.txt',sep='') ,header=TRUE) } all=Reduce("+", my.list) / length(my.list) This works quit fine when all...

Java8 stream.reduce() with 3 parameters - getting transparency

java,java-8,reduce,java-stream,accumulate
I wrote this code to reduce a list of words to a long count of how many words start with an 'A'. I'm just writing it to learn Java 8, so I'd like to understand it a little better [Disclaimer: I realize this is probably not the best way to...

return sum all numbers in a range

javascript,sorting,reduce
function sumAll(arr) { var list = []; for (var i = arr[0]; i <= arr[1]; i++) { list.push(i); } var total = list.reduce(function(a, b) { return a + b; }); return total; } sumAll([10, 5]); //sumAll([1, 4]); //returns 10 //sumAll([5, 10]); //returns 45 //sumAll([4, 1]); I need to sum every...

reduceByKey with two columns in Spark

python,apache-spark,reduce,pyspark
I am trying to do group by two columns in Spark and am using reduceByKey as follows: pairsWithOnes = (rdd.map(lambda input: (input.column1,input.column2, 1))) print pairsWithOnes.take(20) The above maps command works fine and produces three columns with the third one being all ones. I tried summing the third by the first...

Working With Reducer class in hadoop [duplicate]

java,hadoop,mapreduce,reduce
This question already has an answer here: How do I compare strings in Java? 23 answers I am building a map reduce job. The problem is that comparing is not working correctly. How can I compare these Strings? public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException...

Underscore JS: reducing into an array causes undefined method error on the accumulator

javascript,arrays,underscore.js,reduce
I have code which looks similar to this, which I'm trying to use to produce an array consisting of three sub-arrays: f = [1, 2.5, 3, 10] p = [1.2, 5.1, 6.3, 11] r = [1, 1, 1, 1] coords = _.reduce([f, p, r], function(memo, series){ if(series.length){ memo.push(_.map(series, function(s, i){...

reduce(x+y, xs) and sum(xs) are not equivalent in python?

python,sum,tuples,reduce,equational-reasoning
I would expect the two to mean the same, from a functional equational standpoint, however: x = [1, 2, 3] y = ['a', 'b', 'c'] reduce(lambda x, y: x + y, zip(x, y)) # works sum(zip(x, y)) # fails Why is sum failing here?...

Reduce by key in python

python,reduce
I'm trying to think through the most efficient way to do this in python. Suppose I have a list of tuples: [('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)] And suppose I have a function which takes two of these tuples and combines them: def my_reduce(obj1, obj2): return (obj1[0],max(obj1[1],obj2[1]),min(obj1[2],obj2[2])) How do I...

Cleaner map reduce with Java 8 and a HashMap

java,java-8,reduce,java-stream
Right now I have a HashMap I'm trying to reduce to a total. Here's the current code: HashMap map = new HashMap<String, Long>(); map.put("ex1", 757L); map.put("ex2", 77L); map.values() .stream() .reduce(0L, (a, b) -> a + b); Is there a more elegant way to do this? I'd like to use the...

Apache Spark aggregation through reduce

apache-spark,reduce
I am trying to decide whether to use Apache Spark for a private project, and I am curious how the reduce function in Spark works. The function signature for reduce is reduce(f:(T,T)⇒T). When I have X nodes processing data and then aggregating the resultant data through the use of a...

Return ternary operator in JavaScript reduce

javascript,arrays,indexof,reduce
I have a data structure like this: var example = [ { name: "item1", year: 2013, value: 100 }, { name: "item1", year: 2012, value: 97 }, { name: "item3", year: 2013, value: 93 }, { name: "item3", year: 2012, value: 91 }, { name: "item2", year: 2012, value: -6...

Spark: value reduceByKey is not a member

vector,apache-spark,reduce,mllib
After clustering some sparse vectors I need to find intersection vector in every cluster. To achieve this I try to reduce MLlib vectors as in the following example: import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.mllib.clustering.KMeans import org.apache.spark.mllib.linalg.Vectors //For Sparse Vector import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.mllib.util.MLUtils import org.apache.spark.rdd.RDD import org.apache.spark.mllib.linalg.{Vector, Vectors} object Recommend...

In JavaScript, recursively build a dictionary / nested object from a set of arrays

javascript,arrays,json,recursion,reduce
I feel like a bit of a dummy, but I'm struggling to find a solution to this. I have a set of arrays, and I need to use them to build a JSON-ish object. e.g. [a] [a, b] [a, b, c] [a, b, d] [e] [e, f] [e, f, g]...

How to re-create Underscore.js _.reduce method?

javascript,functional-programming,underscore.js,reduce
For education purposes, I was trying to re-create Underscore.js's _.reduce() method. While I was able to do this in an explicit style using for loops. But this is far from ideal because it mutates the original list that was supplied as an argument, which is dangerous. I also realized that...

Matlab equivalent of Python's 'reduce' function

python,matlab,reduce,equivalent
I have a bunch of matrices of the same size m*n: a, b, c, d, and I'd like to find the maximum of them elementwise, like: mx = max(a, max(b, max(c, d))); apparently the code above is not concise enough, I've googled and didn't find much help about max on...