I'm trying to find the sum of all positive numbers in an array. So far, I have come up with this;
int largest_sum_sequence(int list, int size)
{
int sum = 0, *index = 0;
for (index < size; index = size; index++)
{
if (list[index] > 0)
{
sum = sum + list[index];
}
}
printf("%d", sum);
return sum;
}
My program keeps crashing. I'm pretty sure it has something to do with index. Whenever I use list[index] it says that I need to use a pointer for index, but I don't know how to do that properly. Help is appreciated!
You do not want index to be a pointer, and your for loop is incorrect. Try:
int sum = 0, index = 0;
for (; index < size; index++)
The compiler tells you actually exactly what to do.
First of all you need an array or a pointer as a parameter, like
int largest_sum_sequence(int *list, int size)
{
....
}
or
int largest_sum_sequence(int list[], int size)
{
....
}
where the latter might be easier to read.
The second thing is, you don't want to iterate with a pointer through the list, but more with a simple integer.
so you declare
int sum = 0, index = 0;
The for() loop isn't quite correct either. Instead of initializing something, you test if index < size and discard the result. This is syntactically correct, but doesn't make sense.
The first part in the for-statement is executed before the loop starts, but doesn't influence the starting itself. It is meant for initializing the loop variable (index in this case). The second part is the termination condition. The loop terminates if the condition evaluates to false. The last part of the loop is for incrementing (or decrementing, more abstract, changing) the loop variable.
Having said this, it is halfway obvious it should look like:
for (index = 0; index < size; ++index) {
....
}
Assuming your list isn't very long (such that the sum could exceed 2^{31} - 1), the rest is correct. Although I'd add an \n to the printf() pattern.
Where is the list coming from? Can't answer that from your code, but you've room for mistakes here too :-)
Function argument doesn't except an array.
Quick function I wrote.
int getSums(int myArray[], int size)
{
int total = 0;
int index = size;
for ( int i = 0; i < index; i++)
{
if (myArray[i] > 0)
total += myArray[i];
}
return ( total );
};
Related
I am creating an array that contains the locations of sites in space. So for array[2], I also want to say array[2].num = 2 I want each site to have a unique site number num from 0 to N-1. Output different values of i for array[i].num gives 0, 1, 32767. Whereas, for increasing i, I want to see incrementing values from 0 to N-1.
I am very new to structures so if you could explain where I am making my mistakes I would much appreciate your help as a noice programmer.
typedef struct site_t
{
int num; // want to add more varaibels later hence type struct //
} site;
site fillStruct( site[], int);
int main()
{ int i;
const int N = 20;
site array[N];
fillStruct(array, N);
for (i = 0; i < N; i++) {
printf("location of site %d\n", array[i].num);
}
}
site fillStruct(site array[], int size) {
for (int k = 0; k < size; k++) {;
array[k].num = k;
return array[k];
}
}
If I'm understanding your question correctly, I think your problem comes from your fillStruct() function. The loop in this function will only execute once, instead of N times. You never exceed k=0, so you set the num member for array[0] and then return array[0].
When you return to your main function, you print the location for array[0] accurately, but subsequent site numbers in the array are just random uninitialized values.
Instead, you want the return statement to be outside of the loop block, so the function should like like...
site fillStruct(site array[], int size) {
int k;
for (k = 0; k < size; k++) {;
array[k].num = k;
}
return array[k-1]; // Returns the last site in the array
}
Now, when you return to your main function you will have 20 sites numbered 0 to 19 (for N=20).
Also note that in the code you gave, you are not using the return value of fillStruct().
Hope that helps, let me know if I missed something.
EDIT:
I forgot to mention that I do not want to allocate another temporarily array.
I am trying to solve a problem in C, which is:
Suppose you were given an array a and it's size N. You know that all of the elements in the array are between 0 to n-1. The function is supposed to return 0 if there is a missing number in the range (0 to n-1). Otherwise, it returns 1. As you can understand, duplicates are possible. The thing is that its supposed to run on O(n) runtime.
I think I managed to do it but i'm not sure. From looking at older posts here, it seems almost impossible and the algorithm seems much more complicated then the algorithm I have. Therefore, something feels wrong to me.
I could not find an input that returns the wrong output yet thou.
In any case, I'd appreciate your feedback- or if you can think of an input that this might not work for. Here's the code:
int missingVal(int* a, int size)
{
int i, zero = 0;
for (i = 0; i < size; i++)
//We multiply the element of corresponding index by -1
a[abs(a[i])] *= -1;
for (i = 0; i < size; i++)
{
//If the element inside the corresponding index is positive it means it never got multiplied by -1
//hence doesn't exist in the array
if (a[i] > 0)
return 0;
//to handle the cases for zeros, we will count them
if (a[i] == 0)
zero++;
}
if (zero != 1)
return 0;
return 1;
}
Just copy the values to another array placing each value in its ordinal position. Then walk the copy to see if anything is missing.
your program works and it is in O(N), but it is quite complicated and worst it modify the initial array
can be just that :
int check(int* a, int size)
{
int * b = calloc(size, sizeof(int));
int i;
for (i = 0; i != size; ++i) {
b[a[i]] = 1;
}
for (i = 0; i != size; ++i) {
if (b[i] == 0) {
free(b);
return 0;
}
}
free(b);
return 1;
}
This problem is the same as finding out if your array has duplicates. Here's why
All the numbers in the array are between 0 and n-1
The array has a size of n
If there's a missing number in that range, that can only mean that another number took its place. Which means that the array must have a duplicate number
An algorithm in O(n) time & O(1) space
Iterate through your array
If the sign of the current number is positive, then make it negative
If you found a negative this means that you have a duplicate. Since all items are originally greater (or equal) than 0
Implementation
int missingVal(int arr[], int size)
{
// Increment all the numbers to avoid an array with only 0s
for (int i = 0; i < size; i++) arr[i]++;
for (int i = 0; i < size; i++)
{
if (arr[abs(arr[i])] >= 0)
arr[abs(arr[i])] = -arr[abs(arr[i])];
else
return 0;
}
return 1;
}
Edit
As Bruno mentioned if we have an array with all zeros, we could have run into a problem. This is why I included in this edit an incrementation of all the numbers.
While this add another "pass" into the algorithm, the solution is still in O(n) time & O(1) space
Edit #2
Another great suggestion from Bruno which optimizes this, is to look if there's more than one zero instead of incrementing the array.
If there's 2 or more, we can directly return 0 since we have found a duplicate (and by the same token that not all the numbers in the range are in the array)
To overcome the requirement that excludes any extra memory consumption, the posted algorithm changes the values inside the array by simply negating their value, but that would leave index 0 unchanged.
I propose a different mapping: from [0, size) to (-1 - size, -1], so that e.g. {0, 1, 2, 3, 4, ...} becomes {-1, -2, -3, -4, -5, ...}. Note that, for a two's complement representation of integers, INT_MIN = -INT_MAX - 1.
// The following assumes that every value inside the array is in [0, size-1)
int missingVal(int* a, int size) // OT: I find the name misleading
{
int i = 0;
for (; i < size; i++)
{
int *pos = a[i] < 0
? a + (-a[i] - 1) // A value can already have been changed...
: a + a[i];
if ( *pos < 0 ) // but if the pointed one is negative, there's a duplicate
break;
*pos = -1 - *pos;
}
return i == size; // Returns 1 if there are no duplicates
}
If needed, the original values could be restored, before returning, with a simple loop
if ( i != size ) {
for (int j = 0; j < size; ++j) {
if ( a[j] < 0 )
a[j] = -a[j] - 1;
}
} else { // I already know that ALL the values are changed
for (int j = 0; j < size; ++j)
a[j] = -a[j] - 1;
}
I have got an assignment and i'll be glad if you can help me with one question
in this assignment, i have a question that goes like this:
write a function that receives an array and it's length.
the purpose of the function is to check if the array has all numbers from 0 to length-1, if it does the function will return 1 or 0 otherwise.The function can go through the array only one.
you cant sort the array or use a counting array in the function
i wrote the function that calculate the sum and the product of the array's values and indexes
int All_Num_Check(int *arr, int n)
{
int i, index_sum = 0, arr_sum = 0, index_multi = 1, arr_multi = 1;
for (i = 0; i < n; i++)
{
if (i != 0)
index_multi *= i;
if (arr[i] != 0)
arr_multi *= arr[i];
index_sum += i;
arr_sum += arr[i];
}
if ((index_sum == arr_sum) && (index_multi == arr_multi))
return 1;
return 0;
}
i.e: length = 5, arr={0,3,4,2,1} - that's a proper array
length = 5 , arr={0,3,3,4,2} - that's not proper array
unfortunately, this function doesnt work properly in all different cases of number variations.
i.e: length = 5 , {1,2,2,2,3}
thank you your help.
Checking the sum and product is not enough, as your counter-example demonstrates.
A simple solution would be to just sort the array and then check that at every position i, a[i] == i.
Edit: The original question was edited such that sorting is also prohibited. Assuming all the numbers are positive, the following solution "marks" numbers in the required range by negating the corresponding index.
If any array cell already contains a marked number, it means we have a duplicate.
int All_Num_Check(int *arr, int n) {
int i, j;
for (i = 0; i < n; i++) {
j = abs(arr[i]);
if ((j >= n) || (arr[j] < 0)) return 0;
arr[j] = -arr[j];
}
return 1;
}
I thought for a while, and then i realized that it is a highly contrained problem.
Things that are not allowed:
Use of counting array.
Use of sorting.
Use of more than one pass to the original array.
Hence, i came up with this approach of using XOR operation to determine the results.
a ^ a = 0
a^b^c = a^c^b.
Try this:
int main(int argc, char const *argv[])
{
int arr[5], i, n , temp = 0;
for(i=0;i<n; i++){
if( i == 0){
temp = arr[i]^i;
}
else{
temp = temp^(i^arr[i]);
}
}
if(temp == 0){
return 1;
}
else{
return 0;
}
}
To satisfy the condition mentioned in the problem, every number has to occour excatly once.
Now, as the number lies in the range [0,.. n-1], the looping variable will also have the same possible range.
Variable temp , is originally set to 0.
Now, if all the numbers appear in this way, then each number will appear excatly twice.
And XORing the same number twice results in 0.
So, if in the end, when the whole array is traversed and a zero is obtained, this means that the array contains all the numbers excatly once.
Otherwise, multiple copies of a number is present, hence, this won't evaluate to 0.
I have an array of integers and I'm trying to find which one is the highest and set a new integer to the highest ones value. I'm very new to C, I literally just started learning it.
There is probably some kind of logical problem with what I'm doing but I haven't been able to spot it yet. so...
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > my_array[i++]) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
else {
if (my_array[i++] > highest_int) {
highest_int = my_array[i++]
}
}
}
So I loop through my array 4 times (4 elements) and I look at the iteration value and the next one and if the iteration value is highest I check it's also higher than the current value of the current 'highest integer' and if it is I set the current highest integer to the new highest value. If the value after the iteration value is higher I do the same thing but with that value instead.
That's what went through my head when I wrote this but when I enter 4 values it always comes out with the 3rd value in the array. No matter what I set those values to.
Can anyone tell me why?
Thanks a lot.
Why you are incrementing i inside the loop? Why do you need the else part?
Here's a simple way:
int my_array[4];
int highest_int = my_array[0];
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
You're making this way more complicated than it really is :) Furthermore, you're writing i++ in too many places; each time i++ gets executed you're skipping over an array entry, which is probably not what you want.
Also, there's no need to compare to the previous value. Just compare to the highest one you've seen so far.
Here's a fixed version, just by deleting code, nothing changed or added:
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
Note that this incorrectly reports 0 if all numbers in the array are negative. Start off highest_int = INT_MIN in case you need to handle those correctly, or use unsigned int.
If you are trying to find the highest number, here is the code:
int my_array[4];
int highest_int = my_array[0];
//Before entering the loop, assuming the first number to highest
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) { //Compare every number with highest number
highest_int = my_array[i];
}
}
//Now we have the highest number
printf("Highest Number: %d",highest_int);
I am trying to solve this problem:
In an integer array all numbers occur exactly twice, except for a single number which occurs exactly once.
A simple solution is to sort the array and then test for non repetition. But I am looking for better solution that has time complexity of O(n).
You can use "xor" operation on the entire array. Each pair of numbers will cancel each other, leaving you with the sought value.
int get_orphan(int const * a, int len)
{
int value = 0;
for (int i = 0; i < len; ++i)
value ^= a[i];
// `value` now contains the number that occurred odd number of times.
// Retrieve its index in the array.
for (int i = 0; i < len; ++i)
{
if (a[i] == value)
return i;
}
return -1;
}