# Software Engineer Assessment Solution
###### tags: `Assessment`
> Just play, have fun & enjoy :brain: :video_game: :rainbow:
[toc]
## Logic question
1. Before Mt. Everest was discovered, what was the tallest mountain in the world?
**Answer:**
Kanchanjunga (with sea-level 8,586 m) was considered to be the highest mountain from 1838 until 1852.
2. A cow weighs 800 kilograms, and the weight load of the bridge is 700 kilograms, how does the cow cross the bridge?
**Answer:**
Several to help the cow to cross the bridge:
- If the cow need not be alived, kill the cow and cut it in several part then cross the bridge multiple time.
- Reinforce the bridge so it can support heavier weight load and the cow can easily cross it.
3. What is the largest possible number you can write using only 2 numbers - just 2 numbers, no other mathematical symbols?
**Answer:**
99 or 9<sup>9</sup>
5. There are 3 light bulbs in a hidden room and 3 switches outside the room that correspond to those light bulbs. You do not know which switch affects which bulb and you cannot see inside of the room. You are allowed to go inside of the room only one time. How do you find out which switch corresponds to which bulb?
**Answer:**
A clue here is the bulb will get hot if we turn it on for a long period of time. Hence, the sequence should be:
First, turn on switch 1 and switch 2, wait for a few minutes.
Second, turn off switch 1, then enter the room. Whichever bulb is on is wired to switch 2. The off and hot bulb is wired to switch 1
Third, we can easily identify the third bulb wired to the third switch.
7. You have two sand timers, which can show 4 minutes and 7 minutes respectively. Use both the sand timers (at a time or one after other or any other combination) and measure a time of 9 minutes.
**Answer:**
Let FOUR = 4 minute timer, SEVEN = 7 minute timer.We can start the FOUR and SEVEN simulatenously, and let the FOUR flip twice. When SEVEN complete, it mean FOUR only left one minute (4+4 -7 = 1minute). Then, we can simply count 8 minute by flipping the FOUR twice.
9. A snail is at the bottom of a 30 foot well. Every hour the snail is able to climb up 3 feet, then immediately slide back down 2 feet. How many hours does it take for the snail to get out of the well?
**Answer:**
Since the snail climb up 3 feet and slide back down 2 feet every one hour, the net distance is 1 feet/hr. Therefore, the snail should take 27 hrs to climb 27 feet. At 28th hours, the snail can climb 3 feet, and successfully reach 30 foot well. Hence, the total hours is 28 hours.
## Object Oriented Programming Corner
7. What is object-oriented programming?
**Answer:**
According to [techtarget](https://www.techtarget.com/searchapparchitecture/definition/object-oriented-programming-OOP), object-oriented programming is a computer programming model that organizes software design around data, or objects, rather than functions and logic. It relies on the concept of "class" and "object".The data is in the form of fields (often known as attributes or properties), and the code is in the form of procedures (often known as methods).
9. What are the basic concepts of OOPS.
**Answer:**
OOPs made of a few fundamental building blocks known as "classes","objects", "methods" and "atributes". The main concept is about creating an object. According to [analyticsvidhya](https://www.analyticsvidhya.com/blog/2020/09/object-oriented-programming/),
an object is a group of interrelated variables and functions. These variables are often referred to as properties of the object and functions are referred to as the behavior of the objects. These objects provide a better and clear structure for the program.
For example, a human can be a class. If we consider the human as an object then the properties would be the name, age, height, result and etc. Then, the behavior/function would be run, eat, jump and etc.
11. What is the difference between class and an object?
**Answer:**
The class is like a blueprint or template, whereas an object is instantiated from the class.
13. Write a function that will return 3 possible values, Success, Pending, Failed. Write the code in any language.
**Answer:**
C#
```
using System;
public class Program
{
public static string ReturnSuccessPendingFailed(int score)
{
if (score>90)
{
return "Success";
}
else if (score>50)
{
return "Pending";
}
else
{
return "Failed";
}
}
public static void Main()
{
Console.WriteLine(ReturnSuccessPendingFailed(80));
}
}
```
11. Initially, write a function that receive a string. At later stage, the same function is required to receive 2 parameters, 1 is number and 1 is DateTime. And later stage the number of parameters may be changed again. Write the snippet for this in the language that you are comfort with.
**Answer:**
Python
```
def ReceiveAnyParam(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
```
C#
```
using System;
namespace Coreikon
{
public class Program
{
public static void Main()
{
ReceiveAnyParam(1,2,3,"4");
}
public static void ReceiveAnyParam(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
}
}
```
12. Write a function named GetUserSummary that return Name & Age, another function named GetUserDetail that return Name, Age, BirthDate, Gender. Write the code in any language.
**Answer:**
Python
```
class User:
def __init__(self, name, age,birthdate, gender):
self.name = name
self.age = age
self.birthdate = birthdate
self.gender = gender
def GetUserSummary(self):
return (self.name, self.age)
def GetUserDetail(self):
return (self.name, self.age, self.birthdate,self.gender)
```
13. Given an array of ints, write a method to total all the values that are even numbers. (Can be any OOP language)
**Answer:**
Python
```
def sumEven(list):
total = 0
for num in list:
if num%2 ==0: #even value
total+=num
return total
```
## SQL Corner
14. What is the difference between DELETE and TRUNCATE?
**Answer:**
The DELETE command is used to delete particular records from a table.
The TRUNCATE command is used to delete the complete data from the table.
15. What does UNION do? What is the difference between UNION and UNION ALL?
**Answer:**
UNION is used to concatenate 2 or more results set.
UNION only keep unique records, which mean it delete duplicate records; whereas UNION ALL keep all the record include the duplicate one.
16. What is the difference between IN and EXISTS?
**Answer:**
IN is used to select a list of matching value, whereas EXISTS
checks the subquery result and returns an either TRUE or FALSE value
17. What will be the result of the query below? Explain your answer and provide a version that behaves correctly.
select case when null = null then 'Yup' else 'Nope' end as Result;
**Answer:**
A null value cannot be equal to another null value, therefore Result= 'nope'. Besides, we have to use "is" operator instead of "=". The corrected version is shown below:
```
SELECT
CASE
WHEN null IS null THEN 'yup'
ELSE 'nope'
END AS Result;
```
19. How do you copy data from one table to another table?
**Answer:**
We can write something as shown below to copy entire table to another table (table_1 is the original table, table_2 is the copied table)
```
CREATE TABLE table_2 SELECT * from table_1;
```
## Web Development Questions
20. What’s the difference between GET and POST methods in HTTP requests?
**Answer:**
GET is used to request data from a specified resource. Data is send in the header, hence only small amount of data can be sent.
POST is used to send data to a server to create/update a resource. Data is sent in body, so large amount of data can be sent.
21. List out the different ways of CSS code to style below html element highlighted in RED.**
```
<p>This paragraph refers to two classes. </p>
```
**Answer:**
* Use ``<mark>`` tag
<mark>This paragraph refers to two classes.</mark>
* Use `style` within the tag.<p style="background-color: #FFFF00"> This paragraph refers to two classes. </p>
* We can also define the style in CSS file (check **edit mode**)
<style>
.highlightme { background-color:#FFFF00; }
p { background-color:#FFFFFF; }
</style>
<p class="highlightme">This paragraph refers to two classes.</p>
22. List out the different ways an HTML element can be accessed in a JavaScript code.
**Answer:**
According to [geeksforgeeks](https://www.geeksforgeeks.org/different-ways-to-access-html-elements-using-javascript/), we can acces HTML element in Javascript code with 5 different way
* Get HTML element by Id (`getElementById`)
* Get HTML element by className (`getElementsByClassName`)
* Get HTML element by Name (`getElementsByName`)
* Get HTML element by tagName (`getElementsByTagName`)
* Get HTML element by CSS Selector(`querySelector` or `querySelectorAll`)
23. What would be the result of 2+5+”3” in JavaScript?
**Answer:**
The result is 73.
24. What will be the output when the following code is executed? Explain.
```
console.log(false == '0')
console.log(false === '0')
```
**Answer:**
The outputs are true and false respectively. The reason is because ``==`` compare value only, whereas `===` compare both value and type. For `false === '0'`, false is boolean whereas '0' is string.
25. In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?
```
(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 1000);
setTimeout(function(){console.log(3)}, 0);
console.log(4);
})();
```
**Answer:**
The output is 1,4,3,2 because `setTimeout` will put the code to run in another thread. In other word, `console.log(2)` and `console.log(2)` are put in an event queue; hence, the program only execute them until all the in-line code (i.e. `console.log(1)` & `console.log(4) `) have been executed.
26. What would the following lines of code output to the console? Explain your answer.
```
console.log("0 || 1 = "+(0 || 1));
console.log("1 || 2 = "+(1 || 2));
console.log("0 && 1 = "+(0 && 1));
console.log("1 && 2 = "+(1 && 2));
```
**Answer:**
Since the expression is string + integer, the output will be in string type. The program will do the comparison for the integer part first, then only concatenate with the string. Hence, the output should be:
* 0 || 1 = 1
* 1 || 2 = 1
* 0 && 1 = 0
* 1 && 2 = 2
According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators), expr1 && expr2 returns expr1 if it can be converted to false; otherwise, returns expr2. This is why `1 && 2 ` is equal to 2, but `0 && 1` return 0.
## Backend 面試題目
## Q27:簡單 JOIN
### 資料表格式說明
- 會員資料表 [Member]:
- Id:`PRIMARY KEY`
- Account:會員帳號
- 會員詳細資料資料表 [MemberDetail]:
- Id:`PRIMARY KEY`
- MemberId:`[Member]` 的 Id
- Name:真實姓名
- PhoneNumber:電話號碼
### 資料表內容:
`[Member]`
| Id | Account |
| ---- | ---- |
| 1 | jack1234 |
| 2 | mark5678 |
| 3 | tom5566 |
`[MemberDetail]`
| Id | MemberId | Name | PhoneNumber |
| ---- | ---- | ---- | ---- |
| 1 | 1 | Jack | 0912345678 |
| 2 | 3 | Tom | 0987654321 |
### 問題:
請寫一段語法,查詢出會員帳號與詳細資訊
需顯示的欄位為:
| Account | Name | PhoneNumber |
| ---- | ---- | ---- |
**Solution:**
```
CREATE DATABASE coreikon;
USE coreikon;
CREATE TABLE member (
id INT NOT NULL,
account VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE memberdetail (
id INT NOT NULL,
memberId INT NOT NULL,
name VARCHAR(50) NOT NULL,
phoneNumber LONG NOT NULL,
FOREIGN KEY(memberId) REFERENCES Member(id)
);
INSERT INTO member(id,account)
VALUES(1,'jack1234'),
(2,'mark5678'),
(3,'tom5566');
INSERT INTO memberdetail(id,memberId,name,phoneNumber)
VALUES(1,1,'Jack',0912345678),
(2,3,'Tom',0987654321);
SELECT
member.account AS 'Account',
memberdetail.name AS 'Name',
memberdetail.phoneNumber AS 'PhoneNumber'
FROM member JOIN memberdetail on member.id = memberdetail.memberId;
```

## Q28:List 資料更新
### 問題
請處理以下程式中的 `DeleteMembers`:
將傳入 `DeleteMembers` 中的 `members` 做軟刪除
`※ 註:軟刪除就是將 IsDelete 變為 true`
並將已刪除的 member id 轉為 List 回傳
```csharp=
using System;
using System.Collections;
using System.Collections.Generic; // to use List
using System.Linq; //list.Add function
namespace Coreikon
{
class Program
{
static void Main(string[] args)
{
var members = new List<Member>()
{
new Member(1, "Jack"),
new Member(2, "Mark"),
new Member(3, "Tom"),
};
var result = DeleteMembers(members);
foreach(var i in result){
Console.WriteLine(i);
}
// Console.ReadLine();
}
/// <summary>
/// 刪除會員
/// </summary>
/// <param name="members"></param>
/// <returns></returns>
public static List<int> DeleteMembers(List<Member> members)
{
List<int> resultIds = new List<int>();
// ******** 作答區 ********
// 1. 軟刪除:將 IsDelete 變為 true
// 2. 將已經刪除的會員 id 回傳出來
// ***********************
foreach (var member in members) {
member.IsDelete = true;
resultIds.Add(member.Id);
}
return resultIds;
}
/// <summary>
/// 會員
/// </summary>
/// <returns></returns>
public class Member
{
public Member(int id, string name)
{
Id = id;
Name = name;
IsDelete = false;
}
/// <summary>
/// 會員 Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 會員名稱
/// </summary>
public string Name { get; set; }
/// <summary>
/// 是否已刪除
/// </summary>
public bool IsDelete { get; set; }
}
}
}
```
## Q29. 請回答以下 Console.WriteLine 分別會顯示什麼?
``` C#
namespace Util.Test
{
class Program
{
static void Main(string[] args)
{
var Tbank = new TaiwanBankAccount();
var LineBank = new LineBankAccount();
Console.WriteLine($"1.{Tbank.WithdrawMoney()}");
Console.WriteLine($"2.{Tbank.BankCode}");
Console.WriteLine($"3.{LineBank.BankCode}");
Console.WriteLine($"4.{LineBank.GetMoney(1)}");
Console.WriteLine($"5.{LineBank.GetMoney(1, 2)}");
Console.WriteLine($"6.{LineBank.LimitAccount}");
Console.ReadLine();
}
}
public class BankAccount
{
public int LimitAccount = 13;
public virtual string BankCode => "001";
public virtual string WithdrawMoney() {
return "";
}
}
public class TaiwanBankAccount : BankAccount
{
public override string WithdrawMoney()
{
return "Web";
}
public override string BankCode => "002";
}
public class LineBankAccount : BankAccount
{
public override string WithdrawMoney()
{
return "Bank";
}
public int GetMoney(int amount)
{
return amount * 2;
}
public int GetMoney(int amount, int amount2)
{
return amount * amount2;
}
}
}
```
**Answer:**
Technically we are not able to see any result. This is because the variable `BankAccount.LimitAccount` is inaccessible due to protection level, and an error will pop up while running the programme. By changing this line of code `private int LimitAccount = 13;` to `public int LimitAccount = 13;`, we are able to see the following result:
1. Web
2. 002
3. 001
4. 2
5. 2
6. 13