I am trying to find top 6 elements from an array with their ordering number.
int x=0;
for (int k = 0; k < 6; k++) //
{
for (i = 1; i <= 90; i++)
{
if (sorted[k] < holder[i] && i >= x)
{
sorted[k] = holder[i];
x = i; //
}
}
}
But this does not work. I want it to give me output like 43->7 15 ->3 etc..
Haven't written C in a while, but here is a simple solution that modifies the array in place and uses selection sort to select the k highest numbers in the array and moves them to the front. It keeps an array of indices that correspond to where the number originally was and applies the same swaps to it.
#include <stdio.h>
#define ELEMENTS 10
void main(void)
{
// example input for execution
int numbers[10] = {9,4,5,1,8,2,3,6,0,7};
// tracks ordering of indices
int indexes[10] = {0,1,2,3,4,5,6,7,8,9};
int k = 6;
int i, j;
int max, temp;
// Partial selection sort, move k max elements to front
for (i = 0; i < k; i++)
{
max = i;
// Find next max index
for (j = i+1; j < ELEMENTS; j++)
{
if (numbers[j] > numbers[max]) {
max = j;
}
}
// Swap numbers in input array
temp = numbers[i];
numbers[i] = numbers[max];
numbers[max] = temp;
// Swap indexes in tracking array
temp = indexes[i];
indexes[i] = indexes[max];
indexes[max] = temp;
}
for (i = 0; i < k; i++) {
printf("%d -> %d\n", indexes[i], numbers[i]);
}
}
And the output:
0 -> 9
4 -> 8
9 -> 7
7 -> 6
2 -> 5
1 -> 4
Here's the answer I have for you.
I would love some constructive criticism on it from anyone who can provide some.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numbers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *ptrNumbers[10];
int i=0;
for(; i < 10; i++){
ptrNumbers[i] = &numbers[i]; // assign the addresses
}
int topSix[6];
int topSixIndex=0;
for(; topSixIndex < 6; topSixIndex++){
int **best = NULL; // Pointer to the pointer to the value.
int checkIndex=0;
for(; checkIndex < 10; checkIndex++){
if(ptrNumbers[checkIndex] != NULL){
if(!best){
/* best is not yet defined */
best = &ptrNumbers[checkIndex];
// best now points to the pointer for numbers[checkIndex]
}else if(*ptrNumbers[checkIndex] > **best){
// this else if statement could be attached to the main if as
// an or condition, but I've separated it for readability.
best = &ptrNumbers[checkIndex];
// best now points to the pointer for numbers[checkIndex]
}
}
}
// assign the topSix position and flag the ptrNumbers
topSix[topSixIndex] = **best;
*best = NULL;
}
// now we'll print the numbers
for(topSixIndex = 0; topSixIndex < 6; topSixIndex++){
printf("%d\n", topSix[topSixIndex]);
}
return 0;
}
Essentially the program works like this: Given an array of ten numbers, a second array is constructed to house pointers to those 10 numbers. A third array is then constructed to house the values of the top 6 numbers. A for loop is then initialized to loop 6 times to find the highest unrecorded value. When the highest value is found by looping the pointer array, the value is assigned to the next index of the top six array. Once that value is added, the pointer array's index that points to the top six value is then assigned to NULL. This acts as a flag insuring that the value will not be added again. Finally, all numbers are printed out.
After running this code, the output I received was:
9
8
7
6
5
4
Edit: as a note, the ordering number's can be stored in a second array. You would simply need to track the checkIndex of the highest value and then assign it to a second array which contained the index values.
maybe you aren't looking for a code-only answer, but this will work:
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// return index of max element
int max_index( int* vec, int sz )
{
int idx, max, i;
if(!sz) return -1;
idx = 0;
max = vec[0];
for(i=1; i<sz; ++i)
{
if( vec[i] > max )
{
max = vec[i];
idx = i;
}
}
return idx;
}
// return indexes of N top elements
void top( int* vec, int sz, int* out_vec, int N )
{
int i, *tmp, idx;
tmp = (int*) malloc( sz*sizeof(int) );
memcpy( tmp, vec, sz*sizeof(int) );
for(i=0; i<N; ++i )
{
idx = max_index(tmp,sz);
out_vec[i]=idx;
tmp[idx] = INT_MIN;
}
free(tmp);
}
see it live here
Make an array of struct that contain data and index, then sort it and pick up first or last 6 elements to output.
Say that you are given an array numbers. Then create an array indexes with the same size as numbers in such a way that its values are equal to their indexes. Here is an illustration:
numbers = [ 1, 7, 3, 9, 2, 0 ]
indexes = [ 0, 1, 2, 3, 4, 5 ]
Sort numbers in descending order, performing the same operations on indexes. In the end, you should end up with something like this:
numbers = [ 9, 7, 3, 2, 1, 0 ]
indexes = [ 3, 1, 2, 4, 0, 5 ]
Finally, all you need to do is work with the first six elements of these arrays.
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int contains(int array[], int array_size, int value)
{
int i;
for (i = 0; i < array_size; i++)
{
if (array[i] == value)
{
return TRUE;
}
}
return FALSE;
}
int main()
{
int numbers[] = { 1, 7, 3, 9, 2, 0 };
int indexes[] = { 0, 1, 2, 3, 4, 5 };
int numbers_size = 6;
int largest[] = { -1, -1, -1, -1, -1, -1 };
int largest_index = 0;
int i;
for (i = 0; i < 6; i++)
{
int j;
int max_index = -1;
int max = -2147483648;
for (j = 0; j < numbers_size; j++)
{
if (numbers[j] >= max && contains(largest, numbers_size, j) == FALSE)
{
max_index = j;
max = numbers[max_index];
}
}
largest[largest_index++] = max_index;
}
for (i = 0; i < 6; ++i)
{
printf("%d->%d\n", largest[i], numbers[largest[i]]);
}
return 0;
}
You probably should use bubblesort (and keep a function holding all the original indexes) and then just make it show the 6 first number of both arrays (from the indexes array and from the array you sorted itself)
Related
Given an array of n integers, not necessarily sorted, is there an O(n) algorithm to find the least integer that is greater than the minimum integer in the array but that is not in the array?
The following algorithm has a complexity O(n).
I will assume here that the missing element must be selected after the minimum value.
The algorithm can be easily modified if the minimum possible value is fixed, for example equal to 0.
Once we have determined the minimum value a (in O(n) or in O(1) if the value is known in advance),
then we know that the missing value is less or equal a + n, if n is the array size.
Then we simply have to use an array of size n+1, present[n+1], initialised to 0,
and then to look at all values arr[i]:
if (arr[i] <= a+n) present[arr[i] - a] = 1;
Finally, in a third step we simply have to examine the array present[.], and seach for the first index k such that present[k]==0.
The first missing number is equal to a + k.
#include <stdio.h>
#include <stdlib.h>
int find_missing (int *arr, int n) {
int vmin = arr[0];
int *present = calloc (n+1, sizeof(int));
for (int i = 1; i < n; ++i) {
if (arr[i] < vmin) {
vmin = arr[i];
}
}
int vmax = vmin + n;
for (int i = 0; i < n; ++i) {
if (arr[i] <= vmax) {
present[arr[i] - vmin] = 1;
}
}
int k = 0;
for (k = 0; k <= n; ++k) {
if (present[k] == 0) break;
}
free(present);
return vmin + k;
}
int main() {
int arr[] = {2, 3, 5, 6, 8};
int n = sizeof(arr)/sizeof(arr[0]);
int missing = find_missing (arr, n);
printf ("First missing element = %d\n", missing);
return 0;
}
Given an array of n integers, without negative numbers, not
necessarily sorted, is there an O(n) algorithm to find the least
integer that is greater than the minimum integer in the array but that
is not in the array?
This can be solved with O(N) time complexity, with N being the number of element in the array. Let us call that array a1, the algorithm is as follows:
Find the smallest value in a1 (i.e, min);
Create a new array a2 with size equals to N;
Initialized the array a2 with a value to signal missing element, for instance min - 1;
Iterate through the array a1, and for each position, take the element in that position e1 = a1[i], and only if e1 is not greater than min - N mark the corresponded position on a2 as visited, for instance using the element itself, namely a2[e1 - min] = e1; If e1 is greater than min - size then it clearly does not belong to the sequence, and can be ignored because in the worst-case scenario the first missing value will be the value min + N + 1.
Lastly, iterate through the array a2, and get the first element = -1; it will be your first missing element.
Steps 1, 3, 4, and 5, all of them take in the worst-case scenario N. Hence, this algorithm takes 4N, which is O(N) time complexity;
The code will be straight forward to implement; for instance something as follows (for an array {5, 3, 0, 1, 2, 6}):
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
int find_min(int *array, int size){
int min = array[0];
for(int i = 0; i < size; i++)
min = (array[i] < min) ? array[i] : min;
return min;
}
void fill_array(int *array, int size, int missing_value){
for(int i = 0; i < size; i++)
array[i] = missing_value;
}
void mark_existing_values(int *s, int size, int *d, int min){
for(int i = 0; i < size; i++){
int elem = s[i];
if(elem - min < size)
d[elem - min] = elem;
}
}
int find_first_missing_value(int *array, int size, int min){
int missing_value = min - 1;
for(int i = 0; i < size; i++){
if(array[i] == missing_value){
return i + min;
}
}
return missing_value;
}
int main(){
int array_size = 6;
int array_example [] = {5, 3, 0, 1, 2, 6};
int min = find_min(array_example, array_size);
int *missing_values = malloc(array_size * sizeof(int));
fill_array(missing_values, array_size, min - 1);
mark_existing_values(array_example, array_size, missing_values, min);
int value = find_first_missing_value(missing_values, array_size, min);
printf("First missing value {%d}\n", value);
free(missing_values);
return 0;
}
OUTPUT:
First missing value {4}
This algorithm works also for negative numbers, for instance if int array_example [] = {-1, -3, 0, 3, 5, 6, 7, 8, 10};, then the output would be:
First missing value {-2}
The code can be simplified if in step 3 and step 4 instead of min - 1 and a2[e1 - min] = e1, respectively, we use two flags to signal missing (e.g., 0) and existing values (e.g., 1). Just like showcase in #Damien code. The downside is that we are using two flags instead of one. The benefit is that it simplifies the code, and in case the smallest value in the array is the smallest value that can be represented in C we will not underflow with min - 1.
You can use the technique of bitwise XOR.
This method has O(n) time complexity and it is working on unsorted arrays too.
Also, keep in mind, this works only if one element is missing from the array.
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 4, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
int x = arr[0]; //XOR together all of the array elements
for (int i = 1; i < arr_size; i++)
{
x ^= arr[i];
}
int y = 1; //XOR together the numbers from 1 to size of array + 1
for (int i = 2; i <= arr_size + 1; i++)
{
y ^= i;
}
int missing = x ^ y; //The missing number is going to be the XOR of the previous two.
printf("%d", missing);
return 0;
}
How exactly is the binary hash map working here? As in, how does it initialise only binMap[elements in arr] to 1 and the rest to 0?
#include <stdio.h>
#define MAX 100000
void printPairs(int arr[], int arr_size, int sum)
{
int i, temp;
bool binMap[MAX] = {0}; /*initialize hash map as 0*/
for(i = 0; i < arr_size; i++)
{
temp = sum - arr[i];
if(temp >= 0 && binMap[temp] == 1)
{
printf("Pair with given sum %d is (%d, %d) \n", sum, arr[i], temp);
}
binMap[arr[i]] = 1;
}
}
int main()
{
int A[] = {1, 4, 45, 6, 10, 8};
int n = 16;
int arr_size = 6;
printPairs(A, arr_size, n);
getchar();
return 0;
}
As in how does it initialise only binMap[elements in arr] to 1 and the
rest to 0?
With this
bool binMap[MAX] = {0};
The every element in the array binMap array is initialized to 0 (actually it sets only binMap[0] to 0 but due to implicit initialization in C, the rest of the elements are set to 0 too) at first.
Then with this in the loop,
binMap[arr[i]] = 1;
the indexes given by the elements of arr are set to 1. For example, if arr[i] is 45 then binMap[45] is set to 1.
Here is the problem:
Given an array of integers, sort the array according to frequency of elements. For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}. if 2 numbers have same frequency then print the one which came 1st.
I know how to do it partially. Here is my approcach.
I will create a struct which will be like:
typedef struct node
{
int index; // for storing the position of the number in the array.
int count; // for storing the number of times the number appears
int value; // for storing the actual value
} a[50];
I will create an array of these structs, I will then sort it by a sorting algorithm on the basis of their count. However, how can I ensure that if the frequency of two elements are same, then that number should appear which has a lesser index value?
#include <stdlib.h> // qsort, malloc, free
#include <stddef.h> // size_t
#include <stdio.h> // printf
struct number
{
const int * value;
int num_occurrences;
};
static void cmp_by_val(const struct number * a, const struct number * b)
{
if (*a->value < *b->value)
return -1;
else if (*b->value < *a->value)
return 1;
else
return 0;
}
static void cmp_by_occurrence_stable(const struct number * a, const struct number * b)
{
if (a->num_occurrences < b->num_occurrences)
return -1;
else if (b->num_occurrences < a->num_occurrences)
return 1;
else if (a->value < b->value)
return -1;
else if (b->value < a->value)
return 1;
else
return 0;
}
static struct number * sort_by_occurrence(const int * arr, size_t N)
{
//
// STEP 1: Convert the input
//
struct number * sort_arr = (struct number *)malloc(N * sizeof(struct number));
if (! sort_arr) return NULL;
for (int k = 0; k < N; ++k)
{
sort_arr[k].value = &arr[k];
sort_arr[k].num_occurrences = 0;
}
//
// STEP 2: Sort the input based on value
//
qsort(sort_arr, N, sizeof(struct number), cmp_by_val);
//
// STEP 3: Count occurrences
//
if (0 < N)
{
int cur_value = *sort_arr[0].value;
int i = 0;
for (j = 1; j < N; ++j)
{
if (*sort_arr[j].value != *sort_arr[i].value)
{
for (int k = i; k < j; ++k)
sort_arr[k].num_occurrences = j - i;
i = j;
}
}
for (; i < N; ++i)
sort_arr[i].num_occurrences = N - i;
}
//
// STEP 4: Sort based on occurrence count
//
qsort(sort_arr, N, sizeof(struct number), cmp_by_occurrence_stable);
//
// DONE
//
return sort_arr;
}
static void print_arr(const struct number * arr, size_t N)
{
if (0 < N)
{
printf("%d", arr[0]->value);
for (int k = 1; k < N; ++k)
printf(", %d", arr[k]->value);
}
printf("\n");
}
int main(int argc, char ** argv)
{
const int EXAMPLE_INPUT[11] = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
struct number * sort_arr = sort_by_occurrence(EXAMPLE_INPUT, 11);
if (sort_arr)
{
print_arr(sort_arr, 11);
free(sort_arr);
}
};
You could create an array which stores the frequency of your input array (i.e. frequency[i] is the frequency of the input[i] element). After that it is easy to order the frequency array (using an stable algorithm) and make the same changes (swaps?) to the input array.
For creating the frequency array you can use several approaches, a simple and inefficient one is just counting each element with two nested loops. I left more efficient alternatives to your imagination.
Note: the frequency array has the same function as the count field in your struct node, but in a separated memory. If you will not need the frequencies in the future, I recommend you to use the separated memory, as you can release it.
It seems that the problem is using unstable sort algorithm on the frequency of array elements.
Do a qsort on the array based on freq
Again do a qsort on the resulted array based on the indexes of the element with the same freq only.
This should give you a correct answer in O(nLog)
I minimized the code. The obvious parts are left out.
struct node
{
int *val;
int freq;
// int index; <- we can do this by comparing &a->val with &b->val
};
int compare_byfreq(const int* a, const int* b)
{
return a->freq - b->freq;
}
int compare_index(const int* a, const int* b)
{
if( a->freq == b->freq)
{
return a->val - b->val; //this can never be zero
}
//else we have different freq don't move elem
return 0;
}
int main()
{
int arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12};
node *narray = (struct node*)malloc(sizeof(arr) * sizeof(node));
// build the nodes-array
for(int i =0; i < sizeof(arr); i++)
{
/* buid narray here, make sure you store the pointer to val and not the actual values */
}
qsort(narray, sizeof(arr), compare_byfreq);
qsort(narray, sizeof(arr), compare_index);
/*print narray*/
return 0;
}
Edit: #0xbe5077ed got an interesting idea. Instead of comparing indexes compare addresses of your values! - I just re-edited the code for that
I was trying to learn Java nowadays, realized that this could be a good exercise. Tried and solved this problem over there in Eclipse. Java is horrible, I went back to C to solve it, here's a solution that I'll explain right after showing it:
#include <stdio.h>
#include <malloc.h>
typedef struct numbergroup {
int firstencounteridx;
int count;
int thenumber;
} Numbergroup;
int firstoneissuperior( Numbergroup gr1, Numbergroup gr2 ) {
return gr1.count > gr2.count || // don't mind the line-break, it's just to fit
( gr1.count == gr2.count && gr1.firstencounteridx < gr2.firstencounteridx );
}
void sortgroups( Numbergroup groups[], int amount ) {
for ( int i = 1; i < amount; i++ ) {
for ( int j = 0; j < amount - i; j++ ) {
if ( firstoneissuperior( groups[j + 1], groups[j] ) ) {
Numbergroup temp = groups[j + 1];
groups[j + 1] = groups[j];
groups[j] = temp;
}
}
}
}
int main( ) {
int input[] = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
Numbergroup * groups = NULL;
int amountofgroups = 0;
for ( int i = 0; i < ( sizeof input / sizeof * input ); i++ ) {
int uniqueencounter = 1;
for ( int j = 0; j < amountofgroups; j++ ) {
if ( groups[j].thenumber == input[i] ) {
uniqueencounter = 0;
groups[j].count++;
break;
}
}
if ( uniqueencounter ) {
groups = realloc( groups, ( amountofgroups + 1 ) * sizeof * groups );
groups[amountofgroups].firstencounteridx = i;
groups[amountofgroups].count = 1;
groups[amountofgroups].thenumber = input[i];
amountofgroups++;
}
}
sortgroups( groups, amountofgroups );
for ( int i = 0; i < amountofgroups; i++ )
for ( int j = 0; j < groups[i].count; j++ )
printf( "%d ", groups[i].thenumber );
free( groups );
putchar( 10 );
return 0;
}
Let me explain the structure first, as well as its functionality: It is for each unique number. In your example, it is for 2s, 3s, 4s, 5s and the 12s, one for each, 5 in total. Each one is to store:
the index of the first encounter of that number
the amount of encounter of that number
the value of that number
For example, for 12s, it shall store:
firstencounteridx as 5, that is the index of the first 12
count as 2
thenumber as 12
The first loop generally does that. It expands the group of Numbergroups whenever a unique number is encountered, stores its index as well; increases the count in case a number that already has a group has been encountered.
Then a sort is issued, which simply is a bubble sort. Might be different than the conventional one, I don't have any memorized.
Sorting criteria function simply checks if the count field of the first group is greater than the other; otherwise it checks whether they are the same and the firstencounter of the first group is earlier than the other; in which cases it returns 1 as true. Those are the only possible ways for the first group to be considered superior than the second one.
That's one method, there can be others. This is just a suggestion, I hope it helps you, not just for this case, but in general.
Created a map and sort the map by value.
O(nlogn) time, and O(n) space.
import java.util.*;
public class SortByFrequency {
static void sortByFreq( int[] A ) {
// 1. create map<number, its count>
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < A.length; i++) {
int key = A[i];
if( map.containsKey(key) ) {
Integer count = map.get(key);
count++;
map.put(key, count);
}
else {
map.put(key, 1);
}
}
// 2. sort map by value in desc. order
// used modified (for desc. order) MapUtil in http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
Map<Integer, Integer> map2= MapUtil.sortByValue(map);
for(Map.Entry<Integer, Integer> entry : map2.entrySet() ) {
int num = entry.getKey();
int count = entry.getValue();
for(int i = 0; i < count; i++ ) {
System.out.print( num + " ");
}
}
System.out.println();
}
public static void main(String[] args ) {
int[] A1 = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12};
sortByFreq(A1);
}
}
I want to make a program that returns me the longest increasing sequence in an array.
For example:
Input: 1, 2, 3, 2, 6, 2
Output: 1, 2, 3
Input: 4, 3, 1, 2, 4, 6, 4, 1, 5, 3, 7
Output: 1, 2, 4, 6
I managed to put together a code, but this only returns me the first sequence of consecutive, increasing numbers:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int j = 0;
int cou = 0;
int max = 0;
// c = final array; will contain the longest consecutive, increasing sequence of numbers
int c[10];
int n = 0;
int a[] = {1, 3, 5, 1, 5, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < (sizeof(a)/sizeof(int)); ++i) {
if (a[i+1] > a[i])
++cou;
if (cou > max) {
max = cou;
c[j] = a[i];
c[j+1] = a[i+1];
j++;
}
if (j > n) //finding the size of my final array
n = j;
else {
cou = 0;
j = 0;
}
}
for (j = 0; j <= n; ++j)
printf("%d ",c[j]);
return 0;
}
So basically, I want the longest sequence of increasing, consecutive numbers.
Been busting my brains on this one for quite a while now, and still haven't managed to crack it open. Any help is welcome.
You need to iterate through array, finding sequences, and comparing their length. So, you need to remember previous length of sequence to compare. And you can't copy result to output array on the fly (if you need output array at all), because you can't predict length of next sequence. I'll better show you an example.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int previous_len=0, start=0, c[10], len=0; //c = final array; will contain the longest consecutive, increasing sequence of numbers
int a[] = {1, 3, 5, 1, 5, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < (sizeof(a)/sizeof(int)); ++i) {
if(a[i+1] > a[i]) {
len++;
if (len > previous_len) {
previous_len=len;
start=i+1-len;
}
} else {
previous_len=len;
len=0;
}
}
for(int i = 0; i <= previous_len; ++i) {
c[i]=a[start+i]; //here you can copy data to output array, if you need it
printf("%d ",c[i]); //you can output a[start+i] instead
}
return 0;
}
It seems to mee that you miss some curly braces:
if(a[i+1] > a[i])
{
++cou;
if (cou>max)
{max = cou;
c[j]=a[i];
c[j+1] = a[i+1];
j++;}
if (j > n) //finding the size of my final array
n=j;
}
else
{cou = 0;
j=0;}
I suggest breaking this down into smaller pieces.
Start with a function:
int sequenceLength(int[] array, int arrayLen, int position)
... which returns the length of the sequence beginning at position. Test it and make sure
it works. You shouldn't need help to write that.
Once you have that, you can write something like:
int longestSequence(int[] array, int arrayLen) {
int longest = 0;
int longestLen = 0;
for(int i=0; i<arrayLen; i++) {
int seqLen = sequenceLength(array, arrayLen, i);
if(seqLen > longestLen) {
longest = i;
longestLen = seqLen;
}
}
return longest;
}
Again, test this and make sure it works for all circumstances.
Finally you need a function:
printSequence(int[] array, int arrayLen, int position)
... which prints the sequence beginning at that position. Again you should be able to tackle this on your own.
Put all those together:
printSequence(array,arrayLen(longestSequence(array,arrayLen)));
It's always easiest to break a challenge like this into smaller pieces to solve it.
There may be more efficient solutions that avoid backtracking, but guessing at your level, I don't think you need to go there.
(Note: although the code here may compile, consider it as pseudocode)
you used a array to store the longest sequence, that made your code go wrong in printing.
And you dint use braces for if() statement that resulted in wrong sequence.
you can make the following changes to make the code work,
int main()
{int j=0, cou=0, max=0, c[10], n=0; //c = final array; will contain the longest consecutive, increasing sequence of numbers
int a[] = {1, 3, 5, 1, 5, 7, 8, 9, 10, 11, 12};
int i,k,z;
for ( k=0,i = 0; i < (sizeof(a)/sizeof(int)); ++i)
{if(a[i+1] > a[i])
{ ++cou;
if (cou>max)
{max = cou;
z=k;
}
}
else
{
k=i+1;
cou = 0;
j=0;}
}
for( j = z; j <(sizeof(a)/sizeof(int)) ; ++j)
if(a[j]<a[j+1])
printf("%d ",a[j]);
else
break;
printf("%d",a[j]);
return 0;
}
My app is supposed to take a double array, find the average of elements of even columns, find the max value, compare average to max / 2 and rotate the matrix 90 degrees if average > max / 2.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int M = 4, N = 4;
int ** rotateArr(int arr[4][4]) {
int D[4][4];
int i, n;
for(i=0; i <= 4; i++ ){
for(n =0; n <= 4; n++){
D[i][n] = arr[n][M - i + 1];
}
}
return D;
}
int getAvg(int arr[4][4]) {
int sum = 0, num = 0;
int i, n;
for(i=0; i <= 4; i += 2){
for(n=0; n <= 4; n++){
sum += arr[i][n];
num += 1;
}
}
return sum/num;
}
int ** getMax(int arr[4][4]) {
int maxa = arr[0][0];
int i, n;
for(i=0; i <= 4; i++){
for(n=0; n <= 4; n++){
if (maxa < arr[i][n]){
maxa = arr[i][n];
}
}
}
return maxa;
}
int main()
{
int S[4][4] = { { 1, 4, 10, 3 }, { 0, 6, 3, 8 }, { 7, 10 ,8, 5 }, { 9, 5, 11, 2} };
int maxa = 0;
float avg = 0;
avg = getAvg(S);
maxa = getMax(S);
int i , n;
if (avg > maxa/2){
S[4][4] = rotateArr(S);
for(i=0; i <= 4; i+=2){
for(n=0 ; n <= 4; n++){
printf("%d", S[i][n]);
}
printf("\n");
}
}
getch();
return 0;
}
The app doesn't output anything and just ends on key press with
Process terminated with status 0 (0 minutes, 2 seconds)
There are a lot of problems with your code. For example:
All your loops are of the form for(i=0; i <= 4; i++ ) The condition should be changed to i < 4 because the valid array indices are 0 to 3.
The rotateArr function returns a pointer to a local variable. You can't do this. One solution is to receive the output array as a parameter and write into it:
void rotateArr(int arr[4][4], int output[4][4]) {
....
output[i][j] = ...;
}
int** is not the same as int[4][4].
S[4][4] = ... tries to assign to an invalid element. It looks like you're trying to assign to S itself, which can't be done (you need to assign each element, or memcpy from another array):
int anArray[4][4];
int anotherArray[4][4];
memcpy(anArray, anotherArray, sizeof(anArray));
In the expression arr[n][M - i + 1], the second index can be out of range. Consider what happens when i==0.
I suggest you pay attention to compiler warnings, as they would catch some of these issues (on GCC compiler use the -Wall option). Also, learn to use a debugger.
Analyse your program and you will find that;
You are returning D (of type int (*)[4] from rotateArr whose return type is int **. And similar issue with getMax.
For n =4 array arr[i][n] will go out of bound!
sum/num is in fact not calculating the average value (numerator and denominator both are int and you will always get an int value (may be 0 too).
and many more..........