Unité IN3S02 - TD3
Corrigé
2.1- Tableau inverse (*)
public static void inverse(int[] t) {
int x ;
int j ;
for(int i = 0 ; i <
(t.length)/2 ; i++ ) {
j =
t.length - i - 1 ;
x = t[i];
t[i]
= t[j];
t[j]
= x ;
}
}
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 (*)
/**
* @param String s : characters not in ['a', 'z'] are
* interpreted as non
letters and are ignored
*/
public static boolean isPalindrome(String s) {
char[] t = s.toCharArray() ;
boolean ok = true ;
int iLeft = 0 ;
int iMiddle = t.length / 2 ;
int iRight = t.length - 1 ;
do {
if ('a'<=t[iLeft] &&
t[iLeft]<='z') {
if
('a'<=t[iRight] && t[iRight]<='z') {
ok = t[iLeft]==t[iRight] ;
iLeft++;
iRight--;
} else {
iRight--;
}
} else {
iLeft++;
}
} while (ok && iLeft<iMiddle &&
iMiddle<iRight);
return ok ;
}
2.4- Horner (*)
public static double
evalPolynom(double[] p, double x) {
double value = 0 ;
for(int i = p.length - 1 ; i >= 0 ; i--) {
value = value*x + p[i] ;
}
return value ;
}
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 (*)
public static boolean
isSymetric(int[][] t) {
boolean ok = true ;
for(int i = 0 ; i < t.length && ok ; i++
)
for(int j = 0 ; j < t[0].length && ok ;
j++)
ok = t[i][j]==t[j][i] ;
return ok ;
}
2.7- Tri à bulles (**)
public static void
bubbleSort(double[] t) {
double x ;
int i, j ;
for(i = 0; i < t.length ; i++) {
for(j = t.length-1 ; j > i ;
j--) {
if (t[j]
< t[j-1]) {
x = t[j] ;
t[j] = t[j-1] ;
t[j-1] = x ;
}
}
}
}
2.8- Conversion tableau vers entier (**)
public static int toInt(char[]
t) {
boolean isNegative = t[0]=='-' ;
int result = 0 ;
int i = 0 ;
if (t[0]=='+' || t[0]=='-') i = 1 ;
for( ; i<t.length; i++) {
result = result * 10 + (int)t[i]
- (int)'0' ;
}
if (isNegative) result = -result ;
return result ;
}