I’ve been hunting jobs since my current jobs are not satisfying me.
Here are my preparation on some C# and Unity questions.
what is c#
c# is an object-oriented, type-safe, and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language. object-oriented is a paradigm based on the concept of “objects”, which can contain data in the form of field and code in the form of procedures. A feature is that the code procedure can modify the data fields of itself. An object is an instance of a class through which we access the methods of that class. “new” is the keyword to create an object.
Serialization
the process of converting an object into a stream of bytes is called serialization. using ISerialize Interface to make an object serializable. De-serialization is the reverse process of creating an object from a stream of bytes to an object.
Constants vs. read only
Constants are declared variables and initialized at compile time. It can’t be changed afterward. Read-only is used only when we want to assign the value at run time. Compile time is the time at which the source code is converted into an executable code. Run time is the time at which the executable code is started running.
What is an Interface?
Interface is an abstract class which has only public abstract methods. Methods only have declaration but not the definition. These methods must be implemented in the inherited classes.
value type vs. reference type
a value type holds a data value within its own memory space. a value type can be a structure type or an enumeration type. structure type (struct
) usually contains the data and provides little or no behavior. enumeration type defines a set of named constants of the underlying integral numeric type. a reference type stores the address of the object where the value is being stored. It’s a pointer. a structure type can be a class, an interface, or a delegate.
Interface, Virtual, Abstract, Overload, Override
Interface is class has only public undefined methods, but Abstract can have private and concrete methods. In the children class, we’ll use override to define these methods.
Virtual means use this class’s version if it has one otherwise use the base class’s version.
Overloading is creating multiple methods with the same name, unique signatures in the same class. Override is to extend class.
String vs. StringBuilder
string is immutable. A new memory is allocated to the new value and the previous memory allocation released when a string is modified. StringBuilder can perform operations without allocation of separated memory location.
System.Array.CopyTo() vs. System.Array.Clone()
Both are shallow copy. Clone() creates a new array object containing all the elements in the original Array. CopyTo() copies all the elements in to another existing array.
Sort an array in descending order?
Sort() followed by Reverse() method.
C# syntax to catch an exception
try
{ DoSomething(); }
catcth (Exception e)
{}
Finalize() vs. Dispose()
Both of them are called when we want for an object to release any unmanaged resources. But Finalize() doesn’t assure the garbage collection of an object.
Object pool
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. It reduces the overhead of creating and re-creating objects.
Delegate and Event
class DelegateExplanation
{
delegate void DelegateExample(int a);
void Start()
{
DelegateExample myDelegate = Foo ; //assign a delegate
Bar(Foo); // pass a delegate
Bar( (x) => ++x ); //lambda
myDelegate.Invoke(5);
}
void Foo(int a) { }
void Bar(DelegateExample myDelegate) { myDelegate(5); }
}
function can be assigned to a delegate as long as they have the same return types and parameters. One delegate can have multiple assigned functions. Invoke() will call them all.
However, delegate can be overwritten by other scripts too.
class Player
{
public delegate void DeathDelegate();
public DeathDelegate deathEvent;
void Die()
{
deathEvent?.Invoke();
}
}
class Achievements
{
void Start()
{
FindObjectOfType<Player>().deathEvent = OnPlayerDeath();
FindObjectOfType<Player>().deathEvent();
}
public void OnPlayerDeath() { }
}
class UserInterface
{
void Start()
{
FindObjectOfType<Player>().deathEvent += OnPlayerDeath();
}
public void OnPlayerDeath() { }
}
Achievements will override UserInterfrace’s subscription. In addition, anyone who can access the delegate can invoke(). Hence we use the keyword event
public delegate void DeathDelegate();
public event DeathDelegate deathEvent;
any code outside the delegate definition scope can only use += or -=.
Actions and Funcs are shortcuts for creating delegates without a declaration. Both can accept parameters, while only Funcs have a return type.
public event Action deathEvent;
public event Action deathEvent<T1, T2>;
public event Action deathEvetn<T1, T2, T3>; //accept T1, and T2, return T3
Singleton
A singleton is globally accessible and instantiated only once. Singleton resolves the problem: how to access other scripts, but it hides the dependencies. It makes debug and develop difficultly. Monobehavior Singletons should check if it is the only instance in the project during the runtime because the “single instance” restriction can be circumvented by adding another prefab to the scene or simply using object.instantiate
. Any newly created singleton object should destroy themselves when created. However, if the object order is wrong in the hierarchy, the wrong singleton is going to be deleted.
Singleton Criteria
- Absolutely required to exist only once.
- Must be accessible from every part of the code.
- Controls concurrent access to a resource.
Data Structures
Arrays
A collection of elements which identified by index or key. Basic operations: Insert, Get, Delete, Size
Q: find the 2nd minimum element in an Array? A: traverse once. use first
and second
two variables to help comparison. if the current element is smaller than first
, update both; if it’s smaller than second
, update second
.
Q: first non-repeating integers in an array A: traverse the array and use a dictionary or hash table to count the element appearance times.
Q: merge 2 sorted arrays. A: create an 3rd array. Compar the element of two arrays and copy the smaller element to the 3rd array. Increase the index of picked array and continue the comparison. At theend, any left elements is copied directly to the 3rd array.
Q: rearrange positive and negative numbers. A: Quick sort.
Stacks
Basic operations: Push, Pop, isEmpty, Top(returns the top element without removal)
Q: Sort the stack. A: create a tempStack and temp. Pop a value to temp. If the tempStack is empty, or temp is equal or greater than the tempStack’s Top, Push temp to the tempStack. if the temp is smaller than the stack’s Top, Pop tempStack and Push the value to the input stack until the tempStack’s Top is smaller than the temp.
Q: check balanced parentheses in an expression? A: parentheses are pairs. Traverse the expression and Push any left parentheses to a stack. Pop the stack if any right parentheses. If the two doesn’t match, it’s not balanced.
Queue
Queue is similar to stack but it’s FIFO. Basic operations: Enqueue, Dequeue, isEmpty, Top
Q: Implement stack by using a queue? A: when use Push, the queue will dequeue all elements to another queue, enqueue the new element, and enqueue all old elements from another queue.
Q: reverse first k elements of a queue A: use dequeue to separate the k elements and the rest elements. dequeue the k elements but stop before the last one, we extract the last element. Repeat multiple times.
Q: Generate binary numbers from 1 to n using a queue A: in a loop, adding “Top + 0” and “Top + 1”, and Dequeue in each iteration.
Linked List
Like a chain of nodes, where each node contains info like data and pointer to the succeeding node. There’s a head pointer pointing to the first element. Used to implement file systems, hash tables, and adjacency lists. Singly Linked List is undirectinal, Doubly Linked List is bi-direcitonal.
Basic operations: InsertAtEnd, InsertAtHead, Delete, DeleteAtHead, Search, isEmpty
Q: reverse a linked list? A: next = current→next; current→next = prev; prev = current; current = next; until the current is null.
Q: loop in the linked list? A: using Hash Table to count the node appearance. If there is a null, no loop. If the appearance is more than once, there is a loop.
Q: return Nth node from the end in a linked list? A: traverse twice. The 1st time is for length. The 2nd times is to find the Nth node. Total (length - n) + 1 is the position. or using a slide window with the size of N.
Q: remove duplicates from a linked list A: 2 loops. Outer loop picks the elements one by one, and inner loop compares the picked element with the rest of the elements. Sort the linked list, and the duplicates will be next to each other. Counting appearance.
Graph
It’s consist of vertex and edge. There are directed and undirected graph.
Q: Breadth First Search and Depth First Search.
Q: Check if a graph is a tree? A: A graph is a tree if there’s no cycle and nodes are connected. Use BFS or DFS to search the graph, it any adjacent vertex is visited but this vertex is not its parent, there’s a cycle.
Q: Count the number of edges? A: traverse the tree and count the adjacent vertex. Divided by 2 is the answer. (Handshaking Lemma)
Q: Dijkastra Algorithm
Trees
a hierarchical data structure comprise vertices and edges that connect them. Extensively used in Artificial Intelligence and complex algorithms to provide efficient storage.
Types of trees: N-ary, Balanced, Binary, Binary Search, AVL, REd Black, 2-3 Tree
Q: The height of a binary tree. A: empty tree’s height is 0. Get the max depth of left, right trees and compare them. Recursion can do it.
Hash Table
Hashing is a process used to uniquely identify objects and store each object at some pre-calculated unique index called “key”. the object is stored in the form of a “key-value” pair vs. Dictionary? Dictionary is generic while Hash Table is non generic.
3 Factors:
- hash function calculates the index
- size of the hash table
- collision handling method
Q: Find if an array is a subset of another array? Check if given arrays are disjoint? A: use hash table to count the element appearance.
Sorting Algorithms
Quick Sort
The concept is to choose a pivot, and make sure everything in left is smaller than the pivot, and everything in the right is greater. Median of three is a common way to choose the pivot. Compare the first, last and the middle element, pick the median one.
Merge Sort
It’s an external algorithm. Divide and conquer. It use auxiliary array. Recursion. Split the elements into 2 sub collections. Again and again. Then merge them together and put everything in the proper order.
Insertion Sort
Concept: Iterate over list and place each element in its correct place as you get to it from first to last.