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;
}
};
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 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;
}
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;
}
I'm currently training myself for sorting algorithms, and I got a problem with quicksorting a string array.
My code looks like this:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void strQsrt(string * ary, int l, int r);
int main ()
{
int i=0;
string temp;
string ary[100];
ifstream input("inputtext.txt");
while( !input.eof() )
{
input >> ary[i];
cout << i+1 << " : " << ary[i] << endl;
i++;
};
cout << endl;
strQsrt(ary, 0, 99);
return 0;
}
void strQsrt(string * ary, int l, int r)
{
int i=l, j=r;
string temp;
string mid=ary[ (l+r)/2 ];
while( i <= j )
{
while( ary[i] < mid )
{
i++;
};
while( ary[j] > mid )
{
j++;
};
if( i <= j )
{
temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
i++;
j++;
};
};
if( l < j )
{
strQsrt(ary, l, j);
};
if( i < r )
{
strQsrt(ary, i, r);
};
for( int c = 0; c < 100; c++)
{
cout << c+1 << " : " << ary[c] << endl;
};
}
I was trying to sort one hundred random names in alphabetical order. This code compiles properly, but I keep getting a segmentation fault. When I run this program in CygWin, it looks like this:
$ ./binarysearch.exe
1 : Brittny
2 : Margarett
3 : Mariella
4 : Amanda
5 : Isabella
6 : Meghan
7 : Junior
8 : Pamela
9 : Arnette
10 : Toi
11 : Serina
12 : Kim
13 : Peggy
14 : Ellena
15 : Paul
16 : Alica
17 : Keli
18 : Dorine
19 : Conception
20 : Ora
21 : Nakia
22 : Elmer
23 : Teddy
24 : Jacinda
25 : Paris
26 : Beula
27 : Lavette
28 : Marla
29 : Brandi
30 : Neva
31 : Niesha
32 : Dustin
33 : Lane
34 : Season
35 : Norene
36 : Karisa
37 : Johnathon
38 : Dan
39 : Lavenia
40 : Zonia
41 : Chau
42 : Stanton
43 : Patty
44 : Shyla
45 : Elfriede
46 : Leida
47 : Fawn
48 : Karrie
49 : Joanne
50 : Rivka
51 : Roslyn
52 : Cris
53 : Enola
54 : Rafaela
55 : Bula
56 : Teressa
57 : Jackqueline
58 : Antoinette
59 : Lizeth
60 : Torie
61 : Farrah
62 : Stefani
63 : Tamisha
64 : Masako
65 : Margarita
66 : Sandi
67 : Beau
68 : Candelaria
69 : Lia
70 : Tamra
71 : Anne
72 : Lona
73 : Odell
74 : Alethia
75 : Tama
76 : Lina
77 : Carli
78 : Viviana
79 : Dorothy
80 : Rima
81 : Robert
82 : Karolyn
83 : Silvana
84 : Florine
85 : Kandice
86 : Ernesto
87 : Nola
88 : Jasper
89 : Dalia
90 : Lashunda
91 : Ralph
92 : Delois
93 : Mathew
94 : Doretta
95 : Aron
96 : Barrie
97 : Hazel
98 : Lino
99 : Danna
100 : Nancy
Segmentation fault (core dumped)
I know segmentation fault is from some kind of bad pointer usage, but I don't think I can find where I messed it up. Where did I do wrong? How can I deal with this error?
You are setting initial valule of j in strQsrt function to 99. Then you are incrementing that value. Segmentation fault pops out when j =101, that is past the ary size. If you want to see for yourself modyfy your function to
void strQsrt(string * ary, int l, int r)
{
int i=l, j=r;
string temp;
string mid=ary[ (l+r)/2 ];
while( i <= j )
{
while( ary[i] < mid )
{
i++;
}
while( ary[j] > mid )
{
cout<<"j="<<j<<endl;
j++;
}
if( i <= j )
{
temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
i++;
j++;
}
}
if( l < j )
{
strQsrt(ary, l, j);
};
if( i < r )
{
strQsrt(ary, i, r);
};
for( int c = 0; c < 100; c++)
{
cout << c+1 << " : " << ary[c] << endl;
};
}
while( !input.eof() )
{
input >> ary[i];
cout << i+1 << " : " << ary[i] << endl;
i++; <------- when this gets to 100, what happens on next iteration?
};
your
string ary[100];
goes from 0 to 99 for 100 elements.
Changing the code to the following
while( i < 100 && !input.eof() )
{
input >> ary[i];
cout << i+1 << " : " << ary[i] << endl;
i++;
};
avoids crashes during read of data.
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.