I found iterable functions, but I am not sure how I can use.
For example, skip, take, map, forEach, fold and join
Could you give me examples how to use?
Yes, let's check the following sample code.
List<int> values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
print(values.skip(5).toList());
//[6, 7, 8, 9]
print(values.skip(5).take(3).toList());
//[6, 7, 8]
values.skip(5).take(3).map((e) => e.toString()).forEach((element) {print(element);});
//6 7 8
String str = values.fold("initialValue",
(previousValue, element) => previousValue + ", " + element.toString());
print(str);
//initialValue, 1, 2, 3, 4, 5, 6, 7, 8, 9
str = values.join(", ");
print(str);
//1, 2, 3, 4, 5, 6, 7, 8, 9
skip(1) skips the first value, 1, in the values list literal.
take(3) gets the next 3 values 2, 3, and 4 in the values list literal.
map() Returns a new lazy [Iterable] with elements that are created by calling f on each element of this Iterable in iteration order.
fork() Reduces a collection to a single value by iteratively combining each element of the collection with an existing value
join() Converts each element to a [String] and concatenates the strings.
Hi Avdienko and welcome to Stack Overflow. I will give you an example for a .forEach iterable function performed on a List.
List<int> listOfIntegers = [1, 2, 3, 4, 5];
listOfIntegers.forEach((element) {
print(element.toString() + " ");
});
This code will result in printing "1 2 3 4 5 " to the console.
Related
I have a list containing few elements like this: [1, 1, 2, 2, 3, 3]. I want to combine these numbers into one number without summing them so I want the final number to be: 112233; Is there a way to do it
You should use list.join() method:
List<int> list = [1, 1, 2, 2, 3, 3];
String concatList = list.join().toString();
print(concatList);
you can use reduce method from list
List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
String s = "";
for(int i in list) {
s += i.toString();
}
int result = int.parse(s); //result = 12345678910
result maximum value is 2^63-1, otherwise you will get an overflow!!!
I would like to get a index of array satisfying the condition.
Then, I'd like to get max of them.
With Ruby:
# normal array
array.index{|n| n>W }
# 2-dimensional array
matrix.map{|arr| arr.index{|n| n>W}}
How to do this with Dlang ?
You can use countUntil, it accepts a predicate :
[1, 2, 3, 4, 5, 6, 7, 8].countUntil!(c => c > 5).writeln;
To get the index of the max element, use the aptly name maxIndex function :
[1, 2, 3, 4, 5, 6, 7, 8].maxIndex.writeln;
So, my goal is to capture data in a buffer.
I need speed and I just need a fixed size so I was thinking that a circular array would be the best.
But what I want to do is at each step to:
first, overwrite the latest information in the array with the newest that just arrived
next, using the all array starting from the oldest to the newest
repeat
I have difficulty to see how to handle the second step in C++ while being efficient. Or maybe something else than a circular array would be better? Any advise or point of view is welcome.
To have something more graphic:
for step in steps:
(current writing position = 2)
current buffer = [8, 9, 3, 4, 5, 6, 7]
new info = 10
overwrite buffer(new info)
new buffer = [8, 9, 10, 4, 5, 6, 7]
current writing position += 1 //(3)
array to use = [4, 5, 6, 7, 8, 9, 10]
function(array to use)
(I used integer following each other to see the chronology of each information in the buffer)
What I am thinking about is to copy the last part and first part and then concatenate them:
std::vector<int> buffer{8, 9, 10, 4, 5, 6, 7};
std::vector<int> oldest(&buffer[3],&buffer[6]);
std::vector<int> youngest(&buffer[0],&buffer[2]);
oldest.insert( oldest.end(), youngest.begin(), youngest.end() );
function(oldest)
If you know something that would be quicker please tell me.
If you really need speed you should not copy elements but use the index information you already have to access the elements in the right order.
So the handling function would just need a pointer to the array (or reference to std::vector), know the size and the current working pos.
// process from working pos to end of buffer
for(int i = current_pos; i < buffer_size; ++i) {
processElement(new_buffer [i]);
}
// process the remainder from begin to working pos
for(int i = 0; i < curent_pos; ++i) {
processElement(new_buffer [i]);
}
This should not be to hard to inplement as your working position marks both, the begin and end of your data to process.
This approach reduces the copy overhead n-fold where n is the number of extra array elements + 1 used.
Example: array with 2 extra elements
Note, in this case, the oldest value is on the left, the function has been called with pointer to arr[0] (start_pos = 0)
arr == [3, 4, 5, 6, 7, 8, 9, x, x]
now, lets insert the new value 10
arr == [3, 4, 5, 6, 7, 8, 9, 10, x]
start_pos += 1
call function with pointer to the second element (the old 3 won't be used)
function(arr + start_pos)
and now add the 11 and increment the working position (the old 4 won't be used)
arr == [3, 4, 5, 6, 7, 8, 9, 10, 11]
start_pos += 1
function(arr + start_pos)
Now, the array is full.
And only now it is needed to copy the last elements to the begin of the array (after the start_pos to the end) and set working_pos back to 0
depending on the number of extra elements this needs to be done only every 10th, 100th or even 1000th iteration !
result of copying would be:
arr == [6, 7, 8, 9, 10, 11, 9, 10, 11]
*
start_pos = -1 // prepare for the +1 in regular iteration.
next added value (12) will overwrite the * value
arr == [6, 7, 8, 9, 10, 11, 12, 10, 11]
start_pos += 1 // is 0 now
function(arr + start_pos)
Of course, you need one variable to determine the pos to insert the new element behind the other val or you derive from start_pos + nElemsToProcess
If your function() does only take std containers it is probably not the right choice to met the need for speed.
I need to port a snippet written in Python to C++
but that snippet is using combinations from itertools in python.
The line that I'm really interested to porting over to C++ is this one:
for k in combinations(range(n-i),2*i):
range(n-i) in Python will generate a list from 0 to (n-i) - 1
Let n = 16, i = 5
print range(n-i)
outputs:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and python combinations will generate all possible combinations in that list.
e.g.
print list(combinations(range(n-i),2*i))
outputs:
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(0, 1, 2, 3, 4, 5, 6, 7, 8, 10),
(0, 1, 2, 3, 4, 5, 6, 7, 9, 10),
(0, 1, 2, 3, 4, 5, 6, 8, 9, 10),
(0, 1, 2, 3, 4, 5, 7, 8, 9, 10),
(0, 1, 2, 3, 4, 6, 7, 8, 9, 10),
(0, 1, 2, 3, 5, 6, 7, 8, 9, 10),
(0, 1, 2, 4, 5, 6, 7, 8, 9, 10),
(0, 1, 3, 4, 5, 6, 7, 8, 9, 10),
(0, 2, 3, 4, 5, 6, 7, 8, 9, 10),
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]
I want to generate similar output using std::vector and next_permutation from C++ but I'm still getting erroneous results. This is my current approach:
for(int j = 0; j < n-i; j++) {
temp_vector.push_back(j);
}
That snippet is equivalent to range(n-i) in Python.
But the following snippet:
do {
myvector.push_back(temp_vector);
} while(next_permutation(temp_vector.begin(),temp_vector.begin()+2*i));
cout<<myvector.size()<<endl;
Is not equivalent to combinations(range(n-i),2*i)) in Python, and I've tried many variations and still haven't been able to come up with the results I'm expecting.
For example:
Let n = 16
i = 5
Python
>>> print len(list(combinations(range(n-i),2*i)))
11
C++
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> temp_vector;
vector< vector<int> > myvector;
int n = 16, i = 5;
for(int j = 0; j < n - i; j++) {
temp_vector.push_back(j);
}
do {
myvector.push_back(temp_vector);
} while(next_permutation(temp_vector.begin(), temp_vector.begin()+2*i));
cout<<myvector.size()<<endl;
return 0;
}
g++ combinations.cpp
./a.out
3628800
Any guidance will be greatly appreciated! Thanks a lot!
combinations and permutations are not the same thing.
A combination is an unordered list of a subset of the items from another set. A permutation is a unique order of the items in the list.
You're generating all combinations of 10 things from a list of 11 things, so you'll get 11 results, each one missing a different one of the original 11 items.
Generating every permutation will generate every unique order of the original 11 items. Since the items in this case are all unique that means the result would be 11! lists where each contains all 11 items. You're only generating permutations from the first 10 items however, so you're getting 10! lists, none of which contain the 11th item.
You need to find an algorithm for generating combinations instead of permutations.
There's no built-in algorithm for combinations. std::next_permutation can be used as part of an algorithm to generate combinations: See Generating combinations in c++.
Here's an old draft proposal for algorithms for combinations, including code.
So I've been playing around with python and noticed something that seems a bit odd. The semantics of -1 in selecting from a list don't seem to be consistent.
So I have a list of numbers
ls = range(1000)
The last element of the list if of course ls[-1] but if I take a sublist of that so that I get everything from say the midpoint to the end I would do
ls[500:-1]
but this does not give me a list containing the last element in the list, but instead a list containing everything UP TO the last element. However if I do
ls[0:10]
I get a list containing also the tenth element (so the selector ought to be inclusive), why then does it not work for -1.
I can of course do ls[500:] or ls[500:len(ls)] (which would be silly). I was just wondering what the deal with -1 was, I realise that I don't need it there.
In list[first:last], last is not included.
The 10th element is ls[9], in ls[0:10] there isn't ls[10].
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10] doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:
>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
when slicing an array;
ls[y:x]
takes the slice from element y upto and but not including x. when you use the negative indexing it is equivalent to using
ls[y:-1] == ls[y:len(ls)-1]
so it so the slice would be upto the last element, but it wouldn't include it (as per the slice)
-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".
so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3].
The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.
I hope this is somewhat understandable.