I want to fill a 8 x 8 matrix with values in a special order (see example below), but I don´t know how to do that. Each numer stands for the ordering number: For example: #3 in the matrix is the third value of a e.g. a measurment I want to add.
The Order should be:
1 2 5 6 17 18 21 22
3 4 7 8 19 20 23 24
9 10 13 14 25 26 29 30
11 12 15 16 27 28 31 32
33 34 37 38 49 50 53 54
35 36 39 40 51 52 55 56
41 42 45 46 57 58 61 62
43 44 47 48 59 60 63 64
Does anybody knows an algorithmus to do that?
I have tried this, but that´s not a good way to to it, and it´s not working for the whole matrix
int b= 0, ii = 0, a = 0, iii = 0
i are different measurement values
and now a for loop
if (ii == 1)
{
b++;
}
if (ii == 2)
{
a++, b--;
}
if (ii == 3)
{
b ++;
}
tempMatrix[a][b] = i;
cout << "TempMatrix " << tempMatrix[a][b] << " a " << a << " b " << b << endl;
if (ii == 3)
{
ii = -1;
a --;
b ++;
}
if (iii == 7)
{
a = a + 2;
b = 0;
iii = -1;
}
Use recursion:
#include <iostream>
using namespace std;
void f(int a[8][8], int current, int x, int y, int size) {
if (size == 1) {
a[x][y] = current;
return;
} else {
size /= 2;
int add_for_each_square = size * size;
f(a, current, x, y, size);
f(a, current + add_for_each_square, x, y + size, size);
f(a, current + 2 * add_for_each_square, x + size, y, size);
f(a, current + 3 * add_for_each_square, x + size, y + size, size);
}
}
int main() {
int a[8][8];
f(a, 1, 0, 0, 8);
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
cout << a[i][j] << " ";
}
cout << endl;
}
}
If the matrix will always be a fixed size, then you can generate two lookup tables for row and column indexes into the matrix. Then, just pass your index through these tables to get the desired positions in the matrix.
const auto MATRIX_SIZE = 8;
const std::array<int, MATRIX_SIZE*MATRIX_SIZE> row_lookup = {{...}}; //put pre-computed values here.
const std::array<int, MATRIX_SIZE*MATRIX_SIZE> col_lookup = {{...}};
for(size_t i = 0; i < MATRIX_SIZE * MATRIX_SIZE; i++)
{
auto val = get_coefficient(i);
auto row = row_lookup[i];
auto col = col_lookup[i];
mat[col][row] = val;
}
Related
I have written a code for knights tour problem which work for 2D array but not for vector<vector<pair<int,int>>
WORKING CODE
#include <bits/stdc++.h>
#define N 8
using namespace std;
bool isPossible(int sol[N][N], int x, int y)
{
if ( sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
{
return true;
}
return false;
}
bool KNT(int sol[N][N], int moveNUM, int x, int y, int movex[8], int movey[8])
{
int i,next_x,next_y;
if (moveNUM == N * N)
{
return true;
}
for ( i = 0; i < 8; i++)
{
next_x = x + movex[i];
next_y = y + movey[i];
if (isPossible(sol, next_x, next_y))
{
sol[next_x][next_y]=moveNUM;
if (KNT(sol, moveNUM + 1, next_x, next_y, movex, movey))
{
return true;
}
sol[next_x][next_y] = -1; //Backtracking
}
}
return false;
}
int main()
{
int sol[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
sol[i][j]=-1;
}
}
int movex[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int movey[8] = {1, 2, 2, 1, -1, -2, -2, -1};
KNT(sol,1,0,0,movex, movey);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << sol[i][j] << " ";
}
cout << endl;
}
}
NON WORKING CODE
#include <bits/stdc++.h>
#define N 8
using namespace std;
bool isPossible(vector<vector<pair<int, int>>> &Brd, int x, int y)
{
if ((Brd[x][y].first == -1) && x >= 0 && x < N && y >= 0 && y < N)
{
return true;
}
return false;
}
bool KNT(vector<vector<pair<int, int>>> &Brd, int moveNUM, int x, int y, int movex[8], int movey[8])
{
int i,next_x,next_y;
if (moveNUM == N * N)
{
return true;
}
for ( i = 0; i < 8; i++)
{
next_x = x + movex[i];
next_y = y + movey[i];
if (isPossible(Brd, next_x, next_y))
{
Brd[next_x][next_y].first = 1;
Brd[next_x][next_y].second = moveNUM;
if (KNT(Brd, moveNUM + 1, next_x, next_y, movex, movey))
{
return true;
}
Brd[next_x][next_y].first = -1;
Brd[next_x][next_y].second = 0;
//Backtracking
}
}
return false; //Check for error
}
int main()
{
vector<vector<pair<int, int>>> Brd;
for (int i = 0; i < N; i++)
{
vector<pair<int, int>> temp;
for (int j = 0; j < N; j++)
{
temp.push_back(make_pair(-1, 0));
}
Brd.push_back(temp);
}
int movex[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int movey[8] = {1, 2, 2, 1, -1, -2, -2, -1};
KNT(Brd,1,0,0,movex,movey);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << Brd[i][j].second << " ";
}
cout << endl;
}
}
In NON WORKING code when I run the code it doesn't give any output but rather ends abruptly.
P.S. Any help will mean a lot I have already wasted around 2 days trying to find the solution for this.
Both programs have undefined behavior because you access the 2D array/vector out of bounds.
You first check if sol[x][y] == -1 and then you check if x and y are within bounds:
bool isPossible(int sol[N][N], int x, int y)
{
if (sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
You need to check the bounds first.
Your first solution should do:
if (x >= 0 && x < N && y >= 0 && y < N && sol[x][y]==-1)
Your second solution should do:
if(x >= 0 && x < N && y >= 0 && y < N && Brd[x][y].first == -1)
Note: The two programs produce different solutions. You'll have to decide which one is correct (if any).
First:
-1 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
Second:
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
I want to build a histogram with ell intervals. The size of each interval is computed as k = ceil(m/ell) where m is the maximum number in the data set. That is, the interval i should be [(i - 1) * k, i * k). If a data set is given by the numbers 16 33 55 57 8 47 1 21 14 73 6 59 29 57 20 95 77 5 62 48 and the number of intervals is ell = 10, the histogram has to be textually represented as
0: 4
10: 2
20: 3
30: 1
40: 2
50: 4
60: 1
70: 2
80: 0
90: 1
I need to write a program, that reads in the following values (from the standard input cin) :
the number ell of intervals
the size n of the data set
n non-negative integers
Here is my code so far:
#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;
int main() {
double ell;
int n; // size of the data set
double m = 0;
int * a;
int * x;
int * y;
cin >> ell;
cin >> n;
a = new int[n];
// finding max element in array a
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] > m) {
m = a[i];
}
}
int k = ceil(m/ell);
x = new int[(int)(ell)];
y = new int[(int)(ell)];
for (int i = 1; i <= ell; i++) {
x[i] = (i - 1) * k;
for (int j = 0; j < n; j++) {
if (a[j] >= (i - 1) * k && a[j] < i * k && x[i] != (ell - 1) * k) {
y[i] += 1;
} else if (a[j] >= (ell - 1) * k && x[i] == (ell - 1) * k) {
y[i] += 1;
} else {
y[i] += 0;
}
}
cout << x[i] << ": " << y[i] << endl;
}
delete [] a;
delete [] x;
delete [] y;
return 0;
}
If I input this:
10 20 16 33 55 57 8 47 1 21 14 73 6 59 29 57 20 95 77 5 62 48
I get
0: 4
10: 2
20: 3
30: 1
40: 2
50: 4
60: 1
70: 2
80: 0
90: 1
But if I input the same many times, I will get a weird output like
0: 4
10: 268501820
20: 1073741827
30: 112
40: 2
50: 4
60: 1
70: 2
80: 0
90: 6
Why is this happening and how can I fix my problem?
x = new int[(int)(ell)];
y = new int[(int)(ell)];
Creates objects on the heap, but unless the objects (i.e. int) have a constructor, then the memory is left uninitialized.
The array x is correctly initialized, but y is left (expected to be 0).
So the fix is ...
x = new int[(int)(ell)];
y = new int[(int)(ell)];
for( int i = 0; i < ell ; i++ ){
x[i] = 0; // tidier to do it obviously.
y[i] = 0; // essential to get y[i] += 1; to be meaningful.
}
You never initialise your memory. You create dynamic arrays with both x and y but you are not guaranteed that the memory is zeroed. You get lucky for the most part that but when there are values left in the memory your program uses you get the outliers that you see. Put something like this in and it should fix your issues.
for(int m = 0;m < (int)ell; m++) {
x[m] = 0;
y[m] = 0;
}
void allocateTriangle(int ** & twoDArray, int numRows);
void printTriangle(int ** twoDArray, int numRows);
void growToSquare(int ** & twoDArray, int numRows);
void printSquare(int ** & twoDArray, int numRows);
using namespace std;
int main(int argc, char ** argv){
srand((unsigned int)time(NULL));
int ** twoDArray;
int numRows = 10;
allocateTriangle(twoDArray, numRows);
cout << "******* Triangle array *******" << endl;
printTriangle(twoDArray, numRows);
growToSquare(twoDArray, numRows);
cout << "******* Sqaure array *******" << endl;
printSquare(twoDArray, numRows);
return 0;
}
void allocateTriangle(int ** & twoDArray, int numRows) {
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++){
twoDArray[x] = new int[x];
for (int y = 0; y <= x; y++){
twoDArray[x][y] = rand() % 100;
}
}
}
void printTriangle(int ** twoDArray, int numRows){
for (int x = 0; x < numRows; x++){
for (int y = 0; y <= x; y++){
cout << setw(5);
cout << twoDArray[x][y];
}
cout << endl;
}
}
void growToSquare(int ** & twoDArray, int numRows) {
for (int x = 0; x < numRows; x++){
int *tempArray = new int[x];
*tempArray = *twoDArray[x];
--> delete [] twoDArray[x];
twoDArray[x] = new int[numRows];
for (int y = 0; y < numRows; y++){
if (y <= x)
twoDArray[x][y] = tempArray[y];
else
twoDArray[x][y] = rand() % 100;
}
}
}
void printSquare(int ** & twoDArray, int numRows){
for (int x = 0; x < numRows; x++){
for (int y = 0; y <= numRows; y++){
cout << setw(5);
if (y <= x)
cout << twoDArray[x][y];
else if (y - 1 == x)
cout << " ";
else
cout << twoDArray[x][y - 1];
}
cout << endl;
}
}
The arrow is pointing to where this program likes to crash. Giving me a Heap Corruption, I've spent the last 6 hours looking at this and other posts, I got nothing.
The main gets to growToSquare() and when I try to 'resize' the 2D array by deletion and allocation again, it stopes at deletion. I've commented out other lines to code to see if something else is triggering, nada.
Any words of advice? (I am using Visual studio 2013)
WhozCraig spotted it, in his comment above.
y <= x should be y < x, in multiple places in this code. – WhozCraig
Imagine that numRows is 1 here, for the sake of simplicity. Follow the code logic in that simple case.
void allocateTriangle(int ** & twoDArray, int numRows) {
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++){
twoDArray[x] = new int[x];
for (int y = 0; y <= x; y++){
twoDArray[x][y] = rand() % 100;
}
}
}
Here is the code that would execute, which assigns to a zero-length array.
twoDArray = new int*[1];
twoDArray[0] = new int[0];
twoDArray[0][0] = rand() % 100;
Memory has now been corrupted.
Plausible Solution for Triangle Allocation
Though there a about a half-dozen different ways to calculate the indices, this way is likely the easiest to understand.
void allocateTriangle(int ** & twoDArray, int numRows)
{
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++)
{
twoDArray[x] = new int[x+1]; // NOTE: size
for (int y = 0; y <= x; y++)
twoDArray[x][y] = rand() % 100;
}
}
void printTriangle(int ** twoDArray, int numRows)
{
for (int x = 0; x < numRows; cout << endl, ++x)
for (int y = 0; y <= x; y++)
cout << setw(5) << twoDArray[x][y];
}
This allows you to keep your indexing (mostly) while sizing the allocations to appropriate lengths.
Growing a Triangle Into A Square
Similarly, the following will extend your triangle into a square. Note: you can invoke this on something already extended to a square. It will simply re-random-generate the right-half diagonal when doing so (and rather expensively at that).
void growToSquare(int ** & twoDArray, int numRows)
{
for (int x = 0; x < numRows; x++)
{
int *tempArray = new int[numRows];
for (int y=0; y<=x; ++y)
tempArray[y] = twoDArray[x][y];
for (int y=x+1; y<numRows; ++y)
tempArray[y] = rand() % 100;
delete [] twoDArray[x];
twoDArray[x] = tempArray;
}
}
void printSquare(int ** & twoDArray, int numRows)
{
for (int x = 0; x < numRows; cout << endl, ++x)
for (int y = 0; y < numRows; y++)
cout << setw(5) << twoDArray[x][y];
}
Output
Using the above methods, your output will look something like this. Obviously the random nature will result in different values, but the important thing is the bottom-left portion of the square retains the original triangle.
******* Triangle array *******
80
80 1
45 93 28
19 96 90 7
38 70 23 26 98
97 26 98 48 37 97
77 25 43 0 28 84 90
95 78 48 16 23 30 14 64
14 29 83 60 7 83 14 77 94
79 1 43 55 22 14 80 34 40 53
******* Sqaure array *******
80 10 62 17 62 94 62 47 87 3
80 1 56 67 56 91 85 51 25 8
45 93 28 9 42 57 95 56 19 42
19 96 90 7 46 67 42 77 53 73
38 70 23 26 98 53 22 34 69 3
97 26 98 48 37 97 8 18 53 55
77 25 43 0 28 84 90 7 82 43
95 78 48 16 23 30 14 64 94 33
14 29 83 60 7 83 14 77 94 75
79 1 43 55 22 14 80 34 40 53
I have Hexadecimal format IP4 address which needs to be converted to string. Could you please let me know what needs to be changed in the below code to get the right answer. Thanks a lot for the support.
int main (void) {
char buff[16];
string IpAddressOct = "EFBFC845";
string xyz="0x"+IpAddressOct+"U";
unsigned int iStart=atoi(xyz.c_str());
sprintf (buff, "%d.%d.%d.%d", iStart >> 24, (iStart >> 16) & 0xff,(iStart >> 8) & 0xff, iStart & 0xff);
printf ("%s\n", buff);
return 0;
}
The output I am getting is 0.0.0.0, but expected output is 239.191.200.69
atoi() only takes integers. If you call atoi("1"), it will return 1. If you call atoi("a"), it will return 0.
What you should do is create a mapping between hex values and do the calculation every two character. The following is an example:
1 #include <map>
2 #include <iostream>
3 #include <cstring>
4 #include <string>
5 #include <vector>
6
7 using namespace std;
8
9 static std::map<unsigned char, int> hexmap;
10
11 void init() {
12 hexmap['0'] = 0;
13 hexmap['1'] = 1;
14 hexmap['2'] = 2;
15 hexmap['3'] = 3;
16 hexmap['4'] = 4;
17 hexmap['5'] = 5;
18 hexmap['6'] = 6;
19 hexmap['7'] = 7;
20 hexmap['8'] = 8;
21 hexmap['9'] = 9;
22 hexmap['a'] = 10;
23 hexmap['A'] = 10;
24 hexmap['b'] = 11;
25 hexmap['B'] = 11;
26 hexmap['c'] = 12;
27 hexmap['C'] = 12;
28 hexmap['d'] = 13;
29 hexmap['D'] = 13;
30 hexmap['e'] = 14;
31 hexmap['E'] = 14;
32 hexmap['f'] = 15;
33 hexmap['F'] = 15;
34 }
35
36 vector<int> parseIp(string income) {
37 vector<int> ret;
38 if (income.size() > 8)
39 // if incoming string out of range
40 return ret;
41 int part = 0;
42 char buf[4];
43 for (int i = 0; i < income.size(); ++i) {
44 part += hexmap[income[i]];
45 cout << income[i] << " " << hexmap[income[i]] << " " << part << endl;
46 if ((i % 2) == 1) {
47 ret.push_back(part);
48 part = 0;
49 } else {
50 part *= 16;
51 }
52 }
53
54 return ret;
55 }
56
57 int main(void) {
58 init();
59 string ipAddressOct = "EFBFC845";
60 vector<int> ip = parseIp(ipAddressOct);
61 cout << ip[0] << "." << ip[1] << "." << ip[2] << "." << ip[3] << endl;
62 }
The above could be overly complicated. It is intended for example only.
//2D array with row4 and column4
11 12 18 40
14 15 13 22
11 17 19 23
17 14 20 28
My question is how do i looping the idea like this
. When looping for [0][0] = 11.
for the same entire rows which is 12 , 18 , 40 and same entire column 14 , 11 , 17 cannot be count.going through, After that my second looping will just looping the table sample like this
**11** **12** **18** **40**
**14** 15 13 22
**11** 17 19 23
**17** 14 20 28
my looping just can read those number without ** .
for second time. will choose the second column, which number is smallest and store into a variable temporaryA , and third looping will choose third column, choose smallest value and store into temporaryB, and fourth looping will choose fourth column and store into temporaryC
Finally. My answer will be the first number i choose just now
ANswer = 11 + temporaryA + temporaryB +temporaryC
void BranchandBound( int **minimumCost , int p , int j ){
/*
11 12 18 40
14 15 13 22
11 17 19 23
17 14 20 28
*/
bool *stars = new bool[4];
int totalMin = 0;
for( int y = 0 ; y < p ; y++ ){
int min,iMin = -1;
for( int x = 0 ; x < j ; x++ ){
if( !stars[y] || (iMin < 0 || min > minimumCost[y][x]) ){
min = minimumCost[y][x];
cout << "minimum : " << min << endl;
iMin = min;
totalMin += min;
}
stars[iMin] = 1;
}
}
cout << "Total : " << totalMin << endl;
}
You want to exclude columns where the minimum was (marked with stars in your question). Let's just remember them:
bool stars[4] = { 0 };
Now find the minimum as usual...
for (int y = 0; y < sz; y++) {
int min, iMin = -1;
for (int x = 0; x < sz; x++) {
Here, we have to skip columns where minimum already was:
if (!stars[x] && (iMin < 0 || min > numbers[x][y])) {
min = numbers[x][y];
iMin = x;
}
And now remember where the next minimum came from:
stars[iMin] = 1;
}
}
Done! Summing all the min is left as an exercise to the reader.