I have solved this programming problem and when I submitted my code, the judge said it was wrong. I tried and I couldn't figure out the bug. Can someone give me a hint please?
Because stack overflow won't accept my question if I don't specify more details, I am copying the question here
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the
differences between successive elements take on all possible values 1 through n − 1. For
instance,
1 4 2 3
is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively. The
definition implies that any sequence of a single integer is a jolly jumper. Write a program
to determine whether each of a number of sequences is a jolly jumper.
Input
Each line of input contains an integer n < 3, 000 followed by n integers representing the
sequence.
Output
For each line of input generate a line of output saying “Jolly” or “Not jolly”.
The code
#include <stdio.h>
#define SEQ_SIZE 3000
static char stack[SEQ_SIZE];
void initStack(int count)
{
for(int i=0;i<count; ++i)
stack[i]=0;
}
int absDiff(int a, int b)
{
return (a-b)>=0?((a-b)%SEQ_SIZE):(((a-b)*-1)%SEQ_SIZE);
}
int main()
{
int n,prev,curr;
/*FILE *sample=fopen("SampleInput","r");
if(!sample)
return 0;*/
while(scanf("%d",&n)!=EOF)
{
scanf("%d",&prev);
if(n<1)
break;
else if(n==1)
printf("Jolly\n");
else
{
int i;
for(i=1; i<n; ++i)
{
scanf("%d",&curr);
stack[absDiff(curr,prev)-1]=1;
prev=curr;
}
for(i=0; i<(n-1); ++i)
{
if(stack[i]==0)
break;
}
if(i<n-1)
printf("Not jolly\n");
else
printf("Jolly\n");
initStack(n);
}
}
}
I think your solution is fine except the line
return (a-b)>=0?((a-b)%SEQ_SIZE):(((a-b)*-1)%SEQ_SIZE);
No need to use % here. It should be
return (a-b)>=0?((a-b)): (a-b)*(-1));
To limit n below 3000 you can do as
if(n<1 || n >= 3000) // I merged it with n<1 condition
break;
Related
Question :
Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.
My code :
#include<stdio.h>
#include<stdlib.h>
int compare(int m) {
int b;
b=73-m; ///I chose my number as 73 here.
if (b=0) printf("Congrats, you won.");
else {
if (-5 < b < 5) printf("Very Close\n"); ///always gives me this output two times.
else {
if (-15 < b < 15) printf("Close");
else {
printf("You are far");
}
}
}
return b;
}
int main() {
int arr[100],guess,count=0,i,m; ///I have 99 tries.
arr[0]=0;
for(i=1 ; i<=100 ; i++) {
printf("Enter your guess\n");
scanf("%d",&guess);
if(guess==arr[i-1]) {
arr[i]=guess;
printf("Guess is same as the previous input.\n");
} else {
arr[i]=guess;
compare(guess);
if (m = compare(guess)) {
count=count+1; /// can i create a separate function to keep the count?
printf("%d is the number of tries.\n",count);
break;
} else {
printf("\n");
}
}
}
return 0;
}
This is always giving me the same output two times i.e "Very close Very close". This is either faulty code (syntax) or wrong logic, I think. Also I want to know a better algorithm/logic with the code to solve this question (possibly shorter). Lastly I am new to programming with C as my first language.
The condition -5 < b< 5 is equal to (-5 < b) < 5, which means you compare the boolean (0 or 1) result of -5 < b with 5.
If you need to compare b to a range you need to do -5 < b && b < 5. I.e. compare b explicitly against both ends of the range.
Also, b = 0 is assignment not comparison, you need to use == for comparison.
Hey there i'm currently developing a lotto type game and one of my requirements is to record the frequency of the numbers inputted by the user and then display them if the users wishes to see them. The program also must be modular hence the functions.
My problem is that i can't seem to figure out how to keep track of the numbers I tried numerous things and this is the closest I've gotten...
void num_free(int *picked_nums)
{
static int elements[MAX] = { 0 };
int i;
for (i = 0; i < MAX; i++)
if (*(picked_nums + i) == i)
{
elements[i]++;
}
for (i = 0; i < MAX; i++)
{
if (elements[i] != 0)
{
printf("\nThe amount of times you chose %d is %d", i, elements[i]);
}
}
printf("\nEnter any key to return to main menu");
getchar();
}
The output of this every time i run it no matter the input is
"The amount of times you chose 11 is 1"
I'm really clueless as to what to do next so any and all help would be appreciated. Thanks in advance!
EDIT: The user can play multiple rounds and thats how the frequency of the numbers can add up.
I think the main problem in your code is here:
if (*(picked_nums + i) == i)
{
elements[i]++;
}
you actually check if the i-th number the user chose equals to i. That means that increment is done only in that case - which is not what you want (if I got you right).
I think you should give up the if statement, and, assuming that the user chooses only non-negative numbers (and that the elements array is properly zeroed at the beginning), do this:
elements[picked_nums[i]]++;
Namely, you increment the array cell matching the chosen number (and the i is only the index you use to iterate the picked_num array).
The problem is how you count and store the numbers:
if (*(picked_nums + i) == i)
{
elements[i]++;
}
Your i is moving and at the same time the element chosen from picked_nums is moving. This loop will not count or store properly.
The provided solution assumes that picked numbers are stored in the numbers array. I assumed that numbers are in 1 to 64 range. You can adjust program to your needs. Test provided:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void num_free(int picked_nums[], int size )
{
static int elements[65] = { 0 }; // numbers can be from 1 to 64 range
int i;
for (int j = 0; j < size; j++)
{
int n = picked_nums[j];
for (i = 1; i < 65; i++) // numbers can be from 1 to 64 range
{
if ( n == i)
{
elements[i] = elements[i]+1;
}
}
}
for (i = 0; i < 65; i++)
{
if (elements[i] != 0)
{
printf("\nThe amount of times you chose %d is %d", i, elements[i]);
}
}
// printf("\nEnter any key to return to main menu");
// getchar();
}
// array of entered numbers:
int numbers[] = { 2, 2, 2, 40, 7, 7, 8, 9, 40 };
int main(void) {
num_free(numbers, 9); // call with sizeof numbers
return 0;
}
Test:
The amount of times you chose 2 is 3
The amount of times you chose 7 is 2
The amount of times you chose 8 is 1
The amount of times you chose 9 is 1
The amount of times you chose 40 is 2
I have to write a program that finds every number (except 0) which can be factored by numbers from 2-9.
For example first such a number would be number 2520 as it can be divided by every single number from 2 to 9.
It also has to be a number that contains only 1 type of digit of its own (no multiple digits in a number). So for example 2520 will not meet this requirement since there are two same digits (2). The example of a number that meets both requirements is number 7560. That is the point I don't how to do it. I was thinking about converting value in an array to string, and then putting this string in another array so every digit would be represented by one array entry.
#include <stdio.h>
#include <math.h>
int main() {
int i, n, x, flag, y = 0;
scanf("%d", &n);
double z = pow(10, n) - 1;
int array[(int)z];
for (i = 0; i <= z; i++) {
flag = 0;
array[i] = i;
if (i > 0) {
for (x = 2; x <= 9; x++) {
if (array[i] % x != 0) {
flag = 1;
}
}
if (flag == 0) {
y = 1;
printf("%d\n", array[i]);
}
}
}
if (y == 0) {
printf("not exist");
}
return 0;
}
This should give you a base:
#include <stdio.h>
#include <string.h>
int main()
{
char snumber[20];
int number = 11235;
printf("Number = %d\n\n", number);
sprintf(snumber, "%d", number);
int histogram[10] = { 0 };
int len = strlen(snumber);
for (int i = 0; i < len; i++)
{
histogram[snumber[i] - '0']++;
}
for (int i = 0; i < 10; i++)
{
if (histogram[i] != 0)
printf("%d occurs %d times\n", i, histogram[i]);
}
}
Output:
Number = 11235
1 occurs 2 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
That code is a mess. Let's bin it.
Theorem: Any number that divides all numbers in the range 2 to 9 is a
multiple of 2520.
Therefore your algorithm takes the form
for (long i = 2520; i <= 9876543210 /*Beyond this there must be a duplicate*/; i += 2520){
// ToDo - reject if `i` contains one or more of the same digit.
}
For the ToDo part, see How to write a code to detect duplicate digits of any given number in C++?. Granted, it's C++, but the accepted answer ports verbatim.
If i understand correctly, your problem is that you need to identify whether a number is consisted of multiple digits.
Following your proposed approach, to convert the number into a string and use an array to represent digits, i can suggest the following solution for a function that implements it. The main function is used to test the has_repeated_digits function. It just shows a way to do it.
You can alter it and use it in your code.
#include <stdio.h>
#define MAX_DIGITS_IN_NUM 20
//returns 1 when there are repeated digits, 0 otherwise
int has_repeated_digits(int num){
// in array, array[0] represents how many times the '0' is found
// array[1], how many times '1' is found etc...
int array[10] = {0,0,0,0,0,0,0,0,0,0};
char num_string[MAX_DIGITS_IN_NUM];
//converts the number to string and stores it in num_string
sprintf(num_string, "%d", num);
int i = 0;
while (num_string[i] != '\0'){
//if a digit is found more than one time, return 1.
if (++array[num_string[i] - '0'] >= 2){
return 1; //found repeated digit
}
i++;
}
return 0; //no repeated digits found
}
// test tha function
int main()
{
int x=0;
while (scanf("%d", &x) != EOF){
if (has_repeated_digits(x))
printf("repeated digits found!\n");
else
printf("no repeated digits\n");
}
return 0;
}
You can simplify your problem from these remarks:
the least common multiple of 2, 3, 4, 5, 6, 7, 8 and 9 is 2520.
numbers larger than 9876543210 must have at least twice the same digit in their base 10 representation.
checking for duplicate digits can be done by counting the remainders of successive divisions by 10.
A simple approach is therefore to enumerate multiples of 2520 up to 9876543210 and select the numbers that have no duplicate digits.
Type unsigned long long is guaranteed to be large enough to represent all values to enumerate, but neither int nor long are.
Here is the code:
#include <stdio.h>
int main(void) {
unsigned long long i, n;
for (n = 2520; n <= 9876543210; n += 2520) {
int digits[10] = { 0 };
for (i = n; i != 0; i /= 10) {
if (digits[i % 10]++)
break;
}
if (i == 0)
printf("%llu\n", n);
}
return 0;
}
This program produces 13818 numbers in 0.076 seconds. The first one is 7560 and the last one is 9876351240.
The number 0 technically does match your constraints: it is evenly divisible by all non zero integers and it has no duplicate digits. But you excluded it explicitly.
I was trying to solve this tricky question, but for some reason my code is doing something wrong... I don't exactly know why, but I'll try to explain as much as I can.
Consecutive products:
Write a program that reads a positive integer
from standard input and verifies if it's equal to the product of three
natural and consecutive numbers. For example, the number 120 is equal
to 4x5x6, as for number 90 there aren't any three consecutive natural
numbers whose product is 90. Your program should generate as output
'S' if there are 3 consecutive natural numbers whose product is the
value read, or 'N' if none.
Input
120
Expected Output
"S"
Input
60
Expected Output
"S"
Input
80
Expected Output
"N"
Input
120
Expected Output
"S"
And this is my code:
#include <stdio.h>
int main(){
int int1,i,count=10,j,k,w=0;
scanf("%i",&int1);
for (i = 1; i <= count; ++i)
{
for (j = 1; j <= count+1; ++j)
{
for ( k = 1; k <= count+2; ++k)
{
if ((i==j+1 && i==k+2) && (i*j*k==int1)){
w=1;
}
}
}
}
if (w==0)
{
printf("N");
}
else{
printf("S");
}
}
So basically what this does is I have 3 loops that will generate random numbers in a k*i*j form... and it checks if we are getting what we want(the product of three natural and consecutive numbers) . This is for an assignment.
I modified your code. Please let me know if the problem still exists. The change made is exactly as WDS said.
#include <stdio.h>
int main(){
int int1,i,count=10,j,k,w=0,comp;
scanf("%i",&int1);
for (i = 1; i <= count; ++i)
{
comp = i*(i+1)*(i+2);
if(comp==int1)
{
w = 1;
}
}
if (w==0)
{
printf("N");
}
else
{
printf("S");
}
return 0;
}
You don't need 3 loops. One trival approach would be:
int test(int num)
{
for (int i = 1; i < num; i++)
{
int product = i * (i + 1) * (i + 2);
if ( product == num )
return true;
else if (product > num)
break;
}
return false;
}
You might want to add the algorithm tag on this question. That said, my approach would be to consider what the product of 3 consecutive numbers is. You could write it as x * (x+1) * (x+2). But there is a better way.
Write it as (x-1) * x * (x+1). Then multiply and simplify. The result is x^3-x.
Now for any given number, start a single loop on x from x = 2 (because if x=1 then x-1=0 and this will never be a solution) and incrementing by 1 each loop. Check on each loop for a match with the input number. If it is a match, return true. If it is not a match and exceeds the input number return false. If it is not a match and is less than the input number, loop again.
Here are two functions below that compile perfectly but I seem to be getting a weird error with the very first inputted integer. I have tried debugging in GDB but when it's only the first inputted value that is having this weird error, then it makes things complicated.
#include <stdio.h>
#include "Assg9.h"
#include <stdlib.h>
#include <assert.h>
#include <math.h>
void getPrimes(int usernum, int* count, int** array){
(*count) = (usernum - 1);
int sieve[usernum-1], primenums = 0, index, fillnum, multiple;
for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){
sieve[index] = fillnum;
}
for (; primenums < sqrt(usernum); primenums++)
{
if (sieve[primenums] != 0){
for (multiple = primenums + (sieve[primenums]); multiple < usernum - 1; multiple += sieve[primenums])//If it is not crossed out it starts deleting its multiples.
{
if(sieve[multiple]) {
--(*count);
sieve[multiple] = 0;
}
}
}
}
int k;
for (k = 0; k < usernum; k++)
if (sieve[k] != 0)
{
printf("%d ", sieve[k]);
}
*array = malloc(sizeof(int) * (usernum +1));
assert(array);
(*array) = sieve;
}
void writeToOutputFile(FILE *fpout, const int *array, int n, int count){
int i;
fprintf(fpout, "There are %d prime numbers less than or equal to %d \n", count, n);
for(i = 0; i < count; i++)
{
if(*(array + i) != 0){
fprintf(fpout, "%d ", *(array + i));
}
}
}
Our Output:
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2 32664
Do you want to try again? Press Y for Yes and N for No: y
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2
Do you want to try again? Press Y for Yes and N for No: n
Good bye. Have a nice day
Expected output should obviously just display 2. This is the case for any integer from 2-2000 for the very first inputted integer. The very last, or last 2, prime numbers print very large numbers, sometimes even negative numbers. I have no clue why, but after the first inputted value everything works perfectly. Tried debugging this with GDB like crazy but with no luck. Would really appreciate someone's help for this bizarre error
You aren't initializing the sieves array to 0s. So you're looping from 0 to usernum-1, printing out every number that isn't a 0. Since you didn't initialize the array, the 2nd element is a random value and is being printed out
This code is a problem:
(*array) = sieve;
You are are assigning the address of sieve, a temporary local array, to *array. You need to copy the array contents instead.
Are you also this person who has asked three questions about identical code?