Skip to content

Instantly share code, notes, and snippets.

@Riduidel
Created March 26, 2019 15:13
Show Gist options
  • Save Riduidel/4c1fc9ecf00490aad7b46d2942cd48b1 to your computer and use it in GitHub Desktop.
Save Riduidel/4c1fc9ecf00490aad7b46d2942cd48b1 to your computer and use it in GitHub Desktop.
Un exemple de transformation en nombre romain
public class Converter {
private static class Bound {
public final int number;
public final char symbol;
public Bound(int number, char symbol) {
super();
this.number = number;
this.symbol = symbol;
}
}
private Bound from;
private Bound through;
private Bound to;
private int increment;
private Converter next;
public Converter from(int i, char c) {
this.from = new Bound(i, c);
this.increment = i;
return this;
}
public Converter through(int i, char c) {
this.through = new Bound(i, c);
return this;
}
public Converter to(int i, char c) {
this.to = new Bound(i, c);
return this;
}
public boolean containsNumber(int currentNumber) {
return currentNumber>=from.number;
}
public Converter next(Converter next) {
this.next = next;
return this;
}
public String doConvert(int number) {
return doConvert(number, new StringBuilder());
}
public String doConvert(int number, StringBuilder builder) {
while(containsNumber(number)) {
if(number>=to.number) {
number -= to.number;
builder.append(to.symbol);
} else if(number>=to.number-increment) {
number -= to.number-increment;
builder.append(from.symbol).append(to.symbol);
} else if(number>=through.number) {
number -= through.number;
builder.append(through.symbol);
} else if(number>=through.number-increment) {
number -= through.number-increment;
builder.append(from.symbol).append(through.symbol);
} else {
number -= from.number;
builder.append(from.symbol);
}
}
if(next!=null) {
return next.doConvert(number, builder);
} else {
return builder.toString();
}
}
public static String convert(int number) {
Converter converter = new Converter()
.from(100, 'C')
.through(500, 'D')
.to(1000, 'M')
.next(new Converter()
.from(10, 'X')
.through(50, 'L')
.to(100, 'C')
.next(new Converter()
.from(1, 'I')
.through(5, 'V')
.to(10, 'X')));
return converter.doConvert(number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment