Mathematica: adding a list of lists elementwise - list

I have a list of lists of numbers. I add them into one list by adding all of the first elements together, all of the second elements together, etc. For example, if my list were { {1,2,3}, {1,2,3}, {1,2,3,4} } I would want to end up with {3,6,9,4}. How do I do this in Mathematica?

a = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}};
Total#PadRight#a
{3, 6, 9, 4}

Among its many useful features, Flatten will transpose a 'ragged' array (see here for a nice explanation, or check out the 'applications' subsection of the documentation on Flatten)
Total /# Flatten[#, {{2}}] &#{{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}}
{3, 6, 9, 4}

If all the rows were the same length then adding the rows would do this.
So make all the rows the same length by appending zeros and then add them.
lists = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}};
max = Max[Length /# lists]; min = Min[Length /# lists];
zeros = Table[0, {max - min}];
Plus ## Map[Take[Join[#, zeros], max] &, lists]

Related

I want to create a 2D vector with each index being a vector of int

I want my data structure to look something like this when populated:
[[1, 2, 3] [3, 3, 3] [4, 4, 4]]
[[5, 4, 5] [3, 4, 5] [3, 3, 3]]
I'm not sure where to go from here. I've tried doing:
vector<vector<vector<int> > > x;
But I'm having trouble populating it. I think it's basically a matrix of vectors? I'm just not sure how to go about it.
EDIT: Sorry, I should've specified a bit more.
The core functionality of my program is to create multiple vector of size 3 and push them 1 by 1 in a 30x3 matrix of vectors. The matrix will be initially completely empty.
I want to be able to push a vector at a specific row, similar to something like this
vector<int> y{1, 2, 3};
x.at(row).push_back(y);
I'm not sure if that's the correct syntax of how to approach that but I want that to be the final functionality. My goal is to create a 30x3 matrix with each index in the matrix being a vector of size 3
It seems like you want this:
std::vector<std::vector<std::vector<int>>> x(30, std::vector<std::vector<int>>(3, std::vector<int>(3)));
The constructor I am using takes (std::size_t n, T t) as in n elements of type T.
If you want to replace a vector in a given cell, you can use:
x[2][4] = {2, 7, 9};
Or you can replace an entire row of 3like this:
x[1] = {{2, 7, 9}, {1, 1, 8}, {6, 2, 1}};
use {} instead of []:
std::vector<std::vector<std::vector<int>>> x{
{{1, 2, 3}, {3, 3, 3}, {4, 4, 4}},
{{5, 4, 5}, {3, 4, 5}, {3, 3, 3}}
};

Generate all possible ordered subset from a set

I'm aware how to generate all possible subsets from a set incorporating bit twiddling. For instance,
//Get if nth position's bit is set
bool IsBitSet(int num, int bit)
{
return 1 == ((num >> bit) & 1);
}
int subsetMaxIterCount = pow(2, someList.size());
for (int i = 0; i < subsetMaxIterCount; i++) {
vector<A> subset;
for (size_t i = 0; i < jobList.size(); i++)
{
if (IsBitSet(jobSubsetIdx, i)) {
//Add to subset here
}
}
//Here we have a subset for some i
}
However, this doesn't take into account of ordering.
For instance, if I had a set of {1, 2, 3}, the above algorithm generates subsets of:
{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1,2,3}
What I need in reality is this
{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1,2,3}, {2, 1}, {2, 1, 3}, {2, 3, 1}, {3, 1}, {3, 2}, {3, 1, 2}, {3, 2, 1}
Not sure if the above list is exhaustive. What's an effective algorithm in generating something like this? (Is this all possible subsets with permutation by the way?)
The way we generate the subsets using bit twiddling, every subset is sorted within it e.g. {1, 2, 3}, {2, 3}, {1, 3}. You can generate permutation for each subset using next_permutation
vector<vector<int>> mySubsetGenerator(vector<vector<int>>& subsets) {
vector<vector<int>> extendedSubset;
for(int i = 0; i < subsets.size(); ++i) {
do {
extendedSubset.push_back(subsets[i]);
} while(next_permutation(subsets[i].begin(), subsets[i].end()));
}
return extendedSubset;
}
Moreover, you can use only backtracking to generate all possible permutations by taking one or more elements of array.

Iteratively calculate the power set of a set or vector

While there are plenty of examples on how to generate the actual power set of a set, I can't find anything about iteratively (as in std::iterator) generating the power set. The reason why I would appreciate such an algorithm is the size of my base set. As the power set of a n-element set has 2^n elements, I would quickly run out of memory when actually computing the set. So, is there any way to create an iterator for the power set of a given set? Is it even possible?
If it would be easier, an iterator that creates sets of ints would be fine - I could use them as indices for the actual set/vector.
As I actually work on a std::vector, random access would be possible if neccessary
Using for_each_combination from Combinations and Permutations one can easily iterate through all members of the power set of a std::vector<AnyType>. For example:
#include <vector>
#include <iostream>
#include "../combinations/combinations"
int
main()
{
std::vector<int> v{1, 2, 3, 4, 5};
std::size_t num_visits = 0;
for (std::size_t k = 0; k <= v.size(); ++k)
for_each_combination(v.begin(), v.begin()+k, v.end(),
[&](auto first, auto last)
{
std::cout << '{';
if (first != last)
{
std::cout << *first;
for (++first; first != last; ++first)
std::cout << ", " << *first;
}
std::cout << "}\n";
++num_visits;
return false;
});
std::cout << "num_visits = " << num_visits << '\n';
}
This visits each power set member of this vector, and executes the functor, which simply counts the number of visits and prints out the current power set:
{}
{1}
{2}
{3}
{4}
{5}
{1, 2}
{1, 3}
{1, 4}
{1, 5}
{2, 3}
{2, 4}
{2, 5}
{3, 4}
{3, 5}
{4, 5}
{1, 2, 3}
{1, 2, 4}
{1, 2, 5}
{1, 3, 4}
{1, 3, 5}
{1, 4, 5}
{2, 3, 4}
{2, 3, 5}
{2, 4, 5}
{3, 4, 5}
{1, 2, 3, 4}
{1, 2, 3, 5}
{1, 2, 4, 5}
{1, 3, 4, 5}
{2, 3, 4, 5}
{1, 2, 3, 4, 5}
num_visits = 32
The syntax I've used above is C++14. If you have C++11, you will need to change:
[&](auto first, auto last)
to:
[&](std::vector<int>::const_iterator first, std::vector<int>::const_iterator last)
And if you are in C++98/03, you will have to write a functor or function to replace the lambda.
The for_each_combination function allocates no extra storage. This is all done by swapping members of the vector into the range [v.begin(), v.begin()+k). At the end of each call to for_each_combination the vector is left in its original state.
If for some reason you want to "exit" the for_each_combination early, simply return true instead of false.

Mathematica: converting output from Cluster[]

Imagine a data set like this:
{{{1,2},{3,4}},{{8,8},{3,7},{5,2}}}.
Note that at the top level this list has {{1,2},{3,4}} as the first element and {{8,8},{3,7},{5,2}} as the second.
Using that fact, the desired output would be:
{{1,2,1},{3,4,1},{8,8,2},{3,7,2},{5,2,2}}
I have already tried using Map[].
This arose because I was using cluster analysis which gave me a list, rather than an indexing of various clusters. I did not find an option in Cluster[] to do this directly.
In[1]:= v = {{{1, 2}, {3, 4}}, {{8, 8}, {3, 7}, {5, 2}}};
Flatten[Table[Map[Join[#, {i}] &, v[[i]]], {i, 1, Length[v]}], 1]
Out[1]= {{1, 2, 1}, {3, 4, 1}, {8, 8, 2}, {3, 7, 2}, {5, 2, 2}}
This is how I would go about the conversion, using the steps as they naturally come to mind.
v = {{{1, 2}, {3, 4}}, {{8, 8}, {3, 7}, {5, 2}}};
Note the result obtained using MapIndexed :-
MapIndexed[{#1, First[#2]} &, v]
{{{{1, 2}, {3, 4}}, 1}, {{{8, 8}, {3, 7}, {5, 2}}, 2}}
To append the part specs (1 & 2) to the subelements I would use MapThread. This requires multiple part specs, e.g. {2, 2, 2} for element 2 :-
MapThread[Append, {{{8, 8}, {3, 7}, {5, 2}}, {2, 2, 2}}]
{{8, 8, 2}, {3, 7, 2}, {5, 2, 2}}
So the MapIndexed expression is modified to produce the necessary part specs :-
MapIndexed[{#1, ConstantArray[First[#2], Length[#1]]} &, v]
{{{{1, 2}, {3, 4}}, {1, 1}}, {{{8, 8}, {3, 7}, {5, 2}}, {2, 2, 2}}}
Now MapThread can be used in the MapIndexed expression :-
MapIndexed[MapThread[Append, {#1, ConstantArray[First[#2], Length[#1]]}] &, v]
{{1, 2, 1}, {3, 4, 1}}, {{8, 8, 2}, {3, 7, 2}, {5, 2, 2}}}
Finally, the first list level is flattened :-
Flatten[MapIndexed[MapThread[Append,
{#1, ConstantArray[First[#2], Length[#1]]}] &, v], 1]
{{1, 2, 1}, {3, 4, 1}, {8, 8, 2}, {3, 7, 2}, {5, 2, 2}}

2D int array in C++

So I want to initialize an int 2d array very quickly, but I can't figure out how to do it. I've done a few searches and none of them say how to initialize a 2D array, except to do:
int [SOME_CONSTANT][ANOTHER_CONSTANT] = {{0}};
Basically, I've got 8 vertices, and I'm listing the 4 vertices of each face of a cube in an array. I've tried this:
int[6][4] sides = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
But that tells me that there's an error with 'sides', and that it expected a semi-colon. Is there any way to initialize an array quickly like this?
Thanks!
You have the [][] on the wrong side. Try this:
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
Keep in mind that what you really have is:
int **sides
(A pointer to a pointer of ints). It's sides that has the dimensions, not the int. Therefore, you could also do:
int x, y[2], z[3][4], ...;
I think You meant to say
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
int array[n][m] behaves just like int array[n * m].
In fact, array[i][j] = array[m * i + j] for all i, j.
So int array[2][3] = {1, 2, 3, 4, 5, 6}; is a valid declaration and, for example,
array[1][1] = array[3 * 1 + 1] = array[4] = 5.
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
I'm not a regular c++ programmer but I looks like int sides[6][4] seems to compile while int[6][4] sides fails. Languages like C# lets you have the [][] on either sides but apparently c++ doesn't.
int sides[6][4] = ... should do the trick. This sounds like you may be coming from a Java (or other language) background so I do recommend a C++ book The Definitive C++ Book Guide and List for more details.
Yes, the intended type of sides is int[6][4], but C++ has confusing syntax sometimes. The way to declare said array is:
int sides[6][4] = {/*stuff*/};
You run into this with function pointers too, but even worse:
int (*myfuncptr)(int); //creates a function pointer called myfuncptr
With function pointers though, you can do this:
typedef int (*func_ptr_type)(int);
func_ptr_type myfuncptr;
Unfortunately, there's no corresponding magic trick for arrays.
i would make a array outside of function and just assign it it to your local. this will very likely invoke memcpy or just inline memory copying loop
this is the fastest you can get