It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
The exercise asks to find which of the numbers from 1 to 500, the sum of the numbers specific digits, raised to the third power equals that particular number.
for example 1^3=1
and 371 makes 3^3+7^3+1^3 = 371
How I approached the problem:
I was thinking if I could have an array of strings with 500 slots, each slot containing a string converted number, then I could do math with each slot's string. If they met the criteria I would apply then that slot would be printed.
I tried the function sprintf without much success. In a loop it just initializes the strings (or is it arrays? after 3 hours I am confused) [0] slot, leaving all other slots unchanged.
I don't want you to solve the exercise, rather than guide me with my logic. Please ask me to add code of what I did if you want to.
Always start by clearly defining your algorithm, so you know what you are doing. Split it up into simple steps. Something like this:
For each integer i in the interval 1 to 500:
Check if the condition holds for this i
If it holds:
Print i
else:
Do nothing
Now you need to define "Check if the condition holds for this i". I would use some modulo and division arithmetics to extract the digits, but I leave the details to you.
Note that I have talked nothing about C or any other programming language. Only when you know your algorithm should you start thinking about implementation.
(There is actually the possibility of a slightly different algorithm than the one given above, where you have one loop for each digit nested inside each other. That solution may be acceptable to you but it will not be as generic)
for(i=1;i<=500;i++)
{
//loop for checking each number i
int sum=0; // to store the sum of cube of digits
int n=i; //copy of i
//The below while loops does the task. It extracts a digit from the number and adds its cube to the sum
// last digit from the number can be seen by taking its remainder by 10 . For eg 35%10=5
//once we have used this digit make the number shorter by dividing by 10. For eg 35/10 becomes 3 (because of integer divisions)
while(n>0)
{
int rem=n%10; //extract the last digit
sum+=cube(rem); //cube function raises a number to its cube
n/=10; //remove the digit we had extracted earlier from the number
}
if(sum==i) //we got the number we wanted
printf("%d\n",i);
}
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
weather.outdooe_temp is a float value which is being updated every time I press a button. set_temp is a float to ascii function. If I use that the thing works, but not if I use the code below.
char Thermo_Buff66[4];
static void SetBox(ScreenObj_t const *pS, EVENT_MSG const *pMsg)
{
//set_temp(weather.outdoor_temp,&a);//it works if i use this function.
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
(void)sprintf(Thermo_Buff,"%s\xc2\xb0""",Thermo_Buff66);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
//currently displaying any # value....!!ing!!
}
char Thermo_Buff66[4];
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
The buffer you have allocated (Thermo_Buff66) is too short for a floating number representing outdoor temperature (often 2 digits) plus a . plus a digit after. Indeed, it doesn't have space for the terminating '\0' character. So immediate correction would be to set the size to 5. Still, in case of armageddon (or simply being in a non-SI country ... cough ... US), the temperature could even get to above 100, in which case again you overflow your buffer. Do yourself a favor and use snprintf.
Regardless, you sprintf into a buffer, then using %s you sprintf it into something else, which there is no point to. You can do it all directly in one, removing Thermo_Buff66 altogether:
(void)sprintf(Thermo_Buff, "%.1f\xc2\xb0", weather.outdoor_temp);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
Side note: the . and the precision digit already take up 2 characters. Setting minimum width to 2 is therefore reduntant. Perhaps you thought the 2 in %2.1 is the number of digits before the .? Well it's not. It's the minimum overall width.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Given a shifted array (for example):
[17 34 190 1 4]
which shifted from (we don't know original)
[1 4 17 34 190]
What would be a good function to find the position of that number?
For example if I pass 1, it would return 3th position.
linear search for answer would always work, but I believe you can get there in O(log) time.
Some sort of binary search for the shift point via checking if the value of the shift sorted array goes against what it is supposed it. Like creating a trie. Keep forming the sorted tree until you find the "illegal" node (man this is glossing over a lot of details - I know). That tells you where the inflection point is and you now treat the array as 2 sorted vectors. Quickly check to see if the value to find is larger than the max entry of each so we know which vector to search. BSearch the sorted vector for your value and return its index.
The hard part is finding the inflection point. :)
You would have to scan the array.
size_t pos_in_arr(int *arr, size_t arr_size, int match)
{
size_t i;
for (i = 0; i < arr_size; i++)
if (arr[i] == match)
break;
return i;
}
This function would return the position as asked, or one more than the maximum position in case the element is not found.
The solution is what you ask, but it is probably not what you need, because it does not use in any way the fact that the array has been shifted. I suspect the original problem to be more complex.
For example if you knew that in the original array one element was fifth and now is seventh, and the element you are looking for was twenty-third, you could answer "twenty-fifth" without actually scanning the array up to the twenty-fifth position, which could be the point of the whole exercise. But to build such a solution, one would need to know more about the problem.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I found some code similar to this (not exactly just the weird logic has been replicated) :
for(int counter = 0 ; counter < array.length() ; counter ++ ) {
array.removeObjectAtIndex(i);
counter -- ;
}
Is this bad code ? What should one do assuming there is no primitive method to empty the whole array or that we need to do some extra cleanup after removing each element ?
If you go from the top down, you won't need counter--, and it's more efficient because it won't have to shift the array elements above each time removeObjectAtIndex is called.
Interfering with a loop counter inside the loop body is never a good idea.
Despite not knowing what array is, a better way would be to continuously remove the array head until the array is empty.
int length = array.length();
for(int counter = 0 ; counter < length ; counter++ )
{
array.removeObjectAtIndex(0);
}
Well, the first thing to note here is that at the end of every loop there's a counter++ and a counter--. Effectively canceling each other out.
I suspect a junior programmer was taught that for loops require the format
for(int i=0;i<len;i++) {/*code*/}
Going forth on that logic, due to the length for the array shifting by one with each pass in the loop, he required counter to get decremented as well (as to not generate fake results).
for(int c=0;c<a.length();c++){a.remove(i);c--;}
If you remove c-- from this implementation, you would remove only half the indexes. Counter would go up as length would go down, effectively meeting half way.
Now a different implementation that feels less rigid
for(;array.length()>0;){array.removeObjectAtIndex(i);}
// also this
for(;array.length();array.removeObjectAtIndex(i));
OP mentioned .length() might be inefficient, so:
for(int len=array.length();len--;array.removeObjectAtIndex(i));
For's are incredibly powerful, I personally find them highly underused in some situations.
I agree with acraig5075's comment about interfering with a loop counter inside the loop body is bad habbit
i think bottom up approach as below code will work fine
for(int counter = array.length - 1; counter >= 0; counter--)
{
array.removeObjectAtIndex(counter);
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I would like to get the distinct count of the column of a large data file using C.How can I do it.Please kindly advise me.Thanks.My sample data file is as below.
For 2nd attribute the distinct count is 6.
399547,v4149,p3178,1990,2065,fraud
399940,v5852,p3194,8278,2180,fraud
399983,v3476,p3199,766,1125,fraud
400206,v3467,p3216,494,311000,fraud
400345,v4497,p3219,1211,432100,fraud
400471,v3473,p3225,41392,3710,fraud
400498,v3476,p3225,102,23820,fraud
401325,v4497,p3297,1322,1110,fraud
Make a search tree for every column. Let's say you have 10 rows in a file with 2 distinct values for the nth column viz. 3456 and 3457. Your search tree for nth column will look like:
You'll end up with 6 Search trees. Once you have read the entire file, traverse all possible paths in each search tree and that will give you the number of distinct values.
Read and split every line.
Put the second attributes into an array.
qsort the array
You have now an array with equal strings adjacent to each other. You can loop over the array and count different entries.
If your entries are all 5 characters long, otherwise you must malloc() memory for each attribute.
char (*array)[6];
int i;
int n; /* number of lines read */
int distinct = 1;
/* read the data file and put it into array */
/* qsort() array */
for (i = 1; i < n; ++i) {
if (strcmp(array[i], array[i - 1]) != 0)
++distinct;
}
printf("There are %d distinct rows\n", distinct);
You can use std::map<std::string,int> - it will hold key-value pairs, where key is vNNNN, and value is number of repetitions.
First loop will scan input file and populate this map, then number of keys in map will be distinct count.
EDIT: If you cannot use C++ and do require C, you will have to find some hashmap library for C, like sparsehash.
If amount of data is really, really big, it is possible that it will not fit in memory. In this case, I would recommend to use SQLite temporary database to parse, store and index your data and then use standard SELECT DISTINCT on it.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is there any way to generate a random number in C without using seed.
Here what have so far but it still using srand(time(NULL)); which is a seed.
#include <stdio.h>
#include <time.h>
#include <math.h> /* required for sqrt() */
#include <stdlib.h> /* required for rand() */
int gen_rand(); /* note these are declarations of functions */
void main()
{
int number;
srand (time(NULL)); /* everytime you run program, it will give you different result */
number = gen_rand();
printf("%d is the power of 2 of %.0lf\n", number, sqrt(number));
}
/* Function generates random number power 2 of 20 - 230 */
int gen_rand()
{
int n;
n = rand() % 211; /* n is random number in range of 0 - 210 */
n = n + 20; /* n is now in range of 20 - 230 */
return(n*n); /* return n to the power of 2 */
}
Yes and no.
There are basically two methods to get even remotely random numbers in c.
1) have a pseudo random number generator with seed -- that is an algorithm, that produces some sequence of numbers using clever arithmetic operators and possible lots of internal variables that are mixed, permuted, twisted and whatever. The seed can be implicit (i.e. always zero and each time you run the program, the same sequence is generated). Or it can be explicit, where the seed can be changed somehow between runs.
2) Using external source of data, that somehow changes in between runs. That could come from a timer, environment variables (program id perhaps), noise from camera, mouse movements etc.
1+2) use the external source of noise as seed to pseudo random number generator.
All non-hardware based PRNG require some form of random input to combat their deterministic nature, thus a seed will always be required.
You can try abuse /dev/rand under linux (but it also is a PRNG), or if you have a very modern Intel CPU, their new digital RNG facilities would work.
No. If you don't seed the automatic number generator, it will behave deterministically and yield the same numbers every time.
Yes. Generating random numbers by using the rand() function without using a seed will give you the same set of random numbers though.