I have a small program to sort random numbers into the right sequence number. Well, I want to see every random number move. what should be added to it?
#include <iostream>
using namespace std;
void pindah (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void tukar (int arr[], int n) {
int i, j;
bool trade;
for (i=0; i < n-1; i++) {
trade = false;
for (j=0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
pindah(&arr[j], &arr[j+1]);
trade = true;
}
}
if (trade == false)
break;
}
}
void cetakArray (int arr[], int n) {
int i;
for (i=0; i<n; i++) {
cout << arr[i] << " "; //tampil data
}
}
int main () {
int arr[] = {4, 6, 7, 2, 1, 5, 8, 10, 9, 3};
int n = sizeof(arr) / sizeof(int); //menghitung jumlah data array
cout << "setelah diurutkan : \n";
tukar (arr, n);
cetakArray (arr, n);
}
please help me
Assuming that by "into the right sequence" you mean from small to large, and assuming that you are willing to use C++11, we can easily obtain this with a lambda function. See the following example.
#include <vector>
#include <algorithm>
std::vector<int> values({4, 6, 7, 2, 1, 5, 8, 10, 9, 3});
int number_of_moves = 0;
std::sort(begin(values), end(values), [&](int lhs, int rhs)
{
if (lhs > rhs)
return false;
++number_of_moves;
std::cout << "I am going to swap " << lhs << " with " << rhs << '\n';
return true;
});
std::cout << "I took me " << number_of_moves << " move(s) to sort the vector\n";
Note: it is not clear to me what you mean by "movements in c++ boolean", so I chose to print the numbers that are going to be swapped.
EDIT: based on the comments I guess you want to count the number of movements, so I have added a counter. Note that a bool can only be true/false and cannot be used for counting.
Related
Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]
C++ program for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to find the missing elements
void printMissingElements(int arr[], int N)
{
// Initialize diff
int diff = arr[0] - 0;
for (int i = 0; i < N; i++) {
// Check if diff and arr[i]-i
// both are equal or not
if (arr[i] - i != diff) {
// Loop for consecutive
// missing elements
while (diff < arr[i] - i) {
cout << i + diff << " ";
diff++;
}
}
}
}
Driver Code
int main()
{
// Given array arr[]
int arr[] = { 5,2,6 };
int N = sizeof(arr) / sizeof(int);
// Function Call
printMissingElements(arr, N);
return 0;
}
How to solve this question for the given input?
First of all "plzz" is not an English world. Second, the question is already there, no need to keep writing in comments "if anyone knows try to help me".
Then learn standard headers: Why should I not #include <bits/stdc++.h>?
Then learn Why is "using namespace std;" considered bad practice?
Then read the text of the problem: "Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]"
You need to "return the numbers from 1 to 10 which are missing."
I suggest that you really use C++ and get std::vector into your toolbox. Then you can leverage algorithms and std::find is ready for you.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
std::vector<int> missingElements(const std::vector<int> v)
{
std::vector<int> missing;
for (int i = 1; i <= 10; ++i) {
if (find(v.begin(), v.end(), i) == v.end()) {
missing.push_back(i);
}
}
return missing;
}
int main()
{
std::vector<int> arr = { 5, 2, 6 };
std::vector<int> m = missingElements(arr);
copy(m.begin(), m.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
return 0;
}
If you want to do something with lower computational complexity you can have an already filled vector and then mark for removal the elements found. Then it's a good chance to learn the erase–remove idiom:
std::vector<int> missingElements(const std::vector<int> v)
{
std::vector<int> m = { -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (const auto& x: v) {
m[x] = -1;
}
m.erase(remove(m.begin(), m.end(), -1), m.end());
return m;
}
By this approach we are using space to reduce execution time. Here the time complexity is O(N) where N is the no of elements given in the array and space complexity is O(1) i.e 10' .
#include<iostream>
void printMissingElements(int arr[], int n){
// Using 1D dp to solve this
int dp[11] = {0};
for(int i = 0; i < n; i++){
dp[arr[i]] = 1;
}
// Traverse through dp list and check for
// non set indexes
for(int i = 1; i <= 10; i++){
if (dp[i] != 1) std::cout << i << " ";
}
}
int main() {
int arr[] = {5,2,6};
int n = sizeof(arr) / sizeof(int);
printMissingElements(arr, n);
}
void printMissingElements(int arr[], int n,int low, int high)
{
bool range[high - low + 1] = { false };
for (int i = 0; i < n; i++) {
if (low <= arr[i] && arr[i] <= high)
range[arr[i] - low] = true;
}
for (int x = 0; x <= high - low; x++) {
if (range[x] == false)
std:: cout << low + x << " ";
}
}
int main()
{
int arr[] = { 5,2,6,6,6,6,8,10 };
int n = sizeof(arr) / sizeof(arr[0]);
int low = 1, high = 10;
printMissingElements(arr, n, low, high);
return 0;
}
I think this will work:
vector<int> missingnumbers(vector<int> A, int N)
{ vector<int> v;
for(int i=1;i<=10;i++)
v.push_back(i);
sort(A.begin(),A.end());
int j=0;
while(j<v.size()) {
if(binary_search(A.begin(),A.end(),v[j]))
v.erase(v.begin()+j);
else
j++;
}
return v;
}
I'm having an issue in my program with my insertElement() function. What I had intended insertElement to do is to take the index from the prototype and move all the values to the right, including the value on that index, to the right ONCE. So, If I were to have my array {1, 2, 3, 4} and I wanted to insert the value "10" at the index "2", the resulting array would be {1, 2, 10, 3, 4}.
I know I'd have to tweak my insertElement() function to fix this issue, but I'm not sure where to start, could anybody give me a hand? Here is my code:
#include <iostream>
using namespace std;
const int CAPACITY = 20;
void displayArray(int array[], int numElements)
{
for (int i = 0; i < numElements; i++)
cout << array[i] << " ";
cout << endl;
}
bool insertElement(int array[], int& numberElements, int insertPosition, int insertTarget)
{
int p = 0;
int j = 1;
int arrayPositionFromLast = (numberElements-1);
if (numberElements>=CAPACITY)
{
cout << "Cannot insert an element, array is full." << endl;
return false;
} else {
for (int i=arrayPositionFromLast; i>insertPosition; i--)
{
array[arrayPositionFromLast-p]=array[arrayPositionFromLast-j];
p++;
j++;
}
array[insertPosition] = insertTarget;
}
return true;
}
int main()
{
int array[6] = {1, 2, 3, 4, 5, 6};
int numArrayElements = 6;
int endOfArrayValue, insertedValue, insertedValuePosition;
cout << "Enter a value and a position to insert: ";
cin >> insertedValue >> insertedValuePosition;
insertElement(array, numArrayElements, insertedValuePosition, insertedValue);
displayArray(array, numArrayElements);
}
first you should define your array with CAPACITY
int array[CAPACITY] = {1, 2, 3, 4, 5, 6};
You can move your data with memmove.
if (numberElements>=CAPACITY)
{
cout << "Cannot insert an element, array is full." << endl;
return false;
} else {
memmove(array + insertPosition+ 1, array + insertPosition, (numberElements - insertPosition) * sizeof (int));
array[insertPosition] = insertTarget;
}
I made this program to sort a list of numbers. It is supposed to be selection sort, but my teacher said it works more like bubble sort and I need to fix it. Any suggestions on what parts I need to change?
#include <iostream>
using namespace std;
void printArr(const int a[], int s);
void swapVals(int& v1, int& v2);
void sortArr(int a[], int s);
int main()
{
const int s = 20;
int arr[s] = {8, 38, 25, 4, 47, 47, 38, 36, 3, 33, 2, 19, 16, 30, 5, 47, 16,
38, 13, 1
};
cout << "Unsorted array:\n";
printArr(arr, s);
cout << "\n\n";
sortArr(arr, s);
cout << "Sorted Array:\n";
printArr(arr, s);
cout << "\n";
return 0;
}
void sortArr(int a[], int s)
{
for (int i = 0; i < s-1; i++)
{
int index = i;
for (int j = i + 1; j < s; j++)
if (a[j] < a[index])
index = j;
swapVals(a[index], a[i]);
}
}
void swapVals(int& v1, int& v2)
{
int temp = v1;
v1 = v2;
v2 = temp;
}
void printArr(const int a[], int s)
{
for (int i=0; i<s; i++)
{
cout << a[i];
if (i != s-1)
cout << " ";
}
}
I believe it's selection sort, just the way you write the code makes it easy for people to misunderstand.
For which part to change, I'll have to say, it's inside your sortArr function, the inner loop, better to add a comment here "find the index of min starting from i + 1" or you can just call the findMin you have defined. From the call routine: main call sortArr, sortArr only call swap and does not call findMin, it looks really like a bubble sort.
Also, your findMin is not good, it's finding min value, not the index of min value.
I have an array let's say with 5 items, if element[i] is less than 3 need to move element[i+1] in place of element[i].
int array[5] = {4, 2, 3, 5, 1};
int number = 3;
for (int i = 0; i < number; i++)
{
if (array[i] > number)
{
for (int j = 0; j < i - 1; j++)
{
array[j] = array[j + 1];
}
number = number - 1;
}
}
expected result is array = {2, 3, 1, anyNumber, anyNumber};
A O(n) working code for the above problem.. But as others pointed out in the comments.. You end up with an array that is using less space then allocated to it..
#include<stdio.h>
int main()
{
int arr[] = {4, 2, 3, 5, 1};
int* temp1 = arr;
int* temp2 = arr;
int i, n1 = 5, n2 = 5;
for(i = 0; i < n1; i++)
{
if(*temp2 >= 3)
{
*temp1 = *temp2;
temp1++;
temp2++;
}
else
{
n2--; //the number of elements left in the array is denoted by n2
temp2++;
}
}
}
Nested loops give you O(n2) complexity, and non-obvious code.
Better use std::remove_if:
int array[5] = {4, 2, 3, 5, 1};
int number = 3;
remove_if( begin( array ), end( array ), [=]( int x ) { return x>number; } );
Disclaimer: code untouched by compiler's hands.
Try this code. You should not decrease number at each step. Also, the second loop should start at i and stop at the end of array:
int array[5] = {4, 2, 3, 5, 1};
int number = 3;
for (int i = 0; i < number; i++)
{
if (array[i] > number)
{
for (int j = i; j < 5; j++)
{
array[j] = array[j + 1];
}
}
}
Here's a more compact and idiomatic (that's how I view it anyway) way to remove items from an array:
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
int array[] = {4, 2, 3, 5, 1};
int* begin = array;
int* end = begin + sizeof(array)/sizeof(array[0]);
int number = 3;
end = std::remove_if(begin, end, [&number](int v) {return v > number;});
std::copy(begin, end, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
Just for comparison, here's a version using std::vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> array = {4, 2, 3, 5, 1};
int number = 3;
auto end = std::remove_if(array.begin(), array.end(), [&number](int v) {return v > number;});
std::copy(array.begin(), end, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
As an alternative, if you want to keep your items, but denote what will be at some later time, "removed", the algorithm that can be used is stable_partition:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <functional>
int main()
{
int vValues[] = {4,2,3,5,1};
// partition the values on left and right. The left side will have values
// <= 3, and on right >3. The return value is the partition point.
int *p = std::stable_partition(vValues, vValues + 5,
std::bind2nd(std::less_equal<int>(), 3));
// display information
std::cout << "Partition is located at vValues[" << std::distance(vValues, p) << "]\n";
std::copy(vValues, vValues + 5, std::ostream_iterator<int>(std::cout, " "));
}
Output:
Partition is located at vValues[3]
2 3 1 4 5
You will see that 2,3,1 are on the left of partition p, and 4,5 are on the right of the partition p. So the "removed" items start at where p points to. The std::partition ensures the elements are still in their relative order when done.
I created my own example, hope this helps people as a reference:
// Removing an element from the array. Thus, shifting to the left.
void remove(){
int a[] = {1, 2, 3, 4, 5, 6};
int size = sizeof(a)/sizeof(int); // gives the size
for(int i = 0; i < size; i++){
cout << "Value: " << a[i] << endl;
}
int index = 2; // desired index to be removed
for(int i = 0; i < size; i++){
if(i == index){
for(int j = i; j < size; j++){
a[j] = a[j+1];
}
}
}
size--; // decrease the size of the array
cout << "\nTesting output: " << endl;
for(int i = 0; i < size; i++){
cout << "Value: " << a[i] << endl;
}
}
int main(){
remove();
return 0;
}
Well, I have to find how many different numbers are in an array.
For example if array is: 1 9 4 5 8 3 1 3 5
The output should be 6, because 1,9,4,5,8,3 are unique and 1,3,5 are repeating (not unique).
So, here is my code so far..... not working properly thought.
#include <iostream>
using namespace std;
int main() {
int r = 0, a[50], n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < j; k++) {
if (a[k] != a[j]) r++;
}
}
cout << r << endl;
return 0;
}
Let me join the party ;)
You could also use a hash-table:
#include <unordered_set>
#include <iostream>
int main() {
int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 };
const size_t len = sizeof(a) / sizeof(a[0]);
std::unordered_set<int> s(a, a + len);
std::cout << s.size() << std::endl;
return EXIT_SUCCESS;
}
Not that it matters here, but this will likely have the best performance for large arrays.
If the difference between smallest and greatest element is reasonably small, then you could do something even faster:
Create a vector<bool> that spans the range between min and max element (if you knew the array elements at compile-time, I'd suggest the std::bitset instead, but then you could just compute everything in the compile-time using template meta-programming anyway).
For each element of the input array, set the corresponding flag in vector<bool>.
Once you are done, simply count the number of trues in the vector<bool>.
A std::set contains only unique elements already.
#include <set>
int main()
{
int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 };
std::set<int> sa(a, a + 9);
std::cout << sa.size() << std::endl;
}
How about this?
#include <list>
int main()
{
int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5};
std::list<int> la(a, a+9);
la.sort();
la.unique();
std::cout << la.size() << std::endl;
return 0;
}
Since you've stated that you cannot use the standard library and must use loops, let's try this solution instead.
#include <iostream>
using namespace std; // you're a bad, bad boy!
int main()
{
int r = 0, a[50], n;
cout << "How many numbers will you input? ";
cin >> n;
if(n <= 0)
{
cout << "What? Put me in Coach. I'm ready! I can do this!" << endl;
return -1;
}
if(n > 50)
{
cout << "So many numbers! I... can't do this Coach!" << endl;
return -1;
}
cout << "OK... Enter your numbers now." << endl;
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "Let's see... ";
// We could sort the list but that's a bit too much. We will choose the
// naive approach which is O(n^2), but that's OK. We're still learning!
for (int i = 0; i != n; i++)
{ // Go through the list once.
for (int j = 0; j != i; j++)
{ // And check if this number has already appeared in the list:
if((i != j) && (a[j] == a[i]))
{ // A duplicate number!
r++;
break;
}
}
}
cout << "I count " << n - r << " unique numbers!" << endl;
return 0;
}
I urge you to not submit this code as your homework - at least not without understanding it. You will only do yourself a disservice, and chances are that your instructor will know that you didn't write it anyways: I've been a grader before, and it's fairly obvious when someone's code quality magically improves.
I think the location for increasing the value of r is incorrect
#include <iostream>
using namespace std;
int main()
{
int r=0,a[50],n;
cin >>n;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=0;j<n;j++)
{
bool flag = true;
for(int k=;k<j;k++)
{
if(a[k]!=a[j])
{
flag = false;
break;
}
}
if (true == flag)
{
r++;
}
}
cout << r << endl;
return 0;
}
However, my suggestion is using more sophisticated algorithms (this algorithm has O(N^2)).
this should work, however its probably not the optimum solution.
#include <iostream>
using namespace std;
int main()
{
int a[50],n;
int uniqueNumbers; // this will be the total numbers entered and we will -- it
cin >>n;
uniqueNumbers = n;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
/*
the and clause below is what I think you were missing.
you were probably getting false positatives when j == k because a[1] will always == a[1] ;-)
*/
if((a[k] == a[j]) && (k!=j))
{ uniqueNumebers--; }
}
}
cout << uniqueNumbers << endl;
return 0;
}
We can use C++ STL vector in this program .
int main()
{
int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5};
vector<int>v(a, a+9);
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
cout<<v.size()<<endl;
return 0;
}
Please dry run your code
See in the outer for loop for each element it is counted more than one inside inner loop.let us say the loop contains 1,2,3,4.1.....elements dry run it in the second iteration and third iteration 1 is counted because 1 is 1!=2 as well as 1!=3
Now solution time!!
#include<iostream>
#include<vector>
#include<algorithm>
#define ll long long
using namespace std;
ll arr[1000007]={0};
int main()
{
ios_base::sync_with_stdio(false);//used for fast i/o
ll n;cin>>n;
for(ll i=1;i<=n;i++)
cin>>arr[i];
sort(arr,arr+n);
ll cnt=0;
for(ll i=1;i<=n-1;i++)
{
if(arr[i+1]-arr[i]==0)
cnt++;
}
cout<<n-cnt<<endl;
cin.tie(NULL);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int find_unique(int arr[], int size){
int ans = 0;
for(int i = 0; i < size; i++){
ans = ans^arr[i]; // this is bitwise operator .its call XOR it's return only unique value..
}
return ans;
}
void print_array(int arr[], int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL); // use for fast input and output....
int arr[5] = {1, 3, 5, 3, 1};
cout <<"Orginal array: " << endl;
print_array(arr, 5);
int result = find_unique(arr, 5);
cout << result << endl;
return 0;
}