Add an element to C array only if element does not exist - c

I am trying to learn how to code in C, and I am trying to add unique characters to an array, from an input array, only if the character does not already exist in the unique array, in a very simple way.
I am really stumped and would appreciate some assistance how to think it through correctly.
Here's my code:
/* get each character and how many times it shows up
* to do this we need to store each unique char in a char array, and the count for each
* unique char in an int array */
char unique_chars[count];
for(int each = 0; each < count; ++each)
unique_chars[each] = '0';
/* count is the total number of chars stored in theinput array. */
int no_times = 0;
for(int each = 0; each < count; ++each)
{
if(theinput[each] != unique_chars[each])
unique_chars[each] = theinput[each];
if(theinput[each] == unique_chars[each])
continue;
for(int item = 0; item < count; ++item){
if(theinput[each] == unique_chars[item]){
++no_times;
}
}
printf("%c is in theinput array %d times.\n", theinput[each], no_times);
no_times = 0;
}
/* print all the values in the unique_chars array*/
printf("values in unique_chars are: \n");
for(int each = 0; each < count; ++each);
printf("\n");
return 0;
This is one of the many things I have tried. It returns the following:
./uniquely
exsss
The characters typed in are: exsss
Number of characters are: 6
values in unique_chars are:
e x s s s
Please how can I do this right?

You should rework the algorithm of your program as follows:
set count_unique to zero
for each index in the input
set count to zero
go through input to again using index i
if input[index] is the same as input[i]
count++
if count is 1 after the loop
unique_chars[count_unique++] = input[index]
for each index from zero to count_unique
print unique_chars[index]
However, this is the long way of doing it. The short way is to walk through the input once, increment counts, then walk through the counts, and print indexes of values of 1:
int counts[256];
for (int i = 0 ; i != count ; i++) {
counts[(unsigned)input[i]]++;
}
for (int i = 0 ; i != 256 ; i++) {
if (counts[i] == 1) {
printf("%c ", i);
}
}
printf("\n");

Related

How to loop for a specific amount

I am writing a program that would iterate through a sequence of characters, where every 4 counts would add the iterated 4 characters into a char array which means that it must be able to constantly be updating every 4 counts.
For example,
The sequence:
char sequence[32] = "qRiM1uOtGgXl5yuNPJwKo4+bAdQuPUbr";
I want a loop that would be able to get every four characters, which in this case the first 4 characters is "qRiM".
Then I would want it to be stored in a char array:
char test[4]; (This must be able to print qRiM)
Then when 4 counts has been done then the cycle would repeat where the next 4 characters would be "1uOt"
I've tried to attempt this but it would only print out qRiM and that the test[4] array is not updating.
int count_steps = 0;
for (int i = 0; i < 32; i++) {
// Adds a character from a sequence into the test array until 4
while(count_steps < 4) {
test[i] = sequence[i];
count_steps++;
}
// Checks if four counts has been done
if (count_steps == 4) {
//decoder(test, decoded_test);
// Prints out the four characters
for(int j = 0; j < 4; j++) {
printf("%c\n", test[j]);
}
// Resets back to 0
count_steps = 0;
}
else {
continue;
}
}
With details explaination from torstenvl, you can rewrite code:
for (int i = 0; i < 32; i++) {
test[i%4] = sequence[i];
if ((i+1) % 4 == 0) {
printf("\n");
for(int j = 0; j < 4; j++) {
printf("%c\n", test[j]);
}
}
}
test[i] = sequence[i];
This line assigns the ith entry in test to the ith entry in sequence. But test only has 4 entries, so on the second iteration, you are writing to test[4] throught test[7]. You need to use count_steps as the index in test.
You also need to add count_steps to i when accessing sequence so that the correct index in sequence is set in test.
And since you're adding processing 4 characters in each iteration of the for loop, you need to increment i by 4, not by 1
demo
for (int i = 0; i < 32; i += 4/* increment by 4 */) {
// Adds a character from a sequence into the test array until 4
while(count_steps < 4) {
test[count_steps] = sequence[i + count_steps]; // use count_steps as index in test and offset in sequence
count_steps++;
}
...
}

Trying to find smallest array elements from 2 arrays returns 0 (doesn't work) and the other works. (C lang)

I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums

Writing a txt file while running some calculations

I am trying to create a program that outputs in a txt file the results of Collatz conjecture. However when I try to do it with big numbers, like 1,000,000, it does not work properly and always stops at 113383.
Here is the code:
int n, count, number, mayor, masvueltas, top;
char c = '#';
freopen("output MILLION.txt", "w", stdout);
count = 0;
number = 1;
mayor = 0;
masvueltas = 0;
while(number != 1000000) {
printf("\n%d did ", number);//this will say that number did COUNT loops
n = number;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
count++;
}
else {
n = 3 * n + 1;
count++;
}
}
printf(" %d saltos.\n", count);//Here continoues the sentence
char graf[count];//creates an array to print the # character COUNT times
for (int i = 0; i < count; i++) {
graf[i] = c;
printf("%c", graf[i]);
}
if(masvueltas < count) {
masvueltas = count;
mayor = number;
}
number++;
count = 0;
}
Also if you know how to print the ASCII character 219, block, in a txt file it would be great. Is not important just so I have a cleaner txt file.
This happened because for number = 113,383 the calculations reach the value of 827,370,449 after 119 counts, the next count max the value 2,482,111,348 which is more than the maximum value of int variable 2,147,483,647, which makes the value of n becomes negative, -1812855948, and the loop fails to reach 1. You should use long long n instead to get the results you want. I also recommend that you use for loop instead of while loop.

Deleting Duplicates in array and replacing them with unused values

My objective for this program is to let the user determine the size of the array and dynamically allocate memory for whatever size they choose. Once the user defines the size of the array, random numbers that do no exceed the size of the array are placed into all of the allotted positions. Where I am having issues is removing duplicates from the array and replacing them with a value that is not being used,
Example:
Please enter the size of the array:
User Input: 5
Output of code: 5, 3, 3, 1, 2
I would need it to be something like this:
Please enter the size of the array:
User Input: 3
Output of program: 3, 1, 2
Currently reading "C Programming - A Modern Approach" by K.N. King (Second Edition).
if someone could point me in the right direction on how to approach this, it would be much appreciated.Here is my code thus far.
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef int bool;
int main() {
int *UserData;
int TempPost;
int replace;
int UserInput;
int i;
int result;
bool digit_seen[UserInput];
int digit;
srand ((unsigned) time(NULL));
printf("Please enter the size of the array using a whole number: \n");
scanf("%d", &UserInput);
UserData = malloc(sizeof(int) * (UserInput ) +1);
for(i=0; i < UserInput; i ++) {
result = (( rand() % UserInput) + 1);
}
// check for duplicate values while putting values in array
while(UserInput>0){
digit = UserInput % UserInput;
if(digit_seen[digit])
break;
digit_seen[digit] = true;
UserInput /= UserInput;
if(UserInput > 0)
printf("Repeated digit \n");
else
printf("No repeated digit \n");
}
// Sorting the array using a Bubble sort
while(1){
replace = 0;
for (i=0; i<(UserInput - 1); i++){
if(UserData[i]>UserData[i+1]){
TempPost = UserData[i];
UserData[i] = UserData[i+1];
UserData[i+1] = TempPost;
replace = 1;
}
}
if(replace==0){
break;
}
}
printf("%d \n", result);
return 0;
}
It's not the most efficient way, but you can do it as you're generating the random numbers. When you pick a random number, go through all the previous elements of the array and see if it's already been used. Keep looping until you pick an unused number.
for (i = 0; i < UserInput; i++) {
do {
result = ( rand() % UserInput) + 1;
} while (in_array(result, UserData, i-1));
UserData[i] = result;
}
int in_array(int val, int* array, int array_size) {
for (int i = 0; i < array_size; i++) {
if (array[i] == val) {
return 1;
}
}
return 0;
}
A slightly more efficient way to do it is to initialize the array to 0. Then instead of picking random numbers, pick a random index to fill in, and repeat this until you pick an index that contains 0.
UserData = calloc(UserInput, sizeof(int));
for (i = 1; i <= UserInput; i++) {
int index;
do {
index = rand() % UserInput;
} while (UserData[index] != 0)
UserData[index] = i;
}
What you can do is shuffle the array instead. Just fill the array with all the numbers in order using a simple for loop, then shuffle it with something like this:
//read user input
//create array and fill with all the numbers in order
//[0,1,2,3,4,5 .. ... ]
int index, temp;
// size is the size of the array
for(int i = 0; i < size; i++)
{
index = rand()%size;//random place to pick from
temp = array[i];
array[i] = array[index];
array[index] = temp;
}
This is a lot more effecient -and less error prone- than your current approach.

How to count how many times values were used in the array C?

Here's my problem
If certain number has been entered into an array I need that number to be displayed and occurrence of that number in the array.
for example if user enters number 5 three times then "The number 5 has been entered 3 times so far" and so on
Here's my code so far:
int i,j;
int num_count = 0;
for(i=0;i<6;i++) {
num_count = 0;
for(j=1;j<43;j++) {
if( *(num + i) == j) {
printf("The number %d has been used %d times\n",j,num_count);
}//end if
}//end inner for
}//end outer for
I will like to suggest you a very time efficient method for this, but it needs some extra memory.
Assume the upper limit of numbers inside array is 'MAX_NUM_IN_ARRAY',
so you should create array (say counter) of size 'MAX_NUM_IN_ARRAY+1' and initialize it to 0.
int counter[MAX_NUM_IN_ARRAY+1]={0};
now scan the input array from first to last element,
for each number:
//say number is num
counter[num]++;
and at the end you have to just scan that counter array from index 1 to MAX_NUM_IN_ARRAY.
Sample code:
Suppose input array is a[],
number of elements in array is n,
maximum limit of number inside array is MAX_LIMIT
int counter[MAX_LIMIT]={0};
int i;
for(i=0; i<n; i++)
{
counter[a[i]]++;
}
for(i=0; i<MAX_LIMIT; i++)
{
printf("Number %d is appeared for %d times\n", i, counter[i]);
}
============EDIT
You could write a series of functions that handle your collection. the collection could be a 2 dimentional array like so numbers[][] where numbers[n][0] is your number, and numbers[n][1] is the number of times it occurred... and the gold would be in your add() function
add() does a few things, a user passes a value to add(),
first checks if number exists in numbers[n][0]
if the value exists at numbers[n][0]
numbers[n][1]++;
if it doesn't already exist,
check if the array is full
if it is full, copy all the data to a new, larger array
add it to the end of the array.. this is how to do it.
==OR
just design a 1 dimentional array numbers[] that holds all of your numbers.. and the add() function only:
if(it is full){copies to larger array}
adds number to the end;
and modify the code I wrote earlier (Below).. to print the most common number and it's occurrence count
============EDIT
I'm a Java guy so you'll need to translate (shouldn't be too hard..)
This is going to be just like a sorting algorithm with a little bit of extra logic (later search for Selection Sort)
int[] temp = {4,3,2,4,4,5};
////// find the most commonly occuring value
int times;
int moreTimes = 1;
int value = temp[0];
for(int i = 0; i < temp.length; i++) {
times = 1;
for(int j = i+1; j < temp.length; j++) {
if(temp[i] == temp[j])
times++;
}
if(times > moreTimes) {
moreTimes = times;
value = temp[i];
}
}
/////// count the most common value
int count = 0;
for(int i = 0; i < temp.length; i++) {
if(temp[i] == value)
count++;
}
System.out.println("number: " + value + ", count: " + count);

Resources