Skip to content

Instantly share code, notes, and snippets.

@charlesdarkwind
Created October 12, 2018 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesdarkwind/978f7cb6a7127db50ac7b5a0d339ee76 to your computer and use it in GitHub Desktop.
Save charlesdarkwind/978f7cb6a7127db50ac7b5a0d339ee76 to your computer and use it in GitHub Desktop.
Initialisation a l'algorithmique Java
package exercice1;
import java.util.ArrayList;
import java.util.stream.IntStream;
public class Exercice1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, -2, -3};
System.out.println("Somme de tout les entiers: \t\t" + getSum(arr));
System.out.println("Valeur maximum: \t\t\t" + getMax(arr));
System.out.println("Nombre d'entiers negatifs: \t\t" + getNegativeCount(arr));
System.out.println("Nombres qui survennant plus d'une fois: " + afficherDoublons(arr));
System.out.println("Le mot kayak est-il un palindrome?: \t" + isPalindrome("kayak"));
System.out.println("X a la puissance N donne: ");
puissance(4, -3);
}
// 1. Retourner somme des entiers d'un tableau.
public static int sum(int[] arr) {
int sum = 0;
for (int val : arr) sum += val;
return sum;
}
// Version courte
public static int getSum(int[] arr) { return IntStream.of(arr).sum(); }
// 2. Retourne la plus grande valeur d'un tableau
public static int max(int[] arr) {
int max = arr[0];
for (int val : arr) if (val > max) max = val;
return max;
}
// Version courte
public static int getMax(int[] arr) { return IntStream.of(arr).max().getAsInt(); }
// 3. Retourner nombre d'entiers negatifs d'un tableau
public static int getNegativeCount(int[] arr) {
return Math.toIntExact(IntStream.of(arr).filter(val -> val < 0).count());
}
// 4. Retourner index du dernier entier pair d'un tableau ou -1
public static int getLastIntIndex(int[] arr) {
int last = -1;
for (int val : arr) {
if (val % 2 == 0) {
last = val;
}
}
return last;
}
// 5. Afficher doublons (returns actual list)
public static ArrayList<Integer> afficherDoublons(int[] arr) {
ArrayList<Integer> res = new ArrayList<>();
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
res.add(arr[i]);
}
}
return res;
}
// 6. Est un palindrome? (Takes an actual string)
public static boolean isPalindrome(String mot) {
for (int i = 0; i < mot.length() / 2; i++) {
if (mot.charAt(i) != mot.charAt(mot.length() - (1 + i))) {
return false;
}
}
return true;
}
// 7. Retourner x a la puissance n
public static void puissance(int x, int n) {
if (n == 0) {
System.out.println(1);
} else if (n == 1) {
System.out.println(x);
} else {
int y = x;
for (int i = 1; i < n; i++) {
y = y * x;
}
System.out.println(n > 0 ? y : (float) 1 / y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment