Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Various Methods for the CAB201 (Sem 2 16) Practice exam
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Q1 A
public static bool IsLeapYear(int year) {
return year % 4 == 0 && (!(year % 100 == 0) || (year % 400 == 0));
}
// Q1 B
public static bool IsArraySorted(int[] numbers) {
int[] sortedArray = numbers.ToArray();
Array.Sort(sortedArray);
return Enumerable.SequenceEqual(numbers, sortedArray) || Enumerable.SequenceEqual(numbers.Reverse(), sortedArray);
}
// Q2 A
public void Reverse(double[] values, int start, int finish) {
for (int i = 0; i <= (finish - (start * 2));i++) {
Swap(values, start + i, finish - i);
}
}
// Q2 B
public static int LastPairOfDuplicates(int[] anArray) {
int lastItem = anArray[anArray.Length-1];
for (int i = anArray.Length - 2; i >= 0; i--) {
if (anArray[i] == lastItem) {
return i;
}
lastItem = anArray[i];
}
return -1;
}
// Q3 A
public static bool NumberValid(int number) {
string numberString = number.ToString();
int sum = 0;
if (numberString.Length == 9) {
for (int i = 0; i < 9; i++) {
sum += Convert.ToInt32(char.GetNumericValue(numberString[i])) * (9 - i);
}
if (sum % 11 == 0) {
return true;
}
}
return false;
}
// Q3 B
static int CalculateAge(Date birthday, Date today) {
int yearDifference = today.GetYear() - birthday.GetYear();
if (today.GetMonth() >= birthday.GetMonth()){
if (today.GetDay() >= birthday.GetDay()) {
return yearDifference;
}
}
return yearDifference - 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment