Programming Challenge in HackerRank

Task
  • You are given two values  and . 
  • Perform integer division and print .
Input Format
  • The first line contains , the number of test cases. 
  • The next  lines each contain the space separated values of  and .
Constraints
  • 0 < T < 10
Output Format
  1. Print the value of . 
  2. In the case of ZeroDivisionError or ValueError, print the error code.
Solution:
===
num_of_cases = input()
for i in range(0,int(num_of_cases)):
try:
a, b = map(int, input().split())
print(a//b)
except (ZeroDivisionError, ValueError) as e:
print("Error Code:", e)

===

C++ Code Cave Function Template

#define _CRT_SECURE_NO_WARNINGS 

#include
#include
#include

typedef int(__stdcall *__MessageBoxA)(HWND, LPCSTR, LPCSTR, UINT);

class cavedata {
public:
char chMessage[256];
char chTitle[256];
DWORD paMessageBoxA;
};

DWORD GetProcId(char* procname)
{
PROCESSENTRY32 pe;
HANDLE hSnap;

pe.dwSize = sizeof(PROCESSENTRY32);
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(hSnap, &pe)) {
do {
if (strcmp(pe.szExeFile, procname) == 0)
break;
} while (Process32Next(hSnap, &pe));
}
return pe.th32ProcessID;
}

DWORD __stdcall RemoteThread(cavedata *cData)
{
__MessageBoxA MsgBox = (__MessageBoxA)cData->paMessageBoxA;
MsgBox(NULL, cData->chMessage, cData->chTitle, MB_ICONINFORMATION); //call it
return EXIT_SUCCESS;
}


int main()
{
cavedata CaveData;
ZeroMemory(&CaveData, sizeof(cavedata));
strcpy_s(CaveData.chMessage, "function called from remote process");
strcpy_s(CaveData.chTitle, "title from codecave");
HINSTANCE hUserModule = LoadLibrary("user32.dll");
CaveData.paMessageBoxA = (DWORD)GetProcAddress(hUserModule, "MessageBoxA");
FreeLibrary(hUserModule);

HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetProcId((char*)"coreshredder.exe"));
LPVOID pRemoteThread = VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, pRemoteThread, (LPVOID)RemoteThread, sizeof(cavedata), 0);
cavedata *pData = (cavedata*)VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, pData, &CaveData, sizeof(cavedata), NULL);
HANDLE hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)pRemoteThread, pData, 0, 0);
CloseHandle(hThread);
VirtualFreeEx(hProcess, pRemoteThread, sizeof(cavedata), MEM_RELEASE);
CloseHandle(hProcess);
getchar();
return 0;
}

C Code Helper Template

I. XOR string function

string XOR(string data, char key[])
{
string xorstring = data;
for (int i = 0; i < xorstring.size(); i++) {
xorstring[i] = data[i] ^ key[i % (sizeof(key) / sizeof(char))];
}
return xorstring;
}

II. GetSerialNumber function

LPCWSTR GetSerialNumber(void)
{
DWORD ser;
WCHAR sw[32];
GetVolumeInformationA(NULL, NULL, 0, &ser, NULL, NULL, NULL, 0);
wsprintfW(sw, L"\nVOLUME INFORMATION: %X", ser);
return sw;
}

III. GetComputerName function

LPCWSTR GetComputer(void)
{
WCHAR lu[32];
WCHAR du[32];
DWORD bufCharCount = INFO_BUFFER_SIZE;
GetComputerNameW(lu, &bufCharCount);
wsprintfW(du, L"\nLOCAL COMPUTERNAME: %s", lu);
return du;
}

IV. GetLocalUser function

LPCWSTR LocalUser(void)
{
WCHAR lu[32];
WCHAR du[32];
DWORD bufCharCount = INFO_BUFFER_SIZE;
GetUserNameW(lu, &bufCharCount);
wsprintfW(du, L"\nLOCAL USERNAME: %s", lu);
return du;
}

V. GetCurrentPath function

LPCWSTR GetCurrentPath(void)
{
WCHAR proc[MAX_PATH];
WCHAR du[255];
GetModuleFileNameW(NULL, proc, sizeof(proc));
wsprintfW(du, L"\nCURRENT PATH: %s", proc);
return du;
}

VI. GetLocalTime function

LPCWSTR GetTime(void)
{
SYSTEMTIME lt;
GetLocalTime(&lt);
WCHAR du[255];
wsprintfW(du, L"\nSYSTEM TIME IS: %02d:%02d", lt.wHour, lt.wMinute);
return du;
}

VII.  GetLanguage function

LPCWSTR GetLanguage(void)
{
WCHAR du[255];
LANGID languer = GetSystemDefaultLangID();
wsprintfW(du, L"\nSYSTEM LANGUAGE CODE: %d", languer);
return du;
}

VIII. GetProcessList function

char* GetProcessList()
{
char ps_buffer1[10030];
char ps_buffer[10000];
DWORD pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pInfo;
pInfo.dwSize = sizeof(PROCESSENTRY32);
while (Process32Next(snapshot, &pInfo))
{
lstrcat(ps_buffer, ":");
lstrcat(ps_buffer, pInfo.szExeFile);
//MessageBox(NULL, buffer, buffer, MB_OK);
}
CloseHandle(snapshot);
wsprintf(ps_buffer1, "\nSYSTEM PROCESS LIST: %s", ps_buffer);
return ps_buffer1;
}

IX. GetProcessByName function

DWORD GetProcessByName(char* pName)
{
DWORD pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pInfo;
pInfo.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &pInfo))
while (Process32Next(snapshot, &pInfo))
{
if (_stricmp(pName, pInfo.szExeFile) == 0)
{
pid = pInfo.th32ProcessID;
CloseHandle(snapshot);
return pid;
}
}
CloseHandle(snapshot);
return 0;
}

X. ReadMemory function

byte* ReadMemory(DWORD address, DWORD size, DWORD pID)
{
static byte* bytes = new byte[size];
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pID);
ReadProcessMemory(hProcess, (void*)address, bytes, size, NULL);
CloseHandle(hProcess);
return bytes;
}

XI. str::string to LPCWSTR  function (string to LPCWSTR)

std::wstring string_to_lpwstr(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}

std::wstring stemp = string_to_lpwstr(xored);
LPCWSTR result = stemp.c_str();
XII. char_array_to_lpwstr function

LPCWSTR char_array_to_lpwstr(char* characterarray)
{
size_t newsize = strlen(characterarray) + 1;
wchar_t * wcstring = new wchar_t[newsize];
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wcstring, newsize, characterarray, _TRUNCATE);
return wcstring;
}

XIII. GetDebugPrivilege function

void GetDebugPrivilege()
{
HANDLE hToken;
LUID sedebugnameValue;
    TOKEN_PRIVILEGES tp;
    OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue);
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = sedebugnameValue;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges( hToken,FALSE,&tp,sizeof(tp),NULL,NULL);
    CloseHandle(hToken);
}

Let’s Code in Python for HackerRank: Sorting Problem

You are given data in a tabular format. The data contains  rows, and each row contains  space separated elements.
You can imagine the  items to be different attributes, (like height, weight, energy, etc.) and each of the  rows as an instance or a sample.
Your task is to sort the table on the th attribute and print the final resulting table.
Note: If two attributes are the same for different rows, print the row that appeared first in the input.
Input Format
The first line contains  and  separated by a space.
The next  lines each contain  elements.
The last line contains .
Output Format
Print the  lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.
Sample Input
5 3
10 2 5
7 1 0
9 9 9
1 23 12
6 5 9
1
Sample Output
7 1 0
10 2 5
6 5 9
9 9 9
1 23 12
#!/bin/usr
# Coded by @VK_Intel for HackerRan

N, M = map(int, input().split(" "))
rows = [input() for i in range(N)]
K = int(input())

class C:
@staticmethod
def func():
for row in sorted(rows, key=lambda row: int(row.split()[K])):
print(row)
return
if __name__ == "__main__":
try:
elem = C()
elem.func()
except Error as e:
print("Error", e)
raise

Let’s Learn: C++ & Structs

Source: hackerrank.com

struct is a way to combine multiple fields to represent a composite data structure, which further lays the foundation for Object Oriented Programming. For example, we can store details related to a student in a struct consisting of his age (int), first_name (string), last_name (string) and standard (int).

struct can be represented as
struct NewType {
type1 value1;
type2 value2;
.
.
.
typeN valueN;
};
You have to create a struct, named Student, representing the student’s details, as mentioned above, and store the data of a student.
Input Format
Input will consist of four lines.
The first line will contain an integer, representing age.
The second line will contain a string, consisting of lower-case Latin characters (‘a’-‘z’), representing the first_name of a student.
The third line will contain another string, consisting of lower-case Latin characters (‘a’-‘z’), representing the last_name of a student.
The fourth line will contain an integer, representing the standard of student.
Note: The number of characters in first_name and last_name will not exceed 50.
Output Format
Output will be of a single line, consisting of agefirst_namelast_name and standard, each separated by one white space.
P.S.: I/O will be handled by HackerRank.
Solution:
#include 
#include
#include
#include
#include
using namespace std;

struct Student{
unsigned int age;
char first_name[51];
char last_name[51];
unsigned int standard;
};

int main() {
Student st;
cin >> st.age >> st.first_name >> st.last_name >> st.standard;
cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;

return 0;
}


Let’s Learn: eval() in Python

The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.
For example:
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5
Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings.
For example:
>>> type(eval("len"))


Without eval()

>>> type("len")

Task
You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var).
#Python3 Solution by VK
N = input()
class C:
@staticmethod
def m(N):
return eval(N)
if __name__ == "__main__":
try:
j = C()
j.m(N)
except IOError as e:
print("I/O error({0}): {1}".format(e.errno, e.strerror))
raise