Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Last active November 19, 2016 22:33
Show Gist options
  • Save FernandoBasso/8b492d97ca8ed930151de4236f2c8793 to your computer and use it in GitHub Desktop.
Save FernandoBasso/8b492d97ca8ed930151de4236f2c8793 to your computer and use it in GitHub Desktop.
Part of code to solve the "Temperatures" puzzle from codinggame.com
// https://www.codingame.com/training/easy/temperatures
// gcc -std=c99 -Wall -pedantic -o temperatures temperatures.c
// ./temperatures <<< $(cat input.txt)
//
// input.txt
// 9
// 7 22 -99 0 -1 35 -2 +7654 21
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXARRSIZE 257
// String to Signed Int.
// len is the length of the input string.
// Returns the number of ints in nums, and fills nums by reference.
int str2sint(char* input, int* nums);
int closest_to_zero(int* nums, int len);
int main(void) {
// the number of temperatures to analyse
int n;
int closest;
int nums_len; // Quantity of numbers parsed.
// the n temperatures expressed as integers ranging from -273 to 5526
char temps[MAXARRSIZE] = {'\0'};
int nums[MAXARRSIZE] = {'\0'}; // temps converted to signed ints.
scanf("%d", &n);
fgetc(stdin); // Reads the newline?
// the n temperatures expressed as integers ranging from -273 to 5526
fgets(temps, MAXARRSIZE, stdin);
nums_len = str2sint(temps, nums);
closest = closest_to_zero(nums, nums_len);
fprintf(stdout, "Closest: %d\n", closest);
return 0;
}
int str2sint(char* input, int* nums) {
short int minus, digit;
int temp_num, i;
minus = 0;
digit = 0;
temp_num = 0;
i = 0;
while (*input != '\0') {
if (*input == '-') {
minus = 1;
input++;
}
while (*input >= '0' && *input <= '9') {
digit = 1;
temp_num += *input - '0';
temp_num *= 10;
input++;
}
if (digit == 1 && (*input < '0' || *input > '9')) {
temp_num /= 10;
if (minus == 1) {
temp_num *= -1;
}
nums[i++] = temp_num;
temp_num = 0;
minus = 0;
digit = 0;
}
input++;
}
return i;
}
int closest_to_zero(int* nums, int len) {
int i;
int closest = 0;
int distance, temp_distance;
short int positive, negative;
positive = negative = 0;
if (len == 0) {
return 0;
}
for (i = 0; i < len; ++i) {
if (*nums > 0) positive = 1;
if (0 == i) {
closest = *nums;
distance = abs(0 - *nums);
++nums;
continue; // Back to start of loop.
}
temp_distance = abs(0 - *nums);
if (temp_distance < distance) {
distance = temp_distance;
closest = *nums;
}
++nums;
}
// There were no positive numbers.
if (positive == 0) {
// Returns without inverting the sign.
return closest;
}
// If there are -3 and 3 which are closest, return the positive one.
if (closest < 0 && distance == abs(closest)) {
closest *= -1;
}
return closest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment