I would like to to generate random values in C - c

I would like to ask about random values in C.
My C program has coding as below.
int random_a( int current_s,int r[num_s][num_a])
{
int i;
for(i=0;i<4;i++)
{
if(r[current_s][i] > -1) break;
}
return i;
}
For example condition
r[current_s][0] and r[current_s][2] > -1
If I run my program, answer have only i = 0. But I would like to get random answer that is 0 and 2 (1 and 3 not included because r[current_s][1] and r[current_s][3] = -1).
As my plan, I would like to get a random value between 0 and 3 using (rand()%4); if (r[current_s][i] > -1) is correct I will return that value. But if (r[current_s][i] = -1) generate a random number again until r[current_s][i] > -1 then return value.
What should I do?

Assuming that current_s is the row number of your matrix which contains the values -1 or greater, you can use this code :
int random_a(int current_a, int r[num_s][num_a])
{
if (current_a>num_s) return 0; //checking condition as current_a changes below
int i;
for (i=0;i<4;i++)
{
if(r[current_s][i] > -1) return i;
else if (r[current_s][i] && i==3) return (random_a(current_a+1,r[num_s][num_a])
else i++;
}
}
here you can change current_a based on your need.

Related

How do I generate 4 random variables and only printing if it doesn't contain the int 0

this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}

what thing i should change from this code

I want to make a program to count the sum of digits in a string but only using stdio.h
but the program needs to count until its less than 10
so the example you input 56 it would be 5+6=11 then 1+1=2 and so on
here's my code. For now I'm just confused how to check if its whether more than 9 or not
#include<stdio.h>
int plus(int n);
int main(void)
{
int n, digit, test;
scanf("%d", &n);
test = plus(n);
while(test != 0)
{
if(test > 9)
plus(test);
else
break;
}
printf("%d", test);
}
int plus(int n)
{
int digit=0,test=0;
while(n != 0)
{
digit = n%10;
test = test + digit;
n = n/10;
}
return test;
}
You are not storing the value returned by plus function in the while body.
You can change the condition in while to check whether it is greater than 9 or not, and assign test as test = plus(test);
So, your while will look like this.
while(test > 9)
{
test=plus(test);
}
You need to recursively call the function plus() until the value returned by it becomes less than 10. Like shown below:
int main(void)
{
int n=56;
while(n> 10)
{
n = plus(n);
}
printf("%d", n);
}

Display prime number

This programming I wrote below is used to display prime number from a list (20 numbers) which keyed in by user. But it only can detect 2 and 3 as prime number. I don't know why it doesn't work. Please tell me where is the errors and help me improve it. TQ.
#include <iostream>
#include <conio.h>
using namespace std;
void main ()
{
int i,number,list[20];
int t,p,prime=0;
cout<<"please key 20 numbers from 0 to 99"<<endl;
for(i=1;i<21;i++)
{
cin>>number;
if((number<0)||(number>99))
{
cout<<"Please key in an integer from 0 to 99"<<endl;
}
list[i]=number;
}
for(p=1;p<21;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if (prime==0&&list[p]!=1)
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
}
getch();
}
So there are a few issues with your code, but the one that will solve your issue is simply algorithmic.
When you start at the next iteration of p, you don't reset the value of prime and therefore it's always > 0 after we detect the second prime number and you'll never print out any again.
Change this:
for(p=1;p<21;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if (prime==0&&list[p]!=1)
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
}
To this (I've added some brackets for clairty and so we're certain the condition evaluates as we expect it to):
for(p=0;p<20;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if ( (prime==0) && (list[p]!=1) )
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
prime = 0;
}
And your issue will be solved.
HOWEVER: I would like to reiterate this does not solve all of your code issues. Make sure you think very carefully about the input part and what you are looping over (why is p 1 to 21? Why not 0 to 20 ;) arrays are zero indexed in C meaning that your list of 20 numbers goes from list[0] to list[19], you're currently looping from list[1] to list[20] which is actually out of range and I'm surprised you didn't get a segfault!)
What happens in your code is someone types in "123" or "-15"? Check and see if you can fix the error.
When you have fixed that, we can look at your prime checking code. Hint: there are a lot of prime testing code examples on the web.
Check this
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}
More Efficient Way
def print_hi(n):
if(n == 1 ):
return False;
if( n == 2 or n == 3):
return True;
if(n % 2 == 0 or n % 3 == 0):
return False;
for i in range (5,n,6):
if( i * i <= n):
if(n % i == 0 or n % (i+2) == 0):
return False
return True
if __name__ == '__main__':
x = print_hi(1032)
print(x)

How can I do this again? in C

#define G 10
int main(){
int grid[G][G],c,x;
for(c=1;c<=5;c++){
for(x=1;x<=5;x++){
if(c+x<=5)
grid[c][x]=+1;
else if(c+x>=7)
grid[c][x]=-1;
else
grid[c][x]=0;
printf("%2d\t ",grid[c][x]);
}
printf("\n");
}
getch();
return 0;
}
its output is
Which is what I really wanted to do but now I need to make it look like
and now I don't have any idea on how to do it, it's hurting my head now
I would do it like this
for(c=0; c<5; c++) { /* arrays start at 0, not 1. */
for(x=0; x<5; x++) { /* arrays start at 0, not 1. */
if (c == x) { /* looking at your output, the 0's occur when c == x */
grid[c][x] = 0;
} else if (c > x) { /* the -1 when c > x */
grid[c][x] = -1;
} else { /* obviously c > x */
grid[c][x] = 1;
}
/* nothing else changed */
printf("%2d\t ",grid[c][x]);
}
printf("\n");
}
It's quite simple, you have three distinct cases:
if both c and x are equal, your grid shows zero
if x is greater than c, your grid shows 1
else (ie, when x is less than c), your grid shows -1
Basically, we've written the if-else structure you need in your loop to get the desired output:
if (c == x) grid[c][x] = 0;
else if (x > c) grid[c][x] = 1;
else grid[c][x] = -1;
Thus, the full code looks like this:
#include <stdio.h>
#define G 10
int main()
{
int grid[G][G],c,x;
for(c=0;c<5;++c)
{//zero indexed
for(x=0;x<5;++x)
{//perhaps change 5 with G, or another macro or some int
if(c == x) grid[c][x] = 0;
else if (c < x) grid[c][x] = 1;//1 is fine, the + is not required
else grid[c][x] = -1;
printf("%2d\t ",grid[c][x]);
}
printf("\n");
}
return 0;
}
Which as you can see on this codepad works just fine.
note:
As I said, the + in +1 is optional. I'd even advise against it. If I happen to come across a statement like some_int = +1; I might assume that it's a bug, and it was supposed to read some_int += 1;, which is a different thing all together.
The major diagonal of matrix is collection of elements that meet row==column condition. Plus we know that row and column elements above(right from) diagonal meet row<column, and below ones row>column condition. And here is how to make that matrix and while making we will show them :
#define G 5
int grid[G][G], row, column;
for (row =0; row < G; row++) {
for (column =0; column < G; column++) {
if (row<column)
grid[row][column] = 1;
else if (row>column)
grid[row][column] = -1;
else
grid[row][column] = 0;
printf("%2d\t ", grid[row][column]);
}
printf("\n");
}
And here is output:
0 1 1 1 1
-1 0 1 1 1
-1 -1 0 1 1
-1 -1 -1 0 1
-1 -1 -1 -1 0
And Here is what was your problem.
You chose minor (secondary) diagonal isntead of main
Your index handling done manually .Like you calculated conditions manually. It is not good
And here is how you should do for minor diagonal without calculating condition manually
#define G 5
int grid[G][G], row, column ;
for(row=0;row<G;row++){
for(column=0;column< G;column++){
if(row+column<G-1)
grid[row][column]=1;
else if(row+column>G-1)
grid[row][column]=-1;
else /*minor diagonal meet row==(G-1)-column //G-1 cause index begins from 0*/
grid[row][column]=0;
printf("%2d\t ",grid[row][column]);
}
printf("\n");
}
Now Swap the first and last columns of your matrix then second and second last. Thats it
#include <stdio.h>
#define G 10
int i,j;
int grid[G][G];
int main() {
for(i=0; i<G; i++) {
for(j=0; j<G; j++) {
if(i==j) grid[i][j]=0;
else if(i<j) grid[i][j]=1;
else if(i>j) grid[i][j]=-1;
printf("%2d\t", grid[i][j]);
}
printf("\n");
}
return 0;
}
you can modify your program as below :
1,for(c=1;c<=5;c++) -->for(c=5;c>=1;c--)
2, grid[c][x]=+1; --> grid[c][x]=-1;
3, grid[c][x]=1; --> grid[c][x]=+1;
#define G 10
int main(){
int grid[G][G],c,x;
for(c=5;c>=1;c--){
for(x=1;x<=5;x++){
if(c+x<=5)
grid[c][x]=-1;
else if(c+x>=7)
grid[c][x]= 1;
else
grid[c][x]=0;
printf("%2d\t ",grid[c][x]);
}
printf("\n");
}
getch();
return 0;
}
You need to create a 2D matrix, where the matrix is diagonally zero, upper triangle would be 1, and lower triangle would be -1.
So,
if **row == column** , then assign 0 to diagonal. (**grid[row][column] = 0**)
else if , **row < column**, then assign 1 to upper triangle. (*grid[row][column*] = 1)
else, **row > column**, then assign -1 to lower triangle. (*grid[row][column] = -1*)

UVA's 3n+1 wrong answer although the test cases are correct . . .?

UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}

Resources