C++ for loop that reverses the digits 10 - 99 - c++

I am trying to write code that will list and reverse all digit pairs from 01 - 99. 01-09 is easy enough since you just have to multiply it by 10. I also know at least one way to reverse a given digit, I just don't know how to properly use it with a for loop.
This is what I have so far.
for ( int num99 =1 ; num99 > 0 && num99 < 100; num99 = num99+1)
{
if (num99 <10){
temp99 = num99 * 10;
cout << temp99 << endl;
}
else {
while (num99 != 0) {
remainder99 = num99 % 10;
reverse99 = (reverse99 * 10) + remainder99;
num99 = num99 / 10;
}
cout << reverse99 << endl;
}
}
Thank you for any help.

You have to reinitialize the values of remainder99, reverse99, temp99, num99 after you have used them.
You also have to prepend 0 to the result, when you reverse 10, 20, 30 etc... to get 01, 02, 03 etc...
After making the necessary changes, your program will look like this.
#include<iostream>
using namespace std;
int main(void)
{
int remainder99 = 0;
int reverse99 = 0;
int temp99 = 0;
for ( int num99 =1 ; num99 > 0 && num99 < 100; num99 = num99+1)
{
if (num99 <10){
temp99 = num99 * 10;
cout << temp99 << endl;
}
else {
temp99 = num99;
while (num99 != 0) {
remainder99 = num99 % 10;
reverse99 = (reverse99 * 10) + remainder99;
num99 = num99 / 10;
}
if(reverse99 < 10) cout << 0;
cout << reverse99 << endl;
reverse99 = 0;
remainder99 = 0;
num99 = temp99;
}
}
return 0;
}
Output is:
10
20
30
40
50
60
70
80
90
01
11
21
31
41
51
61
71
81
91
02
12
22
32
42
52
62
72
82
92
03
13
23
33
43
53
63
73
83
93
04
14
24
34
44
54
64
74
84
94
05
15
25
35
45
55
65
75
85
95
06
16
26
36
46
56
66
76
86
96
07
17
27
37
47
57
67
77
87
97
08
18
28
38
48
58
68
78
88
98
09
19
29
39
49
59
69
79
89
99

What you are trying to do is trying to operate over the loop variable, which causes unexpected results. Instead, separate your loop variable and your num99 variable like this:
for (int i = 1; i < 100; i++) {
int num99 = i;
if (num99 < 10) {
temp99 = num99 * 10;
cout << temp99 << endl;
} else {
remainder99 = num99 % 10;
num99 = num99 / 10;
if (remainder99 == 0) {
cout<<"0"<<num99<<endl;
} else {
reverse99 = remainder99 * 10 + num99;
cout << reverse99 << endl;
}
}
}
I have also taken the liberty of assuming that when you reverse the two digit numbers like 10, 20, etc, you want the output to be 01, 02, like that, if that is not what is expected by you, you can remove the if condition.

There are lot of issues with mentioned code like
Here reverse99 * 10 what is initial value of reverse99 ? Assign it as 0.
Here num99 = num99 / 10; you are modifying original num99 which outer loop variable, instead of this assign num99 to some temporary variable & do operation with that temporary variable.
Sample Code
int main(void) {
int temp99 = 0,remainder99 = 0, reverse99 = 0/* must initialize with 0 */ ;
for ( int num99 =1 ; num99 > 0 && num99 < 100; num99 += 1) {
if (num99 <10){
temp99 = num99 * 10;
std::cout << num99 << std::endl;
}
else {
reverse99 = 0;/*make it as 0 again for every iteration */
temp99 = num99; /* assign loop variable to temp99 & do the operation with that */
while (temp99 != 0) {
remainder99 = temp99 % 10;
reverse99 = (reverse99 * 10) + remainder99;
temp99 /= 10;
}
std::cout << reverse99 << std::endl;
}
}
return 0;
}

A C++11 oriented solution:
#include <vector>
#include <iostream>
#include <numeric>
#include <algorithm>
int main()
{
std::vector<int> in(99);
std::iota(in.begin(), in.end(), 1);
std::for_each(in.begin(), in.end(), [](int& i)
{
i = (i % 10)*10 + (i / 10);
}
);
for (const auto& val : in)
{
std::string out = std::to_string(in);
if (out.size() == 1)
{
out = '0' + out;
}
std::cout << out << std::endl;
}
return 0;
}

Related

Trying to solve Knights Tour on nested vector<vector<pair<int,int>> but is is not working

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

C++ unordered_map weird behaviour

I was solving leetcode problem (Pairs of Songs With Total Durations Divisible by 60) and my solution below uses a map, when I change it to an unordered_map and print the elements inside the loop; the number of elements are much more than the input
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
//cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << 60 - f << "\n";
ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};
Sample Input Test: [15, 63, 451, 213, 37, 209, 343, 319]
And the output is as follows:
3 57
15 45
19 41
29 31
31 29
33 27
37 23
41 19
43 17
45 15
57 3
The number of elements printed should be only 8 inside the loop, but with an unordered_map, the elements are much more.
The code that is not working well is below:
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
unordered_map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
//cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << 60 - f << "\n";
ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};
The only difference is the usage of unordered_map instead of a map
And it prints the elements wrongly as:
19 41
43 17
37 23
33 27
31 29
29 31
3 57
41 19
15 45
41 19
3 57
29 31
31 29
57 3
33 27
37 23
43 17
17 43
19 41
23 37
27 33
Anyone knows why is this odd behavior happening?
Alright I now understand, thank you so much all for the help. As per this link that shows the different ways to access a map, I see that using [] operator creates the elements if they are not there in the map and that is my mistake. When I should use std::map::at to retrieve map element
Fix
Checking if the element exist at first and using at() to access it
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
unordered_map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << i++ << "\n";
if(mod_d.count((60 - f) % 60) > 0) ans += mod_d.at((60 - f) % 60) * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};

Flip matrix across its diagonal [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
What would be the simplest way to reorder my number values in the second matrix with 90 being in the top left and 10 being in the bottom right? My brain is going blank and I know there has to be any easy way to go about this. Any help is appreciated tremendously!
Here's what I'm trying to achieve.
#include <iostream>
using namespace std;
void main() {
cout << "Before:" << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int matrix[9][9] = {
{ 10,11,12,13,14,15,16,17,18 },
{ 19,20,21,22,23,24,25,26,27,},
{ 28,29,30,31,32,33,34,35,36 },
{ 37,38,39,40,41,42,43,44,45 },
{ 46,47,48,49,50,51,52,53,54 },
{ 55,56,57,58,59,60,61,62,63 },
{ 64,65,66,67,68,69,70,71,72 },
{ 73,74,75,76,77,78,79,80,81 },
{ 82,83,84,85,86,87,88,89,90 }
};
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "After:" << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int transMatrix[9][9] = {
{ 10,11,12,13,14,15,16,17,18 },
{ 19,20,21,22,23,24,25,26,27,},
{ 28,29,30,31,32,33,34,35,36 },
{ 37,38,39,40,41,42,43,44,45 },
{ 46,47,48,49,50,51,52,53,54 },
{ 55,56,57,58,59,60,61,62,63 },
{ 64,65,66,67,68,69,70,71,72 },
{ 73,74,75,76,77,78,79,80,81 },
{ 82,83,84,85,86,87,88,89,90 }
};
cout << transMatrix[j][i] << " ";
}
cout << endl;
}
}
You could just loop in reverese.
for (int i = 8; i >= 0; i--) {
for (int j = 8; j >= 0; j--) {
//Print element [j][i] here
}
}
Also move the matrix assignment to outside of the loop as pointed out by Federico
Let's consider the following matrix
#define ROW 3
#define COL 4
int main()
{
int mat [ROW][COL] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
//...
return 0;
}
1/ If you want the backwards matrix
int backwards_mat[ROW][COL];
for(size_t i = 0; i < ROW; ++i)
{
for(size_t j = 0; j < COL; ++j)
{
backwards_mat[i][j] = mat[ROW-1-i][COL-1-j];
}
}
2/ If you want the transposed matrix
int transposed_mat[COL][ROW]; //swap the dimensions
for(size_t i = 0; i < ROW; ++i)
{
for(size_t j = 0; j < COL; ++j)
{
transposed_mat[j][i] = mat[i][j];
}
}
If you prints the two matrices, the backwards will be:
12 11 10 9
8 7 6 5
4 3 2 1
And the transposed will be:
1 5 9
2 6 10
3 7 11
4 8 12
You should be able to easily apply this to your matrix.
Do you mean the following?
#include <iostream>
#include <utility>
int main()
{
const size_t N = 9;
int matrix[N][N] =
{
{ 10,11,12,13,14,15,16,17,18 },
{ 19,20,21,22,23,24,25,26,27,},
{ 28,29,30,31,32,33,34,35,36 },
{ 37,38,39,40,41,42,43,44,45 },
{ 46,47,48,49,50,51,52,53,54 },
{ 55,56,57,58,59,60,61,62,63 },
{ 64,65,66,67,68,69,70,71,72 },
{ 73,74,75,76,77,78,79,80,81 },
{ 82,83,84,85,86,87,88,89,90 }
};
for ( const auto &row : matrix )
{
for ( const auto &item : row ) std::cout << item << ' ';
std::cout << '\n';
}
std::cout << '\n';
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N - i - 1; j++ ) std::swap( matrix[i][j], matrix[N-j-1][N-i-1] );
}
for ( const auto &row : matrix )
{
for ( const auto &item : row ) std::cout << item << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
The program output is
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80 81
82 83 84 85 86 87 88 89 90
90 81 72 63 54 45 36 27 18
89 80 71 62 53 44 35 26 17
88 79 70 61 52 43 34 25 16
87 78 69 60 51 42 33 24 15
86 77 68 59 50 41 32 23 14
85 76 67 58 49 40 31 22 13
84 75 66 57 48 39 30 21 12
83 74 65 56 47 38 29 20 11
82 73 64 55 46 37 28 19 10

Fill Matrix in a special order C++

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;
}

Hexadecimal IP to String using C++

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.