1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add find-outlier-number/c/function

This commit is contained in:
Divlo 2021-09-30 18:56:27 +02:00
parent b46ed6f28e
commit 9ae0cadb72
No known key found for this signature in database
GPG Key ID: 6F24DA54DA3967CF
4 changed files with 50 additions and 38 deletions

View File

@ -0,0 +1,3 @@
# find-outlier-number/c/function
Created by [@Divlo](https://github.com/Divlo) on 30 September 2021.

View File

@ -0,0 +1,47 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool is_odd(int number) {
return number % 2 == 1;
}
int find_outlier_number(int* numbers, size_t length) {
int outlier_number;
int* odd_numbers = malloc(length * sizeof(int));
int* even_numbers = malloc(length * sizeof(int));
size_t odd_length = 0;
size_t even_length = 0;
for (size_t index = 0; index < length; index++) {
if (is_odd(numbers[index])) {
odd_numbers[odd_length] = numbers[index];
odd_length++;
} else {
even_numbers[even_length] = numbers[index];
even_length++;
}
}
if (odd_length == 1) {
outlier_number = odd_numbers[0];
} else {
outlier_number = even_numbers[0];
}
free(odd_numbers);
free(even_numbers);
return outlier_number;
}
int main() {
size_t length = 0;
int number;
int* numbers = malloc(sizeof(int));
do {
scanf("%d", &number);
numbers = realloc(numbers, sizeof(int) * (length + 1));
numbers[length] = number;
length++;
} while (fgetc(stdin) != EOF);
printf("%d\n", find_outlier_number(numbers, length));
free(numbers);
return EXIT_SUCCESS;
}

View File

@ -1,3 +0,0 @@
# find-outlier-number/typescript/function
Created by [@Divlo](https://github.com/Divlo) on 6 June 2021.

View File

@ -1,35 +0,0 @@
import readline from 'node:readline'
const input: string[] = []
const readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout
})
readlineInterface.on('line', (value) => {
input.push(value)
})
readlineInterface.on('close', solution)
interface NumberObject {
value: number
index: number
}
const isOdd = (number: number): boolean => {
return number % 2 !== 0
}
function solution() {
const numbers = input.map((value) => Number(value))
const oddNumbers: NumberObject[] = []
const evenNumbers: NumberObject[] = []
numbers.forEach((number, index) => {
const numberObject: NumberObject = { value: number, index }
return isOdd(number)
? oddNumbers.push(numberObject)
: evenNumbers.push(numberObject)
})
const isValueThatDiffersFromOthers =
oddNumbers.length === 1 ? oddNumbers[0] : evenNumbers[0]
console.log(isValueThatDiffersFromOthers.value)
}