13 Ocak 2022 Perşembe

Quest_28_Implement_strStr

public class Solution
{
    public static void Main()
    {
        var haystack = "aaaaa";
        var needle = "bba";

        Solution solution = new Solution();
        var result = solution.StrStr(haystack, needle);
    }

    public int StrStr(string haystack, string needle)
    {
        if (string.IsNullOrEmpty(needle))
            return 0;

        int len = haystack.Length - needle.Length;
        for (int i = 0; i <= len; i++)
        {
            int j = i;
            foreach (var ch in needle)
            {
                if (ch != haystack[j])
                    break;
                j++;
            }

            if (j - i != needle.Length)
                continue;

            return i;
        }

        return -1;
    }
}

12 Ocak 2022 Çarşamba

LeetCode Question 20: Remove Element - O(n) Complexity

public class Solution
{
    public int RemoveElement(int[] nums, int val)
    {
        int increase = 0;

        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] != val)
            {
                nums[increase] = nums[i];
                increase++;
            }
        }
        return increase;
    }
}

10 Ocak 2022 Pazartesi

LeetCode Question 20: Valid Parentheses - O(n) Complexity with Stack

public class Solution
{
    public bool IsValid(string input)
    {
        Stack<char> stack = new();

        if (input.Length == 1)
        {
            return false;
        }

        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] == '(')
            {
                stack.Push(')');
                continue;
            }

            if (input[i] == '{')
            {
                stack.Push('}');
                continue;
            }

            if (input[i] == '[')
            {
                stack.Push(']');
                continue;
            }

            if (stack.Count == 0)
            {
                return false;
            }

            var pop = stack.Pop();

            if (pop != input[i])
            {
                return false;
            }
        }

        if (stack.Count == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

8 Ocak 2022 Cumartesi

LeetCode Question 14: Longest Common Prefix

public class Solution
{
    public static void Main()
    {
        string[] array = new string[] { "fligg6", "flowerrrr11", "flo" };

        Solution solution = new Solution();
        var result = solution.LongestCommonPrefix(array);
    }

    public string LongestCommonPrefix(String[] strs)
    {
        var result = strs[0];

        for (int i = 1; i < strs.Length; i++)
        {
            while (strs[i].StartsWith(result) == false)
            {
                result = result.Substring(0, result.Length - 1);
            }
        }
        return result;
    }
}

Leetcode etiketler - tags

Başlık: LeetCode Question NUMBER: NAME - O(n) Complexity with Stack) tags: LeetCode Questions, LeetCode Question NUMBER: NAME - O(n) Complexity, LeetCode NAME algoritma sorusu çözümü

LeetCode Question 13: Roman to Integer

public class Solution
{
    public static void Main()
    {
        var romanText = "MXLIV";
        Solution solution = new Solution();
        var result = solution.RomanToInt(romanText);
    }

    public static Dictionary<char, int> _dictionary = new Dictionary<char, int>
    {
        {'I', 1},
        {'V', 5},
        {'X', 10},
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000}
    };

    public int RomanToInt(string romanText)
    {
        if (romanText.Length <= 0)
        {
            throw new Exception();
        }

        var total = 0;
        var last = 0;

        foreach (var letter in romanText)
        {
            var currentLetterValue = TranslateToNumber(letter);

            if (currentLetterValue > last)
            {
                total -= last * 2;
            }

            total += currentLetterValue;
            last = currentLetterValue;
        }

        return total;
    }

    public static int TranslateToNumber(char c)
    {
        return _dictionary[c];
    }
}

7 Ocak 2022 Cuma

LeetCode Algorithms Question 9: Palindrome Number

public class Solution
{
    public static void Main()
    {
        var number = 161;

        Solution solution = new Solution();
        var result = solution.IsPalindrome(number);
    }

    public bool IsPalindrome(int number)
    {
        if (number < 0)
        {
            return false;
        }

        var remainder = 0;
        var reversedNumber = 0;

        var nonEditedNumber = number;

        while (number > 0)
        {
            remainder = number % 10;
            number = number / 10;
            reversedNumber = reversedNumber * 10 + remainder;
        }

        if (reversedNumber == nonEditedNumber)
        {
            return true;
        }

        return false;
    }
}

LeetCode Question 1: Two Sum

namespace Quest_1_TwoSum
{
    public class Solution
    {
        public static void Main()
        {
            int[] array = { 5, 7, 2, 6, 5, 1, 9 };
            int target = 10;

            Solution solution = new Solution();
            var result = solution.TwoSum(array, target);
        }

        public int[] TwoSum(int[] array, int target)
        {
            Dictionary<int, int> dictionary = new();

            var arrayLength = array.Length;

            if (arrayLength < 2 || array == null)
            {
                return Array.Empty<int>();
            }

            for (int i = 0; i < arrayLength; i++)
            {
                var firstNumber = array[i];
                var secondNumber = target - firstNumber;

                if (dictionary.TryGetValue(secondNumber, out int secondNumberIndex))
                {
                    return new int[] { secondNumberIndex, i};
                }

                dictionary[firstNumber] = i;

            }
            return Array.Empty<int>();
        }
    }
}

6 Kasım 2020 Cuma

Design Patterns - 1 - Singleton (Türkçe ve İngilizce)

Exported from Notepad++
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestsWithConsoleApp { // Genelde, singleton'lar ilk ihtiyaçları olduğu zaman çağrılırlar // (instantiation ilk ihtiyaç olunan zamanda gerçekleşir). // Generally, singletons are called when they are needed // instantiation occurs when they are needed first time. // It's called lazy construction. // Creating more than one instances can be a problem in terms // of performance. In these circumstances, we use singleton pattern. // How to ensure that one class has one and only instance? // How to use this unique instance easily? // With singleton, we can find solutions to these questions: // How a class can control of it's intantiation? // How to limit the amount of instantiations of given class? // How to prevent other users to instantiate any other instances? // Sırasıyla: // Class'ın constructor'ı gizlenir (private) // public static bir metot oluşturulur; bu // metot class'ın instance'ını oluşturur // Dışarıdan direk constructor kullanılarak bir // initialization yapılamaz. Yani şu yapılamaz: // SingletonClass singletonClass = new SingletonClass(); // Instance ancak bir metot üzerinden çağrılabilir, // çünkü constructor'a direkt erişim yoktur. // Bu pattern'de ana fikir, bir instance'dan // daha fazlasının üretilmesinin önlenmesi ve // üretilen bu tek instance'ın initialization'ının // class içinde kontrol edilmesidir. class Program { public class Singleton { private static Singleton SingletonObject = new Singleton(); public static int Number = 0; private Singleton() { Number++; Console.WriteLine("Constructor çalışıyor. Kaç kez çalıştı? :" + Number); // Constructor'ın sadece 1 kez çalışmış olduğunu görmüş olduk. } // Burada görüldüğü üzere parametre almayan // constructor'ımızı private yaptık. // Artık Singleton class'ı, bu constructor'ı // kullanarak instantiate edilemez. // Yani şunu yapamayız: Singleton singleton = new Singleton(); public static Singleton ReturnSingletonObject() { return SingletonObject; } public void ShowSomething() { Console.WriteLine("Something"); } } static void Main() { var singleton1 = Singleton.ReturnSingletonObject(); var singleton2 = Singleton.ReturnSingletonObject(); var singleton3 = Singleton.ReturnSingletonObject(); // görünüşte üç değişken oluşturup kullanmış olsak da; // aslında toplamda sadece 1 obje ürettik. // constructor'ın 1 kez çalışmış olmasından bunu anlamış olduk. // Bildiğimiz üzere bir class'tan instantiation işlemi // yapılırken constructor çalışıyor. // Singleton'da amacımız en fazla tek bir obje ( // instance of a class) üretmekti. // Birden fazla objenin üretilmesi engellenmeliydi. // (In software engineering, the singleton pattern is a // software design pattern that restricts the instantiation // of a class to one "single" instance. This is useful when // exactly one object is needed to coordinate actions across the system. // The term comes from the mathematical concept of a singleton.) // Biz de bunu yaptık. Constructor sadece // ilk initialization'da çalıştı (singleton1 için). // singleton2 ve singleton3 için herhangi bir şekilde // constructor'a gidilmedi/instance oluşturulmadı. singleton1.ShowSomething(); singleton2.ShowSomething(); singleton3.ShowSomething(); Console.ReadKey(); // Singleton SingletonObject = new Singleton(); // Yukarıda da bahsettiğimiz gibi, parametresiz // constructor'ı private yaptığımız için class'tan // bu şekilde bir instantiation yapamayız. // Singleton'ı anti-pattern olarak addeden developer'lar vardır. // An anti-pattern is a common response to a // recurring problem that is usually ineffective and risks // being highly counterproductive.[1][2] The term, coined in 1995 // by Andrew Koenig,[3] was inspired by a book, Design Patterns, // which highlights a number of design patterns in // software development that its authors considered to be // highly reliable and effective. } } } // Farklı şekilde singleton: // örneklerin birinde metot, birinde property // kullandığımıza dikkat: csharp'ta bu pattern kullanılırken // instance oluşturma işlemi hem property kullanılarak, // hem metot kullanılarak uygulanmaktadır, ikisinden birisi seçilebilir) public class Singleton { private static Singleton _instance; // initialization'u görüldüğü gibi yukarıdaki satırda yapmıyoruz. // if statement içinde yapıyoruz; // şayet daha öncesinde initialization yapılmamışsa tabi... public int Number { get; set; } private Singleton() { Number++; Console.WriteLine("Constructor çalışıyor. Kaç kez çalıştı? :" + Number); } public static Singleton GetSingletonInstance { get { if (_instance == null) { _instance = new Singleton(); return _instance; } return _instance; } } public void ShowSomething() { Console.WriteLine("Something"); } } static void Main() { var singleton1 = Singleton.GetSingletonInstance; var singleton2 = Singleton.GetSingletonInstance; var singleton3 = Singleton.GetSingletonInstance; singleton1.ShowSomething(); singleton2.ShowSomething(); singleton3.ShowSomething(); Console.ReadKey(); }

3 Kasım 2020 Salı

Data Annotations Örnek Kod Parçası


using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ConsoleAppErenOzten { public class Kisi { [Required(ErrorMessage = "{0} gereklidir.")] [StringLength(50, MinimumLength = 3, ErrorMessage = "Minimum 3, maksimum 50 karakter giriniz.")] [DataType(DataType.Text)] public string Ad { get; set; } [Required(ErrorMessage = "{0} gereklidir.")] [StringLength(50, MinimumLength = 3, ErrorMessage = "Minimum 3, maksimum 50 karakter giriniz.")] [DataType(DataType.Text)] public string Soyad { get; set; } [DataType(DataType.PhoneNumber)] [Phone] public string Telefon { get; set; } [DataType(DataType.EmailAddress)] [EmailAddress] public string Email { get; set; } } class Program { static void Main(string[] args) { var kisi = new Kisi(); kisi.Ad = "Eren"; // Boş bir string değeri atanıyor: kisi.Soyad = ""; kisi.Telefon = "3652978130"; kisi.Email = "eren@gmail.com"; ValidationContext context = new ValidationContext(kisi, null, null); var validationResults = new List<ValidationResult>(); // Aşağıdaki satırda, eğer hatalar oluşmuşsa, // bu hatalar validationResults listesine ekleniyor. // Üçüncü parametreyi inceleyiniz: bool valid = Validator.TryValidateObject(kisi, context, validationResults, true); if (!valid) { foreach (ValidationResult validationResult in validationResults) { Console.WriteLine("{0}", validationResult.ErrorMessage); } } Console.ReadKey(); } } }

27 Ekim 2020 Salı

SortedList kullanımı - C#

using System; using System.Collections; namespace CodeInConsole { public class Solution { public static void Main() { Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList1 örneği"); Console.WriteLine("---"); Console.WriteLine(""); // Creates and initializes a new SortedList. SortedList sortedList = new SortedList(); sortedList.Add("Third", "!"); sortedList.Add("Second", "World"); sortedList.Add("First", "Hello"); // Displays the properties and values of the SortedList. Console.WriteLine(" Count: {0}", sortedList.Count); Console.WriteLine(" Capacity: {0}", sortedList.Capacity); Console.WriteLine(" Keys and Values:"); PrintKeysAndValues(sortedList); } public static void PrintKeysAndValues(SortedList myList) { // \t --> empty space yapıyor, tab'a basılıp yazmaya başlanmış gibi. Console.WriteLine("\t-KEY-\t-VALUE-"); for (int i = 0; i < myList.Count; i++) { Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i)); } Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList2 örneği"); Console.WriteLine("---"); Console.WriteLine(""); SortedList sortedList2 = new SortedList(); // sortedList kapasitesi şu an 0 Console.WriteLine("Capacity: " + sortedList2.Capacity); sortedList2.Add("key1", "val1"); sortedList2.Add("key2", "val2"); sortedList2.Add("key3", "val3"); // sortedlist kapasitesi şu an 16 (veri eklendikten // sonra otomatik olarak 16'ya çıktı) Console.WriteLine("Capacity: " + sortedList2.Capacity); // System.InvalidOperationException: 'Failed to compare two // elements in the array.' ArgumentException: Object must be of type String. // sortedList2.Add(2, 5); // System.InvalidOperationException: 'Failed to compare // two elements in the array.' ArgumentException: Object must be of type String. //sortedList2.Add(true, false); // Ayrıca: key'ler özel olmalıdır. Aynı isimde // iki key değeri girilemiyor, hata veriyor. for (int i = 0; i < sortedList2.Count; i++){ Console.WriteLine("Key: " + sortedList2.GetKey(i) + "\t" + "Value: " + sortedList2.GetByIndex(i)); } Console.WriteLine(""); Console.WriteLine("---"); Console.WriteLine("SortedList3 örneği"); Console.WriteLine("---"); Console.WriteLine(""); SortedList sortedList3 = new SortedList(); sortedList3.Add(true, false); sortedList3.Add(false, true); // Yukarıda bool type'lar eklendi sortedList3'e. // Aşağıda ise aynı listeye string eklendiğinde hata oluşuyor: // System.InvalidOperationException: // 'Failed to compare two elements in the array.' //sortedList3.Add("text1", "text2"); for (int i = 0; i < sortedList3.Count; i++) { Console.WriteLine("Key: " + sortedList3.GetKey(i) + "\t" + "Value: " + sortedList3.GetByIndex(i)); } } } }