Josephus prob using arrays? - c++

http://en.wikipedia.org/wiki/Josephus_problem
The user can choose how many people are in the circle.
The user can choose the value of each person.
The user can choose the counting number for the persons death.
ex. User picks 5, every 5th person shall die.
I was thinking something like -
User choose amount of people ex- 50
PeopleArray becomes PeopleArray[50]
User chooses value of elements in PeopleArray[50]
They would have to type 50 values for the 50 elements
Death
User picks 3 so every third person dies how would I erase that number from the array.
Problem ^-Not sure on how to do the above with arrays
int main(){
int people = 5;
int peopleArray[5];
int peopleValue = 1;
int death;
cout << "Enter the amount of people: ";
cin >> people;
peopleArray[people];
for(int x = 1;x<=people;x++){
cout << "Enter the value of person #" << x << ":";
cin>> peopleValue;
peopleArray[peopleValue]; //Suppose to put the value into the array
}
}

If I understand you correctly what you are trying to do would be something like...
vector<int> totalPeople;
int totalIn;
int deathIn;
int person = 1;
int nthPerson = 0;
cout << "Enter total number of people." << endl;
cin >> totalIn;
cout << endl << "Pick the nth person." << endl;
cin >> deathIn;
for ( int i = 0; i < totalIn; i++ )
{
totalPeople.pushback(person++);
}
nthPerson = deathIn - 1;
while ( nthPerson < totalPeople.size() )
{
totalPeople.erase(totalPeople.begin() + nthPerson);
nthPerson = nthPerson + (deathIn -1);
}
or say that totalPeople[nthPerson] = 0;
This will remove the nth person from the total list of people.

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

How to pull a number out of a loop each time it runs

I have a question where I need to make a simple program that has you input 2 numbers and then use those as bounds and multiply those numbers and all of them in between.
i.e.
1 and 4
1*2*3*4=24
This is what I've got, but I can not figure out how to make it do that and I end up making it multiply the last 2 numbers together instead of all of them. I think this is because I can't figure out how to pull the number in the loop out so I could multiply it by the next number it would give me.
int main()
{
int num1,
num2,
product = 0,
total = 0;
cout << "Enter any two integers(with a space in between: " << endl;
cin >> num1;
cin >> num2;
for (int i = num1; i < num2; i++)
{
product = i * (i + 1);
}
cout << "The total is: " << product << endl;
return 0;
}
I know for sure that I need to do something else to be able to get the product out and be able to multiply it by the next product, but I can not get it to work. I also don't know if it is alright to put the i there an use it to multiply.
You were facing this problem because of your line: product = i * (i + 1);
What was happening is that the product variable was being overwritten by the product of i and i++. This was not added to the previous value of product. This is why your program only multiplied the last 2 numbers together instead of all of them.
This code below should run as intended:
int main()
{
int num1,
num2,
product = 1; // modified. Plus, total is unused, so you can remove it
//total = 0;
cout << "Enter any two integers(with a space in between: " << endl;
cin >> num1;
cin >> num2;
for (int i = num1; i <= num2; i++) // modified
{
product = product * i ; // modified
}
cout << "The total is: " << product << endl;
return 0;
}

Call array storing string type from one while to another

How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?

What container to use when I need to know both the max value and who has achieved it?

I'm trying to work through the beginner exercises from a website.
"Requires:
variables, data types, and numerical operators
basic input/output
logic (if statements, switch statements)
loops (for, while, do-while)
arrays
Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10)
Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast."
I'm unsure on how to get the program to call out the person which enters the most number of pancakes eaten? Surely this would need to be done with a key and value, but the requirements state 'arrays' but not 'maps'?
Below is the code I have come up with, but this only outputs the maximum number of pancakes eaten, so not really answering the question!
Thanks so much for any help!
* I've only used 5 people to quicken the process before I know exactly how to do it *
#include <iostream>
using namespace std;
int main()
{
cout << "how many pancakes did you eat for breakfast?" << endl;
int person1, person2, person3, person4, person5;
cout << "Person 1: ";
cin >> person1;
cout << "Person 2: ";
cin >> person2;
cout << "Person 3: ";
cin >> person3;
cout << "Person 4: ";
cin >> person4;
cout << "Person 5: ";
cin >> person5;
int array[5] = {person1, person2, person3, person4, person5};
int temp = 0;
for (int i = 0; i<5; i++)
{
if (array[i] > temp)
{
temp = array[i];
}
}
cout << "The most pancakes eaten was " << temp << "by " << endl;
}
Surely this would need to be done with a key and value
This is not the only way of doing it. Another way is to use an indexed collection with no key, and make an assumption that position k corresponds to a key k that can be computed from a position alone. For example, if you have an array of ten items corresponding to ten people numbered 1 through 10, then the data for a person number k could be stored in the array at position k-1. No keys are required in this situation.
This long explanation means that if you store the best i in addition to best tmp, you'll have your answer after the loop:
int temp = 0;
int res = -1;
for (int i = 0; i<5; i++) {
if (array[i] > temp) {
temp = array[i];
res = i;
}
}
cout << "The most pancakes eaten was " << temp << "by " << (res+1) << endl;
Note the res+1 is printed, not res. This is because arrays are zero-based, while counting is one-based.
This could be further shortened using a common idiom of using the initial element as the current best, and starting your iterations from 1:
int res = 0;
for (int i = 1 ; i<5 ; i++) {
if (array[i] > array[res]) {
res = i;
}
}
cout << "The most pancakes eaten was " << array[res] << "by " << (res+1) << endl;
What if you kept track of the maximum amount of pancakes eaten as you took input?
#include <iostream>
using namespace std;
// To execute C++, please define "int main()"
int main() {
int numPeople = 5;
int maxPancakes = -1;
int maxPerson = -1;
int currentPancakes = -1;
for (int i = 1; i < numPeople; i++) {
cout << "Person " << i << ": ";
cin >> currentPancakes;
if (currentPancakes > max) {
max = currentPancakes;
maxPerson = i;
}
}
cout << "Person " << maxPerson << " ate the most pancakes: " << maxPancakes;
return 0;
}
Note: my c++ is pretty rusty, I haven't tested this solution. Just an idea ;)
Using Map for this question will be an overkill. Array is more than enough. You don't even need to iterate through the array to check who ate the most. The operation for getting the max is actually O(0) because we can update who ate the most as you are entering the values.
int main(){
const int NUM_PEOPLE = 10;
int cakesEaten[10] = {0};
int maxEaten = 0;
int personId = 0;
cout << "How many pancakes eaten by:" << endl;
for(int x=0; x<NUM_PEOPLE; x++){
cout << "person " << (x+1) << ":";
cin >> cakesEaten[x];
if (cakesEaten[x] > maxEaten){
maxEaten = cakesEaten[x];
personId = x;
}
}
cout << "The most pancakes was eaten by person " << personID << endl;
}
You don't need any storage at all.
As the numbers are entered, compare them and store who has the current max, and its value
Starting with fake values is not needed if you use the first person's value as the start value, this way negative values, could be included if entered. That may be nonsensical here, but in general, its a better practice.
Also note if we want people to start at 1, then it makes more sense to start it at 1, then start at 0 and try to remember to always add 1.
This is also very easy to expand to more people, just change total_people
int main() {
const int total_people=5;
cout << "how many pancakes did you eat for breakfast?" << endl;
int what;
cout << "Person 1: ";
cin >> what;
int who=1;
int max_value=what;
for (int person = 2; person <= total_people; ++person) {
cout << "Person " << person << ": ";
cin >> what;
if (what > max_value) {
max_value=what;
who=i;
}
}
cout << "The most pancakes eaten was " << max_value << "by " << who << endl;
}

Parallel array in C++

I have an assignment where we need to have 2 parallel arrays one is a list of city names and the other is sales amounts. Here is a copy of the problem:
Program Description:
It needs to compile sales totals for various cities in the USA. Specifically, when the program is run, the user will be prompted to enter a city. If the city is correct, the user will then be prompted to enter a sales amount. If the city doesn’t exist on the list, the user will get an error message (and no sales amount prompt). If a sales amount is entered, it will accumulate into a total for that city. Either way (city exists on the list or not) , the user will then be asked to enter another city or quit.
Once the user quits, the city name and total should be displayed for all cities, one per line. Following that the program should stop.
There are only 8 cities to choose from. 2 parallel arrays must be used, initialized as follows:
City (String) Sales (Integer)
------------- ---------------
Atlanta 0
Buffalo 0
Chicago 0
Dallas 0
Houston 0
Honolulu 0
Miami 0
Reno 0
All input is guaranteed to be single-word followed by enter only. It may not match a city name, but there will be no spaces. This keeps your program simple as it lets you avoid using getline( ), which would be needed to deal with blanks between words.
Sales data is guaranteed good when input.
When I attempted to run my program, visual studios went crazy, and I've pulled out my hair trying to fix it. If someone could help give me some pointers on what I've done wrong, I would greatly appreciate it. Here is a copy of my program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName = " ";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i <= 8; i++)
{
if(cityName == city[i])
{cout << "Enter sales amount: ";
cin >> salesAmt;
salesAmt += sales[i];}
else
{cout << "ERROR: CITY NOT AVAILIABLE" << endl;
cout << endl;}
//end if
}
//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i <= 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
A clear error here is the way you have used the index to access the arrays, you can't have the for loop reach 8, as the array's index is only up to 7. change your for loops to:
for(i = 0; i < 8; i++)
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare city and sales array
string city[8] = {" "};
int sales[8] = {0};
//declare variables
string cityName ="";
int cityTotal = 0;
int salesAmt = 0;
int i = 0;
char another = ' ';
//init city array
city[0] = "Atlanta";
city[1] = "Buffalo";
city[2] = "Chicago";
city[3] = "Dallas";
city[4] = "Houston";
city[5] = "Honololu";
city[6] = "Miami";
city[7] = "Reno";
do
{
//input city name and if found input sales amount
cout << "Enter a City: Atlanta, Buffalo, Chicago, Dallas, Houston, Honololu, Miami, or Reno: ";
cin >> cityName;
for(i = 0; i < 8; i++)
{
if(cityName == city[i])
{
cout << "Enter sales amount: ";
cin >> salesAmt;
sales[i] += salesAmt;
} else if (i==7)
{
cout << "ERROR: CITY NOT AVAILIABLE" << endl;
}//end if
}//end for loop
//ask if another city
cout << "Enter another city?: ";
cin >> another;
} //end do loop
while(another == 'Y' || another == 'y');
{
for(i = 0; i < 8; i++)
{
cout << "City: " << " " << "Sales: " << endl;
cout << city[i] << " " << sales[i] << endl;
}
//end for loop
} //end while loop
system("pause");
return 0;
} //end of main
error was for(i = 0; i <= 8; i++) change with for(i = 0; i < 8; i++) and also second for.
Next error changed to sales[i] += salesAmt; and Not salesAmt +=sales[i];.
And your city name is case sensitive when you input city name!