I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:
srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]
Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.
How can I weight it? I've come up with an equivalent formula
List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"
Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?
This is not possible.
You need somehow to allow a variation on your conditions to have a proper distribution.
Related
I was given an assignment to make a program in cpp where you give it the width and length of the square and it will go into a pattern of *s and #s but I can't wrap my head around it. So I'm asking you people at stackoverflow to help me if you can. For reference when you would give an input of
6 6
the output would be:
######
#****#
#*##*#
#*##*#
#****#
######
and an input of
4 3
will give an output of:
####
#**#
####
This assignment is meant to help you understand how to use nested for loops.
for (int i = 0; ...)
{
for (int j = 0; ...)
{
// Do stuff here
}
}
Think about how a row can be formed by repeating a specific action. Then think about how a square can be formed by repeating the action of creating a row.
As for '*' vs '#', you always have access to both the x and y coordinate of the "current cell" you are about to print from inside the inner loop, because they are the counter variables for the two for loops. Remember: i and j are just arbitrary names. You could name those variables anything you want. You also have access to the length of each row and column, because they are given as input. Ask yourself: "what test can I make on the x or y coordinate that will tell me if it is the first or last column"?
Looping (or "iteration") is an extremely important concept in programming. Hopefully this gives you a hint in the right direction without giving too much away. :)
I am currently learning how to use Pari GP and right now i am trying to write out a code on checking whether if the user did key in a prime number or not.
Here is my code.
printf("\t%s \n","PrimeNo(P): To check if it is a prime or not");
PrimeNo(p)={
if(isprime(p)||1, print("Prime numbers only"));
if(isprime(p)||0, print("Prime numbers stored"));
print(p);
}
Problem is my first "if" line works by identifying that it was not a prime, but when i key in a prime number, both line appeared.
Would appreciate if anyone can help.
Your if statements have two tests each, so both are true if p is prime (the first if isprime(p) OR 1, the second if isprime(p) OR 0). I think you want something like:
PrimeNo(p) = { if( isprime(p), print("Yep"), print("Nope") ); print(p); }
Here we're using the if-then-else form of Pari/GP's if, so we do the first item if isprime(p) is true and the second item if it is false. This also has the advantage of only calling isprime once, which is important if your numbers are large (one can also debate ispseudoprime vs. isprime but there is no difference for 64-bit inputs).
I have an array of letters of an unknown number of elements which contains lower case letters. I have written a function for converting a lower case number to its ASCII value
int returnVal (char x)
{
return (int) x;
}
I am trying to combine all of these values into one number. Subtracting 87 from each of these means that the value is always a 2 digit number. I am able to combine an array made up if two elements by:
returnVal (foo[0]) - 87) + returnVal (foo[1] - 87) * 100
an array made up of three elements by
returnVal (foo[0]) - 87) + returnVal (foo[1] -87) * 100 + returnVal (foo[2] - 87) * 100 * 100
I am multiplying each element by 100^its position in the array and summing them. This means that [a,b,c] would become 121110 (yes, the 'flip' having the value for 'c' first and 'a' last is intentional). Could anybody programme this (for an array of an unknown number of elements)?
EDIT: I have received no form of schooling at programming/computer science at any pojnt in my life, this is not homework. I am trying to teach myself and I have got stuck; I don't know anybody in person who I could go to for help so I asked here, apologies to those of you who are offended.
EDIT2: I know that this opinion is going to annoy a lot of people; what is the purpose of stackoverflow.com if it is not to exchange information? If I were a child who was stuck with my homework (I'm not) surely that is a valid reason for using stack overflow? Many people on this website seem to have the mindset that if a problem is asked by a beginner then it is not worth answering, which is completely fine because your time is your own. However, what genuinely bugs me is the people who see a question which they deem trivial and say "homework" and vote it down immediately. I think that this website would be far better if there wasn't an "minimum-level" knowledge required in order to ask questions, the "elitist" mindset is just childish in my opinion.
Since this is a learning exercise, here are some hints for you to complete the task yourself:
Prepare a value that will server as the "running total" for your number so far.
Start the running total at zero.
When you convert a number, say, "1234", to an int, this value would first become 1, then 12, then 123, and finally 1234
The final value of the running total is your end result
To go from a previous value to the next, multiply the prior value by ten, and add the value of the current digit to it
Your returnVal does not make sense, because in C you can very often avoid an explicit conversion of char to int. You can definitely avoid it in this case.
Making a function int digit(char c) that returns a value of decimal digit, i.e. c-'a', would be a lot more useful, because it would let you get rid of your c-87 in multiple spots.
char array[SIZE];
long factor=1;
long result=0;
for(int i=0; i<SIZE; i++)
{
result+=returnVal(foo[i])-87)*factor;
factor*=100;
}
This should work for as long as long is large enough to hold the value of 100^the position and, of course, as long as the result does not overflow.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Our profeesser assigned this project but Im at a loss of how to do it. Normally I would figure it out on my own but Ive got a massive English paper due on the same day and I have to finish that also this weekend. The program is due on 11/12/13 but can be turned in by 11/19/13 with a 20% penalty to grade.
Write and test a C++ program to complete the following project:
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1
to 25).
The second number represents the first value in the table. (-1000 to
+1000)
The third number represents the increment between successive values
in the table. (1 to 20)
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
Square
Square Root (only if the value is positive or zero, display “N/A” for
all other values)
Cube
Cube Root (only if the value is positive or zero, display “N/A” for
all other values)
Whether the number is even or odd
Whether the number is prime or not (Prepare a user-defined function
based on the logic in Assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status. Display “True” or “False” for the number’s prime-ness.
Repeat this process until the user enters a count of zero for the number of values in the table.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Heres' what i have so far:
// TABLEation.cpp : builds a table based on user input.
//
using namespace std;
double square, squareroot,cube,cuberoot;
int initialValue,display,increment;
string even,prime;
const int SIZE=25;
int Value[SIZE];
bool isEven( int integer )
{
if ( integer % 2== 0 )
return true;
else
return false;
}
bool isPrime(int testValue) {
int divisor=0, remainder=0;
if (testValue<2) return false;
for(divisor=2; divisor<=sqrt(testValue);divisor++){
if((testValue % divisor)==0) return false;
}
return true;
}
int _tmain()
{
do{
begining:
cout<<"Enter how many values to show (1-25)."<<endl;
cin>>display;
if((display>0) && (display<=25)){
cout<<"Enter an initial Value (-1000 to 1000)."<<endl;
cin>>initialValue;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
if ((initialValue>= -1000) && (initialValue<=1000)){
cout<<"Enter a number to increment by (1-20)"<<endl;
cin>>increment;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
}
system("pause");
return 0;
}
where should I go from here?
Since there is no question above I am guessing you want someone to either give you the answer, or give you hints towards the right direction. I am going to pretend you are after the latter. The problem is fairly straightforward.
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1 to 25).
he second number represents the first value in the table. (-1000 to +1000)
The third number represents the increment between successive values in the table. (1 to 20)
Since below we see that you are to ask these questions in a loop until the first answer is 0 you could build a function "bool get_input(int &num_values, int &start_num, int &increment)" This function will return false if the user puts in a value that is not within the ranges and true otherwise. Now call this function in a while loop where you exit if the num_values is 0.
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
This is a for loop where i = start_num and at each iteration you increase i+=increment
for each iteration of your for loop you should be calling the following six functions:
Square
int square(int i) which returns the square of the value.
Square Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_square_root(int i, float &square_root) which returns false if the value is negative, otherwise it puts the square root into the reference variable.
Cube
int cube(int i) which returns the cube of the value.
Cube Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_cube_root(int i, float &cube_root) -- as above
Whether the number is even or odd
bool even_or_odd(int i) which returns true if the value is even and false otherwise.
Whether the number is prime or not (Prepare a user-defined function based on the logic in Assignment 5)
bool prime(int i) which returns true if the value is prime. (use assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
for each result store it in an array (square_root_array, cube_root_array, etc.)
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
call a function void display_values(float square_root_array[], ...) which iterates through each of your arrays and prints the values according to the rules listed below:
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status.
Display “True” or “False” for the number’s prime-ness.
The next part is already handled by our while loop.
Repeat this process until the user enters a count of zero for the number of values in the table.
I will leave the Bonus for you to figure out.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Good luck, and get used to working all nighters if you plan on taking a lot of CS. It's par for the course.
P.S. If you follow these directions and look up how to do each step where you are unsure, you could get this project off of your plate in a couple hours.
In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the