The problem that I am working on right now is here, but I am of course not looking for the complete answer to this homework problem. All I am asking for is the steps in the final parts of the question. This is what I have so far:
int main()
{
cout << "Please enter the number of guests attending your party: ";
int k;
cin >> k;
cout << "Please enter the number of rounds of removal you'd like to perform: ";
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
cout << "Please enter the multiple at which you'd like the removal to be at for round " << i << ": ";
int r;
cin >> r;
if (k % r == 0) {
k - r;
}
cout << k << endl;
}
system("pause");
}
This is all so confusing to me, and I truly have no idea where to turn to get answers. It seems like I'd need an array to solve this, but arrays in C++ cannot be variable, and the array length would be k, a variable input. Any help would be very appreciated.
I've read that question. you need a dynamic list like Linked list because you need to put and remove different items from different index so using arrays will be difficult.
Try to use std::vector or std::list, you can add or remove any any of list
#include <list>
std::list<int> mylist;
How can you add and remove values from list, check this link http://en.cppreference.com/w/cpp/container/list
For using your own Linklist, check this link How could i create a list in c++?
According to your question an std::vector will be the best choice because it is a combination of an array & linked list in raw terms or we can simply say it's a dynamic array.
However as you mentioned n your comment that you haven't been taught anything other than basic arrays & want a solution within whatever you have learnt, then you have to take an array. Now the problem is that arrays are static & you cannot delete elements from it. So all you can do is to keep a counter that will take care of the number of elements in it.
// array insert and delete
#include <iostream>
using namespace std;
void see_array (int a[], int f, int b)
{
for (int i=f; i<b; ++i)
cout << a[i] << ' ';
cout << '\n';
}
int get_pos (int a[], int f, int b, int num)
{
for (int i=f; i<b; ++i)
{
if (a[i] == num)
return i;
}
return -1; // if search is unsuccessful
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
int front = 0, back = 10; // as we have 10 elements
// delete last element
--back;
see_array(a, front, back);
// delete first element
++front;
see_array(a, front, back);
// delete element from middle say 6
int pos = get_pos(a, front, back, 6);
if (pos != -1)
{
for (int i = pos; i<back; ++i) // shift elements towards left
{
a[i] = a[i+1];
}
--back; // decrease size of the array
see_array(a, front, back);
}
return 0;
}
/* Output :-
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
2 3 4 5 7 8 9
*/
I hope the above program is of some help to you !!! Good luck !!!
Related
For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<std::endl;
}
The question is:
"Write and test the following function that removes items from an array:
void removeAll(float a[], int& n, float x);
The function removes all occurrences of x among the first n elements of the array and decreases the value of n by the number removed.
I have written a code and it works perfectly fine. Basically, I tagged the value whose occurrences the user wants to remove with Zero and the code skips printing when it encounters zero. Basically we are not removing that value from the array just replacing it with some other value. What if the user entered zero in the array? then the other zeroes will also be skipped which I don't want them too. how can I do this?
Here is my code:
Don't use any classes, objects, vectors, strings nor any function in c++ which is like array.splice in js.
#include<iostream>
using namespace std;
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
a[i] = 0;
}
}
for (int i = 0; i < 10; i++)
{
if (a[i]!=0)
cout << a[i] << endl;
}
}
int main()
{
float a[10], x;
int n;
cout << "Enter values in array: \n";
for (int i = 0; i < 10; i++)
{
cin >> a[i];
}
cout << "Enter the value whose occurrence you want to remove from the array: ";
cin >> x;
cout << "Enter serial no. uptill which you want to remove the occurences";
cin >> n;
removeAll(a, n, x);
}
If you just want to print out the array without a chosen variable you can do it with one condition:
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
// Don't print it
}
else
{
cout << a[i] << endl;
}
}
}
If you want to eliminate the occurrences I would suggest to move the following numbers forward. I won't code it but here is an example:
array: 2,3,4,5,3,7
number to remove: 3
1. Iterate through the array and find '3'
2. If you find one, move all elements on the right side on step to left:
2 3 4 5 3 7 => 2 4 5 3 7 X
^
2 4 5 3 7 X => 2 4 5 7 X X
^
3. Count how many times you have done step two and return the new length/new array
To accomplish this you'll need to do 4 things:
Make a copy of n to hold the number of elements to iterate over: int size = n
Change your loop condition to consider this new element rather than n: i < size
Decrement n each time you replace a value in the nested if-statement
Remove the second for-loop (if you want to print out everything under n but the replaced numbers do that in an else-condition.)
I want to have an array with initial size 4. The user can add as many elements(int type) to it. The function append() will be used for it. Also every time the size of the array is insufficient the same function will double its size and add the element to it.
#include <iostream>
using namespace std;
int n = 4;
int count = 0;
void append(int *a, int k)
{
if(count == n)
{
n *= 2;
int *b = new int[n];
for(int i = 0; i < count; ++i)
{
b[i] = a[i];
}
a = b;
}
a[count] = k;
++count;
}
void display(int *a)
{
for(int i = 0; i < count; ++i)
cout << a[i] << endl;
}
int main()
{
int *array = new int[n];
char t = 'y';
int num;
while(t != 'n')
{
cout << "Enter Value: ";
cin >> num;
append(array, num);
cout << "Do you want to enter more values?(y/n): ";
cin >> t;
}
cout << "The values entered are:\n";
display(array);
return 0;
}
After giving the following values for entering into the array:
1
2
3
4
5
6
7
8
8
9
10
11
12
13
15
I am getting the following output(using display() function)
1
2
3
4
0 [(This value depends on the compiler) #Erroneous Output]
6
7
8
1 [(This value depends on the compiler) #Erroneous Output]
10
11
12
13
14
15
I do not know why I am getting random values for the elements entered just after the array is updated(size is doubled), and how I should fix it.
Vectors, in essence are just dynamically allocated arrays. My question here is why not just use a vector with 4 slots initially. std::vector<int>(4); will do the trick although if you are adamant on remaking the vector class, research the topic of dynamic arrays and create a c++ template class based off them. According to my understanding .append() deallocates all elements in the vector, then reallocates them with the extra element at the end.
There are many articles online created by people trying to accomplish similar tasks, just do a little bit of digging around:
http://www.gamedev.net/topic/528822-c-writing-my-own-vector-class/
https://codereview.stackexchange.com/questions/50975/creating-a-custom-vector-class
Good day,
I'm having a serious problem into generating a list with all the words of length k (the generate function is the function intended to generate all the words of length k, the other function is used to find out if a word is accepted or not) from a DFA just by using the DFS algorithm, here's my attempt:
#include<vector>
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
vector < pair <int,char> > a[100];
int viz[100], v[100];
char s1[100];
void accepted (int q, char c, char s[100], int x) {
c = s[x];
viz[q] = 1;
cout << q;
for (int i = 0; i < a[q].size(); i++)
if (a[q][i].second == c) {
x++;
accepted (a[q][i].first, a[q][i+1].second, s, x);
}
}
void generate (int q, int k) {
int x = 0;
v[q] = 1;
while (x < k) {
cout << a[q][0].second;
for (int i = 0; i < a[q].size(); i++)
if (v[a[q][i].first] == 0)
{
cout << a[q][i].second;
generate(a[q][i].first, k);
}
x++;
}
}
int main() {
ifstream f ("input.txt");
int n, m, x, y, i, j, k;
char c;
char s[100];
f >> n >> m;
for (i = 0; i < m; i++) {
f >> x >> y;
f >> c;
a[x].push_back (make_pair(y,c));
}
for (i = 0; i < n; i++) {
cout << i << ": ";
for (j = 0; j < a[i].size(); j++)
cout << a[i][j].first << a[i][j].second << " ";
cout << endl;
}
cout << endl << "Fiite states: 2, 3" << endl << endl;
cin.get (s,100);
accepted(0, s[0], s, 0);
if (viz[2] == 1) cout << endl << "Accepted";
cout << endl;
cin >> k;
generate (0, k);
cout << endl;
return 0;
}
Also here's how my input looks like:
4 6
0 0 a
0 1 b
1 2 c
2 2 a
2 3 c
3 3 c
Here's how the DFA and the output would look like:
The serious problem I'm facing is that I can't find a way to ouput properly all the obtained words to the screen by calling the generate function.
I changed your generate function as below. Following that is an explanation as to what I thought and how I changed it.
void generate (int q, int k, string &s) {
if (k > 0) {
for (int i = 0; i < a[q].size(); i++)
{
s += a[q][i].second;
generate(a[q][i].first, k-1, s);
s.pop_back();
}
}
else {
cout << s << endl;
}
}
First and foremost, you were attempting a mixture of recursive and repetitive version of DFS, but you had no structure for keeping the stack if you were, and I doubt, going for a repetitive version using an explicit stack. Basically, your outer while loop was wrong, as the depth should increase as you recursively traverse the graph and not repetitively at a single level of recursion using a while loop as you did. You could also, as I mentioned, have a repetitive approach and use an explicitly defined stack other than the one implicitly used by memory when you implement DFS recursively. But it was easier and more intuitive to get a grasp of DFS with its recursive implementation, so I left out the outer loop.
Secondly, keeping a list of visited nodes is not a good idea as you want to list all k-length strings and your DFA is not a simple graph. (i.e. there may exist edges from node u to node u) So I removed the if statement inside the for loop as you could visit the sane node multiple times. Your approach is exponential based on the branching factor of the DFA, but if your k is small enough, it should work regardless of that. And the approach being exponential is not the problem to the solution of which you are looking with this question.
Thirdly, probably due to your usage of while loop, there was a mixup with printing a single character at each level, which is incorrect. Remember, at every node of depth k, you have to print all the characters you encountered starting from the root of the tree. That is why I added a string as the third parameter to your function. Don't worry, though, it's passed by reference and it will only cause an addition of O(k) space complexity to your algorithm, which should be negligible.
If in your main function you start traversing using the call below, you will find that it works properly.
string S;
generate(0, k, S);
#include <iostream>
#include <algorithm>
bool wayToSort(int i, int j) { return i > j; }
bool wayToSortAlt(int i, int j) { return i < j; }
int main()
{
using namespace std;
int size = 5;
int *myArray = new int[size] { 0 };
int option = 0;
cout << "How many numbers do you want to enter?: ";
cin >> size;
cout << "How do you want to sort? ( [1] Greatest [2] Lowest ): ";
cin >> option;
cout << "----\n";
// Get number inputs
for (int count = 0; count < size; ++count)
{
cout << "Enter a number: ";
cin >> myArray[count];
}
cout << "----\nSorted:\n----\n";
// Sort for highest numbers
if (option == 1)
sort(myArray, myArray + size, wayToSort);
else
sort(myArray, myArray + size, wayToSortAlt);
// Print each number
for (int count = 0; count < size; ++count)
{
cout << myArray[count] << "\n";
}
delete[] myArray; // Clean up
myArray = nullptr; //
return 0;
}
I run this code in Visual Community 2013 and if I input a high number such as 10, I get a heap corruption error. From what I have read, the heap corruption error happens when you try to write to an unallocated memory adress, but I don't understand two things:
1) Why does this happen with a dynamic array, and
2) Why does the error only happen when I try to put in a larger number.
Luke,
You have defined the size of the array already. So it is not a dynamic array. It is a pointer to an array that has a size of 5 and can hence only store up to 5 ints.
So you basically have allocated enough space to hold 5 int. This means that if you try to store more than 5, for example the 6th int at index of 5, you are trying to access memory that is not yours to claim.
for example here you have:
[] [] [] [] []
1 2 3 4 5
is good
[] [] [] [] []
1 2 3 4 5 6 7 8 ...
cause the heap corruption.
Might I suggest std::vector ?