In c++ we declare a vector like this. std::vector<int> v(6); how to do it for two dimensional vector - syntax

std::vector<int> v(6);
how to declare a two dimensional vector with limits like above code for one dimension
I'm a noob in c++. I tried like this:
`
std::vector<int> v(6)(2);
`
I expected a two dimensional vector with 6 rows and 2 columns to take input in.
I know how to declare 2d vector. I just wanted it with limit.

In C++, there's no direct type which exactly represents a 2D "vector"/"matrix"/"tensor".
What you can create, is a vector of vectors. You'd write that as std::vector<std::vector<int>> - each element of the outer vector is itself a vector. But there's an important difference here: each of the inner vectors has its own length, and those could be different.
vector has a constructor taking a second argument, the initial value. You can use that here to initialize the inner vectors:
std::vector<std::vector<int>> v(6, std::vector<int>(2));

Related

How to pass large array from three.js to a vertex shader?

Wondering if it's possible to pass a large array into a WebGL shader, like this:
// array here
uniform vec3[hugeSize] arrayOfStars;
void main() {
// iterate through the array here to compare positions with current particule
gl_Position = ...;
}
I would like iterate a vector array which contains the positions of 1 million particles.
I would like for each particle to compare its position with those of the others (or a percentage of the others for better performance) in order to calculate its next position.
(I'm trying to roughly simulate a galaxy)
My problem is that I can't put an array with a size greater than 4075, while I would need an array from vec3 with a size of 1,000,000.

SIMD transpose when row size is greater than vector width

You can find a lot of good answers for transposing a matrix which falls with the natural size of the SIMD instruction set, in particular, where the size of one row is no more than the vector width. Examples would be a 4x4 float transpose in SSE, or a 4x4 double or 8x8 float transpose in AVX/AVX2 (double everything again for AVX-512).
However, what are the options when the matrix is larger than that? E.g., a 16x16 float matrix using AVX2? Can SIMD shuffles be used at all to speed things up, or is a gather + sequential write the only way?
If all your matrix dimensions are a multiple of your packet-size you can do the operation block-wise and swap the blocks as needed. Example for 4x4 double matrix using SSE2:
// transpose vectors i0 and i1 and store the result to addresses r0 and r1
void transpose2x2(double *r0, double* r1, __m128d i0, __m128d i1)
{
__m128d t0 = _mm_unpacklo_pd(i0,i1);
__m128d t1 = _mm_unpackhi_pd(i0,i1);
_mm_storeu_pd(r0, t0);
_mm_storeu_pd(r1, t1);
}
void transpose(double mat[4][4])
{
// transpose [00]-block in-place
transpose2x2(mat[0]+0, mat[1]+0,_mm_loadu_pd(mat[0]+0),_mm_loadu_pd(mat[1]+0));
// load [20]-block
__m128d t20 = _mm_loadu_pd(mat[2]+0), t30 = _mm_loadu_pd(mat[3]+0);
// transpose [02]-block and store it to [20] position
transpose2x2(mat[2]+0,mat[3]+0, _mm_loadu_pd(mat[0]+2),_mm_loadu_pd(mat[1]+2));
// transpose temp-block and store it to [02] position
transpose2x2(mat[0]+2,mat[1]+2, t20, t30);
// transpose [22]-block in-place
transpose2x2(mat[2]+2, mat[3]+2,_mm_loadu_pd(mat[2]+2),_mm_loadu_pd(mat[3]+2));
}
This should be relatively easy to extend to other square matrices, other scalar types and other architectures. Matrices which are not a multiple of packet sizes are perhaps more complicated (if they are large enough, it will probably be worth it to do most the work with vectorization and just do the last rows/columns manually).
For some sizes, e.g. 3x4 or 3x8 matrices there are special algorithms [1] -- if you have a 1003x1003 matrix, you could exploit that for the last rows/columns (and there are probably algorithms for other odd sizes as well).
With some effort you could also write this for rectangular matrices (some thoughts have to be made how to avoid having to cache more than one block at a time, but it is possible).
Godbolt demo: https://godbolt.org/z/tVk_Bc
[1] https://software.intel.com/en-us/articles/3d-vector-normalization-using-256-bit-intel-advanced-vector-extensions-intel-avx
Perhaps one could use the fortran TRANSPOSE intrisic with ISO_C_BINDING and link that with C as a subroutine or function call.
TRANSPOSE is pretty optimised in fortran.
And mixed language skills are sometime useful to know generically. I have even linked F90 with GO.

How can I append elements to a 3-dimensional array in Processing (v. 3.4)?

I am creating a program to render 3D graphics. I have a 3D array 'shapes' which contains all of the polygons to render. It is an array of polygons, where each polygon is itself an array of points, and each point is an array of 3 integer values (x, y, z co-ordinates). I have tried and failed to use the append() function. How else can I get it to work?
I've tried using the append() function, but this seems to not work with multidimensional arrays.
int[][][] addPolyhedron(int[][][] shapes, int[][][] polyhedron)
{
for(int i = 0; i < polyhedron.length; i ++)
{
shapes = append(shapes, polyhedron[i]);
{
return shapes;
}
I wanted this to extend the array shapes to include all of the polygons in the array polyhedron. However, I receive an error message saying 'type mismatch, "java.lang.Object" does not match with "int[][][]".' Thanks in advance.
In Java, arrays (of any dimension) are not extendable - the size is defined, allocated and fixed upon instantiation. You want to add to (and therefore dynamically resize) shapes. Although Processing does provide the append() function, I think it is more appropriate to use the ArrayList built-in Java data type.
Your function could be refactored into something like this:
ArrayList<Integer[][]> addPolyhedron(ArrayList<Integer[][]> shapes, ArrayList<Integer[][]> polyhedron)
{
shapes.addAll(polyhedron);
return shapes;
}
Note that int[][] has become Integer[][] because an ArrayList cannot be declared with primitive types (int, bool, float, etc.).
Adding an individual program-defined polygon to shapes would be done like this:
shapes.add(new Integer[][] {{1,2,5},{3,4,5},{6,5,4}}); // adds a triangle to shapes.
Getting coordinates from the shapes ArrayList would be done like this:
shapes.get(0)[1][1]; // returns 4.

Is there a way to create a summed-are table of a matrix with just one iteration?

Constrains:
You can't iterate the matrix more than once.
If we name the matrix A then there are two of those matrices available, one is 'read-only' and the other is 'read/write'. We will use the 'read/write' matrix to construct the summed-area table.
For example this code here:
http://www.geeksforgeeks.org/submatrix-sum-queries/
Iterares 2 times: 1) summing all columns
2) summing all rows
Useful picture for summed area tables from Wikipedia:
During construction, we already have A, B and C (for the edges, they would be zero), and want to compute D. The area spanned by that rectangle is 1x1 in this case, so we know the sum of the rectangle is X where X is the number from the original matrix at the position of D, so D = C + B - A + X. A is subtracted because the areas belonging to C and B both contain the area of A.
Simply iterating over the matrix and filling every cell using that formula iterates over the matrix only once, and could even be done in-place (replacing the original matrix by its SAT) if your matrix was not read-only.

Floating point number representation in binary

I'm working on a problem out of Cracking The Coding Interview that asks: Given a 2-D graph with points on it, find a line which passes the most number of points.
The solution is to: Draw an infinite line between every two points and, using a hash table, track which line is most common. To find the most common line, we iterate through all line segments using a hash table to count the number of times we've seen each line.
The author goes on to say there's a complication: "we're definining two lines to be equal if the lines have the same slope and y-intercept. We are then, furthermore, hashing the lines based on these values (specifically based on the slope). The problem with floating point numbers cannot always be represented accurately in binary. We resolve this by checking if two floating point numbers are within an epsilon value of each other."
Here's where I'm confused. Even if the slope is a floating point, we can't use that as a hash key? If so, why not just hash the slope as a string instead? Why do we need to introduce into our code hashing based upon keys that are within epsilon of each other?
Have a look at the following example written in c++.
#include <stdio.h>
#include <stdlib.h>
int main() {
double a=10.0;
double b=a/3;
double c=(b-3)*3;
printf("a: %20.50lf\n", a);
printf("b: %20.50lf\n", b);
printf("c: %20.50lf\n", c);
return 0;
}
'c' should be equal to 1 but due to floating point rounding the above code produces the following.
a: 10.00000000000000000000000000000000000000000000000000
b: 3.33333333333333348136306995002087205648422241210938
c: 1.00000000000000044408920985006261616945266723632812
The algorithm you are describing does not need any hash table.
Use histogram instead. This Answer is exact example of this task in C++
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line
If you still want to use floats as keys
Then you need to truncate them so they can be compared as binary. For example let assume you got (assuming C++ syntax):
const float da=1.5*M_PI/180.0; // [rad] comparison precision
float a;
a=atan2(dy,dx); // [rad] your line angle from deltas
a=floor(a/da); // [da] truncated angle
Where dx,dy is your line delta and da is your comparison precision angle. Now to access float a as binary for hashing purposes you can simply do this:
union { float f32; DWORD u32; } b;
b.f32=a;
// here b.u32 is your hash key

Resources