C++: Segmentation Fault, malloc.c: No such file or directory - c++

I was solving a programming problem in C++ which requires examining all the 9! permutation of the 3 X 3 matrix
1 2 3
4 5 6
7 8 9
I think, I have written the correct logic, and infact tested it on a 2 X 2 matrix(by tweaking the code for 2 X 2 from 3 X 3, ofcourse.), which results into the correct output being printed. But when I run the program for the actual constraint(ie. the 3 X 3 matirx), the program terminates with a Segmentation fault. Oddly when debuugged with GDB, it prints out
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74f6bbc in _int_malloc (av=av#entry=0x7ffff7839b20 <main_arena>,
bytes=bytes#entry=12) at malloc.c:3353
3353 malloc.c: No such file or directory.
Here is the C++ code that I wrote:
#include <bits/stdc++.h>
using namespace std;
int min_count;
map<string, bool> mp;
vector<vector<int>>vec(3, vector<int>(3, 0));
// n <= 17
bool isPrime(int n) {
return n == 2 or n == 3 or n == 5 or n == 7 or n == 11 or n == 13 or n == 17;
}
// get a String representation of the matrix vec
string getStringRepresentation(vector<vector<int>> vec) {
string str = "";
for(auto i : vec) {
for(auto j : i)
str += ('0' + j);
}
return str;
}
void printRecursive(vector<vector<int>> &vec, map<string, bool> &mp, int count) {
string str = getStringRepresentation(vec);
if(str == "123456789" and count <= min_count)
min_count = count;
//cout << str << " " << count << endl;
if(mp[str])
return;
mp[str] = true;
for(int i = 0; i < vec.size(); ++i) {
for(int j = 0; j < vec[i].size(); ++j) {
if(j != vec[i].size() - 1 and isPrime(vec[i][j] + vec[i][j+1])) {
swap(vec[i][j], vec[i][j+1]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i][j+1]);
}
if(i != vec.size() - 1 and isPrime(vec[i][j] + vec[i+1][j])) {
swap(vec[i][j], vec[i+1][j]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i+1][j]);
}
}
}
}
// solve for each test case
void solve() {
for(auto &i : vec) {
for(auto &j : i) {
cin >> j;
}
}
//cout << getStringRepresentation(vec) << endl;
min_count = INT_MAX;
printRecursive(vec, mp, 0); // recursively examine all possible states.
// if min_count is not changed(i.e. reamains equal to INT_MAX then the required state is unreachable, print -1 to indicate)
cout << (min_count == INT_MAX ? -1 : min_count) << endl;
}
int main() {
int test; // test are the number of test cases, each will invoke the solve() function.
cin >> test;
while(test--)
solve();
}
For a input
1
7 3 2
4 1 5
6 8 9
The program should have been outputting 6 but results in SIGSEGV as mentioned. What am I doing wrong?

Try using debugging print lines to see where the segmentation fault happens. Also, try to store the matrix as an array of 9 elements rather than a matrix.

Related

Pattern Printing-Where am I going wrong in this C++ code?

I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}

using a user input in a loop and function

My program takes a user input, int n, and prints out the first n amount of prime numbers. This is working as intended
eg. if user inputs 8 as n. the program will print :
2 3 5 7 11 13 17 19
My problem is adding the function isPrime(n) (which is not allowed to be changed)
here is what i've tried but im just getting the output :
2 3 5 7 11 13 17 19 0 is not a prime number,
when it should read 2 3 5 7 11 13 17 19 8 is not a prime number
#include "prime.h"
#include <iostream>
int main()
{
int n;
std::cout << "Enter a natural number: ";
std::cin >> n;
for (int i = 2; n > 0; ++i)
{
bool Prime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
Prime = false;
break;
}
}
if (Prime)
{
--n;
std::cout << i << " ";
}
}
if (isPrime(n))
{
std::cout << n << " is a prime number." << std::endl;
}
else
{
std::cout << n << " is not a prime number." << std::endl;
}
system("pause");
}
prime.h :
#ifndef PRIME_H_RBH300111
#define PRIME_H_RBH300111
bool isPrime(int);
#endif
#pragma once
the definition of isPrime(int)
prime.cpp :
#include <cmath>
#include "prime.h"
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else if (n == 2)
{
return true;
}
else if ((n % 2) == 0)
{
return false;
}
}
I cannot alter the .h file of prime.cpp
I just need the isPrime(n) function to work on the main() function code
the user input n, does not seem to be taking the number 8. but instead 0
giving me the output. 0 is not a prime number
rather than : n (8) is not a prime number
You are decrementing n in the loop. At the time the loop exits, the value of n is 0.
You can solve the problem by:
Using another variable to use in the loop.
Keeping a copy of the n and resetting the value of n after the loop exits.
Here's the second method:
int copyN = n;
for (int i = 2; n > 0; ++i)
{
...
}
n = copyN;
if (isPrime(n))
...
You are decrementing n in the for loop. The for loop has the condition 'n > 0', so you know n isn't > 0 when the loop finishes. You could either save the value of n in a different variable (i.e. "int nOrig = n;") and use that for the prime test, or use a different variable in the loop.

Create all possible combinations using a deque and recursion C++

I have a deque that contains a series of numbers {0, 1, 2, 3, 4, 5, 6} and I am trying to create all possible combinations of these numbers using recursion.
Here is my current code
void combination(vector<node> &comb, deque<node> &numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i].id << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
I've ran this through on paper and it makes sense but when I run it this is the output:
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Why isn't the function printing out all possible combinations?
Also, this is what I want to use - A deque that contains the numbers and a vector that contains each combination.
You are using Pass by reference, i have made some minor changes and it works
code :
#include <bits/stdc++.h>
using namespace std;
void combination(vector<int> comb, deque<int> numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i] << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
int main() {
// your code goes here
vector<int> comb;
deque<int> numbers;
for(int i = 0;i < 7;i++) numbers.push_back(i);
combination(comb, numbers);
return 0;
}
Link to solution on ideone : http://ideone.com/vgukF3

Permutations &/ Combinations using c++

I need a different version of permutations for my code. I could able to achieve what I want but it is not generic enough. my algorithm keeps going bigger along with my requirements. But that should not be.
This is not a home work for any one, I need it for one my critical projects, wondering if any pre-defined algorithms available from boost or any other.
Below is the standard version of next_permutation using c++.
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation
int main ()
{
int myints[] = {1,2,3};
do
{
std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while ( std::next_permutation(myints,myints+3) );
return 0;
}
That gives below output :
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
But my requirement is :- Let's say I have 1 to 9 numbers :
1,2,3,4,5,6,7,8,9
And I need a variable length of permutations and in only ASCENDING order and with out DUPLICATES.
Let's say i need 3 digit length of permutations then i need output as below.
123
124
125
.
.
.
128
129
134 // After 129 next one should be exactly 134
135 // ascending order mandatory
136
.
.
.
148
149
156 // exactly 156 after 149, ascending order mandatory
.
.
.
489 // exactly 567 after 489, because after 3rd digit 9, 2nd digit
567 // will be increased to 49? , so there is no possibility for
. // 3rd digit, so first digit gets incremented to 5 then 6 then
. // 7, in ascending order.
.
.
.
789 // and this should be the last set I need.
My list may contain upto couple of hundred's of numbers and variable length can be 1 to up to Size of the list.
My own algorithm is working for specific variable length, and a specific size, when they both changes, i need to write huge code. so, looking for a generic one.
I am not even sure if this is called as Permutations or there is a different name available for this kind of math/logic.
Thanks in advance.
musk's
Formally, you want to generate all m-combinations of the set [0;n-1].
#include <iostream>
#include <vector>
bool first_combination (std::vector<int> &v, int m, int n)
{
if ((m < 0) || (m > n)) {
return false;
}
v.clear ();
v.resize (m);
for (int i = 0; i < m; i++) {
v[i] = i;
}
return true;
}
bool next_combination (std::vector<int> &v, int m, int n)
{
for (int i = m - 1; i >= 0; i--) {
if (v[i] + m - i < n) {
v[i]++;
for (int j = i + 1; j < m; j++) {
v[j] = v[j - 1] + 1;
}
return true;
}
}
return false;
}
void print_combination (const std::vector<int> &v)
{
for (size_t i = 0; i < v.size(); i++) {
std::cout << v[i] << ' ';
}
std::cout << '\n';
}
int main ()
{
const int m = 3;
const int n = 5;
std::vector<int> v;
if (first_combination (v, m, n)) {
do {
print_combination (v);
} while (next_combination (v, m, n));
}
}
You can use this code and the linked article as inspiration.
This task can be done with a simple iterative algorithm. Just increment the first element that can be incremented and rescale the elements before it until there is no element to be incremented.
int a[] = {0,1,2,3,4,5,6,7,8,9}; // elements: must be ascending in this case
int n = sizeof(a)/sizeof(int);
int digits = 7; // number of elements you want to choose
vector<int> indexes; // creating the first combination
for ( int i=digits-1;i>=0;--i ){
indexes.push_back(i);
}
while (1){
/// printing the current combination
for ( int i=indexes.size()-1;i>=0;--i ){
cout << a[indexes[i]] ;
} cout << endl;
///
int i = 0;
while ( i < indexes.size() && indexes[i] == n-1-i ) // finding the first element
++i; // that can be incremented
if ( i==indexes.size() ) // if no element can be incremented, we are done
break;
indexes[i]++; // increment the first element
for ( int j=0;j<i;++j ){ // rescale elements before it to first combination
indexes[j] = indexes[i]+(i-j);
}
}
Output:
0123456
0123457
0123458
0123459
0123467
0123468
0123469
0123478
0123479
0123489
0123567
0123568
0123569
0123578
0123579
0123589
0123678
0123679
0123689
0123789
0124567
0124568
0124569
0124578
0124579
0124589
0124678
0124679
0124689
0124789
0125678
0125679
0125689
0125789
0126789
0134567
0134568
0134569
0134578
0134579
0134589
0134678
0134679
0134689
0134789
0135678
0135679
0135689
0135789
0136789
0145678
0145679
0145689
0145789
0146789
0156789
0234567
0234568
0234569
0234578
0234579
0234589
0234678
0234679
0234689
0234789
0235678
0235679
0235689
0235789
0236789
0245678
0245679
0245689
0245789
0246789
0256789
0345678
0345679
0345689
0345789
0346789
0356789
0456789
1234567
1234568
1234569
1234578
1234579
1234589
1234678
1234679
1234689
1234789
1235678
1235679
1235689
1235789
1236789
1245678
1245679
1245689
1245789
1246789
1256789
1345678
1345679
1345689
1345789
1346789
1356789
1456789
2345678
2345679
2345689
2345789
2346789
2356789
2456789
3456789

Finding Minimal lexicographical Array

I tried solving this interview question. My code runs for test cases but fails for all the real input test cases. I tried hard to find the mistake but unable to do so. Please find my code below the question
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task. He gives Bob an array and an integer K. The challenge is to produce the lexicographical minimal array after at most K-swaps. Only consecutive pairs of elements can be swapped. Help Bob in returning the lexicographical minimal array possible after at most K-swaps.
Input: The first line contains an integer T i.e. the number of Test cases. T test cases follow. Each test case has 2 lines. The first line contains N(number of elements in array) and K(number of swaps). The second line contains n integers of the array.
Output: Print the lexicographical minimal array.
Constraints:
1 <= T <= l0
1 <= N,K <= 1000
1 <= A[i] <= 1000000
Sample Input (Plaintext Link)
2
3 2
5 3 1
5 3
8 9 11 2 1
Sample Output (Plaintext Link)
1 5 3
2 8 9 11 1
Explanation
After swap 1:
5 1 3
After swap 2:
1 5 3
{1,5,3} is lexicographically minimal than {5,1,3}
Example 2:
Swap 1: 8 9 2 11 1
Swap 2: 8 2 9 11 1
Swap 3: 2 8 9 11 1
#include <iostream>
using namespace std;
void trySwap(int a[], int start, int end, int *rem)
{
//cout << start << " " << end << " " << *rem << endl;
while (*rem != 0 && end > start)
{
if (a[end - 1] > a[end])
{
swap(a[end - 1], a[end]);
(*rem)--;
end--;
}
else end--;
}
}
void getMinimalLexicographicArray(int a[], int size, int k)
{
int start , rem = k, window = k;
for (start = 0; start < size; start++)
{
window = rem;
if (rem == 0)
return;
else
{
//cout << start << " " << rem << endl;
int end = start + window;
if (end >= size)
{
end = size - 1;
}
trySwap(a, start, end, &rem);
}
}
}
int main()
{
int T, N, K;
int a[1000];
int i, j;
cin >> T;
for (i = 0; i < T; i++)
{
cin >> N;
cin >> K;
for (j = 0; j < N; j++)
{
cin >> a[j];
}
getMinimalLexicographicArray(a, N, K);
for (j = 0; j < N; j++)
cout << a[j] << " ";
cout << endl;
}
return 0;
}
Python solution can be easily translated to C++:
def findMinArray(arr, k):
i = 0
n = len(arr)
while k > 0 and i < n:
min_idx = i
hi = min(n, i + k + 1)
for j in range(i, hi):
if arr[j] < arr[min_idx]:
min_idx = j
for j in range(min_idx, i, -1):
arr[j - 1], arr[j] = arr[j], arr[j - 1]
k -= min_idx - i
i += 1
return arr
Here are two failed test cases.
2
2 2
2 1
5 3
3 2 1 5 4
In the first, your code makes no swaps, because K >= N. In the second, your code swaps 5 and 4 when it should spend its third swap on 3 and 2.
EDIT: the new version is still too greedy. The correct output for
1
10 10
5 4 3 2 1 10 9 8 7 6
is
1 2 3 4 5 10 9 8 7 6
.