Unité IN3S02 - TD3
Corrigé
2.1- Tableau inverse (*) 2.2- Plus proche élément (*)
   
    /** PLus proche élément - Solution 1 */
    // (The reference is the index of the nearest element)
    public static double nearestElement1(double[] t, double x) {
        int indexNearest = 0;   // the reference
        double nearestDistance = Math.abs(t[0] - x) ;
        double currentDistance ;
        for (int i = 1 ; i < t.length ; i++ ) {
            currentDistance = Math.abs(t[i] - x) ;
            if (currentDistance < nearestDistance) {
                indexNearest = i ;
                nearestDistance = currentDistance ;
            }
        }
        return t[indexNearest] ;
    }

    /** Plus proche élément - Solution 2 */
    // (The reference is the value of the nearest element)
    public static double nearestElement2(double[] t, double x) {
        double nearestElement  = t[0]; // the reference
        double nearestDistance = Math.abs(nearestElement - x);
        double currentDistance ;
        for (int i = 1 ; i < t.length ; i++ ) {
            currentDistance = Math.abs(t[i] - x) ;
            if (currentDistance < nearestDistance) {
                nearestElement  = t[i] ;
                nearestDistance = currentDistance ;
            }
        }
        return nearestElement ;
    }

2.3- Palindrome (*) 2.4- Horner (*) 2.5- Eratosthène (*)
/**
 * @param   n : natural integer
 */
public static boolean[] Eratosthen(int n) {
    boolean[] t = new boolean[n];
    int i ;
    // init
    t[0] = false ;
    for(i = 1 ; i < n ; i++ ) t[i] = true ;
    // Euclid's algorithm
    for(i = 2 ; i < n/2 ; i++ ) {
        if (t[i]) {
            for(int k = 2 ; i*k < n ; k++ ) {
                t[i*k] = false ;
            }
        }
    }
    return t;
}

2.6- Matrice symétrique (*) 2.7- Tri à bulles (**) 2.8- Conversion tableau vers entier (**)