Tuesday, June 14, 2016

CountX - Recursive

Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string.

countX("xxhixx") → 4
countX("xhixhix") → 3
countX("hi") → 0

Hisoka's Jutsu :
1
2
3
4
5
public int countX(String str) {
  if (str.length() == 0) return 0;
 if(str.charAt(str.length()-1) == 'x') return 1+countX(str.substring(0, str.length()-1));
 return countX(str.substring(0, str.length()-1));
}

Output :
Ooowh... btw... if we want to write countX in C#, it will gonna be like this :
1
2
3
4
5
6
7
  public static int countX(String str)
        {
            //stop condition
            if (str.Length == 0) return 0;
            if (str[(str.Length - 1)] == 'x') return 1 + countX(str.Substring(0, str.Length - 1));
            return countX(str.Substring(0, str.Length - 1));
        }
The output is same, you can check it here 

Add Unitest to C# Console Project

Pertama-tama silahkan buat project console baru...Setelah selese, klik kanan dibagian solution projectnya seperti terlihat di bawah :
Setelah selese ngebuat project unitestnya... Klik kanan di project unit test itu... terus pilih "Add - Reference "
Terus pilih tab "Solution" terus centang project utama kita kyk gini :
Naaah...dibagian reference tar kliatan :
Sampe sini kita udah bisa masukin assert2 dkk... :D
Kyk gini :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestCodingBat
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {        
            Assert.AreEqual(3, Codingbat_csharp.Program.powerN(3, 1));
        }


        [TestMethod]
        public void TestMethod2()
        {
            Assert.AreEqual(1000, Codingbat_csharp.Program.powerN(10, 3));
        }


        [TestMethod]
        public void TestMethod3()
        {
            Assert.AreEqual(32, Codingbat_csharp.Program.powerN(2, 5));
        }
    }
}

Klu kita run :


Hasilnya :



Yeeeei... sekiaan...semoga bermanfaat.. :)