Sorting random numbers into bins - C [closed] - c

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 8 years ago.
Improve this question
I'm trying to write some code that sorts a generated random number, between 0 and 1, and sorts it into a 'bin', which is an array. The window then prints out saying the number of random numbers in each bin. Hope this makes some sense, but I'm really struggling. I'm a complete beginner, and I'm completely stuck, and need some help on how to make the code work and where to go next. Here's what I've got so far.
#include <stdio.h>
#include <stdlib.h>
int main()
{
double x,y;
int i;
int data[i];
unsigned int time_ui;
time_ui = (unsigned int)( time(NULL) );
srand(time_ui);
x = rand()/ (double)RAND_MAX;
data[i]=0;
for (i=0; i<10; i++)
{
(x*10)=y;
if ((int)y == i)
{
data[i]+=1;
}
printf("Bin %d contains %d random numbers\n", i, data[i]);
}
return 0;
}

I guess I understood what you were trying to do, here is what I could come with
#include <stdio.h>
#include <stdlib.h>
int main()
{
double x,y;
int i;
int data[10]; // you will generate 10 bins
unsigned int time_ui;
time_ui = (unsigned int)( time(NULL) );
srand(time_ui);
for (i =0; i<10; i++) // initialize each bin
{
data[i] = 0;
}
for (i=0; i<100; i++) // generate and examine 100 random you can do it for more
{
x = rand()/(double)RAND_MAX; // generate random number
y = 10 *x; // predict in which bin it will be
data[(int)y]++; // increase that bin by 1
}
for (i =0; i<10; i++) // once done, let's print it out
{
printf("Bin %d contains %d random numbers\n", i, data[i]);
}
return 0;
}
EDIT
Not really important, just for fun you can print out results like that :
for (i =0; i<10; i++) // once done, let's print it out
{
printf("\t");
for(j = 0; j<data[i]; j++)
{
printf("_ ");
}
printf("\nBin %d\t", i);
for(j = 0; j<data[i]; j++)
{
printf("_|");
}
printf("%d\n", data[i]);
}
Don't forget to define int j;

Related

How to change iterations to recursion [closed]

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
I've got a problem. I've tried to write program. This is command:
The user specifies a whole number n>0.
Program:
Allocates two arrays of numbers of type int size n+1
Using only these arrays and a small number of statically allocated variables, the program calculates recursively the n line of the Pascal triangle (all binomial symbols with an upper parameter equal to n)
Prints out the calculated values
Memory slowing down
Example
input: 5
output: 1 5 10 10 5 1
I wrote iteration, but I have no idea how change this for recursion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,k;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0') printf("%d", 1);
if(n=='1') printf("%d %d", 1, 1);
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = 1;
array_1[1] = 1;
k=1;
while(k!=n)
{
for(i=0; i<=k+1; i++)
{
if(i==0)
{
array_2[0] = 1;
}
else if(i==n)
{
array_2[i] = 1;
}
else
{
array_2[i] = array_1[i] + array_1[i-1];
}
}
for(i=0; i<=n; i++)
{
array_1[i] = array_2[i];
array_2[i] = 0;
}
k++;
}
for(i=0; i<=n; i++)
{
printf("%d ", array_1[i]);
}
free(array_1);
free(array_2);
return 0;
}
The recursive version could look something like the following, with the actual work being left to fill-in under the two /* ... */ comments. The missing code essentially exists in the iterative version as posted, it just needs to be retrofitted here.
void recurse(int k, int n, int *array_1, int *array_2)
{
/*
print previously calculated k-th row in array_1
*/
// nothing left to do
if (k == n + 1) return;
/*
calculate next (k+1)-th row in array_2
*/
// swap arrays and repeat
recurse(k + 1, n, array_2, array_1);
}
int main()
{
int n, *array_1, *array_2;
if(scanf("%d", &n) != 1) return 1; // input error
if (n < 0) return 1; // invalid input
array_1 = (int*)calloc(n + 1, sizeof(int));
array_2 = (int*)calloc(n + 1, sizeof(int));
array_1[0] = 1;
recurse(1, n, array_1, array_2);
free(array_1);
free(array_2);
return 0; // done
}
Thanks everyone for answer :). This is my code:
#include <stdio.h>
#include <stdlib.h>
void recurse (int k, int n, int *array_1, int *array_2)
{
int i;
if(k==n+1) return;
for(i=1; i<=k+1; i++) array_2[i] = array_1[i] + array_1[i-1];
recurse(k+1, n, array_2, array_1);
}
void output(int n, int *array_1, int *array_2)
{
int i;
if(n%2!=0)
for(i=0; i<=n; i++) printf("%d ", array_1[i]);
else
for(i=0; i<=n; i++) printf("%d ", array_2[i]);
}
int main()
{
int n;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0')
{
printf("%d", 1);
return 0;
}
else if(n=='1')
{
printf("%d %d", 1, 1);
return 0;
}
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = array_1[1] = array_2[0] = 1;
recurse(1, n, array_1, array_2);
output(n, array_1, array_2);
free(array_1);
free(array_2);
return 0;
}

C buggy program [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 4 years ago.
Improve this question
I don't know why this program says that 5 was not found in the array when clearly there is a 5 in the array. Also, rarely it won't output any printf message. Apart from this, it correctly identifies if the specified number is present.
Thank you for your time.
Number 5 present but wrong output message and no output message displayed-
#include <stdio.h>
#include <stdlib.h>
void print_array(int a[], int num_elements);
int findNumber(int array[], int array_size, int value);
void main()
{
srand(time(NULL)); //Produce random numbers
int randomNums[10]; //Array of 1000 ints
int index, value;
//Populate the array with random ints from 1 to 10
int i; //Merely for looping purposes
for (i = 0; i < 10; i++) {
randomNums[i] = rand() % 10 + 1; //Random range from 1 to 10
}
print_array(randomNums, 10);
findNumber(randomNums, 10, 5);
}
void print_array(int anarray[], int num_elements)
{
int i;
for (i = 0; i < num_elements; i++)
{
printf("Element %d: %d \n", i, anarray[i]);
}
printf("\n");
}
int findNumber(int array[], int array_size, int value)
{
int i;
for (i = 0; i < array_size; i++)
{
if(array[i] == value)
{
//Number found
printf("%d found at element %d \n", value, i);
break;
}
if(array[i] == array_size && array[i] != value)
{
//Number not found
printf("%d not found \n", value);
break;
}
}
}
In the loop in findNumber, the statement:
if(array[i] == array_size && array[i] != value)
causes the loop to print a message and stop if array[i] equals array_size. In this, array[i] is an element in the array. You likely intended to test i == array_size instead. However, that is also incorrect, because, inside the loop, i will never equal array_size. The controlling condition in the for statement is i < array_size, which means, if i is not less than array_size, the loop will not do another iteration.
You need to both correct the test to i == array_size and put it after the loop, not in the loop.
Additionally, remove the array[i] != value from that if statement. If i equals array_size, it will refer to an element outside the array.

Can somebody please help me with the mistake in algorithm [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 7 years ago.
Improve this question
Problem Link: https://www.codechef.com/problems/PERMUT2
Problem : Getting non ambiguous for all test cases. There is absolutely no problem in executing the program, no errors.
Can you please point out the mistake in my code/algorithm:
#include <stdio.h>
#include <stdlib.h>
int index_func(int number, int *array, int x);
int main(){
int n;
scanf("%d", &n);
int *nums = (int*)malloc(n*sizeof(int));
int i;
for(i=0; i<n; i++){
scanf("%d", &nums[i]);
}
int j;
int counter = 0;
for(j=0; j<n; j++){
if(nums[j] != index_func(j+1, nums, n)){
counter = 1;
break;
}
}
if(counter == 0){
printf("ambiguous\n");
}else{
printf("non ambiguous\n");
}
return 0;
}
int index_func(int number, int *array, int x){
int z, index;
for(z=0; z<x; z++){
if(number == array[z]){
index = z;
return z;
}
}
}
The numbers in the array start with one, but the indices in C arrays start with 0. A quick fix to your program would be to add one to the returned index when you compare it to the current number:
if (nums[j] != index_func(j + 1, nums, n) + 1) ...
An alternative solution is to adjust the array data by subtracting one after you scan it, so that the array contains zero-based numbers.
A problem may arise with larger arrays, because every call to index_func scans the whole array from the beginning and will traverse half of it on average. The solution will be correct, but very slow.
But you don't have to determine the index to do the comparison. It is sufficient to check whether the number at the index of the current number is the current index. That leads to this function:
int is_ambiguous(const int *array, int n)
{
int i;
for (i = 0; i < n; i++) {
if (array[array[i] - 1] != i + 1) return 0;
}
return 1;
}
Some notes on your original code:
You should return an invalid index, probably −1, from index_funct when the nuber isn't in the array. I know, this shouldn't happen here, but next time you copy and paste the code and the missing return value might bite you.
You don't really need the variable index in index_funct. Separating pieces of code into small functions can make the program control easier. Compare the above function is_ambiguous with your inline solution with a counter variable and a break.
When you allocate, you must also free, which you don't.
try this solution:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int index_func(int number, int *array, int x);
int main(){
int n;
scanf("%d", &n);
int *nums = (int*)malloc(n*sizeof(int));
int i;
for(i=0; i<n; i++) {
scanf("%d", &nums[i]);
}
int j;
int counter = 0;
for(j=0; j<n-1; j++){
if((abs(nums[j+1] - nums[j]) != abs(n-1)) && (abs((nums[j+1] - nums[j]) != 1)))
{
counter = 0;
}
else
{
counter = 1;
}
}
if(counter == 0){
printf("ambiguous\n");
}else{
printf("non ambiguous\n");
}
free(nums);
return 0;
}

Shell sorting random float array not working [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 9 years ago.
Improve this question
I wrote a shell sorting algorithm which works perfectly on integer values, but gives me segmentation fault when trying to sort float numbers. Could you help me with this ? Thank you.
We have a homework at the university and my teacher wrote this program with insert sort and it worked. The homework for us was to rewrite it to shell sort (which I think I did correctly) and maybe expand it further more to sort strings and numbers from files.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int int_cmp(const void *p1, const void *p2){
return *(int*)p1 - *(int*)p2;
}
int float_cmp(const void *p1, const void *p2){
if (*(float*)p1 == *(float*)p2){
return 0;
}
else if (*(float*)p1 < *(float*)p2){
return -1;
}
else {
return 1;
}
}
void shell_sort(void *v, int nr, int size, int(*p_cmp)(const void*, const void*)){
int i, j;
void *pv, *pi, *pj;
pv = malloc(size); //this is where I get segmentation fault
for (int gap = nr/2; gap > 0; gap/=2){
for (i = gap; i < nr; ++i){
for (j = i-gap; j >= 0; j-=gap){
pi = v;
pi = (char*)pi+j*size;
pj = (char*)pi+gap*size;
if (p_cmp(pi, pj) > 0){
memcpy(pv, pi, size);
memcpy(pi, pj, size);
memcpy(pj, pv, size);
}
else {
break;
}
}
}
free(pv);
}
}
int main(){
int a[20], n = 20;
float b[25], m = 25;
srand(time(NULL));
printf("Original integer array: ");
for (int i = 0; i < 20; ++i){
a[i] = rand() % 100;
printf("%i ", a[i]);
}
printf("Original float array: ");
for (int j = 0; j < 25; ++j){
b[j] = (float)rand()/(float)(RAND_MAX)*50;
printf("%f ", b[j]);
}
shell_sort(a, n, sizeof(int), int_cmp);
shell_sort(b, m, sizeof(float), float_cmp);
printf("\nInteger array after sort: ");
for (int i = 0; i < 20; ++i){
printf("%i ", a[i]);
}
printf("\nFloat array after sort: ");
for (int j = 0; j < 25; ++j){
printf("%f ", b[j]);
}
return 0;
}
free(pv); move to outside for-loop(after loop).

C code not displaying the correct thing [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 8 years ago.
Improve this question
I'm trying to do a program with matrix. In four numbers, only the first less 1. When the first matrix finish, just the second matris less 1. And goes by to the end. The 0 number is not allowed.
For example, when I run the code, need to return this:
[2][1][3][3]
[1][1][3][3]
[1][3][3]
[3][3]
[2][3]
[1][3]
[3]
[2]
[1]
But that is not happening with this code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int fila[4], var;
for (var=0;var<4;var++) {
fila[var]=0;
srand(rand());
fila[var]=rand()%3+1;
printf("[%d]",fila[var]);
fila[0]=fila[0]-1;
}
system("pause>NULL");
while(fila[0]>0)
{
printf("[%d][%d][%d][%d]\n",fila[0],fila[1],fila[2],fila[3]);
fila[0]--;
system("pause");
}
fila[1]=fila[1]-1;
while(fila[1]>0)
{
printf("[%d][%d][%d]\n",fila[1],fila[2],fila[3]);
fila[1]--;
system("pause");
}
fila[2]=fila[2]-1;
while(fila[2]>0)
{
printf("[%d][%d]\n",fila[2],fila[3]);
fila[2]--;
system("pause");
}
fila[3]=fila[3]-1;
while(fila[3]>0)
{
printf("[%d]\n",fila[3]);
fila[3]--;
system("pause");
}
return 0;
}
What I'm missing?
Thanks.
That code prints:
[2][1][2][1]
[1][1]
You need two nested loops to do it:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int fila[4], i, j;
srand(rand());
for (i=0;i != 4; i++) {
fila[i]=rand()%3+1;
}
for (i=0 ; i != 4 ; fila[i]--, i += (fila[i] == 0)) {
for (j = i ; j != 4 ; j++) {
printf("[%d] ", fila[j]);
}
printf("\n");
}
return 0;
}
The outer loop iterates until you get to the end of fila; inner loop prints the remaining elements of fila starting at the index of i.
Note that you shouldn't be re-seeding srand in a loop - you do it only once before the loop.
Here is the link to this program on ideone.
What you want looks like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[4];
int i;
for(i = 0; i < 4; i++) {
arr[i] = (rand() % 3) + 1;
}
for(i = 0; i < 4; i++) {
while(arr[i]) {
int j;
for(j = i; j < 4; j++) {
printf("[%d]", arr[j]);
}
printf("\n");
arr[i]--;
}
}
return 0;
}
Notice the nested loops. In particular, the inner for loop lets you print j entries of the matrix without having to copy/paste that code over again -- you get to eliminate lots of redundancy.

Resources