detecting duplicate in columns of a 2D array [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like an algorithm that goes through a 2D array and guarantees that each column has all distinct numbers. If a dupe is found in the array it should be replaced with a random number. The random number must also preserve the uniqueness.
If we put a random number, the whole column, should be unique.
is it possible to get an O(N) solution too ?

The best way I can think of is to make an unordered_map<int,bool> for each column, iterate through the column and if you see a number for the first time set the map to true, if the value is already true it's a dupe replace it with a random number. Then check the random number in the map and do the same thing, if it's also a dupe you will have to replace it with a random number again. This algo will like run in linear time, however because of the random number dupe possibility it could run infinitely.
pseudo code
2d_array // assume M rows by N cols
array_of_hashtables // N length
for each col
for each row
if array_of_hashtables[2d_array[row][col]] == false
set it to true
else
do
set 2d_array[row][col] to random
while array_of_hashtables[2d_array[row][col]] == true
end
end
not a huge fan of writing pseudo code but this is about right

Make a std::set and insert step by step elements of every column while checking the size of the set. If the size changes the inserted value is not a duplicate, if it does just randomize a value and add it again to the set. If size changes, you can continue.

Just for the heck of it, here is an implementation of Alexandru Barbarosie's solution:
#include <iostream>
#include <set>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int L = 3;
int W = 3;
int R = 3;
int a[L][W];
srand(time(NULL));
for (int i = 0; i < L; i++)
{
for (int j = 0; j < W; j++)
{
a[i][j] = rand() % R + 1;
cout << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
set<int> s;
int n = 0;
for (int j = 0; j < W; j++)
{
for (int i = 0; i < L; i++)
{
s.insert(a[i][j]);
if (s.size() != n)
n = s.size();
else
a[i--][j] = rand() % R + 1;
}
s.clear();
n = 0;
}
for (int i = 0; i < L; i++)
{
for (int j = 0; j < W; j++)
cout << a[i][j] << " ";
cout << endl;
}
}

Related

C++ delete duplicates from cstring [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a c-string that looks something like ABBBCACACACBA and I'm supposed to create a function that deletes the duplicate characters so I end up with ABC. I created a nested for loop that replaces every letter that matches the letter in the outer loop with a \0 and increments a counter that keeps track of the repeats. I'm getting -1 as the amount of repeats that should be documented, and from checking it spits out ABBC instead of ABC. I'm stumped, any ideas?
for (int i = 0; i < SIZE; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (letter[i] == letter[j])
{
letter[j] = '\0';
repeatCounter++;
}
}
}
It is not enough to just replace duplicates with '\0', you have to actually remove them from the string and shift the remaining characters down. Try something more like this:
int size = SIZE, i = 0;
while (i < size)
{
int j = i + 1;
while (j < size)
{
if (letter[j] == letter[i])
{
for (int k = j + 1; k < size; k++)
{
letter[k-1] = letter[k];
}
letter[--size] = '\0';
repeatCounter++;
continue;
}
j++;
}
i++;
}
Live Demo
Here's a simple example which does what you want. It uses std::string to store the output. You can copy-n-paste the code here to test and run. Look into using std::string as it has functions which will make your life easy.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input("ABBBCACACACBA");
string output;
for(size_t i = 0; i < input.size(); i++)
{
if(output.find(input[i]) == string::npos)
{
output += input[i];
}
}
cout << "Input: " << input << endl;
cout << "Output: " << output << endl;
return 0;
}

Is it possible to have functions run off the string within a variable rather than the variable name itself in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Its kind of hard to describe, but I'm basically asking whether or not I can have a function calling myString and actually have the string within get put into the function.
My code so far is:
for(uint n = 0; n < 5; n++) {
int r = n * n;
std::string R = std::to_string(n);
std::string currentSquared = ("Squared" + R);
int currentSquared.c_str() = r;
}
I know it's wrong I'd like the output to be a set of variables like:
Squared1 = 1, Squared4 = 16.
Any help would be appreciated.
No, you can't create arbitrary variables like you described, besides variable names are used during compilation and debugging, if you compile without debug symbols they disappear completely.
What you need here is to use an appropriate data structure to hold your data, instead of creating more variables to work with, you can read more about standard library containers here.
I would suggest using std::vector in your case.
std::vector<int> numbers{};
numbers.reserve(10);
for(int i = 0; i < 10; ++i) {
numbers.push_back(i * i);
}
std::cout << "Numbers squared:\n";
for (std::size_t i = 0; i < numbers.size(); ++i) {
std::cout << i << '*' << i << " = " << numbers[i] << '\n';
}
std::vector will take care of storing all the data for you, and should be your 1st choice as a container most of the time.
If you would like a dictionary that would allow you to index element with let's say std::string or const char*, you could also use a std::map.
You can take the help of std::unordered_map to create keys and gather data from them:
#include <iostream>
#include <unordered_map>
int main(void) {
std::unordered_map<std::string, int> variables;
// Initializing the map with their respective required keys
for (int i{1}; i <= 10; i++)
variables["Squared" + std::to_string(i)] = i * i;
// Displaying one of the initialized key
std::cout << variables["Squared4"];
return 0;
}
As a result, it'll display your desired output:
16 // 'Squared4' key holds (4 * 4) = 16
int main() {
vector<string> mystring;
for (int n = 0; n < 5; ++n) {
int squared = n * n;
string str_squared = to_string(squared);
mystring.push_back(str_squared);
}
for (int j = 0; j < mystring.size(); ++j) {
cout << mystring[j] << endl;
}
return 0;
}
I would try to store my strings in a container. In this instance, I used a vector. This allows me to have a set of strings, that are n squared. To display them I can iterate through my vector in the for loop. Not sure if this is what you were trying to achieve from your question.

Selection sort program not sorting correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int n, arr[10], i, j, temp, minin;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
for (i = 0; i < n - 1; i++)
{
minin = i;
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[minin])
minin = j;
temp = arr[minin];
arr[minin] = arr[i];
arr[i] = temp;
}
}
for (i = 0; i < n; i++)
{
cout << arr[i];
}
return 0;
}
There are no compile-time errors. But my code does not sort properly.
This is what I get:
INPUT :
4 //size of the array to be sorted
5 3 2 8 //actual array to be sorted
OUTPUT :
3528
The expected output is the sorted array in ascending order.
Off the top of my head (no testing at all) you need to move the swap code out of the inner loop
Not your code
for(j=i+1;j<n;j++)
{
if(arr[j]<arr[minin])
minin=j;
temp=arr[minin];
arr[minin]=arr[i];
arr[i]=temp;
}
but instead
// calculate the index of the minimum element in the rest of the array
for(j=i+1;j<n;j++)
{
if(arr[j]<arr[minin])
minin=j;
}
// swap the minimum element with the current element
temp=arr[minin];
arr[minin]=arr[i];
arr[i]=temp;
That is what you should do is calculate the minimum index first, and then swap the minimum index with i. These tasks should be separate, your code mixed them up.

Is this the correct implementation of Insertion Sort? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
OUTPUT
#include <iostream>
using namespace std;
int main()
{
//declaring the size of array and taking input from the user
int n = 0;
cout<<"Enter the Number of elements you want in the Array : ";
cin>>n;
//checking the user input
if(n <= 0)
{
cout<<"Not Possible\n";
return 1;
}
//declaring array of size 'n' and taking input from user
int list[n];
cout<<"Enter the Elements of the array of size "<<n<<" : ";
for(int i = 0; i < n; i++)
cin>>list[i];
//Insertion Sort
int swap = 0; //number of swaps
int comp = 0; //number of comparison
int temp; //temporary variable
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(list[j] < list[j-1])
{
//swapping equivalent to shifting
temp = list[j-1];
list[j-1] = list[j];
list[j] = temp;
comp++;
swap++;
}
else
{
comp++;
break;
}
}
//printing the iteration
cout<<"Iteration "<<(i+1)<<" : ";
for(int k = 0; k < n; k++)
cout<<list[k]<<" ";
cout<<"\n";
}
cout<<"\nSwap : "<<swap<<"\n";
cout<<"Comparison : "<<comp<<"\n";
cout<<"Sorted Array : ";
for (int i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
return 0;
}
Is this implementation of insertion sort correct because I have seen many implementation online using while loop and other things?
If not can you point out what is wrong?
Thanks in advance
link - https://github.com/ish-u/DiscreteStructures/blob/master/InsertionSort.cpp
No, this is a different type of sort, known as bubble sort. It still sorts, but insertion sort works in a different way, by keeping the array sorted at all times (moving elements if a new insertion would break the ordering).
So instead of just tagging new elements to the end of the array where you read them from cin, you should place each element directly in the right spot in the array. This will likely involve moving existing elements in order to keep the array sorted.
Note that your line
int list [n];
is wrong; you cannot allocate memory this way (and I'm surprised it even compiles). A better choice would be to use std::vector.

C++ malloc(): memory corruption [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.
When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size
In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;