Comparing a c++ std::vector's elements with each other - vector

I have a std::vector of double values. Now I need to know if two succeeding elements are within a certain distance in order to process them. I have sorted the vector previously with std::sort.
I have thought about a solution to determine these elements with std::find_if and a lambda expression (c++11), like this:
std::vector<std::vector<double>::iterator> foundElements;
std::vector<double>::iterator foundElement;
while (foundElement != gradients.end())
{
foundElement = std::find_if(gradients.begin(), gradients.end(),
[] (double grad)->bool{
return ...
});
foundElements.push_back(foundElement);
}
But what should the predicate actually return? The plan is that I use the vector of iterators to later modify the vector.
Am I on the right track with this approach or is it too complicated/impossible? What are other, propably more practical solutions?
EDIT: I think I will go after the std::adjacent_find function, as proposed by one answerer.

Read about std::adjacent_find.

Can you enhance the grammar of your question?
"I have a std::vector with different double values. Now I need to know if two succeeding ones (I have sorted the vector previously with std::sort) are within a certain distance to process them)."
Do you imply that each element of a vector of type double is a unique value? If that's the case, can it be reasonably inferred that your goal to find the distance between each of these elements?

Related

Represent stream of vectors

I have a stream of vectors ... then i have N number of vectors to best represent this stream. (smallest dist )
To do that I can use algorithm similar to Self Organizing Maps.. i.e. pick the closest vector and move it closer to the data vector. rinse and repeat.
Now my question is:
I want the number of vectors N to be variable and dynamic. For this I will probably need to maximize/minimize some external function ?
What will that function be ?
I will also probably need rules for when to : Merging, Creating or Deleting vectors

Determine if there exists a number in the array occurring k times

I want to create a divide and conquer algorithm (O(nlgn) runtime) to determine if there exists a number in an array that occurs k times. A constraint on this problem is that only a equality/inequality comparison method is defined on the objects of the array (i.e can't use <, >).
So I have tried a number of approaches including splitting the array into k pieces of equal size (approximately). The approach is similar to finding the majority item in an array, however in the majority case when you split the array, you know that one half must have a majority item if such an item exists. Any pointers or tips that one could provide to put me in the right direction ?
EDIT: To clear up a little, I am wondering whether the problem of finding the majority item by splitting the array in half and using a recursive solution can be extended to other situations where k may be n/4 or n/5 etc.
Maybe I should of phrased the question using n/k instead.
This is impossible. As a simple example of why this is impossible, consider an input with a length-n array, all elements distinct, and k=2. The only way to be sure no element appears twice is to compare every element against every other element, which takes O(n^2) time. Until you perform all possible comparisons, you cannot be sure that some pair you didn't compare isn't actually equal.

Storing the results of double for loop in a vector in R

I have an example code for a double for loop. I am having trouble understanding how
Candles<-c(Candles,c) is storing the results of c<-c+n in a vector. Isn't it concatenating Candles and c. Thank you for explanation.
Name<-c("A","B","C","D","E",
"F","G","H","I","J",
"K","L","M")
Age<-c(15,14,21,24,74,
15,3,37,19,39,
17,2,7)
jjj<-data.frame(Name,Age)
Candles<-c()
for(Age in jjj$Age){
c<-0
for (n in 0:Age){
c<-c+n
}
Candles<-c(Candles,c)
}
Candles
In a short sentence, Candles <- c(Candles, c) can be understood as Candels.append(c) in Python in this case.
It is not overwriting the variable Candles in a way, that the new Candles will contain two elements, and the first element is the old Candle the the second element is the c.
For more information about function c, try:
?"c"
I found the details very helpful:
The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression. Pairlists are treated as lists, but non-vector components (such names and calls) are treated as one-element lists which cannot be unlisted even if recursive = TRUE.
c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector. as.vector is a more intuitive way to do this, but also drops names. Note too that methods other than the default are not required to do this (and they will almost certainly preserve a class attribute).

prolog recursion

am making a function that will send me a list of all possible elemnts .. in each iteration its giving me the last answer .. but after the recursion am only getting the last answer back .. how can i make it give back every single answer ..
thank you
the problem is that am trying to find all possible distributions for a list into other lists .. the code
addIn(_,[],Result,Result).
addIn(C,[Element|Rest],[F|R],Result):-
member( Members , [F|R]),
sumlist( Members, Sum),
sumlist([Element],ElementLength),
Cap is Sum + ElementLength,
(Cap =< Ca,
append([Element], Members,New)....
by calling test .. am getting back all the list of possible answers .. now if i tried to do something that will fail like
bp(3,11,[8,2,4,6,1,8,4],Answer).
it will just enter a while loop .. more over if i changed the
bp(NB,C,OL,A):-
addIn(C,OL,[[],[],[]],A);
bp(NB,C,_,A).
to and instead of Or .. i get error :
ERROR: is/2: Arguments are not
sufficiently instantiated
appreciate the help ..
Thanks alot #hardmath
It sounds like you are trying to write your own version of findall/3, perhaps limited to a special case of an underlying goal. Doing it generally (constructing a list of all solutions to a given goal) in a user-defined Prolog predicate is not possible without resorting to side-effects with assert/retract.
However a number of useful special cases can be implemented without such "tricks". So it would be helpful to know what predicate defines your "all possible elements". [It may also be helpful to state which Prolog implementation you are using, if only so that responses may include links to documentation for that version.]
One important special case is where the "universe" of potential candidates already exists as a list. In that case we are really asking to find the sublist of "all possible elements" that satisfy a particular goal.
findSublist([ ],_,[ ]).
findSublist([H|T],Goal,[H|S]) :-
Goal(H),
!,
findSublist(T,Goal,S).
findSublist([_|T],Goal,S) :-
findSublist(T,Goal,S).
Many Prologs will allow you to pass the name of a predicate Goal around as an "atom", but if you have a specific goal in mind, you can leave out the middle argument and just hardcode your particular condition into the middle clause of a similar implementation.
Added in response to code posted:
I think I have a glimmer of what you are trying to do. It's hard to grasp because you are not going about it in the right way. Your predicate bp/4 has a single recursive clause, variously attempted using either AND or OR syntax to relate a call to addIn/4 to a call to bp/4 itself.
Apparently you expect wrapping bp/4 around addIn/4 in this way will somehow cause addIn/4 to accumulate or iterate over its solutions. It won't. It might help you to see this if we analyze what happens to the arguments of bp/4.
You are calling the formal arguments bp(NB,C,OL,A) with simple integers bound to NB and C, with a list of integers bound to OL, and with A as an unbound "output" Answer. Note that nothing is ever done with the value NB, as it is not passed to addIn/4 and is passed unchanged to the recursive call to bp/4.
Based on the variable names used by addIn/4 and supporting predicate insert/4, my guess is that NB was intended to mean "number of bins". For one thing you set NB = 3 in your test/0 clause, and later you "hardcode" three empty lists in the third argument in calling addIn/4. Whatever Answer you get from bp/4 comes from what addIn/4 is able to do with its first two arguments passed in, C and OL, from bp/4. As we noted, C is an integer and OL a list of integers (at least in the way test/0 calls bp/4).
So let's try to state just what addIn/4 is supposed to do with those arguments. Superficially addIn/4 seems to be structured for self-recursion in a sensible way. Its first clause is a simple termination condition that when the second argument becomes an empty list, unify the third and fourth arguments and that gives "answer" A to its caller.
The second clause for addIn/4 seems to coordinate with that approach. As written it takes the "head" Element off the list in the second argument and tries to find a "bin" in the third argument that Element can be inserted into while keeping the sum of that bin under the "cap" given by C. If everything goes well, eventually all the numbers from OL get assigned to a bin, all the bins have totals under the cap C, and the answer A gets passed back to the caller. The way addIn/4 is written leaves a lot of room for improvement just in basic clarity, but it may be doing what you need it to do.
Which brings us back to the question of how you should collect the answers produced by addIn/4. Perhaps you are happy to print them out one at a time. Perhaps you meant to collect all the solutions produced by addIn/4 into a single list. To finish up the exercise I'll need you to clarify what you really want to do with the Answers from addIn/4.
Let's say you want to print them all out and then stop, with a special case being to print nothing if the arguments being passed in don't allow a solution. Then you'd probably want something of this nature:
newtest :-
addIn(12,[7, 3, 5, 4, 6, 4, 5, 2], Answer),
format("Answer = ~w\n",[Answer]),
fail.
newtest.
This is a standard way of getting predicate addIn/4 to try all possible solutions, and then stop with the "fall-through" success of the second clause of newtest/0.
(Added) Suggestions about coding addIn/4:
It will make the code more readable and maintainable if the variable names are clear. I'd suggest using Cap instead of C as the first argument to addIn/4 and BinSum when you take the sum of items assigned to a "bin". Likewise Bin would be better where you used Members. In the third argument to addIn/4 (in the head of the second clause) you don't need an explicit list structure [F|R] since you never refer to either part F or R by itself. So there I'd use Bins.
Some of your predicate calls don't accomplish much that you cannot do more easily. For example, your second call to sumlist/2 involves a list with one item. Thus the sum is just the same as that item, i.e. ElementLength is the same as Element. Here you could just replace both calls to sumlist/2 with one such call:
sumlist([Element|Bin],BinSum)
and then do your test comparing BinSum with Cap. Similarly your call to append/3 just adjoins the single item Element to the front of the list (I'm calling) Bin, so you could just replace what you have called New with [Element|Bin].
You have used an extra pair of parentheses around the last four subgoals (in the second clause for addIn/4). Since AND is implied for all the subgoals of this clause, using the extra pair of parentheses is unnecessary.
The code for insert/4 isn't shown now, but it could be a source of some unintended "backtracking" in special cases. The better approach would be to have the first call (currently to member/2) be your only point of indeterminacy, i.e. when you choose one of the bins, do it by replacing it with a free variable that gets unified with [Element|Bin] at the next to last step.

Are the x,y and row, col attributes of a two-dimensional array backwards?

If I think of the x,y coordinate plane, x,y is the common notation for an ordered pair, but if I use a two-dime array I have myArray[row][col] and row is the y and col is the x. Is that backwards or am I just thinking about it wrong? I was thinking it would look like myArray[x][y] but that's wrong if I want real rows and columns (like in a gameboard.) Wouldn't it be myArray[y][x] to truly mimic a row column board?
You have it right, and it does feel a bit backwards. The row number is a y coordinate, and the column number is an x coordinate, and yet we usually write row,col but we also usually write x,y.
Whether you want to write your array as [y][x] or [x][y] depends mostly on how much you actually care about the layout of your array in memory (and if you do, what language you use). And whether you want to write functions/methods that can operate on rows or columns in isolation.
If you are writing C/C++ code, arrays are stored in Row Major Order which means that a single row of data can be treated as 1 dimensional array. But a single column of data cannot. If I remember correctly, VB uses column major order, so languages vary. I'd be surprised of C# isn't also row major order, but I don't know.
This is what I do for my own sanity:
int x = array[0].length;
int y = array.length;
And then for every single array call I make, I write:
array[y][x]
This is particulary useful for graphing algorithms and horizontal/vertical matrix flipping.
It doesn't matter how you store your data in the array ([x][y] or [y][x]). What does matter is that you always loop over the array in a contiguous way. A java two dimensional array is essentially a one dimensional array storing the second array (eg. in the case of [y][x] you have a long array of [y] in which each y holds the corresponding [x] arrays for that line of y).
To efficiently run through the whole array, it's important to access the data in a way so that you don't continuously have to do searches in that array, jumping from one y-array-of-xarrays to another y-array-of-xarrays. What you want to do is access one y element and access all the x's in there before moving to the next y element.
So in an Array[y][x] situation. always have the first variable in the outer loop and the second in the inner loop:
for (int ys = 0; ys < Array.length; ys++)
for (int xs = 0; xs < Array[y].length; xs++)
{
do your stuff here
}
And of course pre-allocate both Array.lengths out of the loop to prevent having to get those values every cycle.
I love the question. You’re absolutely right. Most of the time we are either thinking (x, y) or (row, col). It was years before I questioned it. Then one day I realized that I always processed for loops as if x was a row and y was a column, though in plane geometry it’s actually the opposite. As mentioned by many, it really doesn’t matter in most cases, but consistency is a beautiful thing.
Actually, It's up to you. There is no right of thinking in your question. For example i usually think of a one-dimension array as a row of cell. So, in my mind it is array[col][row]. But it is really up to you...
I bet there are a lot of differing opinions on this one. Bottom line is, it doesn't really matter as long as you are consistent. If you have other libraries or similar that is going to use the same data it might make sense to do whatever they do for easier integration.
If this is strictly in your own code, do whatever you feel comfortable with. My personal preference would be to use myArray[y][x]. If they are large, there might be performance benefits of keeping the items that you are going to access a lot at the same time together. But I wouldn't worry about that until at a very late stage if at all.
Well not really, if you think of a row as elements on the x axis and then a 2d array is a bunch of row elements on the y axis, then it's normal to use y to operate on a row, as you already know the x (for that particular row x is always the same, it's y that's changing with its indices) and then use x to operate on the multiple row elements (the rows are stacked vertically, each one at a particular y value)
For better or for worse, the inconsistent notation was inherited from math.
Multidimensional arrays follow matrix notation where Mi,j represents the matrix element on row i and column j.
Multidimensional arrays therefore are not backward if used to represent a matrix, but they will seem backward if used to represent a 2D Cartesian plane where (x, y) is the typical ordering for a coordinate.
Also note that 2D Cartesian planes typically are oriented with the y-axis growing upward. However, that also is backward from how 2D arrays/matrices are typically visualized (and with the coordinate systems for most raster images).

Resources