So I would like to know how to write a non-recursive function to print all permutations given an N and r where r^N gives you the total number of permutations.
Example: N = 3, r = 2, total permutations = 8
output:
000
001
010
011
100
101
110
111
This is what I tried but of course it only works for one case:
void perm_iter(int N, int nr_vals){
int pos = N-1;
int i,j,k;
int P_array[N];
for(i=0;i<N;i++){
P_array[i] = 0;
}
int val_array[nr_vals];
for(i=0;i<nr_vals;i++){
val_array[i] = i;
}
do{
for(i=0;i<N;i++){
for(j=0;j<nr_vals;j++){
P_array[pos-1] = val_array[j];
for(k=0;k<nr_vals;k++){
P_array[pos] = val_array[k];
for(i=0;i<N;i++){
printf("%d",P_array[i]);
}
printf("\n");
}
}
pos--;
}
}while(pos > 0);
}
This is an odometer function with variable radix, not really a permutation.
#include <stdio.h>
#include <stdlib.h>
void show(int *a, int n)
{
int i;
for(i = 0; i < n; i++)
printf("%1d", a[i]);
printf("\n");
}
void gen_all_numbers(int r, int n)
{
int i;
int *a;
if(r < 2 || n < 1) /* parameter check */
return;
r -= 1; /* r = max digit value */
a = malloc(n * sizeof(int));
for(i = 0; i < n; i++) /* start with all zeroes */
a[i] = 0;
show(a, n);
while(1){
i = n - 1;
while(a[i] < r){ /* increment last digit */
a[i]++;
show(a,n);
}
/* find next digit to increment */
while(i >= 0 && a[i] == r)
i--;
if(i < 0)break; /* return if done */
a[i]++;
while(++i < n) /* zero following digits */
a[i] = 0;
show(a,n);
}
free(a);
}
int main()
{
gen_all_numbers(2,4);
return 0;
}
This works. Just make sure you use the -lm option when compiling or you'll get an error about the pow function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perm(double r,double N){
double num=pow(r,N);
int count=(int)num;
int n=0,b=0;
for (n=0;n<count;n++){
printf("%d: ",n);
for (b=2;b>=0;b--){ //go through bits 2 to 0.
if (n & (1<<b)){printf("1");}else{printf("0");}
}
printf("\n");
}
}
int main(){
perm(2,3);
return 0;
}
Related
I'm trying to get the average execution time of a function, but whenever I get a single lap of the function in, the recorded time ends up being 0. Even after calling the function 100 times, the recorded execution time for each call is 0. Is there something missing in my code to get the execution time of this function?
Driver.c
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "generateSuffixArray.c"
#include "selectionsort.c"
void DataReset(int A[], int B[], int n){
int i;
for(i = 0; i < n; i++)
{
B[i] = A[i];
}
}
double getAverage(double Laps[], int iterations)
{
int j;
double sum = 0.0, Average;
for(j = 0; j < iterations; j++)
{
sum+=Laps[j];
}
Average = sum/iterations;
return Average;
}
void main(){
int n = 10, k = 100, i, j;
double elapsed;
double Laps[k];
char String[n+1];
int indices[n];
int copy[n];
clock_t start, end;
memset(String, '\0', sizeof(String));
generateSuffixArray(n, indices, String);
DataReset(indices, copy, n);
for(i = 0; i < 2; i++){
for(j = 0; j < k; j++){
start = clock();
if(i == 0){
if(j == 0){
printf("------Selection Sort------\n");
}
startSS(n, indices, String);
}
end = clock();
DataReset(copy, indices, n);
elapsed = ((double) (end - start) / CLOCKS_PER_SEC);
elapsed *= 1000;
Laps[j] = elapsed;
printf("MET = %1f\n", elapsed);
}
}
}
generateSuffixArray.c
#include <stdio.h>
#include <string.h>
#include <time.h>
// --- Print Function to test array content ---//
/*void printSuffixes(int N, int SArray[], char String[]){
int i;
printf("%s\n", String);
for(i = 0; i < N; i++){
printf("%d", SArray[i]);
}
printf("\n");
}*/
// --- From alphabet {a, c, g, t} --- //
void generateSuffixArray(int N, int SArray[], char String[])
{
int i, charNo;
srand(time(NULL));
for(i = 0; i < N; i++)
{
charNo = rand() % (4 - 1 + 1) + 1;
switch(charNo){
case 1: String[i] = 'a';
break;
case 2: String[i] = 'c';
break;
case 3: String[i] = 'g';
break;
case 4: String[i] = 't';
break;
default: charNo = rand() % (4 - 1 + 1) + 1;
i--;
}
SArray[i] = i;
}
//printSuffixes(N, SArray, String);
}
selectionsort.c
#include <stdio.h>
#include <string.h>
void switcher(int *xp, int *yp){
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int n, int indices[], char arr[]){
int i, j, min_idx, curr_idx, key_idx;
char key[n], temp[n];
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
key_idx = indices[i];
strncpy(key, arr + indices[i], strlen(arr) - indices[i]);
key[strlen(key)+1] = '\0';
for (j = i+1; j < n; j++){
strncpy(temp, arr + indices[j], strlen(arr) - indices[i]);
temp[strlen(temp)+1] = '\0';
if(strcmp(key, temp) < 0){
min_idx = j;
strncpy(key, arr + indices[j], strlen(arr) - indices[j]);
key[strlen(key)+1] = '\0';
}
}
// Swap the found minimum element with the first element
switcher(&indices[min_idx], &indices[i]);
}
}
/* UTILITY FUNCTIONS */
// --- Function to print the sorted array --- //
void printArray(int size, int arr[]){
int i, j;
for (i=0; i < size; i++){
printf("%d", arr[i]);
}
}
// --- Start of Insertion Sort process --- //
int startSS(int n, int indices[], char arr[]){
selectionSort(n, indices, arr);
//printArray(n, indices);
}
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 10000
int main(void)
{
int a[MAX_SIZE];
int N;
int L; /* the current size of the list */
/* read in the upper limit. Keep reading until
a valid number between 3 and the maximum that
can be handled by the array is entered */
double b[10000];
int j, i;
L = 0;
printf("Enter the upper limit:\n");
do {
scanf("%d", &N);
} while (N<3 || N>MAX_SIZE+2);
int prime;
for (j = 1; j < N; j++)
{
prime = 1;
for (i = 2; i < j; i++)
{
if (j % i == 0)
{
prime = 0;
break;
}
}
if (prime)
{
a[i] = j;
L++;
}
}
/* write out the result - DO NOT CHANGE THIS */
for(i=0;i<L;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
Program needs to take an integer, calculate primes below that integer, print that list of primes.
I think my problem is related to the loops.
The program is calculating the primes but listing 0 if the number previously there isnt prime eg a[4] is now printing as 0
Any help is appreciated.
thanks.
Is this what you were trying to implement?
#include <stdio.h>
#define MAX_SIZE 100
int main(void)
{
int primes[MAX_SIZE];
int primes_found = 0;
int limit = 0;
while (limit < 3)
{
printf("Enter the upper limit:\n");
scanf("%d", &limit);
}
for (int candidate = 2; candidate <= limit && primes_found < MAX_SIZE; candidate++)
{
int divisor = 2;
int is_prime = 1;
while(is_prime && divisor < candidate)
is_prime = candidate % divisor++ != 0;
if (is_prime)
primes[primes_found++] = candidate;
}
for (int i = 0 ; i < primes_found ; i++)
printf("%d ", primes[i]);
printf("\n");
return 0;
}
I have written a piece of code below, that ask a user input a number N (3 < N < 1.000.000) odd and count the number of prime number pairs whose sum is equal to N. That code works, but I need to optmize it to make more efficient. When the user inputs a number, I count the number of primes up to this number and store each prime number in a vector, and after that count the number of prime number pairs whose sum is equal to this input.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void seleciona_primos (int *vet, int n, int raiz){
int i, j;
vet[2] = 2;
for(i=3; i<=n; i+=2){
vet[i] = i;
}
for (i=3; i<= raiz; i+=2){
if(vet[i]!=0){
for(j=3; j<=n; j+=2){
if ((vet[i]!=vet[j]) && (vet[j]%vet[i] == 0)){
vet[j]=0;
}
}
}
}
}
int conta_pares (int *vet, int n){
int i, j, count=0;
for (i=3; i<=n; i+=2){
if(vet[i]!=0){
for(j=3; j<=n/2; j+=2){
if((vet[j]!=0) && (vet[i] + vet[j] == n)&& (vet[i]!=0)){
//printf("%d ", vet[i]);
//printf("%d\n", vet[j]);
count++;
vet[i] = 0;
}
}
}
}
if(vet[n-2]!=0){
count++;
}
return count;
}
int main()
{
int *vet, n, raiz, i , count;
scanf("%d", &n);
vet = (int *) calloc((n+1), sizeof(int));
raiz = floor(sqrt(n));
seleciona_primos(vet, n, raiz);
count = conta_pares(vet, n);
printf("%d",count);
//for(i=3; i<=n; i+=2){
//if(vet[i]!=0){
//printf("%d\n", vet[i]);
//}
//}
return 0;
}
I make an array who countain the prime numbers from 2 to N(1 has only one divisors and 0 has infinites of divisors), and then I check if two numbers from the array equal to N
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool Prime(int);
int main()
{
long N;
do
{
printf("Give me the number of numbers :");
scanf("%ld",&N);
}while(N<=4||N>1000000);//N must be between 3 & 1000000
int prime[N];
int arr[N];
int j=0;
for(int i=2;i<N;i++)
{
if(Prime(i)==true)
{
prime[j]=i;
j++;
}
}
printf("\n\n");
for(int p=0;p<j-1;p++)
{
for(int q=p+1;q<j;q++)
{
if(N==prime[p]+prime[q])
{
printf("\n%d = %d + %d \n",N,prime[p],prime[q]);
}
}
}
printf("\n\n");
return 0;
}
bool Prime(int n)
{
for(int i=2;i<=(n/2);i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
Example :
Input : N =100;
Output :
100 = 3 + 97
100 = 11 + 89
100 = 17 + 83
100 = 29 + 71
100 = 41 + 59
100 = 47 + 53
Thank you for all suggestions!!
And after some research and tries, I have found the solution that follow bellow:
int isPrime(int x)
{
int i;
for(i = 2; i <= sqrt(x); i++)
{
if(x%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int i, count = 0, n ;
scanf("%d", &n);
for(i = 3; i <= n/2 ; i+=2)
{
if(isPrime(i))
{
if((isPrime(n-i)))
{
count++;
}
}
}
if(isPrime(n-2))
{
count++;
}
printf("%d", count);
return 0;
}
I modified your code to optimize it, I have set two Boolean vectors one for 5 mod(6) prime numbers (vet1[i]=false corresponds to prime number 6 x i-1 es. i=1 corresponds to prime number 5=6 x 1-1) and one (vet2[i]corresponds to prime number 6 x i+1) for prime numbers 1 mod(6)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
void seleciona_primos (bool *vet1, bool *vet2,int n){
int i, i1,imax;
imax=(n-n%6)/6+1;
for (i=1; (6*i-1)*(6*i-1) <=n; i++){
if (vet1[i]==false){
for(int i1 = 6*i*i; i1 <= imax+2*i; i1 += (6*i-1)){
if(i1<imax)
vet1[i1]=true;
vet2[i1-2*i]=true;
}
}
if (vet2[i]==false){
for(int i1 = 6*i*i; i1 <= imax; i1 += (6*i+1)){
vet1[i1]=true;
if(i1<imax-2*i)
vet2[i1+2*i]=true;
}
}
}
}
int conta_pares (bool *vet1, bool *vet2, int n){
int i,imax, count=0,r6;
imax=(n-n%6)/6;
r6=n%6;
if (r6==0){
for (i=1; i<imax; i++){
if(vet1[i]== false && vet2[imax-i]== false)
count++;
}
}
if (r6==2){
for (i=1; i<imax; i++){
if(vet2[i]== false && vet2[imax-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6==4){
for (i=1; i<=imax; i++){
if(vet1[i]== false && vet1[imax+1-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6>0 && r6<3){
if (vet1[imax]==false)
count++;
}
if (r6>2 && r6<5){
if (vet2[imax]==false)
count++;
}
return count;
}
int main()
{
int n, i , count;
bool *vet1, *vet2;
scanf("%d", &n);
vet1 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
vet2 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
seleciona_primos(vet1,vet2, n);
count = conta_pares(vet1,vet2, n);
printf("%d",count);
free(vet1);
free(vet2);
return 0;
}
I am making this code for a random dice roller and I want to get a random number until I get three 6's on the dice. For some reason this produces the same number for all runs, but on my for loop it works. Can I get some help getting this to work?
The pesky While loop in question:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Ran(int max) {
return (rand() % max)+ 1;
}
int main(){
int max = 6;
int nsuc = 0, ncount = 0;
int matt = 40;
srand((unsigned) time(0));
for(int i = 1; i <= 20; i++){
while(!(nsuc >= 3)){
int nr = Ran(max);
if(nr < matt){
ncount++;
if(nr == 6){
nsuc++;
}
}
}
printf("Number of rolls until 3 6's = %d\n", ncount);
}
}
Cleaned up the for loop so it's easier to read now:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void Shuffle() {
srand((unsigned) time(NULL));
}
int Ran(int max) {
return (rand() % max)+ 1;
}
void binomial(int run, int max, int btrials, int *array, int scount){
for(int j = 1; j<=run; j++){
for (int i=1;i<=btrials;i++){
int r = Ran(max);
if(r == 6){
scount++;
}
printf("Trial %i, roll = %d\n",i , r);
}
array[j-1] = scount;
scount = 0;
printf("\nEnd of Run %d\n\n",j);
}
}
int main(){
int Runs;
printf("How many runs do you want to do? > ");
scanf("%d", &Runs);
printf("\n");
int bdist[20];
int distcount = 0;
int max = 6;
int btrials = 20;
int suc[Runs+1];
int scount = 0;
Shuffle();
binomial(Runs, max, btrials, suc, scount);
printf("All counts of succesful 6 rolls.\n");
/*
for(int z = 1; z<=Runs; z++){
printf("Run %d has %d 6's\n", z, suc[z-1]);
}
*/
for(int k = 0; k<=btrials; k++){
for(int j = 1; j<=Runs; j++){
if(suc[j-1] == k){
distcount++;
}
}
bdist[k] = distcount;
distcount = 0;
}
for(int t = 0; t<=btrials; t++){
printf("Number of runs with %d 6s = %d\n", t, bdist[t]);
}
return 0;
}
You never reset nsuc or ncount in the first version with the while loop. After the first time thru, they still have their values from the previous loop so you get the same output.
Not an answer strictly related to the question, but something I noticed.
If I recall, generating ranged random numbers using the (rand % max)+ 1 idiom is not advised.
One.
Two
This program is supposed to sort numbers entered from the command line as -a for small to large sort, or -d for large to small sort. I compiled this program earlier, ran it and the output was fine. I tested it on my laptop later and then the sorting was all wasn't working correctly.
I entered ./sort -a 5 14 10 18 20 2 100 6 7 1 The Result: -1950355064 2 5 6 10 14 18 20 100 I entered: ./sort -d 5 14 10 18 20 2 100 6 7 1 The Result: 761262572 32767 18 14 10 6 20 5 100 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
// function declarations
void small_to_large(int a[], int n);
void large_to_small(int a[], int n);
int main(int argc, char *argv[])
{
int i;
char letter_d[3] = "-d"; // find "-d" in function
char letter_a[3] = "-a"; // find "-a" in function
int arg_d;
int arg_a;
char *find_letter = argv[1];
int stringToInt[N+1];
for( i = 0; i < argc; i++){
printf("%s ", argv[i]);
}
printf("\n");
arg_d = strcmp(find_letter, letter_d);
arg_a = strcmp(find_letter, letter_a);
if (arg_d == 0) {
printf("descend!\n");
for(i = 2; i<argc; i++) {
stringToInt[i] = atoi(argv[i]);
}
large_to_small(stringToInt, N);
for(i = 0; i < N; i++) {
printf(" %d", stringToInt[i]);
}
}
else if (arg_a == 0) {
printf("ascend!\n");
for(i = 2; i < argc; i++) {
stringToInt[i] = atoi(argv[i]);
}
small_to_large(stringToInt, N);
for(i = 0; i < N; i++) {
printf(" %d", stringToInt[i]);
}
}
else {
printf("Invalid command: %s\n", find_letter);
}
printf("\n");
return 0;
}
// small_to_large function
void small_to_large(int a[], int n)
{
int i, largest = 0, temp;
if (n == 1)
return;
for (i = 1; i < n; i++)
if (a[i] > a[largest])
largest = i;
if (largest < n - 1) {
temp = a[n-1];
a[n-1] = a[largest];
a[largest] = temp;
}
small_to_large(a, n - 1);
}
// large_to_small function
void large_to_small(int a[], int n)
{
int i, largest = 0, temp;
if(n == 1)
return;
for (i = n; i >= 2; i--)
if(a[i] < a[largest])
largest = i;
if (largest < n - 1) {
temp = a[n-1];
a[n-1] = a[largest];
a[largest] = temp;
}
large_to_small(a, n-1);
}
There are mainly two problems.
stringToInt[i] = atoi(argv[i]); : index of stringToInt should
start from 0.
large_to_small is wrong. Sorting algorithm may be the same. So you can use the same code.
Fix to sample:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// function declarations
void small_to_large(int a[], int n);
void large_to_small(int a[], int n);
#define OPT_D "-d"
#define OPT_A "-a"
int main(int argc, char *argv[]) {
int i;
for(i = 0; i < argc; i++){
printf("%s ", argv[i]);
}
printf("\n");
int n = argc - 2;//-2 : program_name and option
if(n <= 0){
printf("Usage : %s option(-a or -d) numbers...\n", *argv);
return EXIT_FAILURE;
}
int stringToInt[n];
for(i = 0; i < n; ++i)
stringToInt[i] = atoi(argv[i+2]);
char *opt = argv[1];
bool opt_d, opt_a;
opt_d = !strcmp(opt, OPT_D);
opt_a = !strcmp(opt, OPT_A);
if(opt_d){
printf("descend!\n");
large_to_small(stringToInt, n);
} else if(opt_a) {
printf("ascend!\n");
small_to_large(stringToInt, n);
} else {
printf("Invalid option: %s\n", opt);
return EXIT_FAILURE;
}
for(i = 0; i < n; i++) {
printf("%d ", stringToInt[i]);
}
printf("\n");
return 0;
}
void selection_sort(int a[], int n, bool test(int a, int b)){
int i, select = 0, temp;
if (n == 1)
return;
for (i = 1; i < n; i++)
if(test(a[i], a[select]))
select = i;
if (select != n-1) {
temp = a[n-1];
a[n-1] = a[select];
a[select] = temp;
}
selection_sort(a, n - 1, test);
}
static inline bool greater(int a, int b){
return a > b;
}
static inline bool smaller(int a, int b){
return a < b;
}
// small_to_large function
void small_to_large(int a[], int n) {
selection_sort(a, n, greater);
}
// large_to_small function
void large_to_small(int a[], int n){
selection_sort(a, n, smaller);
}
I believe I managed to get it to work by changing
large_to_small(stringToInt, N); ---> large_to_small(stringToInt, argc);
small_to_large(stringToInt, N); ---> small_to_large(stringToInt, argc);