final Stream<Integer> numbers = Stream.of(5, 3, 2, 7, 3, 13, 7).parallel();
Why the output of the following line is 7?
numbers.reduce(1, (a, b) -> a + b, (x, y) -> x - y));
I have not looked at that link from the comments, but the documentation is pretty clear about identity and it even provides a simple way of testing that:
The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u) is equal to u
So let's simplify your example a bit:
Stream<Integer> numbers = Stream.of(3, 1).parallel();
BiFunction<Integer, Integer, Integer> accumulator = (a, b) -> a + b;
BiFunction<Integer, Integer, Integer> combiner = (x, y) -> x - y;
int result = numbers.reduce(
1,
accumulator,
combiner);
System.out.println(result);
let's say that u = 3 (just a random element from the Stream), thus:
int identity = 1;
int u = 3;
int toTest = combiner.apply(identity, u);
System.out.println(toTest == identity); // must be true, but is false
Even if you think that you would replace identity with zero, that would work; the documentation makes another argument:
Additionally, combiner function must be compatible with the accumulator function; for all u and t, the following must hold:
combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
You can make the same test:
int identity = 0;
int u = 3;
int t = 1;
boolean associativityRespected =
combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t);
System.out.println(associativityRespected); // prints false
Related
For a noise shader I'm looking for a pseudo random number algorithm with 3d vector argument, i.e.,
for every integer vector it returns a value in [0,1].
It should be as fast as possible without producing visual artifacts and giving the same results on every GPU.
Two variants (pseudo code) I found are
rand1(vec3 (x,y,z)){
return xorshift32(x ^ xorshift32(y ^ xorshift32(z)));
}
which already uses 20 arithmetic operations and still has to be casted and normalized and
rand2(vec3 v){
return fract(sin(dot(v, vec3(12.9898, 78.233, ?))) * 43758.5453);
};
which might be faster but uses sin causing precision problems and different results on different GPU's.
Do you know any other algorithms requiring less arithmetic operations?
Thanks in advance.
Edit: Another standard PRNG is XORWOW as implemented in C as
xorwow() {
int x = 123456789, y = 362436069, z = 521288629, w = 88675123, v = 5783321, d = 6615241;
int t = (x ^ (x >> 2));
x = y;
y = z;
z = w;
w = v;
v = (v ^ (v << 4)) ^ (t ^ (t << 1));
return (d += 362437) + v;
}
Can we rewrite it to fit in our context?
func main() {
var a int = 10
var b int = 20
swap(&a,&b)
fmt.Println(a,b)
var c int = 10
var d int = 20
swap2(&c,&d)
fmt.Println(c,d)
}
func swap(x, y *int) {
*x = *y
*y = *x
}
func swap2(x, y *int) {
*x,*y= *y,*x
}
//I want to know why the results are different in these two ways
//20 20
//20 10
The reason why swap2(&c,&d) results in different values being set to c and d is because this function consists of a single assignment statement while swap(&a,&b) consists of two assignment statements. Assignment statements have a particular evaluation order in go. From the language specifications:
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
With this in mind, let's annotate swap(x, y *int):
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1.
*y = *x // 2.
The first assignment statement occurs first, so do that:
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y)
// Now x points to an int with value 20.
*y = *x // 2.
After the first assignment statement finishes, the second assignment statement is run:
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y)
// Now x points to an int with value 20.
*y = *x // 2. (value of int pointed to by y) = (value of int pointed to by x)
// Now y points to an int with value 20.
However, because swap2 uses only a single assignment statement, we have to be careful about what happens in what order. The specifications say that the pointer indirections on the left and the expressions on the right are evaluated at the same time:
// x points to an int with value 10
// y points to an int with value 20
*x,*y = *y,*x
// 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10
Second, the assignments are carried out in left-to-right order. But because we have already evaluated the right-hand side of the statement, those are just values.
// x points to an int with value 10
// y points to an int with value 20
*x,*y = *y,*x
// 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10
// 2. Now x points to an int with value 20, y points to an int with value 10
Put another way, swap2 does the same thing as this function:
swap3(x, y *int) {
valueX := *x
valueY := *y
*x = valueY
*y = valueX
}
The advantage of the form of swap2 is that the function does not explicitly allocate unnecessary temporary variables.
I just want implement multiple if else condition or Below given code in Stream API of java 8.
Greatest Common Divisor Code using recursion Logic -:
if(a == b)
return a;
if(a%b == 0)
return b;
if(b%a == 0)
return a;
if(a>b)
return (gcd(a%b,b));
else
return(gcd(a,b%a));
// gcd (int a,int b) is a function
Streams are not a good choice for replacing recursion or iteration where the state of each iteration depends on the previous one. You can use Streams, but as you can see, it's pretty horrible.
public static int gcd(int a, int b) {
int[][] pair = {{a, b}};
return IntStream.of(
IntStream.range(0, Math.min(a, b))
.mapToObj(i -> pair[0] = (pair[0][0] > pair[0][1]
? new int[]{pair[0][0] % pair[0][1], pair[0][1]}
: new int[]{pair[0][0], pair[0][1] % pair[0][0]}))
.filter(p -> p[0] == 0 || p[1] == 0)
.findAny().orElse(new int[2]))
.max()
.orElse(0);
}
Given a list of size n, Write a program that returns all possible combination of elements contained in each list.
Example:
List A = "x, z"
List B = "a, b, c"
List C = "o, p"
Output:
x a o
x a p
x b o
x b p
.....
z c p
Order doesn't matter, but the hard part is: You can't use recursion.
My solution:
void combos(const char *string)
{
int i, j, k;
int len = strlen(string);
for (i = 0; i < len - 2; i++)
{
for (j = i + 1; j < len - 1; j++)
{
for (k = j + 1; k < len; k++)
printf("%c%c%c\n", string[i], string[j], string[k]);
}
}
}
As you can see, it only works if I know the number of lists before hand. I am curious if recursion is the only way to solve it.
Think of it like how you increment a number, e.g. a base 3 number would go:
000
001
002
010
011
...
222
Now think of each digit being the index into each of the nested lists. You will have as many digits as you have nested lists, i.e. the size of the outer list.
The "base" of each digit may differ, and is the size of the corresponding nested list. A "digit" can be a very large number if a nested list is large.
So, you start by creating a list of "digit", or index values, initializing them to 0. You then print the values of the elements at those indices. You then increment the last index value, rolling over as needed, like you would a normal number, stopping when the first index value rolls over.
Here is a Java implementation using arrays of arrays, i.e. String[][]. You can easily change to List<List<String>> or List<String[]> if needed.
#SafeVarargs
public static void printCombos(String[] ... lists) {
if (lists.length == 0)
throw new IllegalArgumentException("No lists given");
for (String[] list : lists)
if (list.length == 0)
throw new IllegalArgumentException("List is empty");
int[] idx = new int[lists.length];
for (;;) {
// Print combo
for (int i = 0; i < lists.length; i++) {
if (i != 0)
System.out.print(' ');
System.out.print(lists[i][idx[i]]);
}
System.out.println();
// Advance to next combination
for (int i = lists.length - 1; ++idx[i] == lists[i].length; ) {
idx[i] = 0;
if (--i < 0)
return; // We're done
}
}
}
public static void main(String[] args) {
String[][] data = { { "x", "z" }, { "a", "b", "c" }, { "o", "p" } };
printCombos(data);
}
OUTPUT
x a o
x a p
x b o
x b p
x c o
x c p
z a o
z a p
z b o
z b p
z c o
z c p
If you use lists instead of arrays, then the code will use get(int), which may not always be good for performance, e.g. for LinkedList.
If that is the case, replace int[] idx with an Iterator[], initializing each array entry with an iterator for the corresponding list. Resetting a "digit" to 0 would then be done by retrieving a new Iterator from the list in question.
In this case, they don't even have to be lists, but can be any kind of collection, or more specifically Iterable objects.
You do not need recursion. All you need to do is build up a set of intermediate solutions. Here is a non-recursive solution in Python:
# This does NOT use recursion!
def all_comb(list_of_lists):
# We start with a list of just the empty set.
answer = [[]]
for list in list_of_lists:
# new_answer will be the list of combinations including this one.
new_answer = []
# Build up the new answer.
for thing in list:
for prev_list in answer:
new_answer.append(prev_list + [thing])
# Replace the old answer with the new one.
answer = new_answer
# We now have all combinations of all lists.
return answer
# Demonstration that it works.
for comb in all_comb([["x", "y"], ["a", "b", "c"], ["o", "p"]]):
print(" ".join(comb))
Edit: I'm answering this in python, because, although it's currently tagged language-agnostic, python is a good, executable pseudo-pseudocode.
If you can write the function in a form that is Tail-recursive, i.e. in a form that looks like def f(x): return f(g(x)), it's easy to turn it into an iterative form. Unfortunately, you usually won't end up with a tail-recursive call, so you need to know a couple of tricks.
First of all, let's say we have a function that looks like this:
def my_map(func, my_list):
if not my_list:
return []
return [func(my_list[0])] + change_my_list(my_list[1:])
Ok, so it's recursive, but not tail recursive: it's really
def my_map(func, my_list):
if not my_list:
return []
result = [func(my_list[0])] + change_my_list(my_list[1:])
return result
Instead, we need to adjust the function slightly, adding what is traditionally known as an accumulator:
def my_map(func, my_list, acc = [])
if not my_list: return acc
acc = acc + func(my_list[0])
return my_map(func, my_list[1:], acc + func(my_list[0]))
Now, we have a truly tail-recursive function: we've gone from def f(x): return g(f(x)) to def f(x): return f(g(x))
Now, it's quite simple to turn that function into a non-recursive form:
def my_map(func, my_list, acc=[]):
while True: #added
if not my_list: return acc
#return my_map(func, my_list[1:], acc + func(my_list[0])) #deleted
func, my_list, acc = func, my_list[1:], acc + func(my_list[0]) #added
Now, we just tidy up a little bit:
def my_map(func, my_list):
acc = []
while my_list:
acc.append(func(my_list[0])
my_list = my_list[1:]
return acc
Note you can clean it up even further using a for loop or a list comprehension, but that's left as an exercise for the reader.
Ok, so this was a pathological example, hopefully you'd know that python has a builtin map function, but the process is the same: transform into a tail recursive form, replace the recursive call with argument reassignment, and tidy up.
So, if you have:
def make_products(list_of_lists):
if not list_of_lists: return []
first_list = list_of_lists[0]
rest = list_of_lists[1:]
return product_of(first_list, make_products(rest))
You can convert it into a tail recursive form
def make_products(list_of_lists, acc=[]):
if not list_of_lists: return acc
first_list = list_of_lists[0]
rest = list_of_lists[1:]
acc = product_of(acc, first_list)
return make_products(rest, acc)
Then, that simplifies to:
def make_products(list_of_lists):
acc=[]
while list_of_lists:
first_list = list_of_lists[0]
rest = list_of_lists[1:]
acc = product_of(acc, first_list)
list_of_lists = rest
return acc
Again, this can be cleaned up further, into a for loop:
def make_products(list_of_lists):
acc=[]
for lst in list_of_lists:
acc = product_of(acc, lst)
return acc
If you've looked at the builtin functions, you might notice this is somewhat familiar: it's essentially the reduce function:
def reduce(function, iterable, initializer):
acc = initializer
for x in iterable:
acc = function(acc, x)
return acc
So, the final form is something like
def make_products(list_of_lists):
return reduce(product_of, list_of_lists, []) # the last argument is actually optional here
You then just have to worry about writing the product_of function.
As you know, the usual solution is recursion. However, out of boredom I once wrote a java method multiNext to do this without recursion. multiNext uses an array to keep track of a load of indices in an equivalent system of nested loops.
public static boolean multiNext(int[] current, int[] slotLengths) {
for (int r = current.length - 1; r >= 0; r--) {
if (current[r] < slotLengths[r] - 1) {
current[r]++;
return true;
} else {
current[r] = 0;
}
}
return false;
}
public static void cross(List<List<String>> lists) {
int size = lists.size();
int[] current = new int[size];
int[] slotLengths = new int[size];
for (int i = 0; i < size; i++)
slotLengths[i] = lists.get(i).size();
do {
List<String> temp = new ArrayList<>();
for (int i = 0; i < size; i++)
temp.add(lists.get(i).get(current[i]));
System.out.println(temp);
} while (multiNext(current, slotLengths));
}
public static void main(String[] args) {
cross(Arrays.asList(Arrays.asList("x", "z"), Arrays.asList("a", "b", "c"), Arrays.asList("o", "p")));
}
I have few bolded line segments on x-axis in form of their beginning and ending x-coordinates. Some line segments may be overlapping. How to find the union length of all the line segments.
Example, a line segment is 5,0 to 8,0 and other is 9,0 to 12,0. Both are non overlapping, so sum of length is 3 + 3 = 6.
a line segment is 5,0 to 8,0 and other is 7,0 to 12,0. But they are overlapping for range, 7,0 to 8,0. So union of length is 7.
But the x- coordinates may be floating points.
Represent a line segment as 2 EndPoint object. Each EndPoint object has the form <coordinate, isStartEndPoint>. Put all EndPoint objects of all the line segments together in a list endPointList.
The algorithm:
Sort endPointList, first by coordinate in ascending order, then place the start end points in front of the tail end points (regardless of which segment, since it doesn't matter - all at the same coordinate).
Loop through the sorted list according to this pseudocode:
prevCoordinate = -Inf
numSegment = 0
unionLength = 0
for (endPoint in endPointList):
if (numSegment > 0):
unionLength += endPoint.coordinate - prevCoordinate
prevCoordinate = endPoint.coordinate
if (endPoint.isStartCoordinate):
numSegment = numSegment + 1
else:
numSegment = numSegment - 1
The numSegment variable will tell whether we are in a segment or not. When it is larger than 0, we are inside some segment, so we can include the distance to the previous end point. If it is 0, it means that the part before the current end point doesn't contain any segment.
The complexity is dominated by the sorting part, since comparison-based sorting algorithm has lower bound of Omega(n log n), while the loop is clearly O(n) at best. So the complexity of the algorithm can be said to be O(n log n) if you choose an O(n log n) comparison-based sorting algorithm.
Use a range tree. A range tree is n log(n), just like the sorted begin/end points, but it has the additional advantage that overlapping ranges will reduce the number of elements (but maybe increase the cost of insertion) Snippet (untested)
struct segment {
struct segment *ll, *rr;
float lo, hi;
};
struct segment * newsegment(float lo, float hi) {
struct segment * ret;
ret = malloc (sizeof *ret);
ret->lo = lo; ret->hi = hi;
ret->ll= ret->rr = NULL;
return ret;
}
struct segment * insert_range(struct segment *root, float lo, float hi)
{
if (!root) return newsegment(lo, hi);
/* non-overlapping(or touching) ranges can be put into the {l,r} subtrees} */
if (hi < root->lo) {
root->ll = insert_range(root->ll, lo, hi);
return root;
}
if (lo > root->hi) {
root->rr = insert_range(root->rr, lo, hi);
return root;
}
/* when we get here, we must have overlap; we can extend the current node
** we also need to check if the broader range overlaps the child nodes
*/
if (lo < root->lo ) {
root->lo = lo;
while (root->ll && root->ll->hi >= root->lo) {
struct segment *tmp;
tmp = root->ll;
root->lo = tmp->lo;
root->ll = tmp->ll;
tmp->ll = NULL;
// freetree(tmp);
}
}
if (hi > root->hi ) {
root->hi = hi;
while (root->rr && root->rr->lo <= root->hi) {
struct segment *tmp;
tmp = root->rr;
root->hi = tmp->hi;
root->rr = tmp->rr;
tmp->rr = NULL;
// freetree(tmp);
}
}
return root;
}
float total_width(struct segment *ptr)
{
float ret;
if (!ptr) return 0.0;
ret = ptr->hi - ptr->lo;
ret += total_width(ptr->ll);
ret += total_width(ptr->rr);
return ret;
}
Here is a solution I just wrote in Haskell and below it is an example of how it can be implemented in the interpreter command prompt. The segments must be presented in the form of a list of tuples [(a,a)]. I hope you can get a sense of the algorithm from the code.
import Data.List
unionSegments segments =
let (x:xs) = sort segments
one_segment = snd x - fst x
in if xs /= []
then if snd x > fst (head xs)
then one_segment - (snd x - fst (head xs)) + unionSegments xs
else one_segment + unionSegments xs
else one_segment
*Main> :load "unionSegments.hs"
[1 of 1] Compiling Main ( unionSegments.hs, interpreted )
Ok, modules loaded: Main.
*Main> unionSegments [(5,8), (7,12)]
7
Java implementation
import java.util.*;
public class HelloWorld{
static void unionLength(int a[][],int sets)
{
TreeMap<Integer,Boolean> t=new TreeMap<>();
for(int i=0;i<sets;i++)
{
t.put(a[i][0],false);
t.put(a[i][1],true);
}
int count=0;
int res=0;
int one=1;
Set set = t.entrySet();
Iterator it = set.iterator();
int prev=0;
while(it.hasNext()) {
if(one==1){
Map.Entry me = (Map.Entry)it.next();
one=0;
prev=(int)me.getKey();
if((boolean)me.getValue()==false)
count++;
else
count--;
}
Map.Entry me = (Map.Entry)it.next();
if(count>0)
res=res+((int)me.getKey()-prev);
if((boolean)me.getValue()==false)
count++;
else
count--;
prev=(int)me.getKey();
}
System.out.println(res);
}
public static void main(String []args){
int a[][]={{0, 4}, {3, 6},{8,10}};
int b[][]={{5, 10}, {8, 12}};
unionLength(a,3);
unionLength(b,2);
}
}