I have one two dimensional array and one single dimensional array.
The two dimensional array is of NxM size. And the one dimensional array is of size N x M means
it has N X M elements.
Now I want to copy all the elements of the one dimensional array into the 2-D array.
This is what I tried
for(i = 0; i < M; i += 1) {
for(j = 0; j < N; j += 1) {
arr2d[i][j] = arr2d[(i*j +j)];
}
}
But not working Any suggestions???
You can change:
arr2d[i][j] = arr2d[(i*j +j)];
to:
arr2d[i][j] = arr1d[(i*N + j)];
which would probably work out better.
var arr1d = [1,2,3,4,5,6];
var M = 1, N = 2;
var arr2d = [];
var counter = 0;
for(i = 0; i <= M; i += 1) {
for(j = 0; j <= N; j += 1) {
if(j == 0)
arr2d[i] = [];
arr2d[i][j] = arr1d[counter++];
}
}
Related
I am trying to find the location of a target inside of a 1-D array that acts like a table with rows and cols. I could do it using divide and mod, but I am stuck on finding it using nested loops. specifically, I can't seem to assign values inside the nested loop.
here is my code:
#include <stdio.h>
int main()
{
int arr[9] = // act as a 3 X 3 table
{ 2, 34, 6,
7, 45, 45,
35,65, 2
};
int target = 7;// r = 1; c = 0
int r = 0; // row of the target
int c = 0; // col of the target
int rows = 3;
int cols = 3;
for (int i = 0; i < rows; i++){
for (int j = 0; j + i * cols < cols + i * cols; i++ ){
if (arr[j] == target){
c = j; // columns of the target
r = i; // rows of the target
}
}
}
printf ("%d, %d",c, r);
return 0;
}
The code outputs: 0,0.
The problem isn't with the assignment, it's with the wrong loop and if condition.
The outer loop should loop over the i rows
The inner loop should loop over the j columns
within both loops, the cell to evaluate is i * cols + j
Put it all together and you'll get:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++ ) {
if (arr[i * cols + j] == target) {
c = j; // columns of the target
r = i; // rows of the target
}
}
}
Since arr is 1D array and inside for loop, for any i value j will reach upto max 3 only so its not checking after arr[3]
To avoid this problem take int pointer and points to arr and do the operation as below
int *p = arr;
for (i = 0; i < rows; i++){
for ( j = 0; j < cols ; j++ ){
if (p[j] == target){
c = j; // columns of the target
r = i; // rows of the target
}
}
p = p + j;/*make p to points to next row */
}
A better solution would use only one loop:
for (int i = 0; i < rows * cols; i++){
if (arr[i] == target){
r = i / 3;
c = i % r;
}
}
I'm attempting to initialize, populate and parse through an array in order to determine its "stability." To avoid a stack overflow, I decided to create dynamic arrays. The problem is that when it comes to populating the array, I get an exception regarding an access violation to a random location. I don't know if its something in the initialization or in the nested for loop when populating the array. I just can't seem to find anything wrong, nor my classmates/TAs. Thanks in advance for your help! I have tried compiling in VS, XCode, and g++ I have tried commenting out the dynamic array loops as well as the delete loops and gone for "regular arrays" such as float array[x][y] and I still get the same error.
#include <iostream>
#include <array>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int check = 0;
int iteration = 0;
int newIteration = 0;
int newNewIteration = 0;
int const DIMENSION = 1024;
//Initializing the dynamic arrays in
//heap to avoid a stack overflow
float** firstGrid = new float*[DIMENSION];
for (int a = 0; a < DIMENSION; ++a) {
firstGrid[a] = new float[DIMENSION];
}
float** secondGrid = new float*[DIMENSION];
for (int b = 0; b < DIMENSION; ++b) {
secondGrid[b] = new float[DIMENSION];
}
float** thirdGrid = new float*[DIMENSION];
for (int c = 0; c < DIMENSION; ++c) {
thirdGrid[c] = new float[DIMENSION];
}
//Populating the arrays
//All points inside first array
for (int i = 0; i < DIMENSION; ++i) {
for (int j = 0; i < DIMENSION; ++j) {
firstGrid[i][j] = 0.0; //exception occurs here
}
}
for (int i = 1; i < DIMENSION - 1; ++i) {
for (int j = 1; i < DIMENSION - 1; ++j) {
firstGrid[i][j] = 50.0;
}
}
//Pre-setting second array
for (int i = 0; i < DIMENSION; ++i) {
for (int j = 0; i < DIMENSION; ++j) {
secondGrid[i][j] = 0.0;
}
}
for (int i = 1; i < DIMENSION - 1; ++i) {
for (int j = 1; i < DIMENSION - 1; ++j) {
secondGrid[i][j] = 50.0;
}
}
//Pre-setting third array
for (int i = 0; i < DIMENSION; ++i) {
for (int j = 0; i < DIMENSION; ++j) {
thirdGrid[i][j] = 0.0;
}
}
for (int i = 1; i < DIMENSION - 1; ++i) {
for (int j = 1; i < DIMENSION - 1; ++j) {
thirdGrid[i][j] = 50.0;
}
}
//Checking and Populating new arrays
for (int p = 1; p < DIMENSION - 1; ++p) {
for (int q = 1; q < DIMENSION - 1; ++p) {
check = abs((firstGrid[p - 1][q] + firstGrid[p][q - 1] + firstGrid[p + 1][q] + firstGrid[p][q + 1]) / 4
- firstGrid[p][q]);
if (check > 0.1) {
secondGrid[p][q] = (firstGrid[p - 1][q] + firstGrid[p][q - 1] + firstGrid[p + 1][q] + firstGrid[p][q + 1]) / 4;
iteration = iteration + 1;
}
}
}
for (int p = 1; p < DIMENSION - 1; ++p) {
for (int q = 1; q < DIMENSION - 1; ++p) {
check = abs((secondGrid[p - 1][q] + secondGrid[p][q - 1] + secondGrid[p + 1][q] + secondGrid[p][q + 1]) / 4
- secondGrid[p][q]);
if (check > 0.1) {
thirdGrid[p][q] = (secondGrid[p - 1][q] + secondGrid[p][q - 1] + secondGrid[p + 1][q] + secondGrid[p][q + 1]) / 4;
newIteration = newIteration + 1;
}
}
}
for (int p = 1; p < DIMENSION - 1; ++p) {
for (int q = 1; q < DIMENSION - 1; ++p) {
check = abs((thirdGrid[p - 1][q] + thirdGrid[p][q - 1] + thirdGrid[p + 1][q] + thirdGrid[p][q + 1]) / 4
- thirdGrid[p][q]);
if (check > 0.1) {
newNewIteration = newNewIteration + 1;
}
}
}
//Deleting arrays and freeing memory
for (int x = 0; x < DIMENSION; ++x) {
delete [] firstGrid[x];
}
delete [] firstGrid;
for (int x = 0; x < DIMENSION; ++x) {
delete [] secondGrid[x];
}
delete [] secondGrid;
for (int x = 0; x < DIMENSION; ++x) {
delete [] thirdGrid[x];
}
delete [] thirdGrid;
//iteration checking
cout << iteration << endl << newIteration << endl << newNewIteration;
if (iteration == 179 || newIteration == 179 || newNewIteration == 179) {
return 0;
}
else {
return 1;
}
}
You should use j consistently in your second for-loop (where the error occurs):
for(j=0; j < DIMENSION; j++)
I have a matrix M of size m x n which is saved as a one dimensional array N of length m * n. Every cell of this array contains some integer variables which are the ID of data points. The amount of integer variables in every cell changes over time.
N[0] = {1,4,5,7}
N[1] = {2,9,3,1,7,4}
N[2] = {7,1,3,9,8}
N[3] = {6,4,2}
...
I access these elements by using an index function which returns
idx = x + y * n
Given some index idx I want to use all integer variables of the neighbor cells and the central cell with index idx to access an array of data points D of size s. Size s can be very large.
To make my point clear: Instead of such a loop over all data points
for(int i=0; i<s; i++)
// Do something with D[i]
I want something like (but more compact)
// Access central cell
idx = x + y*n;
num_Elements = Number_of_Elements_Cell(x,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]
// Access right cell
idx = (x+1) + y*n;
num_Elements = Number_of_Elements_Cell(x+1,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]
// Access left cell
idx = (x-1) + y*n;
num_Elements = Number_of_Elements_Cell(x-1,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]
and so on. For all cells I have to do that 9 times.
My question: Is there a better way to do that given the structure N?
I'm not sure i understand your question well ....
but you could try :
for (int i=-1 ; i <= 1 ; i++){
for (int j = -1 ; j <=1 ; j++){
idx = (x+i) + (y+j)*n;
// Check if idx is not out of bounds
num_Elements = Number_of_Elements_Cell(x+i,y+j);
for(int k=0; k<num_Elements; k++)
// Do something with D[N[idx][k]]
}
}
Note that your index could very well be out-of-bounds which such a method, so you'll have to implement a test to prevent that.
That's the way to simply iterate on a cell and its 8 neighbors using a double for loop.
If it's not what you expect, let me know, i'll edit/delete.
I'm not sure but maybe you're looking for something like this:
var distinctDataPoints = new List<int>();
for(int z = x - 1, z <= x + 1, z++)
{
if(z < 0 || z > m)
continue;
for(int t = y-1, t <= y + 1, t++)
{
if(t < 0 || t > n)
continue;
idx = z + t * n;
for(int i = 0; i < num_Elements; i++)
{
if(!distinctDataPoints.Contains(N[idx][i])
distinctDataPoints.Add(N[idx][i])
}
}
}
for(int dpIdx = 0; dpIdx < distinctDataPoints.Count; dpIdx++)
{
//Do something with D[dpIdx]
}
So I am writing code that will change the elements of an array and print out ONLY the numbers that come after a certain target. In this case the target is the number 4.
meaning that if my original array contains the numbers
5 6 4 3 2 1
the new array will only contain 3 2 1 because those are the numbers that come after the number 4.
I have this all in a method and so far my code prints out the number that comes after 4 but keeps printing that same number over and over and I don't know how to keep it printing the elements that follow
boolean four;
int location = 0;
four = contains(newArray, 4);
if (four == false) { // this returns the same array if there is no 4
return newArray;
} else {
for (int i = 0; i < newArray.length; i++) {
if (newArray[i] == 4) {
location = i;
}
}
for (int j = 0; j < newArray.length; j++) {
newArray[j] = newArray[location + 1];
}
return newArray;
}
You could also make use of the native implementation of System.arraycopy like this
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
location = i;
break;
}
}
int[] out = new int[arr.length-location-1];
System.arraycopy(arr, location+1, out, 0, arr.length-location-1);
return out;
You should create a new array, since you can't change an array's length :
for (int i = 0; i < newArray.length; i++) {
if(newArray[i] == 4) {
location = i;
break;
}
}
int [] arr = new int[newArray.length - location - 1];
for(int j = 0; j < arr.length; j++) {
arr[j] = newArray[location+1+j];
}
newArray = arr;
If I have a 2D array, it is trivial to loop through the entire array, a row or a column by using for loops. However, occasionally, I need to traverse an arbitrary 2D sub-array.
A great example would be sudoku in which I might store an entire grid in a 2D array but then need to analyse each individual block of 9 squares. Currently, I would do something like the following:
for(i = 0; i < 9; i += 3) {
for(j = 0; j < 9; j += 3) {
for(k = 0; k < 3; k++) {
for(m = 0; m < 3; m++) {
block[m][k] == grid[j + m][i + k];
}
}
//At this point in each iteration of i/j we will have a 2D array in block
//which we can then iterate over using more for loops.
}
}
Is there a better way to iterate over arbitrary sub-arrays especially when they occur in a regular pattern such as above?
The performance on this loop structure will be horrendous. Consider the inner most loop:
for(m = 0; m < 3; m++) {
block[m][k] == grid[j + m][i + k];
}
C is "row-major" ordered, which means that accessing block will cause a cache miss on each iteration! That's because the memory is not accessed contiguously.
There's a similar issue for grid. Your nested loop order is to fix i before varying j, yet you are accessing grid on j as the row. This again is not contiguous and will cache miss on every iteration.
So a rule of thumb for when dealing with nested loops and multidimensional arrays is to place the loop indices and array indices in the same order. For your code, that's
for(j = 0; j < 9; j += 3) {
for(m = 0; m < 3; m++) {
for(i = 0; i < 9; i += 3) {
for(k = 0; k < 3; k++) {
block[m][k] == grid[j + m][i + k];
}
}
// make sure you access everything so that order doesn't change
// your program's semantics
}
}
Well in the case of sudoku couldn't you just store 9 3x3 arrays. Then you don't need to bother with sub arrays... If you start moving to much larger grids than sudoku you would improve cache performance this way as well.
Ignoring that, your code above works fine.
Imagine you have a 2D array a[n][m]. In order to loop a subarray q x r whose upper right corner is at position x,y use:
for(int i = x; i < n && i < x + q; ++i)
for(int j = y; j < m && j < y + r; ++j)
{
///
}
For your sudoku example, you could do this
for(int i = 0; i<3; ++i)
for(int j = 0; j < 3; ++j)
for(int locali = 0; locali < 3; ++locali)
for(int localj = 0; localkj <3; ++localj)
//the locali,localj element of the bigger i,j 3X3 square is
a[3*i + locali][3*j+localj]