Bad exercise statement [closed] - c

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 7 years ago.
Improve this question
Given the problem:
The statement is a bit ambiguous. I don't really understand what they want.
I can display the desired result using just a regular for loop:
int step = 0
for(int i = 1; i < m + 1; i++)
{
if(i != p)
{
printf("(%d, %d)", step, i);
step++;
}
}
Is this what they really want? I see that they are talking about linear time, so I think it can't be that easy? Am I supposed to build the vector that they are talking about, and then delete it?

Something like this? (compile with gcc test.c -lm)
#include <stdio.h>
#include <math.h>
int main(void) {
int i, j;
int n = 4;
int m = (int)pow(2,n);
int p = 5;
for(i = 1; i <= n; i++)
{
for(j = (int)pow(2,i-1); j < ((int)pow(2,i)); j++)
{
if(j == p) {
continue;
}
printf("%d, %d\n", i, j);
// remove vector[j]
if((j == (m-1)) && (m != p)) {
printf("%d, %d\n", i, m);
// remove vector[m]
}
}
}
return 0;
}
Run result n=3, p=5:
1, 1
2, 2
2, 3
3, 4
3, 6
3, 7
3, 8
Run result n=4, p=5:
1, 1
2, 2
2, 3
3, 4
3, 6
3, 7
4, 8
4, 9
4, 10
4, 11
4, 12
4, 13
4, 14
4, 15
4, 16

You should write the full code. Let me make it simple:
It should delete every element of the array.
By the end of the loop your program should print out the step and one of the numbers that were deleted, into the format (k, q) where k is the step you are on, and q is one of the elements you had deleted .
Every time you delete an element you can change it by X.
You also need to remember the algorithm they are telling you to use and the "rules of the game", for example: n should be positive and an integer.
And if you do not understand the algorithm, just try to put the idea on a paper:
When I put n = 1, I should delete one element from the array. When n = 2, 2 elements, When n = 3 it should delete 4 elements , n = 4 it deletes 8 element, etc.
As we can see, it is pretty simple because it goes like a geometric progression.

Related

I can't seem to fix this issue about nested for loops + 2d arrays [closed]

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 5 months ago.
Improve this question
this is the code I am having a problem with 1 2 the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j;
int num[3][2] = { (1, 2),
(3, 4),
(5, 6)
};
for(j = 0; j < 3; j++){
for( i = 0; i < 2; i++ ){
printf("%d, ", num[j][i]);
} printf("\n");
}
return 0;
}
guys I am watching this course of freecodecamp about the C language and the guy tutoring got this code right as it says in the console: 1, 2,
3, 4,
5, 6,
and I typed the EXACT same code but still not working, I double- checked and everything, but nothing seems to work.
3
As #Oka said you need to use {} in the initializer. Also fixing formatting, separators, and localizing variables:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
for(size_t j = 0; j < sizeof(num) / sizeof(*num); j++) {
for(size_t i = 0; i < sizeof(*num) / sizeof(**num); i++ ) {
printf("%d%s",
num[j][i],
i + 1 < sizeof(*num) / sizeof(**num) ? ", " : "\n"
);
}
}
return 0;
}
Both #Oka and #Allan Wind have written that you've used () where {} is the correct way to define data in an array.
Below uses a different layout for the small amount of data being specified.
It also shows (similar #Allan's answer) how to let the compiler measure the array's dimensions, uses those values as limits to the loops.
The compiler "knows" there are 3 rows (better than erring humans could do.) If a 4th row is added, re-compiling will use the right value without the programmer remembering to change the loop counter from 3 to 4.
This version uses fewer {} in the code, certain that there is only one executable statement properly indented.
This alternative style is more compact and less garish.
As nice as they are, i & j are overused and, therefore, meaningless. Notice the use of r & c that hints at being row & col. Easier to keep things straight when variable names suggest their meaning and use.
Notice how the indentation in the two versions highlights when printf( "\n" ); will be executed. Whitespace is important for readability. Respect it.
#include <stdio.h> // don't include what you don't need
int main() {
int r, c, num[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
int nRows = sizeof num/sizeof num[0];
int nCols = sizeof num[0]/sizeof num[0][0];
printf( "Version 1:\n" );
for( r = 0; r < nRows; r++ ) {
for( c = 0; c < nCols; c++ )
printf( "%d, ", num[ r ][ c ] );
printf( "\n" );
}
printf( "\nVersion 2:\n" );
for( r = 0; r < nRows; r++ )
for( c = 0; c < nCols; c++ )
printf( "%d, ", num[ r ][ c ] );
printf( "\n" );
return 0;
}
Output
Version 1:
1, 2,
3, 4,
5, 6,
Version 2:
1, 2, 3, 4, 5, 6,
Others will soon comment that the correct definition would be size_t nRows.... One step at a time...

Algorithm to find product [closed]

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 4 years ago.
Improve this question
I encountered this problem at a coding challenge and was not able to solve it. This is the problem statement:
Given an array of transaction costs t, return an array of expected costs e such that it is 0 if product of all transaction costs in t except e[i] is even, else it is 1(i.e for any element in t[i], find product of all elements of t except t[i]. If that product is even, result for that t[i] is 0 else 1).
For example t = [1, 2, 3, 4], e = [ 0, 0, 0, 0]
Explanation: for t, all products are even:[24, 12, 8, 6]
Constraint: do it in O(n) and without division.
FYI, I did it in O(N^2) but couldn't solve it in O(N)
My solution:
int[] arr = {1, 2, 3, 4};
int[] res = new int[arr.length];
for(int i = 0; i < arr.length; i++){
int prd = 1;
for(int j = 0; j < arr.length; j++){
if(i == j) {
continue;
}
prd *= arr[j];
}
if((prd & 1) == 0){
res[i] = 0;
}else {
res[i] = 1;
}
}
You don't need division; all you need is a simple odd/even check. However you care to do this is fine; for instance, mask off everything but the final bit.
Very simply, if all elements are odd, then e is a vector of 1's. If one element is even, e is a vector of all 0's except for that one position, which is a 1. If more than one element is even, then e is a vector of 0's.
This requires a single pass through t (which is O(N)) to find the quantity of even elements; then you can generate e in O(N) time

Correct way to write a pattern in C language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I want to obtain the following output:
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
The code am running is as follows:
#include <stdio.h>
int main(void) {
int i=1,flag=0,lines=0; //0 for forward, 1 for reverse
while(i!=0 && lines<3){
if(!flag){
printf("%d ",i);
if(i==10){
flag=1;
printf("\n");
lines++;
}
else
i++;
}
else if(flag){
printf("%d ",i);
if(i==1){
lines++;
flag=0;
printf("\n");
}
else
i--;
}
}
return 0;
}
Am getting the desired output from the above code but not sure if it's an optimal code. Any other method/suggestion? Considering unlimited space but time complexity should be kept minimum.
Condition: Use only one loop
Use forloops, minimize code that is repeated
#include <stdio.h>
int main(void) {
int lines, flag=1, val;
for(lines=0;lines<3;lines++)
{
if(flag == 1)
for(val=1;val<=10;val++)
printf("%d ", val);
else
for(val=10;val>0;val--)
printf("%d ", val);
printf("\n");
flag = -flag;
}
return 0;
}
Hint: you can use for loops to iterate in either direction:
for (int i = 1; i <= 10; ++i)
or
for (int i = 10; i >= 1; --i)
Also, a for loop is better than a while here because it really shows to the reader "I am iterating i from this to that."
Use an array and iterate it normally at first iteration, vice versa in the second iteration and then normally again.
Sample code:
#include <stdio.h>
#define SIZE 10
void print_arr(int* array, int size);
void print_rev_arr(int* array, int size);
int main(void)
{
int array[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int iter = 3;
for(int i = 0; i < iter; ++i)
if(i % 2)
print_arr(array, SIZE);
else
print_rev_arr(array, SIZE);
return 0;
}
void print_arr(int* array, int size)
{
for(int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
void print_rev_arr(int* array, int size)
{
for(int i = size - 1; i >= 0; --i)
printf("%d ", array[i]);
printf("\n");
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
IO completely dominates this problem.
But the fastest way to iterate forwards is
for(i=0;i<N;i++)
and the fastest and most elegant way to iterate backwards is
int i = N;
while(N--)
You can do this:
Use a for loop that will start from 1 and reach 10. Print its
counter.
Use a for loop that will start from 10 and stop at 1. Print its
counter.
Use a for loop that will start from 1 and reach 10. Print its
counter.
Sample code:
#include <stdio.h>
#define LEN 10
#define ITER 3
int main(void)
{
for(int i = 0; i < ITER; ++i)
{
if(i % 2)
for(int j = 1; j <= LEN; ++j)
printf("%d ", j);
else
for(int j = LEN; j >0; --j)
printf("%d ", j);
printf("\n");
}
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
There are 2 things to consider.
First is whether the program is optimal or not. Is is quite easy to prove that your program is optimal (at least asymptotically optimal). You need to display 3n numbers, so you need at least 3n iterations. You have 3n iterations, so it's fine. You might be able to further optimize the iterations themselves, but that will arise as an implicit result of the second paragraph.
The second is readability. Your code is a bit verbose and unflexible. Consider the following:
int pattern[] = {1,2,3,4,5,6,7,8,9,10};
int patternSize = sizeof(pattern)/sizeof(int);
for (int i=0; i < 3; i++)
for (int j=0; j<patternSize; j++) {
if (i % 2)
printf("%d", pattern[patternSize - j - 1]);
else
printf("%d", pattern[i])
}
The code is shorter and clearer. Also, it is more maintable. It is clear what you have to do to chanelge the pattern. I could hardcode the pattern size as 10, but that would requite 2 changes when you change the pattern. I could generate the pattern, from the value of j, but that would limit the number of patterns that could be shown.
But what if the pattern is all the numbers from 1 to 200? Of course I'm not going to write them by hand. Just replace the array with a for loop that fills up the array. You don't have to change the code that displays the array. This is a small example of separation of concerns - one part of thr code does pattern generation, another part does the display, and they can be modified independently.
While this is asymptotically optimal, there are optimizations that can be made. For examples, using that array to store the pattern is not as efficient as generating the pattern from j. But in practice, unless more efficiency is needed, the advantages of this method outweigh the small performance penalty.
Okay, here's my take, I think it's more pleasant than most:
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 10; ++j)
{
const int v = (i % 2) ? 10 - j : j + 1;
printf("%d ", v);
}
putchar('\n');
}
return 0;
}
Some points:
Doesn't use an array, instead just generates the very simple pattern from the line number (i) and position (j).
Not designed for "pluggable" patterns by using an array, since the pattern was very simplistic and repeating, that is exploited to simplify the code.
Re-use the inner loop, rather than duplicating it.
Prints a linefeed in the proper place, to actually get separate lines (not all posted solutions to that).
The inner loop's body could be shortened to a single line by folding v into the printf() of course, but I aimed for readability and clarity, there.

Arrays printing sum of values [closed]

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 6 years ago.
Improve this question
I have a problem with counting the sum of values from each line in a multidimensional array in the language C.
Example:
My array with values:
1 2 3 4
5 6 7 8
9 10 11 12
My result array should be:
10
26
42
w - count lines
k - count columns
int tab[w][k]; <-- this is a table just with values(it's example)
int sum[] = {0};
int i,j;
for(i=0;i<w;i++)
{
for(j=0;j<k;j++)
{
sum[i] = sum[i] + tab[i][j];
}
}
It doesn't work well. I've tried do it another way but it only counted the first row.
Please help me, thanks.
sum[] = {0} should be sum[w];, and you should fill it with zeroes before doing the sums.
Then just sum like you did, you can do it better using +=, that works the same as your original code but is easier to write:
#include <stdio.h>
#define w 3
#define k 3
int tab[w][k] = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8}
};
int main()
{
int sum[w];
int i;
int j;
for (i = 0; i < w; i++)
{
sum[i] = 0;
}
for(i = 0 ; i < w ; i++)
{
for(j = 0 ; j < k ; j++)
{
sum[i] += tab[i][j];
}
printf("sum[%d] = %d\n", i, sum[i]);
}
}
Then your code should run fine

Issues with HeapSort [closed]

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 6 years ago.
Improve this question
my task is to write the code to a heapsort according to pseudo code. It should heapsort the input Array (4 3 2 5 6 7 8 9 12 1) and then print it with the printHeap method. I know for a fact that the printHeap works, because I have already used it with a method called buildHeap (to build max heap binary trees, but you all already know that :)) and there it works flawlessly, so my problem lies in heapSort.
It sorts correctly and prints it in the way it's supposed to (parent -- child 1, parent -- 2, etc.), only issue is, that the biggest and last value, which is 12, suddenly turns into 24 and I have no clue why.
The code is the following:
void heapSort(int a[], int n){
int x = n+1;
int i;
int temp;
buildMaxHeap(a, n);
for (i = n; i >= 1; i--){
temp = a[i];
a[i] = a [0];
a [0] = temp;
x--;
heapify(a, 0, x);
}
void printHeap(int a[], int n){
int i;
printf("graph g { \n");
for (i = 0; i < n/2; i++){
printf("%d -- %d\n", a[i], a[left(i)]);
if (right(i) < n){
printf("%d -- %d\n", a[i], a[right(i)]);
}
}
printf("}\n");
Output is following:
1 2 3 4 5 6 7 8 9 24
graph g {
1 -- 2
1 -- 3
2 -- 4
2 -- 5
3 -- 6
3 -- 7
4 -- 8
4 -- 9
5 -- 24
}
just so you know what exactly I have done, I will attach the while .c file here:
https://onedrive.live.com/redir?resid=8BC629F201D2BC63!26268&authkey=!AFqVlm9AptiZ_xM&ithint=file%2cc
Really grateful for your help!
Cheers
Arik
Well, you observe an undefined behavior. (I personally on an online IDE got 0 instead of the 12(24).)
Try:
void heapSort(int a[], int n)
{
int x = n; /* changed from n+1 */
int i;
int temp;
buildMaxHeap(a, n);
for (i = n-1; i >= 0; i--){ /*<-- changed*/
temp = a[i];
a[i] = a[0];
a[0] = temp;
x--;
heapify(a, 0, x);
}
}
Your arrays in almost all general purpose languages of today start with index 0[For thorough information see wiki.] You loop your array for (i = n; i >= 1; i--) wrongly and since the heap is max, don't process the first element and go out of bounds with the last. Although arithmetic with the nth element is defined in the standard, it is not meant so rather < n and some pointer work.
On a side note, you can use macros (#defines) for the left, right etc. functions to improve performance and ease the reading.
I hope that saves the day and the AlgoDat Exercise.

Resources