Thread: Roman numbers
View Single Post
  #8  
Old 03-23-2008, 01:43 AM
Chompy Chompy is offline
¯\(º_o)/¯
Chompy's Avatar
Join Date: Sep 2006
Location: Norway
Posts: 2,815
Chompy is just really niceChompy is just really niceChompy is just really nice
Send a message via MSN to Chompy
Ninja edit btw (err, I started to think about something I did earlier, then I realised you meant {{foo}, {bar}} arrays (multi-dimensional arrays), realised that after like 10 secs after posting that post xD)

Anyways

PHP Code:
public function numberToRoman(number) {
  
temp.table = {
    {
1000,900,500,400,100,90,50,40,10,9,5,4,1},
    {
"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}
  };
  
temp.out = "", temp.number2 = number;
  for(
temp.n : table[0]) {
    while(
number2 >= n) {
      
number2 -= n;
      
out @= table[1][table[0].index(n)];
    }
  }
  return 
out;
}
public function 
romanToNumber(roman) {
  
temp.table = {
    {
1000,900,500,400,100,90,50,40,10,9,5,4,1},
    {
"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}
  };
  
temp.n = 0;
  for(
temp.i = 0; i < roman.length(); i ++) {
    if (
roman.substring(i, 2) in table[1]) {
      
n += table[0][table[1].index(roman.substring(i, 2))];
      
i ++;
    }else 
n += table[0][table[1].index(roman.charat(i))];
  }
  return 
n;
} 

And, the reason why I posted that I posted was because I thought I did something like that, but I did:

PHP Code:
temp.table = {
       
1, "I",
       
5, "V",
      
10, "X",
      
50, "L",
     
100, "C",
     
500, "D",
    
1000, "M"
  
}; 
and that popped into my mind when I saw your post Chris, sorry for the misunderstanding xD

And, some other version of it (romanToNumber()) under:

PHP Code:
public function romanToNumber(number) {
  
temp.table = {
       
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"
  
};
  
temp.number2 = number;
  
temp.out = "";
  for(
temp.i = table.size()-1; i > -1; i -= 2;) {
    
temp.number3 = 0;
    while(
number2 >= table[i-1]) {
      if (
number2 > 0) {
        
number2 -= table[i-1];
        
out @= table[i];
      }
    }
  }
return 
out;
} 
__________________

Last edited by Chompy; 03-23-2008 at 02:32 AM..
Reply With Quote