I have to do a bubble sort with pointers for my class.
I am having trouble with the output
I want every array sort to be on a single line, not individual lines for each element.
Here is an array example that I would want to print.
I flipped the 1 and 9 to ensure that I was printing the proper value, not the location, when it was returning just one number.
[9, 2, 3, 4, 5, 6, 7, 8, 1]
Here is what it prints
[9]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[1]
How do I get this sample array onto just one line?
#include <stdio.h>
#define MAX 9
int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;
int main(){
for (i = 0; i < MAX; i++
{ printf ("[%d]\n", val[i]);
}
return (0);
} //end main
Now I have read that you cant output to one line. I keep reading that you need each element to output individually. The prof has the sample output for the bubble pointer showing that all elements of the array remain on the same line. What am I missing?
FYI this is not the bubble sort with pointer. I am just needing help getting this sample array to output properly.
This must be in C, NOT C++, or C#.
I really don't see why you don't just remove the \n, which causes the newline. Then separate out the different parts of your output.
#include <stdio.h>
#define MAX 9
int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;
int main(void){
putchar('[');
for (i = 0; i < MAX; i++) {
if (i == MAX - 1)
printf ("%d", val[i]);
else
printf ("%d, ", val[i]);
}
puts("]");
return (0);
} //end main
You cannot print the [ in the loop, or else it will print every time. Then, in the loop you want to print a comma unless you are at your last element where no elements should be printed next (if (i == MAX - 1). Finally you print the newline and the closing bracket at the end once the loop finishes. Make note that puts() automatically prints a newline.
Related
I'd like to ask for a help regarding the function which has to return a value of the array element which does not have a matching pair.
For instance,
a) In the array [1, 1, 2, 3, 4, 3, 4], the element without a pair is 2.
b) In the array [1, 1, 2, 4, 3, 4, 2, 3, 4], the element without a pair is 4.
So far I come up with the code below. So basically it checks for the repetitive numbers, and thus works for the b) case; yet it doesn't works for the a) case. Any help regarding how to fix this code, so that it works for a) and b) cases, is welcome.
#include <stdio.h>
int ft_unmatch(int *tab, int length)
{
int i;
int j;
int count;
i = 0;
while (i < length)
{
j = i + 1;
count = 0;
if (tab[i] == tab[j])
{
count++;
while (j < length)
{
if (tab[i] == tab[j])
count++;
j++;
}
if (count % 2 != 0)
return (tab[i]);
}
i++;
}
return (tab[i]);
}
int main(void)
{
//some additional arrays to check the function
int tab[9] = {1, 1, 2, 4, 3, 4, 2, 3, 4};
//int tab[11] = {1, 1, 2, 4, 3, 1, 4, 2, 4, 3, 4};
// int tab[7] = {1, 1, 2, 3, 4, 3, 4};
printf("%d\n", ft_unmatch(tab, 9));
return (0);
}
Assuming that all elements in the array are integer numbers and have a matching pair except one, just keep XORing the elements until the last one. Your result at the end of the scan will be the unmatched element.
The reason why this works is that:
XOR is commutative (so a XOR b = b XOR a)
for every a, a XOR a = 0
for every a, 0 XOR a = a
Every element will be cancelled out by their matching pair except one: the one you are looking for.
example:
int result=0;
for (i = 0; i < length; i++) {
result = result ^ tab[i];
}
return result;
Then handle edge cases as you wish.
Many problems in this code:
You compare every number with all of the following ones. So in a), you compare the first 1 with all the other numbers and count two 1s, but then you count the second 1 again and won't find another, so you code returns 1.
Also, you are missing curly brackets following the if tab[i] == tab[j]) and you only get to the while(j<length)-loop if the first if(tab[i] == tab[j]is true.
One possible solution would be to remove the numbers that were already counted from the array, so you don't count them again, or sort the array and count until each increment. If you are only working with small numbers you could also iterate over every possible number and count how often it appears, although that would be less elegant.
I have a simple function in C to get whether an array is sorted, but I seem to be getting different values every time. Sometimes I get 3 tests passed and sometimes I get 2 tests passed and am unsure what the problem is.
int is_sorted(int a[], int n)
{
for(int i = 0; i < n; i++)
{
if(a[i] > a[i + 1])
{
return 0;
}
}
return 1;
}
int main()
{
int a[] = {2, 4, 9, 8, 12};
int b[] = {-5, -2, 0, 8, 11, 15};
int aa[] = {2, 18, 12, 9, 1, 2, 8, 11, 16, 3};
int c[] = {4, 6, 8, 10};
npassed = 0;
if(!is_sorted(a, 5))
{
npassed++;
}
if(is_sorted(b, 6))
{
npassed++;
}
if(!is_sorted(aa, 10))
{
npassed++;
}
if(is_sorted(c, 5))
{
npassed++;
}
printf("number passed is_sorted : %i\n", npassed);
}
your function accepts two arguments:
a: the array
n: the arrays size
to check if it is sorted you iterate over all elements and see if its next element is bigger than itself. To do that, you count with i from zero (the lowest possible index) to n-1 (the highest possible index).
But you always check if i is greater than i+1. And what happens if you reach the last possible index for i? Then i+1 is equal to n and therefore outside the array. And what's outside your array is random data.
I am doing an problem on Leetcode. The question is that given an array and a value, remove all instances of that value in place and return the new length.
Or you can read it here:
int removeElement(int* nums, int numsSize, int val) {
int *nums_copy;
int count = 0;
int actual_count = 0;
while (actual_count < numsSize) {
if (nums[actual_count] != val) {
nums_copy[count] = nums[actual_count];
count++;
nums_copy = realloc(nums_copy, sizeof(int)* count);
}
actual_count++;
}
nums = nums_copy;
return actual_count;
}
When I tried to test it with [1, 2, 2, 3], 2, the output is [1, 2, 2, 3] while the expected output is [1, 3].
Firstly, you don't need to realloc, the problem says to remove the value in place. Secondly, what you need to do is to simply walk through the array and shift it one position to the left when you encounter the searched value. And decrement the resulted count.
The problem does not need to memory allocation. All that is needed is to have the matching elements towards the end of the list. Here is an example.
array = 3, 2, 5, 2, 7, 2
len = 6
val = 2
We want to achieve something like
array = 3, 7, 5, 2, 2, 2
newlength = 3
SOLUTION One approach is the following
Repeat:
Start with two marker (either index or pointer) one pointing to the leftmost and one pointing to the rightmost element
3, 2, 5, 2, 7, 2
L R
Move the left marker to the right if it matches to 'val'. Do it until the matching stops or it reaches the right marker.
3, 2, 5, 2, 7, 2
L R
(Opposite for right marker.) Move the right marker to the left if it matches to 'val'. Do it until the matching stops or it reaches the left marker.
3, 2, 5, 2, 7, 2
L R
Swap the elements corresponding to the left and right markers.
3, 7, 5, 2, 2, 2
L R
Go to Repeat.
Apparently, you have not specified how much memory you want to allocate after int *nums_copy. Use malloc from stdlib to allocate variable amount of memory on heap, or alloca to allocate on stack, but bear this in mind.
Here this should work:
int removeElement(int* nums, int numsSize, int val) {
int countNums = 0;
int countCpy = 0;
while (countNums < numsSize) {
if (nums[countNums] != val) {
// Copy the number.
nums[countCpy] = nums[countNums];
++ countCpy;
}
++ countNums;
}
return countCpy;
}
As for why this output you got was [1, 2, 2, 3], I don't really understand. As you're trying to set nums_copy[0] before having allocated nums_copy, you should be getting a segfault. I suppose it's due to the platform you're coding on.
The given code uses std::vector, so why not use its build-in functions?
int removeElement(vector<int>& nums,int val){
vector<int> newNums();
for (int i=0; i<nums.size(); i++){
if (nums[i]!=val){
newNums.push_back(nums[i]);
}
}
return newNums.size();
}
int removeElement(int* nums, int numsSize, int val) {
int i, j;
for(i = 0, j = 0 ; i < numsSize ; i++){
if( nums[i] == val ) continue;
nums[ j ] = nums[ i ]; // blind copy
j++;
}
/*
nums = realloc( nums, j * sizeof( int ) );
*/
return j; //actual_count
}
I want to find three largest number(area) from 10 numbers(scanf), I wrote this code, but only the largest number is correct when I run it, second and third largest number is wrong. So, I need help. any suggestions? Merry Christmas!
#include <stdio.h>
#define N 3
int main()
{
int i,j;
int area;
int maxArea[N];
int empty = N;
for(j=0;j<10;j=j+1)
{
printf("Input:");
scanf("%d",&area);
printf("\n");
if(empty > 0)
{
maxArea[N-empty]=area;
empty=empty-1;
}
else
{
for(i=0; i < N; i=i+1)
{
if(area>maxArea[i])
{
maxArea[i]=area;
break;
}
}
}
}
printf("Area1=%d\n",maxArea[0]);
printf("Area2=%d\n",maxArea[1]);
printf("Area3=%d\n",maxArea[2]);
}
#include <stdio.h>
#include <limits.h>
#include <string.h>
#define N 3
int main(){
int i,j;
int area;
int maxArea[N];
for(i=0;i<N;++i)
maxArea[i]=INT_MIN;
for(j=0;j<10;++j){
printf("Input:");
scanf("%d",&area);
printf("\n");
for(i = 0;i<N && i <= j;++i){
if(area > maxArea[i]){
memmove(&maxArea[i+1], &maxArea[i], (N-i-1)*sizeof(*maxArea));
maxArea[i] = area;
break;
}
}
}
printf("Area1=%d\n", maxArea[0]);
printf("Area2=%d\n", maxArea[1]);
printf("Area3=%d\n", maxArea[2]);
return 0;
}
Firstly you should initialize all the array elements to zero.
Also, your code does not work correctly since you only check for the first element in the array that is lesser than the new element.
If the array has 6, 3, 2 and the new element is 7, then 7 shall pop out 6 from the array and the array shall become 7, 3, 2. Instead it should have been 7, 6, 3.
You should pop out the lowest number in the array.
In the general case a minheap would be the best resort. (for k largest elements)
I just want to show you a different approach, you have to decide for yourself what is easier;
First I initialize maxArea with the smallest possible integer. This way I don't need special handling if it does not contain 3 numbers yet. Any number will simply be larger then MIN_INT, so it will be replaced automatically.
for(i=0; i < N; i++)
{
maxArea[i]=MIN_INT;
}
In the loop, I swap area with the old maximum value, and I keep running the loop, so the old value will be reused for the other max values.
for(j=0;j<10;j=j+1)
{
printf("Input:");
scanf("%d",&area);
printf("\n");
for(i=0; i < N; i++)
{
if(area>maxArea[i])
{
// swap both
int temp=maxArea[i];
maxArea[i]=area;
area=temp;
}
}
}
Note that this is not very optimized, but it might be better to read what is happening. maxArea[0] will always be the largers, maxArea[1] the next and so on.
for example if the array is [6, 3, 2], and the new area is 5;
nothing will happen in the first loop, because 5 is smaller than 6.
In the second loop (i=1), the array will become [6, 5, 2] and area will be 3.
In the third loop, the array will become [6, 5, 3], and area will be 2, (but that 2 will not be used any more).
I have the following (incomplete) function:
/* Populates char* name with the named location of the ith (flat) element
* of an array with ndim dimensions where the length of each dimension
* is already stored in the int* dim.
*
* name: a pointer to where the name should be populated
* n: the base name of the array
* dim: an int[] containing the length of each dimension
* ndim: length of the dim array
* i: name of the iteration variable being used
**/
void populateName(char *name, const char *n, int *dim, int ndim, const char *i) {
strcpy(name, n);
char *loc = (char*)(name + strlen(n));
char *curr;
for (int k = 0; k < ndim; k++) {
...
sprintf(loc, "[%s]", curr);
loc += strlen(loc);
}
}
What should go in the "..." in the for loop? For example, calling populateName() with:
int dim[2] = {3, 4};
char name[1024];
populateName(name, "x", dim, 2, "i");
should result in something like:
name = "x[i / 3][i % 4]"
or some other valid name for accessing the ith location in an array defined as:
int x[3][4];
Context: I'm writing a C program which generates C programs which filter large amounts of data based on user-defined data types and rules written in an IDL.
Edit: A python function which returns a tuple containing the location / coordinates in the array might get me going in the right direction. In particular the following array should have each element correspond with it's flat position in the array (using pylab here):
In [14]: x
Out[14]:
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]]])
In [15]: x.flat.copy()
Out[15]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
A good approach to solve a problem like this one is to try out a few examples. Consider the following picture that shows the memory layout for a 3D array x[2][3][5]:
How can we convert offset 14 to position x[0][2][4]? Well, first, we see that each x[i] holds 15 (3*5) blocks, so first of all we determine to which block does 14 belong to, by computing the integer division 14/15 = 0. So, offset 14 is somewhere inside x[0].
We can now apply the same method. x[i][j] holds 5 blocks, so offset 14 belongs to block number 14/5 = 2. In fact, the correct calculation is (14/5)%3, as we will see for offset 18. And finally, x[i][j][k] holds single blocks, so the last index is given by 14%5. Think of it like this: we are interpreting these blocks of memory as if they had different sizes at each step. First, we assume everything is divided in chunks of 15 elements. Then, we assume everything is divided in chunks of 5 elements.
You can play with this example and see that offset 18 maps to x[1][0][3] because 18/15 = 1; (18/5)%3 = 0, and 18%5 = 3.
It can be seen that the general case is that for dimension n, we interpret the memory layout as if it was organized in j blocks, where j is the product of every dimension greater than n, so we have to index position (i/j)%n.
Here's my implementation:
void populateName(char *name, const char *n, int *dim, int ndim, const char *i) {
strcpy(name, n);
char *loc = (char*)(name + strlen(n));
int j;
int *mul = malloc(sizeof(int)*ndim);
mul[ndim-1] = 1;
/* Compute cumulative multipliers array */
for (j = ndim-2; j >= 0; j--) {
mul[j] = mul[j+1] * dim[j+1];
}
for (j = 0; j < ndim; j++) {
loc += sprintf(loc, "[(%s/%d)%%%d]", i, mul[j], dim[j]);
}
free(mul);
}
As you can see, it uses a cumulative array of multipliers, where mul[i] holds the product of every dimension greater than i.
By the way, you don't need curr; since sprintf returns the number of characters printed, we just have to move loc that same amount. It gets a little more efficient than calling strlen repeatedly after sprintf.
I don't have much time to test this, but with the example I showed, I get this:
x[(i/15)%2][(i/5)%3][(i/1)%5]
Which looks correct. Here's an example program:
int main()
{
int dims[] = { 2, 3, 5, 7, 9 };
char name[1024];
populateName(name, "x", dims, 5, "i");
printf("%s\n", name);
return 0;
}
This prints:
x[(i/945)%2][(i/315)%3][(i/63)%5][(i/9)%7][(i/1)%9]
It gets trickier to read for arbitrary n dimensional arrays, but the principle is always the same.