I have a code where i should introduce 3 numbers and an multi-dimensional array. I should print all numbers from array that are divisors with 3 numbers from start..
Here's my code:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int r, p, k, nr, n, m, counter=0, temp;
vector <int> numbers;
cout << "Enter value of r, p, k: ";
cin >> r >> p >> k;
cout << "Enter the number of rows and columns: ";
cin >> n >> m;
int T[n][m];
cout << "Enter values: ";
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> T[i][j];
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
return 0;
}
So, my question is.. how to push in vector numbers that repeats only 1 time.. I mean if in array are 2 the same number, dont print both of them but just one of them.
Thanks in advance.
Use a set: http://en.cppreference.com/w/cpp/container/set
A set does not allow duplicates. For example, if you insert the number 5 more than once, there will still only be one 5 in the set.
First #include<set>.
Then replace vector <int> numbers; with set<int> numbers;
Then replace
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
with
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
numbers.insert(T[i][j]);
Then replace
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
with
for (auto i = numbers.cbegin(); i != numbers.cend(); ++i)
if(r % *i == 0 && p % *i == 0 && k % *i == 0)
cout << *i << ' ';
That should do it. You can eliminate the counter variable from the program because numbers.size() gives you the number of objects in the set. Also, your temp variable is not used, so eliminate that as well. Also, note that set is an ordered container, so printing it like this will print the numbers in ascending order.
(Also note that the length of an array such as int arr[3]; must be known at compile time to be strictly valid C++. Here 3 is a literal and so is known at compile time. Asking the user to input the length of the array means that it is not known at compile time.)
After you fill your vector, you can first sort all elements in it and than call std::unique, to remove all duplicates from it.
Try to look references for std::unique and std::sort
Related
Firstly when I have code this program it was running perfectly but running it again, it is not showing expected output can someone tell what's wrong with it
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[loc],arr[i]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
Forgoing the fact that variable-length arrays are not part of standard C++ (and thus code tutorials that use them should be burned), the code has two main problems.
On an already sorted sequence, the inner-most if body will never be entered, and therefore loc will never receive a determinate value.
The swap is in the wrong place..
Explanation
Within your code...
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min; // loc is INDETERMINATE HERE
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j; // loc ONLY EVER SET HERE
}
swap(arr[loc],arr[i]); // loc IS USED HERE EVEN IF NEVER SET
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
The purpose of the inner loop is to find the location (loc) of the most extreme value (smallest, largest, whatever you're using for your order criteria) within the remaining sequence. No swapping should be taking place in the inner loop, and the initial extreme value location (again, loc) should be the current index of the outer loop (in this case i)
Therefore...
We don't need min. It is pointless.
We must initialize loc to be i before entering the inner loop.
We swap after the inner loop, and then only if loc is no longer i.
The result looks like this.
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1; i++)
{
int loc = i;
for (int j = i + 1; j < n; j++)
{
if (arr[loc] > arr[j])
loc = j; // update location to new most-extreme value
}
// only need to swap if the location is no longer same as i
if (loc != i)
swap(arr[loc], arr[i]);
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
The line swap(arr[loc],arr[i]); should be outside the inner for loop, so move it one line down.
Also, you will want to initialize loc to i at the start of the outer for loop.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
loc=i;
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[i],arr[loc]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
I am trying to write a program which checks if 3 (or more) elements of an array are the same.
I have written a code which works almost perfectly, but it gets stuck when there are 3 pairs of equal elements and I'm not sure how to fix it.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, a[10],skirt=0;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
cout<<skirt<<endl;
if(skirt>=3)
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
}
When I input
6
3 3 2 2 1 1 i
get "TAIP" but I need to get "NE".
You can use the following algorithm: first sort the array. Then iterate each adjacent pair. If they are equal, then increment counter, if not then reset counter to 1. If counter is 3, return true. If loop does not return true, then return false.
Add the following condition in the outer for loop
for(int i = 0; i < n - 2 && skirt != 3; i++)
^^^^^^^^^^^^^^^^^^^^^^^
{
skirt = 1;
^^^^^^^^^
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
Of course before the loop you should check whether n is not less than 3. For example
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
}
Here is a demonstrative program
#include <iostream>
using namespace std;
int main()
{
int a[] = { 6, 3, 3, 2, 2, 1, 1 };
int n = 7;
int skirt = 0;
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if ( a[i] == a[j] )
{
skirt++;
}
}
}
}
cout << skirt << endl;
if ( skirt == 3 )
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
return 0;
}
Its output is
1
NE
because the array does not have 3 equal elements.
Reset skirt to 0 every time you increase i if it is less than 3, or break out the loop otherwise.
Another way to do this is using a std::map, which keeps a count of the number of times a given value occurs in your array. You would stop looking as soon as you have a number that has three occurrences.
Here's a 'minimalist' code version:
#include <iostream>
#include <map>
using std::cin; // Many folks (especially here on SO) don't like using the all-embracing
using std::cout; // ... statement, "using namespace std;". So, these 3 lines only 'use'
using std::endl; // ... what you actually need to!
int main() {
int n, a[10], skirt = 0;
std::map<int, int> gots;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n && skirt < 3; i++) {
skirt = 1;
if (gots.find(a[i]) != gots.end()) skirt = gots[a[i]] + 1;
gots.insert_or_assign(a[i], skirt);
}
cout << (skirt >= 3 ? "TAIP" : "NE") << endl;
return 0;
}
I'm not saying this is any better (or worse) than the other answers - just another way of approaching the problem, and making use of what the Standard Library has to offer. Also, with this approach, you could easily modify the code to count how many numbers occur three or more times, or any number of time.
Feel free to ask for further clarification and/or explanation.
Link to the problem in question: http://codeforces.com/problemset/problem/784/F
It's nothing but a sorting problem so I used bubble sort on my array. But when I submit my answer it keeps rejecting on test 1 even though it works just fine when I run it. I made sure I chose the right compiler for my code so that's not the problem. Is there something wrong with my code?
Here's my code:
int arr[10];
/* number of inputs */
int n;
cin >> n;
/* inputting n numbers to the array */
for (int i = 0; i < n; ++i)
cin >> arr[i];
/* bubble sort array */
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = temp;
}
}
}
/* printing all the numbers in array */
for (int i = 0; i < n; ++i) {
cout << arr[i] << ' ';
}
cout << endl;
You do not need to implement everything your self, just use the standard library:
// number of inputs
int n;
std::cin >> n;
// Vector storing the numbers
std::vector<int> v(n);
// Input n numbers
for (int i = 0; i < n; ++i)
{
std::cin >> arr[i];
}
// Sort the numbers
std::sort(v.begin(), v.end());
// Removed all duplicates (all numbers are unique)
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());
// Print all the numbers
for (int i : v)
std::cout << i << ' ';
std::cout << std::endl;
I make the user to type maximum elements and then enter that elements into first array p,then I want to take only the elements that are bigger than 0 and transfer them to a new array w. Here's the code and where exactly I make mistake:
void main(){
int p[10], w[10], n,i,j;
cout << "Maximum elements: "; cin >> n;
for (i = 0; i < n; i++){
cout << "Enter " << i << "-nd element"; cin >> p[i];
}
j = 0;
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
system("pause");
}
In:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
the inner loop is printing every element of the array w. That loop is executed for every element of p (being it inside the outer for loop).
This mean that, for example, the first time it visits p to check if the first element is 0, it may assign w[0] and then go on and print all the elements of w. Problem is that w is not initialised at that point, so what you see is random garbage (probably).
Just move the loop outside and make it so it only prints the part of the array that is populated:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
}
for (int k = 0; k < j; k++){
cout << w[k];
}
Live demo
Also learn how to use std::vector or std::array and the algorithms in <algorithm>.
Also remember that main has return type int.
Using std::copy_if from <algorithm> do the job you want, as in the example provided in http://www.cplusplus.com/reference/algorithm/copy_if/:
// copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::copy_if, std::distance
#include <vector> // std::vector
int main () {
std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar (foo.size());
// copy only positive numbers:
auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
bar.resize(std::distance(bar.begin(),it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x: bar) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
For you code, the problem is that you modify j in the printing loop whereas it is primary used as output index. Try to reduce scope of your local variable to out spot those issues, creating sub function may also help.
Finnaly, your fixed code may be something like:
void main(){
std::cout << "Maximum elements: ";
int n;
std::cin >> n;
int p[10];
for (int i = 0; i < n; i++){
std::cout << "Enter " << i << "-nd element";
std::cin >> p[i];
}
int w[10];
int w_size = 0;
for (int i = 0; i < n; i++){
if (p[i] > 0){
w[w_size] = p[i];
w_size++;
}
}
for (int i = 0; i < w_size; i++){
std::cout << w[i];
}
system("pause");
}
#include <iostream>
using namespace std;
// Selection Sort function.
// Parameter 'a' is the size of the array.
void ss(int AR[] , int a) {
int small;
for (int i = 0 ; i <a ; i++) {
small = AR[i];
for (int j = i+1 ; j <a ; j++) {
if (AR[j]< small) {
int k = AR[j];
AR[j] = AR[i];
AR[i] = k;
}
}
}
}
int main() {
cout << "Enter the size of Your Aray";
int a;
cin >> a;
int AR[a];
cout << endl;
for (int i = 0; i < a; i++) {
cin >> AR[i];
cout << endl;
}
ss(AR, a);
cout << "The Sorted Array is";
for (int i=0; i < a; i++) {
cout << AR[i] << " ";
cout << endl;
}
}
When I enter the following:
15
6
13
22
23
52
2
The result returned is:
2
13
6
15
22
23
52
What is the bug preventing the list from being sorted numerically as expected?
The function can look like
void ss ( int a[], size_t n )
{
for ( size_t i = 0 ; i < n ; i++ )
{
size _t small = i;
for ( size_t j = i + 1; j < n ; j++ )
{
if ( a[j] < a[small] ) small = j;
}
if ( i != small )
{
int tmp = a[small];
a[small] = a[i];
a[i] = tmp;
}
}
}
It doesn't seem to be the SelectionSort I know. in the algorithm I know during every loop I look for the smallest element in the right subarray and than exchange it with the "pivot" element of the loop. Here's the algorithm
void selectionSort(int* a, int dim)
{
int posMin , aux;
for(int i = 0; i < dim - 1; ++i)
{
posMin = i;
for(int j = i + 1; j < dim; ++j)
{
if(a[j] < a[posMin])
posMin = j;
}
aux = a[i];
a[i] = a[posMin];
a[posMin] = aux;
}
}
and it seems that you change every smaller element you find, but also change the position of the "pivot". I hope the answer is clear.
Everything is ok in the original function, only that the small variable need to be refreshed when two vector elements will be switched.
Also in if statement set the small variable to the new value of AR[i].