Is there a way to stop my program from printing duplicates? - c

I wrote this program, which is supposed to print all combinations whose sum is equal to a given number.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "combinations.h"
int c = 0;
void findsubsets(unsigned int *numnumbers, int n, int i) {
int j;
if (i < 0)
return;
int sum = 0;
for (j = 0; j < n; j++) {
if (i & (1 << j)) {
sum = sum + numnumbers[j];
}
}
if (sum == target) {
c++;
for (j = 0; j < n; j++) {
if (i & (1 << j))
printf("%u ", numnumbers[j]);
}
printf("\n");
}
}
int main() {
unsigned int iterations = pow(2, VECTOR_SIZE);
for (int i = 0; i < iterations - 1 ; i++)
findsubsets(numbers, VECTOR_SIZE, i);
return 0;
}
//header file next
#ifndef Header_h
#define Header_h
#define VECTOR_SIZE 6
unsigned int numbers[VECTOR_SIZE] = {1, 2, 4, 3, 2, 1};
unsigned int target = 4;
#endif /* Header_h */
However, if as in the example in the header, a number is repeated in the given vector, then it prints out some combinations that include the same numbers. Is there a way to prevent it from doing so? I'm thinking maybe I should use linked lists (which would include all the valid combinations and then compare them, eliminate the ones that are equal, and print out the rest) but I'm pretty sure that would be very time-consuming to write and maybe not very efficient. Is there a less complicated way to do this?
Thank you

Related

how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}

Populate and print array with random numbers using C

I'm trying to write a program that will populate an array of 100 elements with numbers between 1 and 22, and then print the array in a 20 x 5 table. I was able to populate the array and print it, but can only get it to work with numbers 1-100, how can I change it to only do numbers 1-22?
#include <stdio.h>
#include <stdlib.h>
#define ARY_SIZE 100
void random (int randNos[]);
void printArray (int data[], int size, int lineSize);
int main(void)
{
int randNos [ARY_SIZE];
random(randNos);
printArray(randNos, ARY_SIZE, 20);
return 0;
}
void random (int randNos[])
{
int oneRandNo;
int haveRand[ARY_SIZE] = {0};
for (int i = 0; i < ARY_SIZE; i++)
{
do
{
oneRandNo = rand() % ARY_SIZE;
} while (haveRand[oneRandNo] == 1);
haveRand[oneRandNo] = 1;
randNos[i] = oneRandNo;
}
return;
}
void printArray (int data[], int size, int lineSize)
{
int numPrinted = 0;
printf("\n");
for (int i = 0; i < size; i++)
{
numPrinted++;
printf("%2d ", data[i]);
if (numPrinted >= lineSize)
{
printf("\n");
numPrinted = 0;
}
}
printf("\n");
return;
}
#Sarah Simply include time.h header file (from the standard library), then rewrite your random function as follow:
void Random(int RandNos[])
{
/*
Since your random numbers are between 1 and 22, they correspond to the remainder of
unsigned integers divided by 22 (which lie between 0 and 21) plus 1, to have the
desired range of numbers.
*/
int oneRandNo;
// Here, we seed the random generator in order to make the random number truly "random".
srand((unsigned)time(NULL));
for(int i=0; i < ARY_SIZE; i++)
{
oneRandNo = ((unsigned )random() % 22 + 1);
randNos[i] = oneRandNo; // We record the generate random number
}
}
Note: You are asked to include time.h in order to use the time() function. If you are
working under Linux Or Mac OSX, you can find more information about this function by
type the command man 3 time in the terminal to easily access the documentation.
Also, naming your function random will conflict with that of the standard library. That is why I use Random instead.

How to randomly pick elements from an array in C?

I have an array of 6 rows and 20 columns :
char name[6][20];
And I enter the names with for :
puts("Enter with 6 names :");
for(i=0; i< 6 ; i++)
{
scanf("%19[^\n]%*c",name[i]);
}
After that, I need to randomly choose three names of the array and display them in the screen. How can I do that ?
PS : Different from the other questions similar to that, I want not to take just one word, but the full word of the array.
Here's a possible solution to your problem, assuming you've stored the array of names, just create an array of positions and then shuffle it few times so the positions will be random ones, finally pick 3 positions (for instance, the first 3 ones):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 6
#define COL 20
#define RND_NAMES 3
void shuffle(int *array, int n, int num_shuffles) {
srand((unsigned)time(NULL));
for (int j = 0; j < num_shuffles; j++) {
for (int i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
int main() {
int i;
char name[ROWS][COL] = {"name1", "name2", "name3",
"name4", "name5", "name6"};
int positions[ROWS] = {0, 1, 2, 3, 4, 5};
shuffle(positions, ROWS, 100);
printf("%s\n", name[positions[0]]);
printf("%s\n", name[positions[1]]);
printf("%s\n", name[positions[2]]);
return 0;
}
With this way, you're guaranteed to pick up 3 random non-repeated names.
Here I wrote a simple solution for what you're trying to achieve.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 6
#define COL 20
#define RND_NAMES 3
int main()
{
int i;
char name[ROWS][COL];
// init pseudo-random number generator
srand((unsigned)time(NULL));
puts("Enter with 6 names: ");
for (i=0; i < ROWS; i++) {
scanf("%19[^\n]%*c", name[i]);
}
puts("Random names: ");
for (i=0; i < RND_NAMES; i++) {
printf("%s\n", name[rand() % ROWS]);
}
return 0;
}

Random numbers that do not match each other

I want to produce different numbers with C.
We can generate a random number using the stdlib library and the srand function.
For example; I want to produce a random number between 0 and 5.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[3];
srand(time(NULL));
for(i = 0; i < n; i++)
{
array[i] = rand() % 5;
printf("%d\n", array[i]);
}
return 0;
But the same numbers may coincide here.Like this:
2
4
4
1
How can I prevent this?
Maybe you can use something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[4];
// Fill an array with possible values
int values[5] = {0, 1, 2, 3, 4};
srand(time(NULL));
for(i = 0; i < n; i++)
{
int t1 = rand() % (5-i); // Generate next index while making the
// possible value one lesser for each
// loop
array[i] = values[t1]; // Assign value
printf("%d\n", array[i]);
values[t1] = values[4-i]; // Get rid of the used value by
// replacing it with an unused value
}
return 0;
}
Instead of random number you can generate random non-zero shift from the previous number:
#include <stdio.h>
#include <stdlib.h>
int myrand() {
static int prev = -1;
if (prev < 0)
prev = rand() % 5;
prev = (prev + 1 + rand() % 4) % 5;
return prev;
}
int main(void) {
int i;
for (i = 0; i < 20; i++)
printf("%d\n", myrand());
}

How to generate random numbers in C two colons?

I need in c code that generates two numbers in horizontally...so that i can get token numbers for my login system.
I need that i get this:
token=0.152644,0.429187
so in example i have token= and random generated numbers that have at beginning 0. and then 6 random generated numbers separated with , sign.
How to get get this in C?
I have try this code but it does not give me what i want_
#include <stdio.h>
#include <string.h>
typedef
union
{
char tmp[sizeof(unsigned long long)];
unsigned long long myll;
} ll_t;
unsigned long long llrand(void)
{
FILE *in=fopen("/dev/urandom", "r");
ll_t ll_u;
fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
fclose(in);
return ll_u.myll;
}
int main()
{
char tmp1[64]={0x0};
char working[64]={0x0};
int i=0;
for(i=0; i< 1; i++)
{
while(strlen(tmp1) < 6)
{
sprintf(working, "%lu", llrand() );
strcat(tmp1, working);
}
tmp1[6]=0x0;
printf("%s\n", tmp1);
*tmp1=0x0;
}
return 0;
}
From output i get this:
747563
102595
Can code be simple and short?
You can use rand() function:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int randomNumber(int min, int max)
{
/* generate secret number between min and max: */
int res = rand() % (max-min+1) + min;
return res;
}
int main()
{
int i = 0;
srand (time(NULL));
for (i=0; i<100; i++)
printf("%d ", randomNumber(10, 1000000));
return 0;
}
That is full detail for rand():
http://www.cplusplus.com/reference/cstdlib/rand/
Here is the code that is working perfect:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n1, n2;
time_t t;
srand((unsigned) time(&t));
n1 = rand() % 1000000 + 1;
n2 = rand() % 1000000 + 1;
printf("token=0.%d,0.%d\n", n1, n2);
return 0;
}
And output is:
token=0.289384,0.930887
A propose a different approach. Instead of generating 2 numbers and format them into the output string, generate 12 different digits and put them directly in place.
srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
for (int k = 0; k < 6; k++) {
output[9 * n + 8 + k] = rand() % 10 + '0';
// you might want to write a function that deals with rand() bias
}
}
puts(output);

Resources