Temperatures


The aim of this puzzle is to find the closest temperature to 0 in a list. It is pretty easy, and perfect to introduce a very commun and fundamental algorithm : the linear search.

C

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
// limits.h contains the macro INT_MAX which is the maximum capacity of an int

int main(int argc, char** argv)
{
    int N;
    scanf("%d\n", &N);

    if (N == 0)
        printf("0");
    else {
        char str[10000];
        fgets(str,10000,stdin);
        char *iter = str;

        int T, len, min=INT_MAX;
        /* Search the temperature of minimum absolute valueReads
        Note a subtilty of the exercice : a temperature T>0 is prefered over -T*/
        while (sscanf(iter, "%d%n", &T, &len) == 1) {
          if (abs(T) < abs(min) || (T == -min && T > 0))
              min = T;
          iter+=len;
        }

        printf("%d", min);
    }
    return EXIT_SUCCESS;
    /* sscanf takes a char* pointer on the string to read
       %d means an integer is expected
       %n means the nb of characters consumed is stored in len
       which is then used to move forward in str
       sscanf returns the number of item read (here 1 or in the end 0)*/
}
            

Java

import java.util.*;
import java.math.*;

class Solution {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        int N = in.nextInt();
        if (N == 0)
            System.out.println("0");
        else {
            int T;
            int min = Integer.MAX_VALUE;
            /* Search the temperature of minimum absolute valueReads
               Note a subtilty of the exercice : a temperature T>0 is prefered over -T */
            for (int i = 0; i < N; i++) {
                T = in.nextInt();
                if (Math.abs(T) < Math.abs(min) || (T == -min && T > 0))
                    min = T;
            }
            System.out.println(min);
        }
    }
}
            

Python 3

N = int(input())
if N == 0:
    print("0")
else:
    min = None
    for T in map(int, input().split()):
        if (min == None) or (abs(T) < abs(min)) or ((T == -min) and (T > 0)):
            min = T
    print(min)