Foros del Web » Programando para Internet » PHP »

Códigos - Reto Romanos

Estas en el tema de Códigos - Reto Romanos en el foro de PHP en Foros del Web. abimaelrc @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código PHP: Ver original <?php function romanNumber ( $number ) {     // Array que contiene los valores númericos, tanto romanos ...
  #1 (permalink)  
Antiguo 20/08/2010, 20:43
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Códigos - Reto Romanos

abimaelrc

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($number){
  3.     // Array que contiene los valores númericos, tanto romanos como los regulares
  4.     $arr = array(
  5.         array(1, 'I'),
  6.         array(5, 'V'),
  7.         array(10, 'X'),
  8.         array(50, 'L'),
  9.         array(100, 'C'),
  10.         array(500, 'D'),
  11.         array(1000, 'M'),
  12.         array(5000, '<span style="text-decoration: overline">V</span>'),
  13.         array(10000, '<span style="text-decoration: overline">X</span>'),
  14.         array(50000, '<span style="text-decoration: overline">L</span>'),
  15.         array(100000, '<span style="text-decoration: overline">C</span>'),
  16.         array(500000, '<span style="text-decoration: overline">D</span>'),
  17.         array(1000000, '<span style="text-decoration: overline">M</span>'),
  18.     );
  19.  
  20.     // rN -> romanNumber
  21.     $rN = '';
  22.  
  23.     // Convertir el valor a string (otra forma de hacerlo es $num = (string)$number;
  24.     $num = "$number";
  25.  
  26.     while(true){
  27.  
  28.         //Solamente verificar los valores que sean mayores de 0
  29.         if($num[0] > 0){
  30.             foreach($arr as $key => $roman){
  31.  
  32.                 // Verifica que el valor del array sea mayor o igual al valor númerico
  33.                 if($roman[0] >= $num){
  34.  
  35.                     // Asigna el valor del array, si el número está entre los valores del array
  36.                     if($roman[0] == $num){ $rN .= $roman[1]; }
  37.  
  38.                     // Si el valor del primer caracter es menor o igual a 3, asigna el valor del array anterior en donde
  39.                     // se encuentre en el bucle por la cantidad de veces que dé el primer caracter
  40.                     elseif($num[0] <= 3){ $rN .= str_repeat($arr[$key - 1][1], $num[0]); }
  41.  
  42.                     // Si el valor del primer caracter es igual a 4, asigna el valor del array anterior primero y el valor que
  43.                     // está en el momento del bucle
  44.                     elseif($num[0] == 4){ $rN .= $arr[$key - 1][1] . $roman[1]; }
  45.  
  46.                     // Si el valor del primer caracter es menor o igual a 8, asigna el valor del array anterior y del que
  47.                     // está antes del anterior, por la cantidad de veces del residuo  de $num[0] - 5
  48.                     elseif($num[0] <= 8){ $rN .= $arr[$key - 1][1] . str_repeat($arr[$key - 2][1], ($num[0] - 5)); }
  49.  
  50.                     // Si el valor del primer caracter es igual a 9, asigna el valor del array del que está antes del anterior
  51.                     // y del valor que está en el momento del bucle
  52.                     elseif($num[0] == 9){ $rN .= $arr[$key - 2][1] . $roman[1]; }
  53.  
  54.                     // Evitar que continúe ya que encontró el valor
  55.                     break;
  56.                 }
  57.             }
  58.         }
  59.  
  60.         // Quita el primer caracter del valor de lo que esté en la variable $num al momento,
  61.         // y así continúa con el proceso hasta que no queda valor
  62.         $num = substr($num, 1);
  63.  
  64.         //Verifica si ya no existe algún valor en la variable $num
  65.         if(empty($num)) break;
  66.     }
  67.  
  68.     return $rN;
  69. }
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #2 (permalink)  
Antiguo 20/08/2010, 20:44
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Códigos - Reto Romanos

Alcalina

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($num) {
  3.   if ($num<1 || $num>10000) {return "&infin;";}
  4.   else
  5.   {
  6.     // Cadena a devolver
  7.     $resultado = "";
  8.     // Eliminamos decimales
  9.     $num = intval($num);
  10.     // Creamos el array con los numeros romanos, lo escribimos de mayor a menor porque orden de miles,centenas,decenas,unidades.
  11.     $romanos = array (1000=>"M",900=>"CM",500=>"D",400=>"CD",100=>"C",90=>"XC",50=>"L",40=>"XL",10=>"X",9=>"IX",5=>"V",4=>"IV",1=>"I");
  12.     // Vamos recorriendo el vector con el numero que nos han pasado
  13.     foreach ($romanos as $numero => $romano)
  14.     {
  15.       // Dividimos para encontrar coincidencias entre el numero que nos han pasado y el vector, y eliminamos decimales
  16.       $coincidencias = intval($num/$numero);
  17.       // Escribimos en el resultado el numero de coincidencias que hemos encontrado en el numero
  18.       $resultado .= str_repeat($romano, $coincidencias);
  19.       // Le restamos el numero ya traspasado a romano
  20.       $num = $num % $numero;
  21.     }
  22.     // Devolvemos el resultado
  23.     return $resultado;
  24.   }
  25. }
  26. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #3 (permalink)  
Antiguo 20/08/2010, 20:45
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Códigos - Reto Romanos

angelAparicio

Código PHP:
Ver original
  1. <?php
  2.  
  3.     define('CINCOMIL', '<span style="text-decoration: overline">V</span>');
  4.     define('DIEZMIL',  '<span style="text-decoration: overline">X</span>');
  5.            
  6.     function romanNumber($num){
  7.        
  8.         $unidad  = $num % 10;
  9.         $decena  = ($num/10) % 10;
  10.         $centena = ($num/100) % 10;
  11.         $millar  = ($num/1000) % 10;
  12.        
  13.         $array_unidades = array(
  14.             0 => '', 1 => 'I', 2 => 'II', 3 => 'III', 4 => 'IV',
  15.             5 => 'V', 6 => 'VI', 7 => 'VII', 8 => 'VIII', 9 => 'IX'
  16.         );
  17.        
  18.         $array_decenas = array(
  19.             0 => '', 1 => 'X', 2 => 'XX', 3 => 'XXX', 4 => 'XL',
  20.             5 => 'L', 6 => 'LX', 7 => 'LXX', 8 => 'LXXX', 9 => 'XC'
  21.         );
  22.        
  23.         $array_centenas = array(
  24.             0 => '', 1 => 'C', 2 => 'CC', 3 => 'CCC', 4 => 'CD',
  25.             5 => 'D', 6 => 'DC', 7 => 'DCC', 8 => 'DCCC', 9 => 'CM'
  26.         );
  27.        
  28.         $array_millar = array(
  29.             0 => '', 1 => 'M', 2 => 'MM', 3 => 'MMM', 4 => 'M'.CINCOMIL,
  30.             5 => CINCOMIL, 6 => CINCOMIL.'M', 7 => CINCOMIL.'MM', 8 => CINCOMIL.'MMM', 9 => 'M'.DIEZMIL
  31.         );
  32.        
  33.         $num = $array_millar[$millar] . $array_centenas[$centena] . $array_decenas[$decena] . $array_unidades[$unidad];
  34.        
  35.         return $num;
  36.     }
  37.  
  38. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #4 (permalink)  
Antiguo 20/08/2010, 20:46
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

carlos_belisario

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($number){
  3.     $romano=array("I","V","X","L","C","D","M","<span style='text-decoration: overline;'>V</span>","<span style='text-decoration: overline;'>X</span>","<span style='text-decoration: overline;'>L</span>","<span style='text-decoration: overline;'>C</span>","<span style='text-decoration: overline;'>D</span>","<span style='text-decoration: overline;'>M</span>");    
  4.     $nume=str_split($number);
  5.     $g=0;            
  6.     for($x=count($nume)-1;$x>=0;$x--){
  7.         $num[$g]=$nume[$x];
  8.         $g++;
  9.     }    
  10.     for($i=0;$i<count($num);$i++){                                
  11.         if($num[$i]>0 && $num[$i]<4){                
  12.             $id=$i+$i;                                                                    
  13.         for($k=0;$k<$num[$i];$k++)                            
  14.             $romanNumber=$romano[$id].$romanNumber;                            
  15.     }
  16.     elseif($num[$i]>3 && $num[$i]<9){
  17.         $id=$i+1;                
  18.         if ($num[$i]<5){
  19.             $id=$id+$i;                                        
  20.             $romanNumber=$romano[$id-1].$romano[$id].$romanNumber;
  21.         }    
  22.         else{                        
  23.             $id=$id+$i;
  24.             $principio=$romano[$id];            
  25.             $numero=$num[$i]-5;                
  26.             for($l=1;$l<=$numero;$l++)                    
  27.                 $principio.=$romano[$id-1];                                
  28.             $romanNumber=$principio.$romanNumber;                
  29.         }                
  30.     }
  31.     elseif($num[$i]==9 || $num[$i]==0){
  32.         $id=($i+1)*2;        
  33.         if($num[$i]==9)                
  34.             $romanNumber=$romano[$id-2].$romano[$id].$romanNumber;}
  35.         else                        
  36.             continue;                    
  37.     }
  38.     return $romanNumber;
  39. }?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #5 (permalink)  
Antiguo 20/08/2010, 20:47
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

dedydamy

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($entrada) {
  3. if ($entrada <0 || $entrada >9999) {return -1;}
  4. $primero = array(1=>"I", 2=>"II", 3=>"III", 4=>"IV", 5=>"V", 6=>"VI", 7=>"VII", 8=>"VIII", 9=>"IX");
  5. $segundo = array(1=>"X", 2=>"XX", 3=>"XXX", 4=>"XL", 5=>"L", 6=>"LX", 7=>"LXX", 8=>"LXXX", 9=>"XC");
  6. $tercero = array(1=>"C", 2=>"CC", 3=>"CCC", 4=>"CD", 5=>"D", 6=>"DC", 7=>"DCC", 8=>"DCCC", 9=>"CM");
  7. $cuarto = array(1=>"M", 2=>"MM", 3=>"MMM", 4=>"MMMM", 5=>"MMMMM", 6=>"MMMMMM", 7=>"MMMMMMM", 8=>"MMMMMMMM", 9=>"MMMMMMMMM");
  8. $unos = $entrada % 10;
  9. $diezes = ($entrada - $unos) % 100;
  10. $cientos = ($entrada - $diezes - $unos) % 1000;
  11. $cmolvido = ($entrada - $cientos - $diezes - $unos) % 10000;
  12. $diezes = $diezes / 10;
  13. $cientos = $cientos / 100;
  14. $cmolvido = $cmolvido / 1000;
  15. if ($cmolvido) {$salida .= $cuarto[$cmolvido];}
  16. if ($cientos) {$salida .= $tercero[$cientos];}
  17. if ($diezes) {$salida .= $segundo[$diezes];}
  18. if ($unos) {$salida .= $primero[$unos];}
  19. return $salida;
  20. }
  21. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #6 (permalink)  
Antiguo 20/08/2010, 20:49
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

exangel

Código PHP:
Ver original
  1. <form action="romanos.php" method="post">
  2.     <input name="elnumero" type="text"><input name="" type="submit" value="enviar" maxlength="4">
  3. </form>
  4. <?php
  5. $elnumero_tx="";
  6. if(isset($_POST["elnumero"])){
  7.     if($_POST["elnumero"]!="" && is_numeric($_POST["elnumero"]) && intval($_POST["elnumero"])<10000){
  8.         $elnumero_tx=strval($_POST["elnumero"]);
  9.     }
  10. }
  11.  
  12. $entradas=array(1 => "I",
  13.                 2 => "II",
  14.                 3 => "III",
  15.                 4 => "IV",
  16.                 5 => "V",
  17.                 6 => "VI",
  18.                 7 => "VII",
  19.                 8 => "VIII",
  20.                 9 => "IX",
  21.                 10 => "X",
  22.                 40 => "XL",
  23.                 50 => "L",
  24.                 90 => "XC",
  25.                 100 => "C",
  26.                 400 => "CD",
  27.                 500 => "D",
  28.                 900 => "CM",
  29.                 1000 => "M"
  30.                 );
  31.                
  32. if($elnumero_tx!=""){
  33.     echo "<br>NÚMERO RECIBIDO: <strong>".$elnumero_tx."</strong><br>LA CONVERSIÓN A ROMANOS: <strong>";
  34.     if(strlen($elnumero_tx)==4) $num4=intval(substr($elnumero_tx,0,1));
  35.    
  36.     if(strlen($elnumero_tx)==3) $num3=intval(substr($elnumero_tx,0,1));
  37.     if(strlen($elnumero_tx)==4) $num3=intval(substr($elnumero_tx,1,1));
  38.    
  39.     if(strlen($elnumero_tx)==2) $num2=intval(substr($elnumero_tx,0,1));
  40.     if(strlen($elnumero_tx)==3) $num2=intval(substr($elnumero_tx,1,1));
  41.     if(strlen($elnumero_tx)==4) $num2=intval(substr($elnumero_tx,2,1));
  42.    
  43.     if(strlen($elnumero_tx)==1) $num1=intval(substr($elnumero_tx,0,1));
  44.     if(strlen($elnumero_tx)==2) $num1=intval(substr($elnumero_tx,1,1));
  45.     if(strlen($elnumero_tx)==3) $num1=intval(substr($elnumero_tx,2,1));
  46.     if(strlen($elnumero_tx)==4) $num1=intval(substr($elnumero_tx,3,1));
  47.    
  48.     if(strlen($elnumero_tx)>3){
  49.         if($num4>0){
  50.             for($h=1;$h<=$num4;$h++){
  51.                 echo $entradas[1000];
  52.             }
  53.         }
  54.    
  55.     }
  56.     if(strlen($elnumero_tx)>2){
  57.         if($num3>0){
  58.             if($num3<4){
  59.                 for($h=1;$h<=$num3;$h++){
  60.                     echo $entradas[100];
  61.                 }
  62.             }else{
  63.                 if($num3==4){
  64.                     echo $entradas[400];
  65.                 }else{
  66.                     if($num3==5){
  67.                         echo $entradas[500];
  68.                     }else{
  69.                         if($num3<=8){
  70.                             echo $entradas[500];
  71.                             for($h=1;$h<=($num3-5);$h++){
  72.                                 echo $entradas[100];
  73.                             }
  74.                         }else{
  75.                             echo $entradas[900];
  76.                         }
  77.                     }
  78.                 }
  79.             }
  80.         }
  81.     }
  82.     if(strlen($elnumero_tx)>1){
  83.         if($num2>0){
  84.             if($num2<4){
  85.                 for($h=1;$h<=$num2;$h++){
  86.                     echo $entradas[10];
  87.                 }
  88.             }else{
  89.                 if($num2==4){
  90.                     echo $entradas[40];
  91.                 }else{
  92.                     if($num2==5){
  93.                         echo $entradas[50];
  94.                     }else{
  95.                         if($num2<=8){
  96.                             echo $entradas[50];
  97.                             for($h=1;$h<=($num2-5);$h++){
  98.                                 echo $entradas[10];
  99.                             }
  100.                         }else{
  101.                             echo $entradas[90];
  102.                         }
  103.                     }
  104.                 }
  105.             }
  106.         }
  107.     }
  108.     if($num1>0) echo $entradas[$num1];
  109.     echo "</strong>";
  110. }
  111. ?>
  112. <br /><br />
  113. <a href="romanos.zip">DESCARGAR PHP</a>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #7 (permalink)  
Antiguo 20/08/2010, 20:51
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

HackmanC

Código PHP:
Ver original
  1. <?php
  2. /*
  3.  *  Class : RomanEncoder
  4.  *  Clase para convertir números arábigos decimales en representación romana.
  5.  *  Versión 1 (PHP)
  6.  */
  7. class RomanEncoder {
  8.    
  9.     public $divs = Array(
  10.          1000000 =>  "m",
  11.           900000 => "cm",
  12.           500000 =>  "d",
  13.           400000 => "cd",
  14.           100000 =>  "c",
  15.            90000 => "xc",
  16.            50000 =>  "l",
  17.            40000 => "xl",
  18.            10000 =>  "x",
  19.             9000 => "Mx",
  20.             5000 =>  "v",
  21.             4000 => "Mv",
  22.             1000 =>  "M",
  23.              900 => "CM",
  24.              500 =>  "D",
  25.              400 => "CD",
  26.              100 =>  "C",
  27.               90 => "XC",
  28.               50 =>  "L",
  29.               40 => "XL",
  30.               10 =>  "X",
  31.                9 => "IX",
  32.                5 =>  "V",
  33.                4 => "IV",
  34.                1 =>  "I"
  35.     );
  36.    
  37.     /*
  38.      *  El método es repetir cada letra o conjunto de letras tantas veces
  39.      *  como la  división entera del número entre el valor de la letra,
  40.      *  mientras se va reduciendo el número al residuo en cada ciclo.
  41.      */
  42.     public function encodeRomanNumber($number) {
  43.         $letter = '';
  44.         foreach ($this->divs as $key => $value) {
  45.             $letter .= str_repeat($value, $number / $key);
  46.             $number %= $key;
  47.         }
  48.         return $letter;
  49.     }
  50.    
  51.     private function insertHTMLstyle($letter) {
  52.         $a = '<span class=\'over\'>'; $b = '</span>';
  53.         return preg_replace('/[a-z]+/', $a . '$0' . $b, $letter);
  54.     }
  55.    
  56.     public function romanNumber() {
  57.         $a = '<span class=\'roman\'>'; $b = '</span>'; $r = rand();
  58.         return $a . number_format($r) . ' = ' .
  59.             $this->insertHTMLstyle($this->encodeRomanNumber($r)) . $b;
  60.     }
  61.    
  62. }
  63. ?>
  64. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  65.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  66. <html xmlns="http://www.w3.org/1999/xhtml">
  67. <head>
  68. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  69. <title>Codificaci&oacute;n de N&uacute;meros Romanos</title>
  70. <style type="text/css">
  71. <!--
  72. body { font-family: Courier New, Courier, monospace; font-size: 14px; }
  73. .roman { text-transform: uppercase; }
  74. .over { text-decoration: overline; }
  75. -->
  76. </style>
  77. </head>
  78.  
  79. <body>
  80. <p><?php
  81. $a = new RomanEncoder();
  82. echo $a->romanNumber();
  83. ?>
  84. </p>
  85. </body>
  86. </html>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #8 (permalink)  
Antiguo 20/08/2010, 20:51
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

Hidek1

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($number){
  3.     $a=array('I','V','X','L','C','D','M');
  4.     for($x='',$v=0;(int)$number;$number/=10){
  5.         $n=++$v*2-1;
  6.         $r=$number%10;
  7.         $x=$r==4||$r==9?$a[$n-1].$a[$r<5?$n:$n+1].$x:
  8.         ($r>4?$a[$n]:'').str_repeat($a[$n-1],$r<4?$r:$r-5).$x;
  9.     }
  10.     return$x;
  11. }
  12.  
  13. function romanNumber($number){
  14.     static$a=array('I','V','X','L','C','D','M');
  15.     for($x='',$v=0;(int)$number;$number/=10){
  16.         $n=++$v*2-1;
  17.         $r=$number%10;
  18.         $x=$r==4||$r==9?$a[$n-1].$a[$r<5?$n:$n+1].$x:
  19.         ($r>4?$a[$n]:'').str_repeat($a[$n-1],$r<4?$r:$r-5).$x;
  20.     }
  21.     return$x;
  22. }
  23. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #9 (permalink)  
Antiguo 20/08/2010, 20:52
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

pateketrueke

Código PHP:
Ver original
  1. <?php
  2. function numberRoman($test)
  3. {
  4.   static $dec = array(
  5.     'I' => 1,
  6.     'V' => 5,
  7.     'X' => 10,
  8.     'L' => 50,
  9.     'C' => 100,
  10.     'D' => 500,
  11.     'M' => 1000,
  12.   ), $expand = array(
  13.     'CM' => 'DCCCC',
  14.     'CD' => 'CCCC',
  15.     'XC' => 'LXXXX',
  16.     'XL' => 'XXXX',
  17.     'IX' => 'VIIII',
  18.     'IV' => 'IIII',
  19.   );
  20.  
  21.   $output = 0;
  22.   $expr = strtr(strtoupper($test), $expand);
  23.   foreach (preg_split('//', $expr) as $i) $output += ! empty($dec[$i])? $dec[$i]: 0;
  24.   return $output;
  25. }
  26. function romanNumber($test)
  27. {
  28.   static $dec = array(
  29.     'M' => 1000,
  30.     'CM' => 900,
  31.     'D' => 500,
  32.     'CD' => 400,
  33.     'C' => 100,
  34.     'XC' => 90,
  35.     'L' => 50,
  36.     'XL' => 40,
  37.     'X' => 10,
  38.     'IX' => 9,
  39.     'V' => 5,
  40.     'IV' => 4,
  41.     'I' => 1,
  42.   );
  43.  
  44.   $output = '';
  45.   do
  46.   {
  47.     foreach ($dec as $letter => $num)
  48.     {
  49.       if ($num > $test) continue;
  50.       $output .= $letter;
  51.       $test -= $num;
  52.       break;
  53.     }
  54.   } while ($test > 0);
  55.   return $output;
  56. }
  57. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #10 (permalink)  
Antiguo 20/08/2010, 20:53
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

portalmana

Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * Clase NumerosRomanos.
  4.  * Convierte un numero en base decimal a Romano.
  5.  *
  6.  * @package     matematicas creado para forosdelweb.
  7.  * @copyright   2010 - ObjetivoPHP
  8.  * @license     Gratuito (Free) http://www.opensource.org/licenses/gpl-license.html
  9.  * @author      Marcelo Castro (ObjetivoPHP)
  10.  * @link        [email protected]
  11.  * @version     0.1.0 (16/08/2010 - 16/08/2010)
  12.  */
  13. abstract class NumerosRomanos
  14. {
  15.     /**
  16.      * Contiene las equivalencias de numeros romanos para unidades, decimales,
  17.      * centenas y miles.
  18.      * @var array
  19.      */
  20.     private static  $_romanos =     array(0   =>    array(1 => 'I',
  21.                                                           2 => 'II',
  22.                                                           3 => 'III',
  23.                                                           4 => 'IV',
  24.                                                           5 => 'V',
  25.                                                           6 => 'VI',
  26.                                                           7 => 'VII',
  27.                                                           8 => 'VIII',
  28.                                                           9 => 'IX'),
  29.                                           1    =>   array(1 => 'X',
  30.                                                           2 => 'XX',
  31.                                                           3 => 'XXX',
  32.                                                           4 => 'XL',
  33.                                                           5 => 'L',
  34.                                                           6 => 'LX',
  35.                                                           7 => 'LXX',
  36.                                                           8 => 'LXXX',
  37.                                                           9 => 'XC'),
  38.                                           2   =>    array(1 => 'C',
  39.                                                           2 => 'CC',
  40.                                                           3 => 'CCC',
  41.                                                           4 => 'CD',
  42.                                                           5 => 'D',
  43.                                                           6 => 'DC',
  44.                                                           7 => 'DCC',
  45.                                                           8 => 'DCCC',
  46.                                                           9 => 'CM'),
  47.                                           3 =>      array(1 => 'M',
  48.                                                           2 => 'MM',
  49.                                                           3 => 'MMM'));
  50.  
  51.     /**
  52.      * Contiene los divisores para identificar por donde comenzar la conversion.
  53.      * @var array
  54.      */
  55.     private static $_divisores   = array(1, 10, 100, 1000);
  56.  
  57.     /**
  58.      * Convierte un numero expresado en decimal a notacion Romana.
  59.      * @param   integer $numero Numero que se desea convertir en romano.
  60.      *                  desde 0 a 3999.-
  61.      * @return  string
  62.      */
  63.     public static function romanNumber($numero)
  64.     {
  65.         $retorno = '';
  66.         $max = (int)log10($numero);
  67.         for ($div = $max; $div > -1; $div--) {
  68.             $aux     =  (int)($numero/self::$_divisores[$div]);
  69.             $retorno.= self::$_romanos[$div][$aux];
  70.             $numero -=self::$_divisores[$div]*$aux;
  71.         }
  72.         return $retorno;
  73.     }
  74. }
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #11 (permalink)  
Antiguo 20/08/2010, 20:54
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

quike88

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($num) {
  3.     $romans = array(1=>'I',4=>'IV',5=>'V',9=>'IX',10=>'X',40=>'XL',50=>'L',90=>'XC',100=>'C',400=>'CD',500=>'D',900=>'CM',1000=>'M');
  4.     $romanNumber='';
  5.     $i=10;
  6.     while($num>0) {
  7.         $roman='';
  8.         $rom=$num%$i;
  9.         if($rom!=0){
  10.             if(!isset($romans[$rom])){
  11.                 $romdec=$rom/($i/10);
  12.                 if($romdec<5){
  13.                     for($j=1;$j<=$romdec;$j++)
  14.                         $roman.=$romans[($i/10)];
  15.                 }
  16.                 else {
  17.                     $roman=$romans[5*($i/10)];
  18.                     $romdec-=5;
  19.                     for($j=1;$j<=$romdec;$j++)
  20.                         $roman.=$romans[($i/10)];
  21.                 }
  22.                 $romanNumber=$roman.$romanNumber;
  23.             }
  24.             else        
  25.                 $romanNumber=$romans[$rom].$romanNumber;            
  26.         }
  27.         $num=floor($num/$i)*$i;
  28.         $i*=10;
  29.     }
  30.     return $romanNumber;
  31. }
  32. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #12 (permalink)  
Antiguo 20/08/2010, 20:55
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

silvanha

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($numero){
  3.     $miles = array("","M","MM","MMM");
  4.     $centenas = array("","C","CC","CCC","CD","D","DC","DCC","DCCC","CM");
  5.     $decenas = array("","X","XX","XXX","XL","L","LX","LXX","LXXX","XC");
  6.     $unidades = array("","I","II","III","IV","V","VI","VII","VIII","IX");
  7.     $numero = str_split($numero);
  8.     switch(count($numero)){
  9.         case 1:
  10.             return $unidades[$numero[0]];
  11.         break;
  12.         case 2:
  13.             return $decenas[$numero[0]].$unidades[$numero[1]];          
  14.         break;
  15.         case 3:                        
  16.             return $centenas[$numero[0]].$decenas[$numero[1]].$unidades[$numero[2]];
  17.         break;
  18.         case 4:                                        
  19.             return $miles[$numero[0]].$centenas[$numero[1]].$decenas[$numero[2]]. $unidades[$numero[3]];
  20.         break;
  21.     }      
  22. }
  23. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #13 (permalink)  
Antiguo 20/08/2010, 20:56
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

Triby

Código PHP:
Ver original
  1. <?php
  2. function romanNumber($number) {
  3.     if($number < 0 || $number > 10000)
  4.         return '* error *';
  5.     $spanv = '<span style="border-top:1px #000 solid;">V</span>';
  6.     $spanx = '<span style="border-top:1px #000 solid;">X</span>';
  7.     if($number == 10000)
  8.         return $spanx;
  9.     $romans = array(
  10.         // Unidades
  11.         1 => array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'),
  12.         // Decenas
  13.         2 => array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'),
  14.         // Centenas
  15.         3 => array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'),
  16.         // Millares
  17.         4 => array('', 'M', 'MM', 'MMM', 'MV', $spanv, $spanv . 'M', $spanv . 'MM', $spanv . 'MMM', 'M' . $spanx),
  18.     );
  19.     $rn = '';
  20.     $number = (string)$number;
  21.     $len = strlen($number);
  22.     for($i = $len; $i > 0; $i--)
  23.         $rn .= $romans[$i][$number[$len - $i]];
  24.     return $rn;
  25. }
  26.  
  27. // EOF;
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #14 (permalink)  
Antiguo 20/08/2010, 20:57
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

truman_truman

Código PHP:
Ver original
  1. <?php
  2. // Por truman_truman
  3.  
  4. //asignamos los valores de unidades decenas centenas millar etc
  5. $db = array ( 0 => array(
  6.               1=>"I",
  7.               2=>"II",
  8.               3=>"III",
  9.               4=>"IV",
  10.               5=>"V",
  11.               6=>"VI",
  12.               7=>"VII",
  13.               8=>"VIII",
  14.               9=>"IX"),    
  15.              
  16.          
  17.           1 => array(
  18.               1=>"X",
  19.               2=>"XX",
  20.               3=>"XXX",
  21.               4=>"XL",
  22.               5=>"L",
  23.               6=>"LX",
  24.               7=>"LXX",
  25.               8=>"LXXX",
  26.               9=>"XC"),
  27.          
  28.           2 => array(
  29.                
  30.                1=>"C",
  31.                2=>"CC",
  32.                3=>"CCC",
  33.                4=>"CD",
  34.                5=>"D",
  35.                6=>"DC",
  36.                7=>"DCC",
  37.                8=>"DCCC",
  38.                9=>"CM"),
  39.          
  40.           3 => array(
  41.               1=>"M",
  42.               2=>"MM",
  43.               3=>"MMM",
  44.               4=>"MMMM",
  45.               5=>"MMMMM",
  46.               6=>"MMMMMM",
  47.               7=>"MMMMMMM",
  48.               8=>"MMMMMMMM",
  49.               9=>"MMMMMMMMM"),    
  50.                              
  51.                           );
  52. function romanNumber($numero_aleatorio){
  53.    
  54.  
  55.       //declaro global el array $db
  56.       global $db;
  57.      
  58.       $cifra = $numero_aleatorio;
  59.       //invierto la cadena
  60.       $cifra = strrev($cifra);
  61.       //cuantos caracteres hay en la cadena ingrasada
  62.       $cant_caract = strlen($cifra);
  63.       //separamos el numero
  64.       $numeros = str_split($cifra);
  65.      
  66.      
  67.       //ejecutamos tantas veces como caracteres tenga la cifra
  68.       for ($i=$cant_caract; $i >= 0; $i--){
  69.          //buscamos en los array y
  70.          $rresult .= $db[$i][$numeros[$i]];
  71.      }
  72.      //Imprimimos en pantalla los resultados
  73.      
  74.     echo  "Numero Aleatorio: <b>".$numero_aleatorio."</b>";
  75.     echo "<br />";
  76.     echo "Numero Romano: <b>".$rresult."</b>";
  77.     echo "<br /><br /><br />";
  78.     echo "<b>Recargue la pagina para ver mas resultados...!!!</b>";
  79.     return $rresult;
  80. }
  81.  
  82.  
  83.  
  84. //Llamamos a la funcion a ver que pasa...!!!!
  85.        $numero_aleatorio = rand(1,1000);
  86.      romanNumber($numero_aleatorio);
  87. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #15 (permalink)  
Antiguo 20/08/2010, 21:06
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

mortiprogramador

Código PHP:
Ver original
  1. <?php
  2. class Roman
  3. {
  4.     var $cant;
  5.     var $roman_number;
  6.     var $array_number;
  7.     var $expression;
  8.     var $roman_ant_number = array(
  9.                                 '1'=>'I',
  10.                                 '5'=>'V',
  11.                                 '10'=>'X',
  12.                                 '50'=>'L',
  13.                                 '100'=>'C',
  14.                                 '500'=>'D',
  15.                                 '1000'=>'M',
  16.                                 '5000'=>'<span style="text-decoration: overline">V</span>',
  17.                                 '10000'=>'<span style="text-decoration: overline">X</span>',
  18.                                 '50000'=>'<span style="text-decoration: overline">L</span>',
  19.                                 '100000'=>'<span style="text-decoration: overline">C</span>',
  20.                                 '500000'=>'<span style="text-decoration: overline">D</span>',
  21.                                 '1000000'=>'<span style="text-decoration: overline">M</span>'
  22.                             );                    
  23.    
  24.     function _construct()
  25.     {
  26.         setNum();
  27.     }
  28.    
  29.     //Get a rand number
  30.     function setNum()
  31.     {
  32.         $this->num = rand(0,10000);
  33.         return $this->num;
  34.     }
  35.    
  36.     function addRoman($times,$pos)
  37.     {
  38.         $add='';
  39.         for($i = 1; $i<=$times; $i++)
  40.         {
  41.             $add.=$pos;
  42.         }
  43.         return $add;
  44.     }
  45.    
  46.     function romanNumber($num)
  47.     {
  48.         $this->expression = '//';
  49.         $this->array_number = preg_split($this->expression,trim($num),-1,PREG_SPLIT_NO_EMPTY);
  50.         switch ($num)
  51.         {
  52.             case 0:
  53.             break;
  54.             case $num > 0:
  55.                 //total of chars
  56.                 $this->cant = count($this->array_number) - 1;
  57.                 //cant to subtraction
  58.                 $min = $this->array_number[0].str_repeat(0,$this->cant);
  59.                 $num -= $min;
  60.                 $pos = '1'.str_repeat(0,$this->cant);
  61.                 if( $this->cant > 0 )
  62.                 {
  63.                     if( $this->array_number[0] > 3 )
  64.                     {
  65.                         $pos *= $this->array_number[0];
  66.                     }
  67.                    
  68.                     $pos4 = $this->array_number[0].'4';
  69.                     $pos9 = $this->array_number[0].'9';
  70.                 }
  71.                 else
  72.                 {
  73.                     $pos4 ='4';
  74.                     $pos9 = '9';
  75.                 }    
  76.                 $next = '1'.str_repeat(0,$this->cant + 1);
  77.                 if( strlen($min) > 1 && $min == '1'.str_repeat(0,$this->cant))
  78.                 {
  79.                     $this->roman_number .= $this->roman_ant_number[$pos];
  80.                 }
  81.                 if( strlen($min) > 1 && $min >= '4'.str_repeat(0,$this->cant))
  82.                 {
  83.                     if( $pos == '4'.str_repeat(0,$this->cant ))
  84.                     {
  85.                         $this->roman_number .= $this->roman_ant_number[$pos-(('1'.str_repeat(0,$this->cant))*3)].$this->roman_ant_number[$pos+10];
  86.                     }
  87.                     if( $pos == '5'.str_repeat(0,$this->cant ))
  88.                     {
  89.                         $this->roman_number .= $this->roman_ant_number[$pos];
  90.                     }
  91.                     if( $pos > '5'.str_repeat(0,$this->cant) && $pos < '9'.str_repeat(0,$this->cant))
  92.                     {
  93.                         $times = substr($pos-('5'.str_repeat(0,$this->cant)),0,1);
  94.                         $this->roman_number .= $this->roman_ant_number['5'.str_repeat(0,$this->cant)].$this->addRoman($times, $this->roman_ant_number[('1'.str_repeat(0,$this->cant))]);
  95.                     }
  96.                     if( $pos == '9'.str_repeat(0,$this->cant))
  97.                     {
  98.                         $this->roman_number .= $this->roman_ant_number['1'.str_repeat(0,$this->cant)].$this->roman_ant_number[$next];
  99.                     }                    
  100.                 }
  101.                 else
  102.                 {
  103.                     switch ($min)
  104.                     {
  105.                         case $min < $pos4:                    
  106.                             $this->roman_number .= str_repeat($this->roman_ant_number[$pos],$this->array_number[0]);
  107.                         break;
  108.                         case $pos4:
  109.                             $this->roman_number .= $this->roman_ant_number[$pos].$this->roman_ant_number[$pos4+1];
  110.                         break;
  111.                         case $min > $pos4 && $min < $pos9:
  112.                             $this->roman_number .= $this->roman_ant_number[$pos4+1];
  113.                             if( $min > $pos4+1 )
  114.                             {
  115.                                 $min -=$pos4+1;
  116.                                 $this->roman_number .= str_repeat($this->roman_ant_number[$pos],$min);
  117.                             }
  118.                         break;
  119.                         case $pos9:
  120.                             $this->roman_number .= $this->roman_ant_number[$pos].$this->roman_ant_number[$next];
  121.                         break;
  122.                     }
  123.                 }
  124.                 //add the roman value
  125.                 $this->romanNumber($num);
  126.             break;
  127.  
  128.         }
  129.         return $this->roman_number;
  130.     }
  131. }
  132.  
  133. ?>
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com
  #16 (permalink)  
Antiguo 20/08/2010, 21:29
 
Fecha de Ingreso: agosto-2010
Ubicación: Venezuela
Mensajes: 24
Antigüedad: 13 años, 8 meses
Puntos: 1
Respuesta: Códigos - Reto Romanos

Una pregunta.. ¿Todos han sido probados y funcionan? Para no tener que ejecutar cada uno :S
  #17 (permalink)  
Antiguo 20/08/2010, 21:31
Colaborador
 
Fecha de Ingreso: octubre-2009
Ubicación: Tokyo - Japan !
Mensajes: 3.867
Antigüedad: 14 años, 6 meses
Puntos: 334
Respuesta: Códigos - Reto Romanos

arregla mi codigo o.o lo publicaste 2 veces.. es solo el de abajo!
__________________
More about me...
~ @rhyudek1
~ Github
  #18 (permalink)  
Antiguo 21/08/2010, 10:52
 
Fecha de Ingreso: abril-2008
Mensajes: 613
Antigüedad: 16 años
Puntos: 22
Respuesta: Códigos - Reto Romanos

Hola,
El mejor a todas luces es el de HIDEK1 pero falla a partir de 4000. Es decir, que no puede mostrar números romanos hasta 10.000. Si no fuera por esto, es el más elegante.
Saludos
__________________
Compartir es vivir
www.programador-php.com
  #19 (permalink)  
Antiguo 21/08/2010, 11:12
Colaborador
 
Fecha de Ingreso: octubre-2009
Ubicación: Tokyo - Japan !
Mensajes: 3.867
Antigüedad: 14 años, 6 meses
Puntos: 334
Respuesta: Códigos - Reto Romanos

@exangel es solo porque no existe un caracter que tenga incluida una linea superior
_
V

de todas formas si le agregas al array los demas caracteres en orden la funcion se adapta sola y te permite llegar hasta el numero que quieras ;)
__________________
More about me...
~ @rhyudek1
~ Github
  #20 (permalink)  
Antiguo 22/08/2010, 13:09
Avatar de angelAparicio  
Fecha de Ingreso: julio-2009
Ubicación: Sevilla
Mensajes: 307
Antigüedad: 14 años, 9 meses
Puntos: 22
Respuesta: Códigos - Reto Romanos

He votado por silvanha. Es la misma idea que la que implemente yo, pero realizada de manera más eficiente.
__________________
Mis webs:
- Programador Web Autónomo
- Conciertos en Sevilla
  #21 (permalink)  
Antiguo 22/08/2010, 13:13
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 11 meses
Puntos: 1517
Respuesta: Códigos - Reto Romanos

No tenían que votar por uno solamente, podían escoger todos los que le gustaron.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #22 (permalink)  
Antiguo 22/08/2010, 17:09
Avatar de truman_truman  
Fecha de Ingreso: febrero-2010
Ubicación: /home/user
Mensajes: 1.341
Antigüedad: 14 años, 2 meses
Puntos: 177
Respuesta: Códigos - Reto Romanos

Cita:
Iniciado por abimaelrc Ver Mensaje
No tenían que votar por uno solamente, podían escoger todos los que le gustaron.
yo voté una vez y ahora no me permite votar mas...
__________________
la la la
  #23 (permalink)  
Antiguo 22/08/2010, 17:29
Avatar de mortiprogramador
Colaborador
 
Fecha de Ingreso: septiembre-2009
Ubicación: mortuoria
Mensajes: 3.805
Antigüedad: 14 años, 7 meses
Puntos: 214
Respuesta: Códigos - Reto Romanos

Cita:
Iniciado por topicosweb Ver Mensaje
Una pregunta.. ¿Todos han sido probados y funcionan? Para no tener que ejecutar cada uno :S
pues tal vez no leiste mis comentarios, allí estan catalogados por funcionamiento
saludos
__________________
"Si consigues ser algo más que un hombre, si te entregas a un ideal, si nadie puede detenerte, te conviertes en algo muy diferente."
Visita piggypon.com

Etiquetas: reto
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 2 personas




La zona horaria es GMT -6. Ahora son las 20:57.