begin process at 2008 08 28 15:45:02
1 233 196 membres
298 nouveaux aujourd'hui
14 291 membres club

Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum.
Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

ROMANOP : UN UTILITAIRE POUR LES NOMBRES ROMAINS (CONVERSION ROMAN -> ENTIERS, ENTIERS -> ROMAINS, CALCULS...)


Information sur la source

Catégorie :Maths et Algorithmes Classé sous : nombres, romain, calculs, conversion, entier Niveau : Débutant Date de création : 03/06/2008 Date de mise à jour : 04/06/2008 11:39:02 Vu / téléchargé: 1 723 / 45

Note :
Aucune note

Commentaire sur cette source (5)
Ajouter un commentaire et/ou une note

Description

Voici une utilitaire sur les nombres romains. Il permet la conversion de nombres romains vers les entiers et inversement.

Il dispose aussi d'un méthode calc() qui prend deux chaines de caractères représentant deux nombres romains et un char correspondant à l'opérateur. Il retourne le résultat sous la forme d'une chaine de caractère représentant le résultat du calcul sous forme romaine.

Cette classe est facilement utilisable pour tout code manipulant les nombres romains.

Un class Main est incluse pour vous aider à comprendre son fonctionnement.

Source

  • package romanop;
  • import java.util.*;
  • /**
  • * @author Delache Michaël
  • */
  • public class RomanOp {
  • private static final List<String> keys = new ArrayList<String>();
  • private static final List<Integer> values = new ArrayList<Integer>();
  • /**
  • * Constructor of the RomanCalc class, initializes the two tables
  • */
  • public RomanOp() {
  • keys.add("M");
  • values.add(1000);
  • keys.add("CM");
  • values.add(900);
  • keys.add("D");
  • values.add(500);
  • keys.add("CD");
  • values.add(400);
  • keys.add("C");
  • values.add(100);
  • keys.add("XC");
  • values.add(90);
  • keys.add("L");
  • values.add(50);
  • keys.add("XL");
  • values.add(40);
  • keys.add("X");
  • values.add(10);
  • keys.add("IX");
  • values.add(9);
  • keys.add("V");
  • values.add(5);
  • keys.add("IV");
  • values.add(4);
  • keys.add("I");
  • values.add(1);
  • }
  • /**
  • * Convert Roman to int
  • * @param s Roman number
  • * @return An int representing the roman number
  • */
  • public int toInt(final String s) {
  • int res = 0;
  • int size = s.length();
  • String tmp = "";
  • if (size == 1) {
  • res = this.getInt(s);
  • }
  • if (size == 2) {
  • if (keys.contains(s)) {
  • res = this.getInt(s);
  • }
  • else {
  • res += this.toInt(s.substring(0,1));
  • res += this.toInt(s.substring(1,2));
  • }
  • }
  • if (size > 2) {
  • if (keys.contains(tmp = s.substring(size-2, size))) {
  • res += this.getInt(tmp);
  • res += this.toInt(s.substring(0, size-2));
  • }
  • else {
  • tmp = s.substring(size-1, size);
  • res += this.getInt(tmp);
  • res += this.toInt(s.substring(0, size-1));
  • }
  • }
  • return res;
  • }
  • /**
  • * Returns the integer value of the roman value given by <i>s</i> or 0 if <i>s</i> is not in the table
  • */
  • public int getInt(final String s) {
  • int res = 0;
  • for (String str : keys) {
  • if (str.equals(s)) {
  • int index = keys.indexOf(str);
  • res = values.get(index);
  • }
  • }
  • return res;
  • }
  • /**
  • * Converts integer value into roman value
  • * @param i the integer to convert
  • * @return a string representing the roman value
  • */
  • public String toRoman(final int i) {
  • int cpt = i;
  • String res = "";
  • while (cpt > 0) {
  • for (int j : values) {
  • if ((cpt/j) >= 1) {
  • int index = values.indexOf(j);
  • res += keys.get(index);
  • cpt -= j;
  • break;
  • }
  • }
  • }
  • return res;
  • }
  • /**
  • * Calculates the result of the operation determined by the two operands and the operator
  • * @param x operand 1
  • * @param y operand 2
  • * @param op operator
  • * @return the result
  • */
  • public String calc (final String x, final String y, final char op) {
  • if (this.isOk(x) && this.isOk(y)) {
  • int x1 = this.toInt(x);
  • int y1 = this.toInt(y);
  • switch (op) {
  • case '+' :
  • return this.toRoman(x1 + y1);
  • case '-' :
  • return this.toRoman(x1 - y1);
  • case '*' :
  • return this.toRoman(x1 * y1);
  • case '/' :
  • return this.toRoman(x1 / y1);
  • default :
  • break;
  • }
  • }
  • return null;
  • }
  • /**
  • * Says if the roman value given by <i>s</i> respect the roman value syntax
  • * @param s the roman value to verify
  • * @return true if <i>s</i> is correctly formed according to the roman value syntax (ie IV for 4 and not IIII), false else
  • */
  • public Boolean isOk(final String s) {
  • int i = this.toInt(s);
  • String str = this.toRoman(i);
  • return s.equals(str);
  • }
  • }
package romanop;

import java.util.*;

/**
 * @author Delache Michaël
 */
public class RomanOp {
	private static final List<String> keys = new ArrayList<String>();
	private static final List<Integer> values = new ArrayList<Integer>();
	
	/**
	 * Constructor of the RomanCalc class, initializes the two tables
	 */
	public RomanOp() {
		keys.add("M");
		values.add(1000);
		keys.add("CM");
		values.add(900);
		keys.add("D");
		values.add(500);
		keys.add("CD");
		values.add(400);
		keys.add("C");
		values.add(100);
		keys.add("XC");
		values.add(90);
		keys.add("L");
		values.add(50);
		keys.add("XL");
		values.add(40);
		keys.add("X");
		values.add(10);
		keys.add("IX");
		values.add(9);
		keys.add("V");
		values.add(5);
		keys.add("IV");
		values.add(4);
		keys.add("I");
		values.add(1);
	}
	/**
	 * Convert Roman to int
	 * @param s Roman number
	 * @return An int representing the roman number
	 */
	
	public int toInt(final String s) {
		int res = 0;
		int size = s.length();
		String tmp = "";
		if (size == 1) {
			res = this.getInt(s);
		}
		if (size == 2) {
			if (keys.contains(s)) {
				res = this.getInt(s);
			}
			else {
				res += this.toInt(s.substring(0,1));
				res += this.toInt(s.substring(1,2));
			}
		}
		if (size > 2) {
			if (keys.contains(tmp = s.substring(size-2, size))) {
				res += this.getInt(tmp);
				res += this.toInt(s.substring(0, size-2));
			}
			else {
				tmp = s.substring(size-1, size);
				res += this.getInt(tmp);
				res += this.toInt(s.substring(0, size-1));
			}
		}
		return res;
	}
	
	/**
	 * Returns the integer value of the roman value given by <i>s</i> or 0 if <i>s</i> is not in the table
	 */
	public int getInt(final String s) {
		int res = 0;
		for (String str : keys) {
			if (str.equals(s)) {
				int index = keys.indexOf(str);
				res = values.get(index);
			}
		}
		return res;
	}
	
	/**
	 * Converts integer value into roman value
	 * @param i the integer to convert
	 * @return a string representing the roman value
	 */
	public String toRoman(final int i) {
		int cpt = i;
		String res = "";
		while (cpt > 0) {
			for (int j : values) {
				if ((cpt/j) >= 1) {
					int index = values.indexOf(j);
					res += keys.get(index);
					cpt -= j;
					break;
				}
			}
		}
		return res;
	}
	
	/**
	 * Calculates the result of the operation determined by the two operands and the operator
	 * @param x operand 1
	 * @param y operand 2
	 * @param op operator
	 * @return the result
	 */
	public String calc (final String x, final String y, final char op) {
		if (this.isOk(x) && this.isOk(y)) {
			int x1 = this.toInt(x);
			int y1 = this.toInt(y);
			switch (op) {
				case '+' :
					return this.toRoman(x1 + y1);
				case '-' :
					return this.toRoman(x1 - y1);
				case '*' :
					return this.toRoman(x1 * y1);
				case '/' :
					return this.toRoman(x1 / y1);
				default :
					break;
			}
		}
		return null;
	}
	
	/**
	 * Says if the roman value given by <i>s</i> respect the roman value syntax
	 * @param s the roman value to verify
	 * @return true if <i>s</i> is correctly formed according to the roman value syntax (ie IV for 4 and not IIII), false else
	 */
	public Boolean isOk(final String s) {
		int i = this.toInt(s);
		String str = this.toRoman(i);
		return s.equals(str);
	}
	
}

Conclusion

Bien évidemment, vous êtes entièrement libre (et même encouragés) de modifier/copier/distribuer ce source.

Si vous voyez des améliorations et/ou bugs dans ce code, je vous invite à me prévenir par email.

Vous pourrez récupérer, ci-joint, un fichier zip contenant les dossier src (source) et doc (Documentation Java) ainsi qu'un fichier jar exécutable.
Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

03 juin 2008 15:19:38 :
Modification des modificateurs pour les attributs keys et values afin de les rendre static
03 juin 2008 16:39:01 :
Modification du code de la méthode calc. Tests "if" remplacés par un switch
04 juin 2008 11:38:32 :
Modifications mineures dont quelques appels non statiques changés en appels statiques vers les attributs keys et values de la classe RomanOp
04 juin 2008 11:39:02 :
Modifications mineures dont quelques appels non statiques changés en appels statiques vers les attributs keys et values de la classe RomanOp
  • signaler à un administrateur
    Commentaire de nosferaltu0 le 03/06/2008 15:01:34

    Tu ferais mieux d'utiliser une Hashtable plutôt que des ArrayList ce serait plus performant. Tu dois d'ailleur pouvoir la rendre static et final.
    private static final Hashtable<String, Integer> chiffres_romain = new Hashtable<String, Integer>();

  • signaler à un administrateur
    Commentaire de vladmanchev le 03/06/2008 15:12:04

    Le problème avec les HashTable c'est que l'ordre n'est pas défini.

    Si tu regardes bien le code de la fonction toRoman, tu verras que ça ne peut pas fonctionner avec une HashTable (puisque les valeurs ne seraient pas dans le bon ordre).

    Mais si je change le code de cette fonction pour mettre une HashTable, je ne sais pas si je gagnerais vraiment en performance.

    As-tu une solution qui améliorerait la performance du code à me proposer?

  • signaler à un administrateur
    Commentaire de vladmanchev le 03/06/2008 15:14:28

    Par contre, effectivement, il me parait raisonnable de changer les modificateurs des atributs keys et values de façon à les rendre static et final.

  • signaler à un administrateur
    Commentaire de nosferaltu0 le 03/06/2008 15:37:52

    Tu peux utiliser un tableau de String :
    private static final chiffres={"M","CM",..};
    et c'est ce tableau que tu parcours. Le string te permet d'accéder à la valeur de l'élément grâce à la hashtable.
    Je pense qu'au niveau complexité c'est mieux.

    On pourrait aussi parcourir le nombre de droite à gauche mais comme j'y vois je ne pense pas que ce serait mieux.

  • signaler à un administrateur
    Commentaire de vladmanchev le 03/06/2008 15:57:23

    D'accord.

    Mais il existe un autre problème.

    Etant donné que je dois parcourir (dans le bon ordre) les valeurs (int dans l'arraylist values) dans la méthode toRoman() et les clés (strings dans n'importe quel ordre, ceux-là) dans la méthode toInt() je n'y vois pas d'améliorations concrètes si ce n'est au niveau du temps d'accès. Mais je pense que cela ajouterait de la complexité au code (complexité au niveau codage pas calcul) pour pas grand chose.

Ajouter un commentaire

Pub



Appels d'offres

Recherche developpeur ...
Budget : 700€
SITE MARCHAND LOCATION...
Budget : 3 000€
SITE MARCHAND POUR HOTEL
Budget : 4 000€

CalendriCode

Août 2008
LMMJVSD
    123
45678910
11121314151617
18192021222324
25262728293031

Téléchargements

Logiciels à télécharger sur le même thème :

Boutique

Boutique de goodies CodeS-SourceS