Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have two arrays and if a number is repeated in 1 array I set that corresponding location in both to a value of zero. I then want to store it in a separate array now ignoring those zeros and copying the rest. However right now if I try this it just copies the array with the zeros, any idea?
for (i = 0; i < linect; i++) //searches array sets repeated points to zero
{
if (array1[i] == array1[i+1])
{
array1[i] = array1[i + 1] = 0;
array2[i] = array2[i + 1] = 0;
}
}
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5){
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
j = 0;
while (j <300){
printf("\n%f", fixarray2[j]);
j++;
}
So when you say "if a number is repeated in 1 array" do you mean if the number in the next index is the same as the current index or if the number is repeated in the entire array? As your code is, you are only checking the next value for repetition.
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5){
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
Will only copy non-zero values into array 2 at the indices where there were non-zero values in array 1. So you're not actually removing any of the 0 values, you're just making another array fixarray2[i] that is the same as array2[i] . You need to keep a separate counter if you want to skip all the zero's from your old array.
In the loop below value is stored in fixarray only when element in array1 is not zero but its index gets incrementated even when element is zero.
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5)
{
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
In this loop index of fixarray should incrementated only when value in array1 is not zero .Something like this -
int j=0;
for(i = 0; i < linect; i++)
{
if(array1[i]>0.5)
{
fixarray1[j] = array1[i];
fixarray2[j] = array2[i];
j++;
}
}
This is will store value in fixarray only when element in array1 is not zero.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Any idea how to do it?. i'm new into programming, and for now im stuck at this exercice.
for(i = 0; i < 9;++i) {
for(j = 0; j < 9;++j) {
printf("%d ", rand()%2);
}
printf("\n");
}
return 0;
I would
Start by creating a matrix with all 0:s.
typedef unsigned char byte;
byte m[9][9] = {0};
Add the number of 1:s you want.
void fill(byte(*arr)[9][9], unsigned count, byte value) {
for(unsigned idx = 0; idx < count; ++idx) {
(*arr)[idx / 9][idx % 9] = value;
}
}
int rnd(int min, int max) {
return rand() % (max - min + 1) + min;
}
// ...
fill(&m, rnd(5, 10), 1); // this will fill it with 5 to 10 1:s
// fill(&m, 10, 1); // alternative if you want exactly 10 1:s
Shuffle the result.
void swap(byte *a, byte *b) {
byte tmp = *a;
*a = *b;
*b = tmp;
}
void shuffle(byte(*arr)[9][9]) {
for (unsigned idx = 9*9 - 1; idx > 0; --idx) {
unsigned swno = rnd(0, idx);
swap(&((*arr)[idx / 9][idx % 9]),
&((*arr)[swno / 9][swno % 9]));
}
}
// ...
shuffle(&m);
This should result in an equal probability for each possible permutation to appear.
Demo
Another option that perhaps is easier to visualize could be to create a basket containing tickets with all the possible positions in the matrix written on them. Then randomly pick tickets from this basket.
Start by creating a matrix with all 0:s just like in the first example.
Create an array with all the positions in your matrix. This is the "basket" mentioned above. You have a 9 x 9 matrix so that's just an array with the numbers 0 to 80. I'll call the basket picklist below.
unsigned picklist[9*9];
for(unsigned idx = 0; idx < 9*9; ++idx) {
picklist[idx] = idx; // fill picklist with the values [0,80]
}
Iteratively and randomly select which position in the above picklist you should choose from, while removing the picked positions from the list and leaving only the non-picked position in it.
for(unsigned co = 1; co <= count; ++co) {
unsigned lastidx = 9*9 - co; // the last non-picked position
// here you put your hand in the basket to draw a ticket:
unsigned pickidx = rnd(0, lastidx); // randomly chosen index in the picklist
// and this is what was written on the ticket:
unsigned chosenidx = picklist[pickidx]; // the position gotten from the picklist
// Assign value to the chosen position
(*arr)[chosenidx / 9][chosenidx % 9] = value;
// Put the last non-picked position in the picklist where the position we just
// used was, leaving only non-picked positions in the lower part of picklist.
// This is equivalent to throwing the chosen ticket away.
picklist[pickidx] = picklist[lastidx];
}
This approach should also assure that all permutations have an equal chance of appearing in the final matrix. It doesn't require that you shuffle the matrix afterwards since every position you pick from the basket will be unique and random.
Demo
This will not result in perfect distribution but should be good enough for a start:
int ones_placed = 0;
// pick one of the following 2 lines. Not both!
int ones_to_place = rand()%11; // for up to 10 entries
int ones_to_place = 10; // for exactly 10 entries
while (ones_placed < ones_to_place)
{
// Get random position for the next 1;
int row = rand() % 9;
int col = rand() % 9;
// Don't count same cell twice but skip instead.
if (arr[row][col] == 0)
{
arr[row][col] = 1;
ones_placed ++;
}
}
int crt_ones = 0
for(i = 0; i < 9;++i) {
for(j = 0; j < 9;++j) {
rand_no = rand() % 2;
if (crt_ones < 9 && rand_no == 1) {
a[i][j] = rand_no;
crt_ones++;
} else a[i][j] = 0;
printf("%d ", rand()%2);
}
printf("\n");
}
return 0;
The idea is to initialise your matrix and to keep track in a variable (crt_ones in out case) how many random one's have I generated so far.
As it is an excercise, I am not writing you the code, but instead giving a hint:
Initialize the matrix all to 0. Initialize a counter to 0.
Randomly select an index into the matrix.
Check if it is 0, write 1 and increment a counter. If it is 1 skip to the next.
Repeat from 2. until the counter is 10
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
for (i = 1 ; i < SIZE; i++) {
j = k;
while (j > 0 && arr[j] != arr[i])
j = j - 1;
if( j == 0){
k = k + 1;
arr[k] = arr[i];
}
else
n--;
}
}
This function was in my test today.
My question is: does someone know what it does?
What does the variable n represent at the end of the function?
At the end of the function, the variable n will have counted how many times each i-th array value in the range [0, SIZE) was unique among the first i array elements..
In addition, the first n elements of the array will contain exactly those elements that were found to be unique in the above sense. All other array entries will remain unchanged.
The other variables will have the following values:
i == SIZE
j == some value between [0, SIZE)
k == n-1
Some inline comments may help understand the code better.
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
// walk through the array up until its 10th element, skipping
// the first entry and hoping that the array actually contains
// at least 10 entries
for (i = 1 ; i < SIZE; i++) {
// similar to i, the variable k also walks up towards 10.
// However it starts at 0, not at 1, and it does not
// necessarily get incremented in every loop iteration. More
// on that below.
// Here, we set the variable j to start out as the same value
// as the current k, but j will walk the opposite direction, i.e.,
// toward 0, not toward 10.
j = k;
// find the largest j in the open interval [0,k) for which
// the array entry arr[j] differs from the current arr[i]
while (j > 0 && arr[j] != arr[i])
j = j - 1;
// if no value in [0, k) was equal to arr[i], we'll end up \
// with j == 0
if( j == 0){
// then we increment k -- that is, k counts how many times
// we encountered a value arr[i] during the for-loop that was
// unique among the first i array entries. But since the
// for loop starts at 1 instead of 0, k will count one
// element too few.
k = k + 1;
// well, so much for 'unique': here, we actually copy the current
// value arr[i] into arr[k]
arr[k] = arr[i];
}
else
// this part in effect assures that the expression
// (n-k) gets decremented in every iteration of the loop,
// no matter if j == 0 is true or false.
// Since we start out with (n-k) = SIZE, and
// the loop body gets executed SIZE-1 times, (n-k) will
// be equal to 1 after the for-loop has terminated.
n--;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to find the index of largest element in a given array in C .
I have tried insertion sort algorithm to determine the largest number in array after that I compared largest value with my all previous array's element and It did not work.
void insertion_array(float array[], int n) //* insertion algorithm*//
{
int i = 1, j;
float x;
for (; i < n; i++) {
x = array[i];
j = i - 1;
while ((j >= 0) && (array[j] > x)) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
uint8_t Largest_Number_Finder(float arr[], uint8_t n) {
uint8_t index;
insertion_array(arr, n);
for (int i = 0; i < n; i++) {
if (arr[i] > arr[n - 1]) {
index = i;
}
}
return index;
}
I expected to take largest number index but Algorithm gives always last elements index. What should I do to make it right?
Edit=What you navigated as duplicate was to find largest element. I am aiming to find the index of largest element in array.
As "Some programmer dude" mentioned in the comment, if your purpose is to just find the index of the largest value, you don't need to implement insertion or any other algorithm to sort the array.
You can probably make a function like this.
int find_max_value(float array[], int length)
{
// set the value of index 0 as the "current max value"
float max_value = array[0];
// the same goes for the index number
int max_index = 0;
// go through the array
for(int i = 1; i < length; i++)
{
// if the next index's value is greater than the "current max value"
// update the max_value and max_index
if(array[i] > max_value)
{
max_value = array[i];
max_index = i;
}
}
return max_index;
}
and try calling that find_max_value() function with whatever input values, like
int result = find_max_value(array1, 10); // just an example supposing that you have declared an array called "array1" and its length is 10
printf("%d", result); // see what the return value of the find_max_value() function would be
The aim of my C program is to take two arrays (both comprised of unique numbers) and merge the two of them into a new array, eliminating any numbers that are the same between both of them. However, when I try to merge the two, it instead prints back both arrays combined without eliminating any duplicates.
My program creates "array_C" by first adding in the elements from "array_A". Afterwards, it checks if there are duplicates between "array_B" and "array_C" using a counter variable. For every value in "array_C" that the for loop checks, if the value of "array_B" is not equal to the value in "array_C", the counter decreases by 1. If after all the values in "array_C" are checked, the counter is <= 0, that means there are no duplicates of that value in "array_C", and it should be added to the end of "array_C". I keep track of this using a "position" variable.
//Creation of array_C
int length_C = length_A + length_B;
int array_C[length_C];
//Copying array_A to array_C
for (i = 0; i < length_A; i++) {
array_C[i] = array_A[i];
}
//Checking array_C against array_B for duplicates
counter = length_A;
int position = length_A;
for (i = 0; i < length_B; i++) {
for (j = 0; j < length_C; j++) {
if (array_B[i] != array_C[j]) {
counter--;
} else {
counter++;
}
}
//this is the position tracker to add new value in array_C
if (counter <= 0) {
array_C[position] = array_B[i];
position++;
}
}
If I entered this:
Enter the length of array 1: 6
Enter the elements of the array: 1 2 3 4 5 6
Enter the length of array 2: 6
Enter the elements of the array: 3 4 5 6 7 8
I expect the results should look like this:
Here is the merged array:
1 2 3 4 5 6 7 8
But instead, it looks like this:
1 2 3 4 5 6 3 4 5 6 7 8
So apparently something is going wrong and it is not understanding that it should only add variables that are not duplicates.
Your logic is flawed. That's why you are getting unexpected outcome. See the following revision in your code:
for (i = 0; i < length_B; i++) {
int skip = 0;
for (j = 0; j < length_C; j++) {
if (array_B[i] == array_C[j]) {
skip=1;
break;
}
}
if(skip == 1) continue;
array_C[position++] = array_B[i];
}
the problem is with the logic inside your inner for loop. according to the problem statement if any value of array_c matches with any value of array_b you should get rid of that value otherwise add the value to array_c. so you can simply try doing the following. please make sure you understand the code. if you have any question feel free to ask.
for (i = 0; i < length_B; i++) {
bool isExistInArrayC = false;
for (j = 0; j < length_C; j++) {
if (array_B[i] == array_C[j]) {
isExistInArrayC = true;
break;
}
}
//this is the position tracker to add new value in array_C
if (isExistInArrayC == false) {
array_C[position] = array_B[i];
position++;
}
}
The suggestions will certainly work, but performance (especially with large size arrays) will be very poor. I would maintain a sorted array "C" and do a binary search into it when adding integers from array B.
You'll need a double-linked list for array C of course.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
All I want to know is whether this statement is feasible or not
for(j = 2; (j <= i) && flag; j++)
flag is initialized to i before this loop. I have not seen any such thing before.
The general for loop condition is like this:-
for(initialization ; condition; increment)
So what you are doing is correct.
Breaking down your for loop means:-
for(j=2;(j<=i)&& flag ;j++)
initialization is j=2;
condition is (j<=i)&& flag ;
increment is j++
One example:-
int main(int argc, const char * argv[])
{
int sum = 0;
int j = 100;
for(int i = 1; i<=100/2 && j>100/2; i++){
sum += i+j;
j--;
}
return sum;
}
Second Example with flag:
Remember bubble sort, In bubble sort we need two nested loops, outer loop runs for number of passes and inner loop do swapping task for each pair a[i], a[i + 1]. To save execution we can make use of some flag variable. If in some pass no swapping done this means no need to execute next pass and sorting completeed, read: Optimizing bubble sort:
Now code for this:
FLAG = 1;
for(i = 0; FLAG && (i < n - 1); i++){//If flag = ), break outer loop sorting done
FLAG = 0; // set flag = 0
for(j = 0; j < n - 1 - i; j++){
if(arr[j] > arr[j + 1]){
swap(arr[j], arr[j + 1]);
FLAG = 1; // if any swapping need, then check in next round
}
}
}
Notice outer loop condition FLAG && (i < n - 1), I think this is what you wants. Hope this help!