Displaying Matrix elements in Strange Order - c++

I was not really sure what this order of printing is called hence called it strange.
Consider the following sample example:
1 3 5
2 6 7
Expected output:
1,2
1,6
1,7
3,2
3,6
3,7
5,2
5,6
5,7
Or this example:
1 2 3
4 5 6
7 8 9
output:
1,4,7
1,4,8
1,4,9
1,5,7
1,5,8
1,5,9
... and so on.
I have analyzed that the number of possible combinations will be rows^columns for any given matrix.Here is my solution:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
void printAllPossibleCombinations(int** a, int h, int n, string prefix)
{
if (h == 0)
{
for (int i = 0; i < n; i++)
{
cout << prefix << a[0][i] << endl;
}
}
else
{
for (int i = 0; i < n; i++)
{
string recursiveString = prefix;
recursiveString.append(to_string(a[h][i]));
recursiveString.append(1, ',');
printAllPossibleCombinations(a, h-1, n, recursiveString);
}
}
}
int main()
{
int **a;
int m,n,k;
cout<<"Enter number of rows: ";
cin>>m;
a = new int*[m];
cout<<endl<<"Enter number of columns: ";
cin>>n;
for(int i=0;i<m;i++)
{
a[i] = new int [n];
}
for(int i=0;i<m;i++)
{
for(int j = 0; j < n;j++)
{
cout<<"Enter a[" << i << "][" << j<< "] = ";
cin>>a[i][j];
cout<<endl;
}
}
printAllPossibleCombinations(a, m-1, n, "");
return 0;
}
Is there an easy and more optimized way of doing it? Please suggest.
Thank You

As you said, there are rows^columns things to physically print out in the algorithm so you can't do better than an O(rows^columns) algorithm and your algorithm is as optimal as you'll get.

Related

How can I start a loop from middle of the array?

There is a given pseudo code.
int Function(X : array[P..Q] of integer)
1 maxSoFar = 0
2 for L = P to Q
I was using C and trying to change it into C++ code.
The reason that I am struggling with it is I have no idea how to express it is start from 'P' in the loop.
I do not know how to do that before initilization even without parameter.
int Function(vector<int> X)
{
int maxSoFar = 0;
for (int I = 0; I < X.size(); I++) ;
}
This is what I did.
I wonder if it is same with the pseudo code or not.
You can just divide your vector size by 2:
#include <vector>
#include <iostream>
using namespace std;
int f(vector<int> v) {
int maxSoFar = 0;
int len = v.size();
for (int i = len / 2; i < len; i++) { // i = len / 2, starts from the middle
maxSoFar += v[i];
cout << v[i] << ' ';
cout << maxSoFar << endl;
}
}
int main(void) {
vector<int> v = {1, 3, 5};
f(v);
}
output:
3 3
5 8
You should take a closer look at the for loop on wikipedia: for (initialization; break condition; incrementation)
#include<iostream>
using namespace std;
int main()
{
int i,n;
cout<<"enter the number of elements : ";
cin>>n;
int a[n];
cout<<endl<<"enter the value of this array : ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<endl<<"print the last half elements of this array : ";
for(i=(n/2);i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}

I want to print out the last result done by the loop C++

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i;
int n=0;
int F[10];
F[0]=0;
F[1]=1;
cin>>n;
for(i=2; i<n+1; ++i)
{
F[i]=(F[i-1])+F[i-2];
cout <<F[i]<<endl;
}
getch();
return 0;
}
now this is a sort of a fibonacci number generator, but it outputs all previous numbers in the fibonacci series. I want it to print the last one. For example, if the input is 8, i want it to output "21" instead of 1 2 3 5 8 13 21.
#include <iostream>
#include <conio.h>
int main()
{
int F[10];
F[0] = 0;
F[1] = 1;
int n = 0;
cin >> n;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i-1] + F[i-2];
}
std::cout << F[n] << std::endl;
getch();
}
Since you already know the index of the last element (n), you can just print that after the loop. I also did some other cleanup that didn't change the functionality of the program.
Note that the program originally and still assumes that n is less than 10.
Just store only 2 last values:
#include <iostream>
using namespace std;
int main()
{
int F[2] = { 1, 1 };
int n = 0;
cin>>n;
for(int i=2; i<n; ++i)
{
swap( F[0], F[1] );
F[1] += F[0];
}
std::cout << F[1] << std::endl;
return 0;
}

Error implementing selection sort in C++

I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
I can't find the error. I'm new to C++.
Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below.
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
The resulting output was as follows:
-5 -4 -3 0 2 3 4 6 100 200
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.

Count how many times elements in an array are repeated

The program I'm trying to write allows me to enter 10 numbers and it should get tell me Number X is repeated X times and so on.
I've been trying this but the problem is I get the result as follows:
For example...{1,1,1,1,4,6,4,7,4}
The number 1 is repeated 4 times
The number 1 is repeated 3 times
The number 1 is repeated 2 times
The number 1 is repeated 1 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 4 is repeated 2 times
The number 7 is repeated 1 times
The number 4 is repeated 1 times
The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before
#include <iostream>
#include <string>
using namespace std;
int main() {
int x[10];
for (int i=0;i<10;i++) {
cin>>x[i];
}
for (int i=0;i<9;i++) {
int count=1;
for (int j=i+1;j<10;j++) {
if (x[i]==x[j]) count++;
}
cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
}
}
The problem with your code is that you re-process numbers that you've already processed. So if there is an occurrence of 1 at position 0 and another occurrence of 1 at position 5, then you will process the 1 at position 5 again when you get there in the loop.
So you need a way to decide if a number has been processed already or not. An easy way is to add a second array (initially all values are set to 0) and whenever you process a number you mark all positions where that element occurs. Now before processing an element you check if it's been processed already and do nothing if that's the case.
Also, try to indent your code properly :)
C++ Code:
int main( void ) {
const int N = 10;
int A[N];
for(int i = 0; i < N; i++)
cin >> A[i];
int seen[N];
for(int i = 0; i < N; i++)
seen[i] = 0;
for(int i = 0; i < N; i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < N; j++)
if(A[j] == A[i]) {
count += 1;
seen[j] = 1;
}
cout << A[i] << " occurs " << count << " times" << endl;
}
}
return 0;
}
Here's a fairly simple implementation using std::map.
#include <map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::map<int, unsigned int> counter(const std::vector<int>& vals) {
std::map<int, unsigned int> rv;
for (auto val = vals.begin(); val != vals.end(); ++val) {
rv[*val]++;
}
return rv;
}
void display(const std::map<int, unsigned int>& counts) {
for (auto count = counts.begin(); count != counts.end(); ++count) {
std::cout << "Value " << count->first << " has count "
<< count->second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 1 has count 4
Value 4 has count 3
Value 6 has count 1
Value 7 has count 1
Compiled using the C++14 standard, but it should also work with C++11. Get rid of the vector initializer and use of auto and it should work with C++98.
Update:
I've updated this code a bit to use std::unordered_map instead of std::map, since order doesn't seem to be an issue. Also, I have simplified the loop controls based on some newer C++ features.
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::unordered_map<int, unsigned int> counter(const std::vector<int>& vals) {
std::unordered_map<int, unsigned int> rv;
for (auto val : vals) {
rv[val]++;
}
return rv;
}
void display(const std::unordered_map<int, unsigned int>& counts) {
for (auto count : counts) {
std::cout << "Value " << count.first << " has count " << count.second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 7 has count 1
Value 6 has count 1
Value 4 has count 3
Value 1 has count 4
In this case, the order of the counts will be random since std::unordered_map is a hash table with no intrinsic ordering.
The most effective way I have recently come across with this...
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int array[10]={1,1,1,1,4,6,4,7,4};
int a[100];
memset(a,0,sizeof(a));
for(int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
a[array[i]]++;
}
for(int i=1; i<sizeof(a)/sizeof(a[0]); i++)
{
if(a[i]>0)
{
cout<<"The number "<<i<<"is repeated "<<a[i]<<" times"<<"\n";
}
}
OUTPUT:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
Pretty simple using map!
See the Repl.it
#include <iostream>
#include <map>
int main()
{
int foo[]{1,1,1,1,4,6,4,7,4};
std::map<int, int> bar;
for (auto const &f : foo)
bar[f]++;
for (auto const &b : bar)
std::cout << "The number " << b.first
<< "is repeated " << b.second
<< "times\n";
}
Expected output:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"enter length of array:"<<endl;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cout<<"enter element:";
cin>>arr[i];
}
sort(arr,arr+n);
/*this is for sort the array so we can find maximum element form user input and
using this element we make one array of that size
*/
int m=arr[n-1];
m++;
int a[m];
for(int i=0;i<m;i++)
{
a[i]=0;
}
for(int i=0;i<n;i++)
{
a[arr[i]]++;
}
cout<<endl;
for(int i=0;i<m;i++)
{
if(a[i]>0)
cout<<i<<"is repeat:"<<a[i]<<"time"<<endl;
}
}
output is like this:
enter length of array:
6
enter element:6
enter element:5
enter element:5
enter element:6
enter element:2
enter element:3
2is repeat:1time
3is repeat:1time
5is repeat:2time
6is repeat:2time
package DP;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class countsofRepeatedNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {1,1,1,1,4,4,6,4,7};
int n=arr.length;
countNumber(arr,n);
}
private static void countNumber(int[] arr, int n) {
TreeMap<Integer,Integer>list= new TreeMap<Integer,Integer>();
Arrays.sort(arr);
int count=1;
for(int i=0;i<n-1;i++) {
if(arr[i]==arr[i+1]) {
count++;
}else {
list.put(arr[i], count);
count=1;
}
}
list.put(arr[n-1], count);
printDatas(list);
}
private static void printDatas(TreeMap<Integer, Integer> list) {
for(Map.Entry<Integer, Integer>m:list.entrySet()) {
System.out.println("Item "+m.getKey()+": "+m.getValue());
}
}
}
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; }
} int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
This code is in just O(n) time and O(1) space
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; } } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
#include <iostream>
#include<map>
using namespace std;
int main()
{
int arr[]={1,1,1,1,4,6,4,7,4};
int count=1;
map<int,int> mymap;
try
{
if(sizeof(arr)/sizeof(arr[0])<=1)
{
throw 1;
}
}
catch(int x)
{
cout<<"array size is not be 1";
return 0;
}
for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)
{
for(int j=i;j<(sizeof(arr)/sizeof(arr[0]));j++)
{
if(arr[i]==arr[j+1])
{
count++;
}
}
if(mymap.find(arr[i])!=mymap.end())
{
auto it = mymap.find(arr[i]);
if((it)->second<=count)
(it)->second=count;
count=1;
}
else if(count)
{
mymap.insert(pair<int,int>(arr[i],count));
count=1;
}
}
for(auto it=mymap.begin();it!=mymap.end();it++)
{
cout<<it->first<<"->"<<it->second<<endl;
}
return 0;
}
Expected Output:
1->4
4->3
6->1
7->1

Removing Duplicate Numbers from an Array and Adding them to the end at c++

i have an array in data.txt file like 9 3 9 4 5 4 3 7 1 9 6
i need to find duplicate numbers and remove them from the array.
After that i need to collect them at the end of the array.
i wrote a code and the output is 9 3 4 5 7 1 6 9 3 4 9, but i need to put the duplicated numbers in array, in the sequence they appear in the original array.
So i need to get { 9, 3, 4, 5, 7, 1, 6, 9, 4, 3, 9 } as output.
What can i do with the code to reach my goal ?
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main(){
ifstream fs("data.txt");
if (!fs)
return 0;
int a[SZ];
for (int i = 0; i < SZ; ++i)
fs >> a[i];
for (int k=0; k<SZ; k++) {
for (int j=k+1; j< SZ ; j++) {
if (a[j]==a[k]) {
for (int l=j; l<SZ-1; l++) {
a[l]=a[l+1];
}
a[10]=a[k];
}
}
}
for (int i = 0; i < SZ; ++i)
cout << a[i];
return 1;}
Here's one strategy.
Keep the notion of whether an entry is duplicate or not in a parallel array.
Print the numbers that are not duplicates first.
Then print the numbers that are duplicates.
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main()
{
ifstream fs("data.txt");
if (!fs)
return 0;
int a[SZ];
int isDuplicate[SZ];
for (int i = 0; i < SZ; ++i)
{
fs >> a[i];
isDuplicate[i] = false;
}
for (int k=0; k<SZ; k++) {
for (int j=k+1; j< SZ ; j++) {
if (a[j]==a[k])
{
isDuplicate[j] = true;
}
}
}
// Print the non-duplicates
for (int i = 0; i < SZ; ++i)
{
if ( !isDuplicate[i] )
cout << a[i] << " ";
}
// Print the duplicates
for (int i = 0; i < SZ; ++i)
{
if ( isDuplicate[i] )
cout << a[i] << " ";
}
cout << endl;
// Not sure why you have 1 as the return value.
// It should be 0 for successful completion.
return 0;
}
If you want to keep the order, you have to compare each number to the previous ones instead of comparing it to the next ones. Your program becomes :
#include <iostream>
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main(){
ifstream fs("data.txt");
if (!fs)
return 0;
int a[SZ];
for (int i = 0; i < SZ; ++i)
fs >> a[i];
// kk limits the number of iteration, k points to the number to test
for (int k=0, kk=0; kk<SZ; kk++, k++) {
for (int j=0; j< k ; j++) {
if (a[j]==a[k]) {
for (int l=k; l<SZ-1; l++) {
a[l]=a[l+1];
}
a[SZ - 1]=a[j];
// a[k] is a new number and must be controlled at next iteration
k -= 1;
break;
}
}
}
for (int i = 0; i < SZ; ++i)
cout << a[i];
return 1;}
I'm inclined to try out a solution that uses std::remove_if and has a deduping unary predicate. That should retain the order of your duplicate elements.
The OP's (#kuvvetkolu) original example has O(SZ^3) complexity, which is brutal. #RSahu's solution is O(SZ^2), an improvement (and correct), but this should not require O(N^2)...
Here's a version that incurs only space overhead (assuming O(1) hash table lookup). You can use a unordered_set (a hash table) to track whether you've already seen a particular number, put it in the appropriate vector and then merge the vectors at the end.
#include <iostream>
#include <fstream>
#include <unordered_set>
#include <vector>
int main() {
std::ifstream fs("data.txt");
if (!fs)
throw std::runtime_error("File not found!");
std::vector<int> a;
std::vector<int> dups;
std::unordered_set<int> seen;
int d;
while (fs) {
fs >> d;
if (seen.find(d) == seen.end())
{
a.push_back(d);
seen.insert(d);
}
else
{
dups.push_back(d);
}
}
a.insert(a.end(), dups.begin(), dups.end());
for (auto n : a)
std::cout << n << " ";
return 0;
}