Showing posts with label CSharp-Problems. Show all posts
Showing posts with label CSharp-Problems. Show all posts

Sorting an Array using "Insertion Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        InsertionSort(numbers);
        Debug.Log("Sorted numbers : " + string.Join(',', numbers));
    }

    public void InsertionSort(int[] nums)
    {
        for (int i = 1; i < nums.Length; i++)
        {
            int temp = nums[i];
            int j;
            for (j = i - 1; j >= 0 && nums[j] > temp; j--)
            {
                nums[j + 1] = nums[j];
            }
            nums[j + 1] = temp;
        }
    }
}

Sorting an Array using "Bubble Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        BubbleSort(numbers);
        Debug.Log("Sorted numbers : " + string.Join(',', numbers));
    }

    public void BubbleSort(int[] nums)
    {
        for (int i = nums.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j <= i; j++)
            {
                if (nums[j] > nums[j + 1])
                {
                    int temp = nums[j + 1];
                    nums[j + 1] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }
}

Sorting an Array using "Selection Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        SelectionSort(numbers);
        Debug.Log("Sorted numbers : "+string.Join(",",numbers));
    }

    public void SelectionSort(int[] nums)
    {
        for (int i = 0; i < nums.Length - 1; i++)
        {
            int smallestNumIndex = i;
            for (int j = i + 1; j < nums.Length; j++)
            {
                if(nums[j]<nums[smallestNumIndex])
                    smallestNumIndex = j;
            }
            if(smallestNumIndex != i)
            {
                int temp = nums[i];
                nums[i] = nums[smallestNumIndex];
                nums[smallestNumIndex] = temp;
            }
        }
    }
}

"Integer to Roman" Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int number = 1;

    void Start()
    {
        Debug.Log("Roman => "+IntToRoman(number));
    }

    public string IntToRoman(int num)
    {
        var lookup = new Dictionary<int, string>
        {
            {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"}
        };

        string result = "";
        foreach (var pair in lookup)
        {
            if (num <= 0)
                break;
            int quotient = num / pair.Key;
            for (int j = 0; j < quotient; j++)
            {
                num -= pair.Key;
                result += pair.Value;
            }
        }
        return result;
    }
}

''Container With Most Water" Problem and it's Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Solution : MonoBehaviour
{
    public int[] heightArray = { 1, 8, 6, 2, 5, 4, 8, 3, 7 };

    void Start()
    {
        Debug.Log(MaxArea(heightArray));
    }

    public int MaxArea(int[] height)
    {
        int leftIndex = 0;
        int rightIndex = height.Length - 1;
        int maxArea = 0;

        while(leftIndex < rightIndex)
        {
            int area = Math.Min(height[leftIndex], height[rightIndex]) * (rightIndex - leftIndex);
            maxArea = Math.Max(maxArea, area);
            if (height[leftIndex] < height[rightIndex])
                ++leftIndex;
            else if (height[rightIndex] < height[leftIndex])
                --rightIndex;
            else
            {
                ++leftIndex;
                --rightIndex;
            }
        }

        return maxArea;
    }
}

"Valid Parentheses" Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string input = "()";

    void Start()
    {
        Debug.Log(IsValid(input));
    }

    public bool IsValid(string s)
    {
        var valid_pairs = new Dictionary<char, char> { { '(', ')' }, { '{', '}' }, { '[', ']' } };
        var openingBrackets = new Stack<char>();
        foreach (var _char in s)
        {
            if(valid_pairs.ContainsKey(_char))
            {
                openingBrackets.Push(_char);
            }
            else
            {
                if(openingBrackets.Count == 0 || _char != valid_pairs[openingBrackets.Peek()])
                    return false;
                openingBrackets.Pop();
            }
        }
        return openingBrackets.Count == 0;
    }
}

Finding "Longest Common Prefix" string amongst an array of strings | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string[] strings = { "flower", "flow", "flight" };

    void Start()
    {
        Debug.Log("LCF => "+LongestCommonPrefix(strings));
    }

    public string LongestCommonPrefix(string[] strs)
    {
        if (strs == null || strs.Length == 0)
            return "";

        string prefix = strs[0];
        for (int i = 1; i < strs.Length; i++)
        {
            while(strs[i].IndexOf(prefix) != 0)
            {
                prefix = prefix.Substring(0, prefix.Length - 1);
                if (string.IsNullOrEmpty(prefix))
                    return "";
            }
        }
        return prefix;
    }
}

'Roman to Integer' Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string s = "III";

    void Start()
    {
        Debug.Log(s + " => " + RomanToInt(s));
    }

    public int RomanToInt(string s)
    {
        var map = new Dictionary<char, int> { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
        int num = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == 0 || map[s[i]] <= map[s[i - 1]])
            {
                num += map[s[i]];
            }
            else
            {
                num += map[s[i]] - 2 * map[s[i - 1]];
            }
        }
        return num;
    }
}

'Two Sum' Problem and its Optimized Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] nums = { 2, 7, 11, 15 };
    public int target = 9;

    void Start()
    {
        var result = TwoSum(nums, target);
        Debug.Log("Result => " + string.Join(',', result));
    }

    public int[] TwoSum(int[] nums, int target)
    {
        var lookup = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++)
        {
            int secondNum = target - nums[i];
            if(lookup.ContainsKey(secondNum))
                return new[] {lookup[secondNum], i};
            lookup[nums[i]] = i;
        }
        return System.Array.Empty<int>();
    }
}

Check if number is 'Palindrome Number' | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int x = 121;

    void Start()
    {
        Debug.Log(IsPalindrome(x));
    }

    public bool IsPalindrome(int x)
    {
        if(x<0 || (x%10==0 && x!=0))
            return false;

        int reversedNum = 0;
        while(x > reversedNum)
        {
            reversedNum = reversedNum * 10 + (x % 10);
            x /= 10;
        }

        return x == reversedNum || x == reversedNum / 10;
    }
}

Two Sum Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] nums = { 2, 7, 11, 15 };
    public int target = 9;

    private void Start()
    {
        var result = TwoSum(nums, target);
        Debug.Log("Result => "+string.Join(',',result));
    }

    public int[] TwoSum(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length-1; i++)
        {
            for (int j = i + 1; j < nums.Length; j++)
            {
                int sum = nums[i] + nums[j];
                if(sum == target)
                    return new int[]{i, j};
            }
        }
        return new int[] { -1, -1 };
    }
}

Getting a Random Value from a List of Weighted Values | Unity Game Engine


WeightedValue.cs
using System;

[Serializable]
public class WeightedValue
{
    public string value;
    public int weight;
}

PrintRandomValue.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintRandomValue : MonoBehaviour
{
    public List<WeightedValue> weightedValues;

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            string randomValue = GetRandomValue(weightedValues);
            Debug.Log(randomValue ?? "No entries found");
        }
    }

    string GetRandomValue(List<WeightedValue> weightedValueList)
    {
        string output = null;

        //Getting a random weight value
        var totalWeight = 0;
        foreach (var entry in weightedValueList)
        {
            totalWeight += entry.weight;
        }
        var rndWeightValue = Random.Range(1, totalWeight + 1);

        //Checking where random weight value falls
        var processedWeight = 0;
        foreach (var entry in weightedValueList)
        {
            processedWeight += entry.weight;
            if(rndWeightValue <= processedWeight)
            {
                output = entry.value;
                break;
            }
        }

        return output;
    }
}

Getting Unique Random Elements from a List in Unity Game Engine


PrintUniqueRandomElements.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintUniqueRandomElements : MonoBehaviour
{
    List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<T> GetUniqueRandomElements<T>(List<T> inputList, int count)
    {
        List<T> inputListClone = new List<T>(inputList);
        Shuffle(inputListClone);
        return inputListClone.GetRange(0, count);
    }

    void Shuffle<T>(List<T> inputList)
    {
        for (int i = 0; i < inputList.Count - 1; i++)
        {
            T temp = inputList[i];
            int rand = Random.Range(i, inputList.Count);
            inputList[i] = inputList[rand];
            inputList[rand] = temp;
        }
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var uniqueRandomList = GetUniqueRandomElements(list, 4);

            Debug.Log("All elements => " + string.Join(", ", list));
            Debug.Log("Unique random elements => " + string.Join(", ", uniqueRandomList));
            Debug.Log("*************************************************************");
        }
    }
}

Shuffling Elements of a List in Unity Game Engine


PrintShuffledList.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintShuffledList : MonoBehaviour
{
    List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    void Shuffle<T>(List<T> inputList)
    {
        for (int i = 0; i < inputList.Count - 1; i++)
        {
            T temp = inputList[i];
            int rand = Random.Range(i, inputList.Count);
            inputList[i] = inputList[rand];
            inputList[rand] = temp;
        }
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("Before Shuffle => " + string.Join(", ", list));
            Shuffle(list);
            Debug.Log("After Shuffle => " + string.Join(", ", list));
            Debug.Log("*****************************************");
        }
    }
}

Getting Random Elements from a List in Unity Game Engine


PrintRandomElements.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintRandomElements : MonoBehaviour
{
    List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<T> GetRandomElements<T>(List<T> inputList, int count)
    {
        List<T> outputList = new List<T>();
        for (int i = 0; i < count; i++)
        {
            int index = Random.Range(0, inputList.Count);
            outputList.Add(inputList[index]);
        }
        return outputList;
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var randomList = GetRandomElements(list, 4);

            Debug.Log("All elements =>  " + string.Join(", ", list));
            Debug.Log("Random elements => " + string.Join(", ", randomList));
            Debug.Log("*****************************");
        }
    }
}