Advertisement
Guest User

Ternary-JUnit

a guest
Apr 19th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. Ternary-JUnit
  2. Program
  3. package PRM_20180125;
  4.  
  5. public class Ternary {
  6.     public static String fromDecadicToTernary(int a) {
  7.         String vysledek = "";
  8.         String konec = "";
  9.         int pom = a;
  10.         int cislo = 0;
  11.         if(pom == 0) {
  12.             return "0";
  13.         } else {
  14.             while(pom > 0) {
  15.             cislo = pom % 3;
  16.             vysledek += cislo;
  17.             pom = pom / 3;
  18.         }
  19.             return new StringBuilder(vysledek).reverse().toString();
  20.         }
  21.        
  22.     }
  23.    
  24.     public static int fromTernaryToDecadic(String a) {
  25.         String pom = a;
  26.         int vysledek = 0;
  27.         double cislo = 0;
  28.         for (int i = 0; i < pom.length(); i++) {
  29.             //cislo = Integer.parseInt(String.valueOf(pom.charAt(i)));
  30.             cislo = Character.getNumericValue(pom.charAt(i));
  31.             int moc = pom.length()-1-i;
  32.             vysledek += cislo * Math.pow(3, moc);
  33.         }
  34.         return vysledek;
  35.     }
  36.    
  37.     public static void main(String[] args) {
  38.         int a = 3;
  39.         String aa = "101";
  40.         System.out.println(fromDecadicToTernary(a));
  41.         System.out.println(fromTernaryToDecadic(aa));
  42.         //System.out.println(Math.pow(3, 0));
  43.     }
  44. }
  45. Test
  46. package PRM_20180125;
  47.  
  48. import org.junit.Test;
  49. import static org.junit.Assert.*;
  50.  
  51. public class TernaryTest {
  52.    
  53.     private final int expectedDekadic[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 99, 100, 666, 1000, 1000000};
  54.     private final String expectedTernary[] = {"0", "1", "2", "10", "11", "12", "20", "21", "22", "100", "101", "120", "1010", "10200", "10201", "220200", "1101001", "1212210202001"};
  55.    
  56.     @Test
  57.     public void testFromDecadicToTernary() {
  58.         for (int i = 0; i < expectedDekadic.length; i++) {
  59.             assertEquals(expectedTernary[i], Ternary.fromDecadicToTernary(expectedDekadic[i]));
  60.         }
  61.     }
  62.    
  63.     @Test
  64.     public void testFromTernaryToDecadic() {
  65.         for (int i = 0; i < expectedDekadic.length; i++) {
  66.             assertEquals(expectedDekadic[i], Ternary.fromTernaryToDecadic(expectedTernary[i]));
  67.         }
  68.     }
  69.    
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement