Inserting values into array while searching another array in C? - c

i'm a beginner in c, i have attempted to insert a value into an array as i scan another array for a value higher than a threshold, if a value is over the set threshold in the array being searched then insert a number into the other array...
for (i = 0; i<lines[i][1]; i++) {
if (lines[i][1] > 6500) {
array[];
}
so what i mean is, if there is a value in lines[i][1] higher than 6500, then insert number "1" into array[].
However, with previous attempts it just overwrites the array rather than stacks on top of previous values.. i have another for loop attempting to do the same thing while searching another array.
for (i = 0; i<lines[i][0]; i++) {
if (lines[i][0] > 6500) {
array[];
}
The ideal output would be something like: 1 for values higher than in lines[i][0] and 2 for values higher than in lines[i][1], "array[] = {1,1,1,2,2,2,2,1,1,1,};"
and the values are inserted into the array as arrays are being scanned.
Please help... thank you

Just start a counter to keep track of the position where you last inserted the item on the destination array. For example:
int destPosition=0;
for (i = 0; i<lines[i][0]; i++) {
if (lines[i][0] > 6500) {
array[destPosition]=1;
destPosition++;
}
}

Related

developing a function that returns number of distinct values that exist in array

I want to create a function that can return the number distinct values present in a given array. If for eg the array is
array[5] = { 1 3 4 1 3}, the return value should be 3(3 unique numbers in array).
I've so far only got this:
int NewFucntion(int values[], int numValues){
for (i=0; i<numValues; i++){
Im a new coder/New to C language and im stuck on how to proceed. Any guidance would be much appreciated. Thanks
Add elements from the array to the std::set<T> and since the set is not allowing duplicate elements, you can then only get the number of elements from the set which gives you the number of distinct elements.
For example:
#include<set>
int NewFucntion(int values[], int numValues){
std::set<int> set;
for(int i=0; i<numValues; i++){
set.insert(values[i]);
}
return set.size();
}
int distinct(int arr[], int arr_size){
int count = arr_size;
int current;
int i, j;
for (i = 0; i < arr_size; i++){
current = arr[i];
for (j = i+1; j < arr_size; j++) // checks values after [i]th element.
if (current == arr[j])
--count; // decrease count by 1;
}
if (count >= 0)
return count;
else return 0;
}
Here's the explanation.
The array with its size is passed as an argument.
current stores the element to compare others with.
count is the number that we need finally.
count is assigned the value of size of the array (i.e we assume that all elements are unique).
(It can also be the other way round)
A for loop starts, and the first (0th) element is compared with the elements after it.
If the element reoccurs, i.e. if (current==arr[j]), then the value of count is decremented by 1 (since we expected all elements to be unique, and because it is not unique, the number of unique values is now one less than what it was initially. Hence --count).
The loops go on, and the value is decremented to whatever the number of unique elements is.
In case our array is {1,1,1,1}, then the code will print 0 instead of a negative value.
Hope that helps.
Happy coding. :)
I like wdc's answer, but I am going to give an alternative using only arrays and ints as you seam to be coding in c and wdc's answer is a c++ answer:
To do this thing, what you need to do is to go through your array as you did, and store the new numbers you go over in a different array lets call it repArray where there wont be any repetition; So every time you add something to this array you should check if the number isn't already there.
You need to create it and give it a size so why not numValues as it cannot get any longer than that. And an integers specifying how many of it's indexes are valid, in other words how many you have written to let's say validIndexes. So every time you add a NEW element to repArray you need to increment validIndexes.
In the end validIndexes will be your result.

Printing Array Items by Index Number in ImageJ (Fiji)

I'm trying to figure out how I can access an item in an array by it's index number. I've written a script which will generate an array, with some number of variables. There's an old script on the imageJ mailing list archive (shown below) which is able to print given index value for a known value within the array, but is there a way to find the value within the array itself? I.e. if I have the user input the number of values that should be in the array, can I have the macro call up the values in the array from that?
My array generator:
Dialog.create("Time Point Input");
Dialog.addNumber("How many time points?", 0)
Dialog.addString("What are your time points (comma separated, no spaces)?:",0);
Dialog.show();
time = Dialog.getNumber();
points = Dialog.getString();
Fpoints = newArray(points);
Where the readouts could be something like:
time = 4
points = 5,10,12,27
Fpoints[0] = 5
Fpoints [1] = 10
Fpoints [2] = 12
Fpoints [3] = 27
Calling up index from array number value example code:
arr = newArray(1,5,3,12);
i = index(arr, 5);
print("index = "+i);
function index(a, value) {
for (i=0; i<a.length; i++)
if (a[i]==value) return i;
return -1;
}
Thank you!
I am not 100% sure if I get your question right.
but is there a way to find the value within the array itself?
The problem is that you cannot create an Array with points since it's a String.
Try something linke:
Fpoints = split(points, ',');
Then you can iterate over Fpoints with a loop, or use you index function to get an index of a given value.
for (i = 0; i < Fpoints.length; i++) {
print(Fpoints[i]);
}

C Duplicates in array

So lets say i have an array of ints (max being its maximum size)
array = { 1, 7, 22, 3, 7, ... }
and i need to find a way to count the duplicates of each element in the previous array into another array like this one
duplicates = { { 1, 2 times }, { 7, 3 times } ...}
i know the syntax is wrong i just wanted to exemplify my goal (hope i expressed myself well enough) .. i have been thinking and i cant think of a way to do this (maybe it's simple but im kinda new at this) so i decided to post here for some guidance.
Thanks in advance
You could sort the array, maybe with an algorithm like qsort and then with a for or a while loop you can count how many times each element appear into the array since the duplicates will be one after another.
If you're under mac/linux type in the terminal man 3 qsort to see how it should be used.
If memory wasting does not cause any trouble in your case:
Define a struct
struct DuplicationInfo{
int number;
int times;
}
Then you can do a loop as follow
DuplicationInfo[max] duplicates;
// Initialze the array
for(int i=0; i < max; i++)
{
duplicates[i].times= 0;
duplicates[i].number = -1; // Any invalid number which you know is not in your array
}
for(int i = 0; i < max; i++){
// Look if the number is still in our duplicates list
for(int j=0; j<max;j++){
if(duplicates[j].number == array[i])
{
duplicates[j].times++;
break;
}
else if(duplicates[j].number == -1)
{
duplicates[j].times= 1;
duplicates[j].number = array[i];
break;
}
}
}
You could either sort the array in order to have the duplicates of a number just after the number and count them with a wile or you could use a structure with a number and frequency field. Each time you have to insert a new number into the array, if it is already into the array you just increase by one the frequency field.

Array in JAVA., repeat?

I'm writing a function using java language that takes in a 1D array and the size of the array as inputs to the function. I want to find out how many function values of are in the array. How would I do this?
Approach 1(O(nlogn)):
Sort the array.
Compare the adjacent elements in array
Increment the count whenever the adjacent elements are unequal. Please take care of three consecutive same elements using an extra variable.
Approach 2(O(n) but space complexity of O(n)):
Create a Hash Table for value.
Insert a value if not present in the hash table.
Count and print the values for present in hashtable
#Find unique items from array:
1. Create one new array
2. Take each item from existing array
3. Check if the item is exist in new array
4. **If not exist push the item into new array** else go for next item
5. After iterating all item in array get the length of new array
#include <stdio.h>
int main ()
{
int n[10] = {1,2,5,5,3,4,1,4,5,11};
int count = 0; int i = 0;
for (i=0; i< 10; i++)
{
int j;
for (j=0; j<i; j++)
if (n[i] == n[j])
break;
if (i == j)
count += 1;
}
printf("The counts are: %d distinct elements", count);
return 0;
}

Test for first empty value of array

Is there anyway to test for the first empty value of a 2 dimensional int array in c?
In my current program, I used 2 for loops before the main program(while loop) to set all the values of my 2 dimensional array to -9999. Then inside my main while loop, I test for the first -9999 value and set it to a value, and then use break to exit from it.
Using this I managed to do my assignment, but I'm not very satisfied, as I think there might be a better solution.
Is there one?
EDIT: Code since you asked for it.
For loop outside while loop:
for(int x=0;x<ctr-1;x++)
{
for(int y=0;y<maxtrips;y++)
{
EmployeeKilos[x][y] = -9999; // Set all the kilos to -9999 to signify emptiness.
}
}
Inside my main while loop:
for(int x=0;x<ctr-1;x++) // and set it to the log kilometers
{
if(employeenames[x].EmployeeNumber == log.Record)
{
for(int y=0;y<maxtrips;y++)
{
if(EmployeeKilos[x][y] == -9999)
{
EmployeeKilos[x][y] = log.Kilometers;
break;
}
}
}
}
All my code: http://pastebin.com/Zb60mym8
As Dave said, checking for empty values cannot be made more efficient than linear time (O(n)), but my answer focuses on a solution that can prevent having to look for it in the first place.
In general you could iterate the matrix in row-major or column-major mode.
Effectively, you can use a single index that translates to a matrix cell like so
for (size_t i=0; i<ROWS*COLS; ++i)
{
int row = i / ROWS;
int col = i % ROWS;
// work with matrix[row][col]
}
This way you could just store and remember the value of i where you last found the first empty cell, so you don't have to restart from the beginning.
If you're not actually interested in row/col addressing, you could forget about those and just use an output iterator to track your current output location.
Here's a demo using 'iterator' style (borrowing from c++ but perfectly C99)
typedef int data;
typedef data* output;
output add_next(data matrix[ROWS][COLS], output startpoint, data somevalue)
{
if (output < (matrix + ROWS*COLS))
*(output++) = somevalue;
return output;
}
Now you can just say:
add_next(matrix, 42);
add_next(matrix, 9);
NOTE the output iterator thing assumes contiguous storage and therefore cannot be used with so-called jagged arrays
HTH
You can use memset to initialise arrays to a fixed value - it's a bit more efficient and cleaner looking than iterating over the array.
Checking for your 'empty' value can't be done much faster than you are doing it, though. :)
This sounds like you should think about your datatype. Since you are already using structs. why don't you add another int for the last unassigned value so you just loop to it. something like
e.g:
struct t_EmployeeKilos{
int kilos[maxtrips];
int nlast;
} EmployeeKilos[N];
and set nlast whenever you assign a new element in kilos. This way it is O(1).
for(int x=0;x<ctr-1;x++) //
{
if(employeenames[x].EmployeeNumber == log.Record)
{
EmployeeKilos[x].kilos[EmployeeKilos[x].nlast] = log.Kilometers;
EmployeeKilos[x].nlast++;
}
}

Resources