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
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 debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am writing a program that calculates the winner of an election using the Tideman electorial system.
I have defined a struct called pair, in which two candidates are compared. The index of the candidate with the most votes is represented by winner and the candidate with the least votes by loser.
// Each pair has a winner, loser
typedef struct
{
int winner;
int loser;
}
pair;
these pairs are stored in a pairs array
pair pairs[MAX * (MAX - 1) / 2];
I am trying to sort this pairs array in decreasing order of strength of victory (defined as vote count for winner minus vote count for loser).
candidates are indexed into vote_count via their candidate index and the elements return their vote count. MAX pertains to the maximum number of candidates.
int vote_count[MAX]; // where i is the index of the candidate and the return value is the number of votes.
Here is my implementation of a selection sort:
int max_idx; // index of element with the highest strength of victory
// one by one move boundary of unsorterd subarray
for (int i = 0; i < array_size - 1; i++)
{
max_idx = i;
for (int j = i + 1; j < array_size; j++)
{
if (vote_count[pairs[j].winner] - vote_count[pairs[j].loser] > vote_count[pairs[i].winner] - vote_count[pairs[i].loser])
{
max_idx = j;
}
}
if (max_idx != i)
{
// swap the element with the highest strength of victory with the first element
swap(&pairs[max_idx], &pairs[i]);
}
}
return;
And here is my implementation of bubble sort:
for (int i = 0; i < array_size-1; i++)
{
for (int j = 0; j < array_size-i-1; j++)
{
if (vote_count[pairs[j].winner] - vote_count[pairs[j].loser] > vote_count[pairs[j+1].winner] - vote_count[pairs[j+1].loser])
{
swap(&pairs[j], &pairs[j+1]);
}
}
}
return;
Each call the swap function:
void swap(pair *xp, pair *yp)
{
pair temp = *xp;
*xp = *yp;
*yp = temp;
}
The vote_count array is filled during the call to another function, vote:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
// iterate through candidates
for (int i = 0; i < candidate_count; i++)
{
if (strcmp (name, candidates[i]) == 0) // if vote is for a valid candidate
{
// update rank array
ranks[rank] = i;
vote_count[i]++;
return true;
}
}
// if no candidate is found
return false;
}
Neither the selection sort or bubble sort is working for me, please let me know where i'm going wrong.
This does not exactly answer your question as asked, but you could create a comparator function and use qsort:
/* Vote count needs to be global or file static for this to work */
int vote_count[...];
...
int compare_pair(const void *p1, const void *p2)
{
int d1 = vote_count[((const pair *)p1)->winner] - vote_count[((const pair *)p1)->loser];
int d2 = vote_count[((const pair *)p2)->winner] - vote_count[((const pair *)p2)->loser];
return d2 - d1;
}
You could write this as a one-liner if you wanted, but it would be harder to read.
The sort then becomes
#include <stdlib.h>
...
qsort(pairs, MAX * (MAX - 1) / 2, sizeof(pair), compare_pair);
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 does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
Story: I tried to convert a c99 script to regular gcc.
Problem: The output is empty.
Expected output: 3,2,1
length is the number of elements in the array.
Update: the script is designed to sort the elements of the array in a descending order.
The code:
#include <stdio.h>
int main() {
int arr[] = { 1,2,3 };
int temp = 0;
int length = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = i + 1;
for (i < length; i++;) {
for (j < length; j++;) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int y = 0;
for (y < length; y++;) {
printf("%d ", arr[y]);
}
return 0;
}
Your syntax for for loops is the issue.
Here is the correct way to write your loops.
int i, j;
for (i = 0; i < length; ++i) // for (initialisation; test condition; operation)
{
for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of
// the outer loop. That's what makes the bubble sort work.
{
/* test and swap if needed */
}
}
for (i = 0; i < length; ++i) // note that i is reset to zero, so we can scan the array from
// a known position (the top) to bottom.
{
/* printout */
}
Your semicolon is in the wrong place, move it to the far left just inside the parentheses.
Loop syntax is:
for (intializer; break condition; iterator)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
#include <stdio.h>
void main()
{
int arrsize;
int randset;
int max;
int min;
int arr[arrsize];
int i, j;
int swap;
float mean;
printf("Input array size:\n");
scanf("%d", &arrsize);
printf("Input random set:\n");
scanf("%d", &randset);
printf("Input maximum possible value:\n");
scanf("%d", &max);
printf("Input minimum possible value:\n");
scanf("%d", &min);
// SORTING //
for (i = arrsize; i > 0; i--)
for(j = 1 ; j < i ; j++)
// Subscripted value is neither array nor pointer vector //
**if(arrsize[j-1] > arrsize[j])**
{
swap = arr[j];
arr[j] = arr[j-1];
arr[j-1] = swap;
}
for (i=0; i < arrsize; i++)
printf("%d", arr[i]);
printf("\n\n");
// MEAN //
for(i = 0 ; i < arrsize ; i ++)
{
//Subscripted value is neither array nor pointer vector //
**mean += arrsize[i];**
mean/= arrsize;
printf("The mean is %.2lf\n\n", mean);
}
// MEDIAN //
if(arrsize%2 == 0)
{
printf("The median is %.2lf", (float)(arr[arrsize/2 -1] + arr[arrsize/2]);
}
else
{
printf("The median is %d", arr [arrsize/2]);
printf("\n\n\n");
}
printf("The midrange is %.2lf\n\n", (float)(arr[0] + arr[arrsize - 1] / 2);
}
void fillintarray(int myarray [], int arrsize, int min, int max, unsigned int randset)
{
int iter;
srand (randset);
for (iter =0 ; iter < arrsize ; iter++)
{
myarray[iter] = rand() % (max - min + 1) + min;
}
}
Hi there! I put the lines where there were errors in bold, and the error was
"Subscripted value is neither array nor pointer vector"
This is an exercise for my ComSci class :) Help would be much appreciated! Thanks! :)
Well, the error message is pretty descriptive - you accessing a scalar variable int arrsize with subscript operator [] which could only be applied to array or pointer type.
You probably want to check j-1-th and j-th array elements, you should use
if (arr[j-1] > arr[j])
You're confusing between the array(arr) and its size(arrsize).
If you don't know the size of array , use malloc .
Use int *array = malloc(arraysize * sizeof(int));instead of int array[arraysize];
And put it afterscanf("%d",&arraysize);
And you also need init the array before use it.