commit e0316ca3ff9d530094216c857de72a89e7718ed9 Author: Jose Caban <43381096+AssKoala@users.noreply.github.com> Date: Sat Jun 7 11:38:03 2025 -0400 first commit diff --git a/ArrayStack/Cpp/arraystack.cpp b/ArrayStack/Cpp/arraystack.cpp new file mode 100644 index 0000000..96bfba5 --- /dev/null +++ b/ArrayStack/Cpp/arraystack.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include + +template class ArrayStack +{ +public: + ArrayStack() + : + m_array(nullptr) + , m_arrayLen(0) + , m_currentHead(0) + , m_growSize(growSize) + { + if (initialSize > 0) + { + grow(initialSize); + } + } + + ~ArrayStack() + { + + } + + void push(T obj) + { + if (m_currentHead+1 >= m_arrayLen) + { + grow(); + } + + m_array[m_currentHead] = obj; + m_currentHead++; + } + + void pop(T *obj) + { + if (m_currentHead > 0) + { + auto temp = m_array[m_currentHead-1]; + *obj = temp; + m_currentHead--; + } + else + { + assert(false); + } + } + + +private: + void grow(size_t size = growSize) + { + // Allocate for the new size + auto newArrayLen = size + m_arrayLen; + auto newArray = (T*)malloc(sizeof(T) * newArrayLen); + + // Copy over the old array + if (newArray) + { + memcpy(newArray, m_array, m_arrayLen * sizeof(T)); + } + + // delete the old one + if (m_array) free(m_array); + + // Set the new array + m_array = newArray; + m_arrayLen = newArrayLen; + } + + + T *m_array; + size_t m_arrayLen; + size_t m_currentHead; + const size_t m_growSize; +}; + +#ifndef EXTERN_MAIN +int main(int argc, char **argv) +{ + ArrayStack stack; + const size_t stackSize = 50; + + for (size_t i = 0; i < stackSize; i++) + { + stack.push(i); + } + + for (size_t i = 0; i < stackSize; i++) + { + int dest; + stack.pop(&dest); + printf("Got: %d\n", dest); + } + + return 0; +} +#endif diff --git a/BreakMemory/CMakeLists.txt b/BreakMemory/CMakeLists.txt new file mode 100644 index 0000000..ce8ed47 --- /dev/null +++ b/BreakMemory/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) diff --git a/BreakMemory/Cpp/CMakeLists.txt b/BreakMemory/Cpp/CMakeLists.txt new file mode 100644 index 0000000..01bd07a --- /dev/null +++ b/BreakMemory/Cpp/CMakeLists.txt @@ -0,0 +1,37 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CppBreakMemory) +set(CURRENT_PROJECT_CODE_NAME breakmemory) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) + + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) + list(APPEND EXTRA_LIBS "Threads::Threads") +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/BreakMemory/Cpp/breakmemory.cpp b/BreakMemory/Cpp/breakmemory.cpp new file mode 100644 index 0000000..f513152 --- /dev/null +++ b/BreakMemory/Cpp/breakmemory.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Incorrect +{ +public: + Incorrect(size_t iterations = 1000) + : mIterations(iterations) + { + isReady = false; + done = false; + newValue = 0xdeadbeef; + } + + void RunAndWait() + { + std::thread consumer(&Incorrect::Consumer, this); + std::thread writer(&Incorrect::Writer, this); + + writer.join(); + consumer.join(); + + } + +private: + void Consumer() + { + while (!done) + { + while (isReady != true); + auto print = newValue; + isReady = false; + printf("New Value: %d\n", print); + } + } + + void Writer() + { + for (auto i = int(mIterations); i > 0; i--) + { + while (isReady != false); + + newValue = i; + isReady = true; + } + + done = true; + } + + const size_t mIterations; + volatile bool isReady; + volatile int newValue; + volatile bool done; +}; + + +int main() +{ + Incorrect incorrect; + incorrect.RunAndWait(); + return 0; +} + diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..183202c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.10) + +project(LanguageBasics) + +include(${CMAKE_CURRENT_SOURCE_DIR}/HelloWorld/CMakeLists.txt) +include(${CMAKE_CURRENT_SOURCE_DIR}/FizzBuzz/CMakeLists.txt) +include(${CMAKE_CURRENT_SOURCE_DIR}/RecurringRainfall/CMakeLists.txt) +include(${CMAKE_CURRENT_SOURCE_DIR}/Endian/CMakeLists.txt) +include(${CMAKE_CURRENT_SOURCE_DIR}/ProducerConsumer/CMakeLists.txt) +include(${CMAKE_CURRENT_SOURCE_DIR}/BreakMemory/CMakeLists.txt) diff --git a/Endian/C/CMakeLists.txt b/Endian/C/CMakeLists.txt new file mode 100644 index 0000000..2464c1f --- /dev/null +++ b/Endian/C/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CEndian) +set(CURRENT_PROJECT_CODE_NAME endian) +set(FILE_EXT c) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/Endian/C/endian.c b/Endian/C/endian.c new file mode 100644 index 0000000..ce22ed4 --- /dev/null +++ b/Endian/C/endian.c @@ -0,0 +1,24 @@ +#include + +void show_memory(const char* begin, size_t length) +{ + size_t i = 0; + for (; i < length; i++) + { + printf(" %.2x", 0xff & begin[i]); // 0xff is necessary due to type promotion + } + printf("\n"); +} + +int main(int argc, char** argv) +{ + (void)argc; + (void)argv; + float f = 42654.2312f; + int i = 7753238; + printf("Printing float %f with size %ld\n", f, sizeof(f)); + show_memory((char*)&f, sizeof(f)); + printf("Printing int %d with size %ld\n", i, sizeof(f)); + show_memory((char*)&i, sizeof(i)); + return 0; +} diff --git a/Endian/CMakeLists.txt b/Endian/CMakeLists.txt new file mode 100644 index 0000000..c1e88f6 --- /dev/null +++ b/Endian/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +#include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) diff --git a/FizzBuzz/Ada/fizzbuzz.adb b/FizzBuzz/Ada/fizzbuzz.adb new file mode 100644 index 0000000..72de7b7 --- /dev/null +++ b/FizzBuzz/Ada/fizzbuzz.adb @@ -0,0 +1,6 @@ +with Ada.Text_IO; + +procedure FizzBuzz is +begin + Ada.Text_IO.Put_Line("Hello, world!"); +end FizzBuzz; diff --git a/FizzBuzz/C/CMakeLists.txt b/FizzBuzz/C/CMakeLists.txt new file mode 100644 index 0000000..427872b --- /dev/null +++ b/FizzBuzz/C/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CFizzBuzz) +set(CURRENT_PROJECT_CODE_NAME fizzbuzz) +set(FILE_EXT c) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/FizzBuzz/C/fizzbuzz.c b/FizzBuzz/C/fizzbuzz.c new file mode 100644 index 0000000..f43240b --- /dev/null +++ b/FizzBuzz/C/fizzbuzz.c @@ -0,0 +1,132 @@ +#include +#include + +void fizzbuzz(int n) +{ + int i; + for (i = 1; i <= n; i++) + { + if (i%3 == 0 || i%5 == 0) + { + if (i % 3 == 0 && i % 5 == 0) + printf("fizzbuzz\n"); + else if (i%3==0) + printf("fizz\n"); + else + printf("buzz\n"); + } + else + { + printf("%d\n", i); + } + } +} + +#define BUF_SIZE 1024 + +void fizzbuzz_fast(int n) +{ + int i; + + char str[BUF_SIZE]; + int curr_str_pos = 0; + + for (i = 1; i <= n; i++) + { + if (i % 3 == 0 || i % 5 == 0) + { + char* strToPrint; + int result; + + if (i % 3 == 0 && i % 5 == 0) + { + strToPrint = "fizzbuzz\n"; + } + else if (i % 3 == 0) + { + strToPrint = "fizz\n"; + } + else + { + strToPrint = "buzz\n"; + } + + result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%s", strToPrint); + if (!(result < BUF_SIZE - curr_str_pos)) + { + printf("%s", str); + curr_str_pos = 0; + result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%s", strToPrint); + } + curr_str_pos += result; + } + else + { + int result; + result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%d\n", i); + + if (!(result < BUF_SIZE - curr_str_pos)) + { + printf("%s", str); + curr_str_pos = 0; + result = snprintf(str + curr_str_pos, BUF_SIZE - curr_str_pos, "%d\n", i); + } + curr_str_pos += result; + } + } + + if (curr_str_pos != 0) + { + printf("%s", str); + } +} + +void fizzbuzz_branchless(int n) +{ + char *zzc[]={"fizz\n","buzz\n","fizzbuzz\n","%d\n"}; + int zxc[]={3,0,0,1,0,0,2}; + for (int i = 1; i < n; ++i) + { + int a=i%3==0; + int b=i%5==0; + int t=b^a; + printf(zzc[zxc[a<<2|(b<<1)|t]],i); + } +} + +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + + int n; + + clock_t reg_start, reg_end, branchless_start, branchless_end, fast_start, fast_end; + + printf("How many fizzbuzzes?: "); + int ret = scanf("%d", &n); + if (ret) + { + reg_start = clock(); + fizzbuzz(n); + reg_end = clock(); + + branchless_start = clock(); + fizzbuzz_branchless(n); + branchless_end = clock(); + + fast_start = clock(); + fizzbuzz_fast(n); + fast_end = clock(); + + printf("regular time: %ld\n", reg_end - reg_start); + printf("branchless time: %ld\n", branchless_end - branchless_start); + printf("fast time: %ld\n", fast_end - fast_start); + } + else + { + printf("Invalid input\n"); + } + + return 0; +} diff --git a/FizzBuzz/CMakeLists.txt b/FizzBuzz/CMakeLists.txt new file mode 100644 index 0000000..2619a62 --- /dev/null +++ b/FizzBuzz/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) diff --git a/FizzBuzz/CSharp/fizzbuzz.cs b/FizzBuzz/CSharp/fizzbuzz.cs new file mode 100644 index 0000000..2928d67 --- /dev/null +++ b/FizzBuzz/CSharp/fizzbuzz.cs @@ -0,0 +1,39 @@ +namespace LanguageBasics +{ + class CSharpFizzBuzz + { + static void FizzBuzz(int n) + { + for (int i = 1; i <= n; i++) + { + if (i%3==0 || i%5==0) + { + if (i%3==0) + { + System.Console.Write("Fizz"); + } + if (i%5==0) + { + System.Console.Write("Buzz"); + } + } + else + { + System.Console.Write(i); + } + System.Console.WriteLine(""); + } + } + + static void Main() + { + System.Console.WriteLine("How many fizzbuzzes?: "); + string input = System.Console.ReadLine(); + + if (System.Int32.TryParse(input, out int num)) + FizzBuzz(num); + else + System.Console.WriteLine("Invalid input"); + } + } +} diff --git a/FizzBuzz/Cpp/CMakeLists.txt b/FizzBuzz/Cpp/CMakeLists.txt new file mode 100644 index 0000000..7399b0b --- /dev/null +++ b/FizzBuzz/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CppFizzBuzz) +set(CURRENT_PROJECT_CODE_NAME fizzbuzz) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/FizzBuzz/Cpp/fizzbuzz.cpp b/FizzBuzz/Cpp/fizzbuzz.cpp new file mode 100644 index 0000000..a69b3f3 --- /dev/null +++ b/FizzBuzz/Cpp/fizzbuzz.cpp @@ -0,0 +1,32 @@ +#include + +void fizzbuzz(int n) +{ + for (auto i = 1; i <= n; i++) + { + if (i%3 == 0 || i%5 == 0) + { + if (i%3 == 0) + std::cout << "fizz"; + if (i%5 == 0) + std::cout << "buzz"; + } + else + { + std::cout << i; + } + std::cout << std::endl; + } +} + +int main() +{ + int n; + std::cout << "How many fizzbuzzes?: "; + std::cin >> n; + if (!std::cin.fail()) + fizzbuzz(n); + else + printf("Invalid input\n"); + return 0; +} diff --git a/FizzBuzz/D/fizzbuzz.d b/FizzBuzz/D/fizzbuzz.d new file mode 100644 index 0000000..519c8e3 --- /dev/null +++ b/FizzBuzz/D/fizzbuzz.d @@ -0,0 +1,35 @@ +import std.stdio; + +void fizzBuzz(int n) +{ + for (int i = 1; i<= n; i++) + { + if (i%3==0 || i%5==0) + { + if (i%3==0) + write("fizz"); + if (i%5==0) + write("buzz"); + } + else + { + write(i); + } + writeln(""); + } +} + +void main() +{ + int i; + write("How many fizzbuzzes?: "); + try { + readf("%d", i); + fizzBuzz(i); + } catch (Exception e) + { + writeln("Invalid input"); + } + + +} diff --git a/FizzBuzz/Fortran/fizzbuzz.f90 b/FizzBuzz/Fortran/fizzbuzz.f90 new file mode 100644 index 0000000..371a1a3 --- /dev/null +++ b/FizzBuzz/Fortran/fizzbuzz.f90 @@ -0,0 +1,37 @@ +subroutine fizzbuzzsub(n) + implicit none + integer, intent(in) :: n + integer :: i + + do i = 1, n + if ((modulo(i,3) == 0) .OR. (modulo(i,5) == 0)) then + if (mod(i,3)==0) then + write(*, "(a)", advance="no") "Fizz" + end if + if (mod(i,5)==0) then + write(*, "(a)", advance="no") "Buzz" + end if + else + write(*, "(i0)", advance="no") i + end if + print *,"" + end do + + + +end subroutine fizzbuzzsub + +program fizzbuzz + implicit none + integer :: n + integer :: Reason + + print *, "How many fizzbuzzes?: " + read (*,*,IOSTAT=Reason) n + + if (Reason > 0) then + print *, "Invalid input" + else + call fizzbuzzsub(n) + end if +end program fizzbuzz diff --git a/FizzBuzz/Haskell/fizzbuzz.hs b/FizzBuzz/Haskell/fizzbuzz.hs new file mode 100644 index 0000000..83a086a --- /dev/null +++ b/FizzBuzz/Haskell/fizzbuzz.hs @@ -0,0 +1,2 @@ +main :: IO() +main = putStrLn "Hello, World!" diff --git a/FizzBuzz/Java/fizzbuzz.java b/FizzBuzz/Java/fizzbuzz.java new file mode 100644 index 0000000..cde8990 --- /dev/null +++ b/FizzBuzz/Java/fizzbuzz.java @@ -0,0 +1,40 @@ +class fizzbuzz +{ + private static void fizzBuzz(int n) + { + for (int i = 1; i <= n; i++) + { + if (i%3 == 0 || i%5 == 0) + { + if (i%3 == 0) + System.out.print("fizz"); + if (i%5 == 0) + System.out.print("buzz"); + } + else + { + System.out.print(i); + } + System.out.println(""); + } + } + + // Your program begins with a call to main(). + // Prints "Hello, World" to the terminal window. + public static void main(String args[]) + { + System.out.print("How many fizzbuzzes?: "); + String input = System.console().readLine(); + + try + { + int n = Integer.parseInt(input); + fizzBuzz(n); + } + catch (Exception e) + { + System.out.println("Invalid input"); + return; + } + } +} diff --git a/FizzBuzz/Python/fizzbuzz.py b/FizzBuzz/Python/fizzbuzz.py new file mode 100644 index 0000000..a531621 --- /dev/null +++ b/FizzBuzz/Python/fizzbuzz.py @@ -0,0 +1,18 @@ +import sys + +try: + N = int(input("How many fizzbuzzes?: ")) +except: + print("Invalid input") + sys.exit() + +for x in range(1,N+1): + if x % 3 == 0 or x % 5 == 0: + if x % 3 == 0: + print("fizz", end="") + if x % 5 == 0: + print("buzz", end="") + else: + print(x, end="") + print("") + diff --git a/FizzBuzz/Rust/fizzbuzz.rs b/FizzBuzz/Rust/fizzbuzz.rs new file mode 100644 index 0000000..da756e6 --- /dev/null +++ b/FizzBuzz/Rust/fizzbuzz.rs @@ -0,0 +1,29 @@ +fn fizzbuzz(n: u32) { + for i in 1..=n { + if i%3==0 || i%5==0 + { + if i%3==0 { + print!("fizz"); + } + if i%5==0 { + print!("buzz"); + } + } + else { + print!("{}",i); + } + println!(""); + } +} + +fn main() { + println!("How many fizzbuzzes? "); + + let mut input_text = String::new(); + std::io::stdin().read_line(&mut input_text).expect("Failed to read from stdin"); + let trimmed = input_text.trim(); + match trimmed.parse::() { + Ok(i) => fizzbuzz(i), + Err(..) => println!("Invalid input"), + }; +} diff --git a/FizzBuzz/problem.txt b/FizzBuzz/problem.txt new file mode 100644 index 0000000..451a74f --- /dev/null +++ b/FizzBuzz/problem.txt @@ -0,0 +1,5 @@ +/* + Write a program that prints the numbers from 1 to 100. + But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. + For numbers which are multiples of both three and five print “FizzBuzz”. +*/ \ No newline at end of file diff --git a/HelloWorld/Ada/helloworld.adb b/HelloWorld/Ada/helloworld.adb new file mode 100644 index 0000000..1429a3b --- /dev/null +++ b/HelloWorld/Ada/helloworld.adb @@ -0,0 +1,6 @@ +with Ada.Text_IO; + +procedure Helloworld is +begin + Ada.Text_IO.Put_Line("Hello, world!"); +end Helloworld; diff --git a/HelloWorld/C/CMakeLists.txt b/HelloWorld/C/CMakeLists.txt new file mode 100644 index 0000000..4d61021 --- /dev/null +++ b/HelloWorld/C/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CHelloWorld) +set(CURRENT_PROJECT_CODE_NAME helloworld) +set(FILE_EXT c) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/HelloWorld/C/helloworld.c b/HelloWorld/C/helloworld.c new file mode 100644 index 0000000..36c7572 --- /dev/null +++ b/HelloWorld/C/helloworld.c @@ -0,0 +1,8 @@ +#include + +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + return printf("Hello, World!\n"); +} diff --git a/HelloWorld/CMakeLists.txt b/HelloWorld/CMakeLists.txt new file mode 100644 index 0000000..c63888c --- /dev/null +++ b/HelloWorld/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) +if (!WIN32) + include(${CMAKE_CURRENT_LIST_DIR}/Fortran/CMakeLists.txt) +endif() diff --git a/HelloWorld/CSharp/helloworld.cs b/HelloWorld/CSharp/helloworld.cs new file mode 100644 index 0000000..afc4f98 --- /dev/null +++ b/HelloWorld/CSharp/helloworld.cs @@ -0,0 +1,10 @@ +namespace LanguageBasics +{ + class CSharpHelloWorld + { + static void Main() + { + System.Console.WriteLine("Hello, World!"); + } + } +} diff --git a/HelloWorld/Cpp/CMakeLists.txt b/HelloWorld/Cpp/CMakeLists.txt new file mode 100644 index 0000000..5fcfd9a --- /dev/null +++ b/HelloWorld/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CppHelloWorld) +set(CURRENT_PROJECT_CODE_NAME helloworld) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/HelloWorld/Cpp/helloworld.cpp b/HelloWorld/Cpp/helloworld.cpp new file mode 100644 index 0000000..11d982c --- /dev/null +++ b/HelloWorld/Cpp/helloworld.cpp @@ -0,0 +1,7 @@ +#include + +int main() +{ + std::cout << "Hello, World!" << std::endl; + return 0; +} diff --git a/HelloWorld/D/helloworld.d b/HelloWorld/D/helloworld.d new file mode 100644 index 0000000..5de808e --- /dev/null +++ b/HelloWorld/D/helloworld.d @@ -0,0 +1,6 @@ +import std.stdio; + +void main() +{ + writeln("Hello, World!"); +} diff --git a/HelloWorld/Fortran/CMakeLists.txt b/HelloWorld/Fortran/CMakeLists.txt new file mode 100644 index 0000000..afc649f --- /dev/null +++ b/HelloWorld/Fortran/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(FortranHelloWorld) +set(CURRENT_PROJECT_CODE_NAME helloworld) +set(FILE_EXT f90) +enable_language(Fortran) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/HelloWorld/Fortran/helloworld.f90 b/HelloWorld/Fortran/helloworld.f90 new file mode 100644 index 0000000..5ca6552 --- /dev/null +++ b/HelloWorld/Fortran/helloworld.f90 @@ -0,0 +1,3 @@ +program hello + print *, "Hello World!" +end program hello diff --git a/HelloWorld/Haskell/helloworld.hs b/HelloWorld/Haskell/helloworld.hs new file mode 100644 index 0000000..83a086a --- /dev/null +++ b/HelloWorld/Haskell/helloworld.hs @@ -0,0 +1,2 @@ +main :: IO() +main = putStrLn "Hello, World!" diff --git a/HelloWorld/Java/helloworld.java b/HelloWorld/Java/helloworld.java new file mode 100644 index 0000000..98448e4 --- /dev/null +++ b/HelloWorld/Java/helloworld.java @@ -0,0 +1,16 @@ +/* + * Implementation note: for simplicity in the makefiles, we violate the + * Coding standard for the name. Rather than use HelloWorld, we write + * helloworld to match the file name. + * It's not the best reason, but it means the makefiles wont build stuff + * that is already built. + */ +class helloworld +{ + // Your program begins with a call to main(). + // Prints "Hello, World" to the terminal window. + public static void main(String args[]) + { + System.out.println("Hello, World"); + } +} diff --git a/HelloWorld/Python/helloworld.py b/HelloWorld/Python/helloworld.py new file mode 100644 index 0000000..78309db --- /dev/null +++ b/HelloWorld/Python/helloworld.py @@ -0,0 +1 @@ +print("Hello, World!") diff --git a/HelloWorld/Rust/helloworld.rs b/HelloWorld/Rust/helloworld.rs new file mode 100644 index 0000000..449508c --- /dev/null +++ b/HelloWorld/Rust/helloworld.rs @@ -0,0 +1,4 @@ + +fn main() { + println!("Hello, World!"); +} diff --git a/ProducerConsumer/CMakeLists.txt b/ProducerConsumer/CMakeLists.txt new file mode 100644 index 0000000..ce8ed47 --- /dev/null +++ b/ProducerConsumer/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) diff --git a/ProducerConsumer/Cpp/CMakeLists.txt b/ProducerConsumer/Cpp/CMakeLists.txt new file mode 100644 index 0000000..93d2f94 --- /dev/null +++ b/ProducerConsumer/Cpp/CMakeLists.txt @@ -0,0 +1,37 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CppProducerConsumer) +set(CURRENT_PROJECT_CODE_NAME producerconsumer) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) + + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) + list(APPEND EXTRA_LIBS "Threads::Threads") +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/ProducerConsumer/Cpp/producerconsumer.cpp b/ProducerConsumer/Cpp/producerconsumer.cpp new file mode 100644 index 0000000..49e5ae9 --- /dev/null +++ b/ProducerConsumer/Cpp/producerconsumer.cpp @@ -0,0 +1,203 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cpp_lib_semaphore + #include + using PCSemaphore = std::counting_semaphore::max()>; +#else + // Simple semaphore since it's not a part of the C++ std + class semaphore final + { + private: + std::mutex m_mutex; + std::condition_variable m_cv; + int m_count; + + public: + semaphore(const int& initValue = 0) : m_count(initValue) {}; + void acquire() // Wait for a signal to unblock the thread + { + std::unique_lock lock(m_mutex); + while (m_count == 0) + { + m_cv.wait(lock); + } + m_count--; + } + + void release() // Notify waiters that data is available for access + { + std::unique_lock lock(m_mutex); + m_count++; + m_cv.notify_one(); + } + }; + using PCSemaphore = semaphore; +#endif + +/* + Simple producer consumer example. + + N producers write ints into a shared queue (mConsumerData). + M consumers read these ints, one at a time, then "sleep" that time to pretend its processing + + Once all the data is done, the threads join and exit. They know based on the global exit flag + + Producers P P P P + write to --> mConsumerData -> Post Semaphore --> repeat + Consumers C C C C C C + wait on semaphore --> pop oldest mConsumerData --> repeat + + The "data" is just an int for how long the consumer will "process" data. + + Essentially, the producer sleeps for some time [min,max] then pushes an int [min,max] + into the queue to simulate producing data. + The consumers wait on that int then sleep for that time to simulate processing of data. +*/ + +class ProducerConsumer final +{ +public: + struct InitParams + { + InitParams() {} + + size_t ProduceCount = 100; // How much "data" to produce + size_t MinProduceDelayMs = 0; // Min time to produce "data" + size_t MaxProduceDelayMs = 100; // Max time to produce "data" + size_t MinConsumeDelayMs = 25; // Min time to consume "data" + size_t MaxConsumeDelayMs = 1000; // Max time to consume "data" + size_t ProducerThreads = 4; // Number of producer threads to start up + size_t ConsumerThreads = 10; // Number of consumer threads to start up + }; + + ProducerConsumer(const InitParams ¶ms = InitParams()); + void Start(); + void WaitDone(); + +private: + void Producer(); + void Consumer(); + + static const int sExitFlag; + InitParams mInitParams; + std::mutex mListLock; + PCSemaphore mSemaphore; + std::queue mConsumerData; + std::vector mProducers; + std::vector mConsumers; + std::atomic_uint mProduced; + std::atomic_bool mShouldExit; +}; + +const int ProducerConsumer::sExitFlag = -1; + +ProducerConsumer::ProducerConsumer(const InitParams ¶ms) + : mInitParams(params) + , mSemaphore(0) + , mProduced(0) + , mShouldExit(false) +{ +} + +void ProducerConsumer::Start() +{ + mShouldExit = false; + + // Kick off all the consumer threads + for (size_t i = 0; i < mInitParams.ConsumerThreads; i++) + { + mConsumers.push_back(std::thread(&ProducerConsumer::Consumer, this)); + } + + // Kick off all the producer threads + for (size_t i = 0; i < mInitParams.ProducerThreads; i++) + { + mProducers.push_back(std::thread(&ProducerConsumer::Producer, this)); + } +} + +void ProducerConsumer::WaitDone() +{ + // Wait for all the producers to finish producing and exit + for (auto &t : mProducers) + { t.join(); } + + // Push the exit data flag to all the consumer threads + mListLock.lock(); + for (size_t i = 0; i < mInitParams.ConsumerThreads; i++) + { + mConsumerData.push(sExitFlag); + mSemaphore.release(); + } + mListLock.unlock(); + + + std::cout << "Waiting on consumers..." << std::endl; + for (auto &t : mConsumers) // Wait for all the consumers to finish and exit + { t.join(); } + std::cout << "All consumers done. Exiting now." << std::endl; +} + +void ProducerConsumer::Producer() +{ + unsigned int oldVal; + std::random_device randDevice; + + while (oldVal = mProduced.fetch_add(1), oldVal < mInitParams.ProduceCount) + { + // "Produce" data + std::cout << "Producing #" << oldVal << std::endl; + int delay = int((randDevice() % mInitParams.MaxProduceDelayMs) + mInitParams.MinProduceDelayMs); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + + // push the "data" onto the queue + mListLock.lock(); + mConsumerData.push(int((randDevice() % mInitParams.MaxConsumeDelayMs) + mInitParams.MinConsumeDelayMs)); + mListLock.unlock(); + + mSemaphore.release(); + } +} + +void ProducerConsumer::Consumer() +{ + int nextData; + + while (true) + { + mSemaphore.acquire(); + + // Pull the next bit of data from the queue + mListLock.lock(); + nextData = mConsumerData.front(); + mConsumerData.pop(); + mListLock.unlock(); + + // When we pull the exit "data", we just need to break + if (nextData == sExitFlag) break; + + // otherwise, "consume" the data + std::cout << "Consuming for " << nextData << "ms" << std::endl; + std::this_thread::sleep_for(std::chrono::milliseconds(nextData)); + } +} + +int main() +{ + ProducerConsumer prod; + + prod.Start(); + prod.WaitDone(); + + return 0; +} + diff --git a/ProducerConsumer/Rust/producerconsumer.rs b/ProducerConsumer/Rust/producerconsumer.rs new file mode 100644 index 0000000..9fb4fdc --- /dev/null +++ b/ProducerConsumer/Rust/producerconsumer.rs @@ -0,0 +1,9 @@ +use std::sync::{Arc, Mutex}; +use std::thread; +use std::collections::VecDeque; + +fn main() { + let shared_queue: VecDeque = VecDeque::new(); + + println!("Hello, World!"); +} diff --git a/RecurringRainfall/Ada/recurringrainfall.adb b/RecurringRainfall/Ada/recurringrainfall.adb new file mode 100644 index 0000000..4100f98 --- /dev/null +++ b/RecurringRainfall/Ada/recurringrainfall.adb @@ -0,0 +1,48 @@ +with Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; +with Ada.Strings.Unbounded; +with Ada.Integer_Text_IO; +with Ada.IO_Exceptions; + +procedure RecurringRainfall is + Current_Average : Float := 0.0; + Current_Count : Integer := 0; + Input_Integer : Integer; + + -- Recursively attempt to get a new integer + function Get_Next_Input return Integer is + Input_Integer : Integer; + Clear_String : Ada.Strings.Unbounded.Unbounded_String; + begin + Ada.Text_IO.Put("Enter rainfall int, 99999 to quit: "); + Ada.Integer_Text_IO.Get(Input_Integer); + return Input_Integer; + exception + when Ada.IO_Exceptions.Data_Error => + Ada.Text_IO.Put_Line("Invalid input"); + -- We need to call Get_Line to make sure we flush the kb buffer + -- The pragma is to ignore the fact that we are not using the result + pragma Warnings (Off, Clear_String); + Clear_String := Ada.Text_IO.Unbounded_IO.Get_Line; + -- Recursively call self -- it'll break when valid input is hit + -- We disable the infinite recursion because we're intentionally + -- doing this. It will "break" when the user inputs valid input + -- or kills the program + pragma Warnings (Off, "infinite recursion"); + return Get_Next_Input; + pragma Warnings (On, "infinite recursion"); + end Get_Next_Input; + +begin + loop + Input_Integer := Get_Next_Input; + exit when Input_Integer = 99999; + + Current_Count := Current_Count + 1; + Current_Average := Current_Average + (Float(1) / Float(Current_Count))*Float(Input_Integer) - (Float(1) / Float(Current_Count))*Current_Average; + + Ada.Text_IO.Put("New Average: "); + Ada.Text_IO.Put_Line(Float'image(Current_Average)); + + end loop; +end RecurringRainfall; diff --git a/RecurringRainfall/C/CMakeLists.txt b/RecurringRainfall/C/CMakeLists.txt new file mode 100644 index 0000000..cdd839b --- /dev/null +++ b/RecurringRainfall/C/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CRecurringRainfall) +set(CURRENT_PROJECT_CODE_NAME recurringrainfall) +set(FILE_EXT c) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/RecurringRainfall/C/recurringrainfall.c b/RecurringRainfall/C/recurringrainfall.c new file mode 100644 index 0000000..f555eed --- /dev/null +++ b/RecurringRainfall/C/recurringrainfall.c @@ -0,0 +1,42 @@ +#include + +int main(int argc, char **argv) +{ + // Unused variables + (void)argc; + (void)argv; + + float currentAverage = 0; + unsigned int currentEntryNumber = 0; + + for (;;) + { + int ret, entry; + + printf("Enter rainfall int, 99999 to quit: "); + ret = scanf("%d", &entry); + + if (ret) + { + if (entry == 99999) + { + printf("User requested quit.\n"); + break; + } + else + { + currentEntryNumber++; + currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage; + + printf("New Average: %f\n", currentAverage); + } + } + else + { + printf("Invalid input\n"); + while (getchar() != '\n'); // Clear input buffer before asking again + } + } + + return 0; +} diff --git a/RecurringRainfall/CMakeLists.txt b/RecurringRainfall/CMakeLists.txt new file mode 100644 index 0000000..2619a62 --- /dev/null +++ b/RecurringRainfall/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.10) + +include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) diff --git a/RecurringRainfall/CSharp/recurringrainfall.cs b/RecurringRainfall/CSharp/recurringrainfall.cs new file mode 100644 index 0000000..b1950ed --- /dev/null +++ b/RecurringRainfall/CSharp/recurringrainfall.cs @@ -0,0 +1,34 @@ +namespace LanguageBasics +{ + class CSharpRecurringRainfall + { + static int ReadNextInput() + { + System.Console.Write("Enter rainfall int, 99999 to quit: "); + string input = System.Console.ReadLine(); + + if (System.Int32.TryParse(input, out int num)) + { + return num; + } + else + { + System.Console.WriteLine("Invalid input"); + return ReadNextInput(); + } + } + + static void Main() + { + double currentAverage = 0; + int currentEntryNumber = 0; + + for (int lastInput = ReadNextInput(); lastInput != 99999; lastInput = ReadNextInput()) + { + currentEntryNumber++; + currentAverage = currentAverage + (1.0/(float)currentEntryNumber)*lastInput - (1.0/(float)currentEntryNumber)*currentAverage; + System.Console.WriteLine("New Average: " + currentAverage); + } + } + } +} diff --git a/RecurringRainfall/Cpp/CMakeLists.txt b/RecurringRainfall/Cpp/CMakeLists.txt new file mode 100644 index 0000000..f3cfd11 --- /dev/null +++ b/RecurringRainfall/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(CppRecurringRainfall) +set(CURRENT_PROJECT_CODE_NAME recurringrainfall) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/RecurringRainfall/Cpp/recurringrainfall.cpp b/RecurringRainfall/Cpp/recurringrainfall.cpp new file mode 100644 index 0000000..1240402 --- /dev/null +++ b/RecurringRainfall/Cpp/recurringrainfall.cpp @@ -0,0 +1,54 @@ +/* + Write a program that will read in integers and + output their average. Stop reading when the + value 99999 is input. + + Example program output/input: + Enter int: 0 + Average: 0 + Enter int: 2 + Average: 1 + ... + Enter int: 99999 +*/ + +#include +#include + +int main() +{ + float currentAverage = 0; + unsigned int currentEntryNumber = 0; + + for (;;) + { + int entry; + + std::cout << "Enter rainfall int, 99999 to quit: "; + std::cin >> entry; + + if (!std::cin.fail()) + { + if (entry == 99999) + { + std::cout << "User requested quit." << std::endl; + break; + } + else + { + currentEntryNumber++; + currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage; + + std::cout << "New Average: " << currentAverage << std::endl; + } + } + else + { + std::cout << "Invalid input" << std::endl; + std::cin.clear(); + std::cin.ignore(std::numeric_limits::max(), '\n'); + } + } + + return 0; +} diff --git a/RecurringRainfall/D/recurringrainfall.d b/RecurringRainfall/D/recurringrainfall.d new file mode 100644 index 0000000..75610f6 --- /dev/null +++ b/RecurringRainfall/D/recurringrainfall.d @@ -0,0 +1,34 @@ +import std.stdio; + +void main() +{ + float currentAverage = 0; + uint currentEntryNumber = 0; + + for (;;) + { + int entry; + + write("Enter rainfall int, 99999 to quit: "); + + try { + readf("%d", entry); + readln(); + } + catch (Exception e) { + writeln("Invalid input"); + readln(); + continue; + } + + if (entry == 99999) { + writeln("User requested quit."); + break; + } else { + currentEntryNumber++; + currentAverage = currentAverage + (1.0/currentEntryNumber)*entry - (1.0/currentEntryNumber)*currentAverage; + + writeln("New Average: ", currentAverage); + } + } +} diff --git a/RecurringRainfall/Fortran/recurringrainfall.f90 b/RecurringRainfall/Fortran/recurringrainfall.f90 new file mode 100644 index 0000000..37d34b4 --- /dev/null +++ b/RecurringRainfall/Fortran/recurringrainfall.f90 @@ -0,0 +1,40 @@ +function getNextInput() result(Input) + implicit none + integer :: Input + integer :: Reason + Reason = 1 + + do while (Reason > 0) + print *, "Enter rainfall int, 99999 to quit: " + read (*,*,IOSTAT=Reason) Input + + if (Reason > 0) then + print *, "Invalid input" + end if + enddo + +end function getNextInput + +program recurringrainfall + implicit none + real :: currentAverage + integer :: currentCount + integer :: lastInput + integer :: getNextInput + + currentAverage = 0 + currentCount = 0 + + do + lastInput = getNextInput() + + if (lastInput == 99999) exit + + currentCount = currentCount + 1 + currentAverage = currentAverage + (1/real(currentCount))*lastInput - (1/real(currentCount))*currentAverage + + print *, 'New Average: ', currentAverage + enddo + + +end program recurringrainfall diff --git a/RecurringRainfall/Java/recurringrainfall.java b/RecurringRainfall/Java/recurringrainfall.java new file mode 100644 index 0000000..09ff691 --- /dev/null +++ b/RecurringRainfall/Java/recurringrainfall.java @@ -0,0 +1,42 @@ +class recurringrainfall +{ + private static int GetNextInt() + { + while (true) + { + System.out.print("Enter rainfall int, 99999 to quit: "); + String input = System.console().readLine(); + + try + { + int n = Integer.parseInt(input); + return n; + } + catch (Exception e) + { + System.out.println("Invalid input"); + } + } + } + + private static void recurringRainfall() { + float currentAverage = 0; + int currentEntryNumber = 0; + + while (true) { + int entry = GetNextInt(); + + if (entry == 99999) + return; + + currentEntryNumber++; + currentAverage = currentAverage + ((float)1/currentEntryNumber)*entry - ((float)1/currentEntryNumber)*currentAverage; + + System.out.println("New Average: " + currentAverage); + } + } + + public static void main(String args[]) { + recurringRainfall(); + } +} diff --git a/RecurringRainfall/Python/recurringrainfall.py b/RecurringRainfall/Python/recurringrainfall.py new file mode 100644 index 0000000..d089f09 --- /dev/null +++ b/RecurringRainfall/Python/recurringrainfall.py @@ -0,0 +1,24 @@ +import sys + +def get_next_input(): + try: + num = int(input("Enter rainfall int, 99999 to quit: ")) + except: + print("Invalid input") + return get_next_input() + return num + +current_average = 0.0 +current_count = 0 + +while True: + next = get_next_input() + + if next == 99999: + sys.exit() + else: + current_count += 1 + current_average = current_average + (1.0/current_count)*next - (1.0/current_count)*current_average + + print("New average: ", current_average) + diff --git a/RecurringRainfall/Rust/recurringrainfall.rs b/RecurringRainfall/Rust/recurringrainfall.rs new file mode 100644 index 0000000..4c7626b --- /dev/null +++ b/RecurringRainfall/Rust/recurringrainfall.rs @@ -0,0 +1,33 @@ + +fn main() { + + let mut current_average:f32 = 0.0; + let mut current_entry_number:u32 = 0; + + loop + { + let current_entry; + + println!("Enter rainfall int, 99999 to quit: "); + let mut input_text = String::new(); + std::io::stdin().read_line(&mut input_text).expect("Failed to read from stdin"); + let trimmed = input_text.trim(); + match trimmed.parse::() { + Ok(new_entry) => current_entry = new_entry, + Err(..) => { println!("Invalid input"); continue; } + }; + + if current_entry == 99999 + { + println!("User requested quit."); + break; + } + else + { + current_entry_number = current_entry_number + 1; + current_average = current_average + (1.0 / current_entry_number as f32)*(current_entry as f32) - (1.0 / current_entry_number as f32)*current_average; + + println!("New Average: {}", current_average); + } + } +} diff --git a/RecurringRainfall/directions.txt b/RecurringRainfall/directions.txt new file mode 100644 index 0000000..cf64384 --- /dev/null +++ b/RecurringRainfall/directions.txt @@ -0,0 +1,5 @@ +/* + Write a program that will read in integers and + output their average. Stop reading when the + value 99999 is input. +*/ diff --git a/RecurringRainfall/icer14.pdf b/RecurringRainfall/icer14.pdf new file mode 100644 index 0000000..9b2609b Binary files /dev/null and b/RecurringRainfall/icer14.pdf differ diff --git a/TestDataServer/Program.cs b/TestDataServer/Program.cs new file mode 100644 index 0000000..1c7e20a --- /dev/null +++ b/TestDataServer/Program.cs @@ -0,0 +1,19 @@ +using System; + +namespace TestDataServer +{ + class Program + { + static void Main(string[] args) + { + TestDataServer server = new TestDataServer(); + + server.StartListening(); + + //server.StopListening(); + + server.WaitUntilThreadsClose(); + + } + } +} diff --git a/TestDataServer/TestDataServer.cs b/TestDataServer/TestDataServer.cs new file mode 100644 index 0000000..00d5fb6 --- /dev/null +++ b/TestDataServer/TestDataServer.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace TestDataServer +{ + class TestDataServer + { + private Mutex Mutex { get; set; } + private Thread Thread { get; set; } + private bool ShouldRun { get; set; } + + public TestDataServer() + { + Mutex = new Mutex(); + ShouldRun = false; + } + + public void StartListening() + { + if (Thread == null) + { + ShouldRun = true; + Thread = new Thread(new ThreadStart(this.ListenFunction)); + Thread.Start(); + } + } + + public void StopListening() + { + ShouldRun = false; + } + + void ListenFunction() + { + Socket listenSocket = new Socket(AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp); + + int port = 2664; + + // bind the listening socket to the port + IPAddress hostIP = (Dns.GetHostEntry(IPAddress.Any.ToString())).AddressList[0]; + IPEndPoint ep = new IPEndPoint(hostIP, port); + listenSocket.Bind(ep); + + // start listening + listenSocket.Listen(64); + + + while (ShouldRun) + { + Socket clientSocket = listenSocket.Accept(); + ThreadPool.QueueUserWorkItem(ClientProcessingFunction, clientSocket); + } + } + + void ClientProcessingFunction(object context) + { + Socket clientSocket = context as Socket; + + byte[] socketBuffer = new byte[1024]; + string data = null; + + // Read data from client until EOF + while (true) + { + int numByte = clientSocket.Receive(socketBuffer); + + data += Encoding.ASCII.GetString(socketBuffer, + 0, numByte); + + if (data.IndexOf("") > -1) + break; + } + + Console.WriteLine("{0}: Text received -> {1} ", Thread.ManagedThreadId, data); + byte[] message = Encoding.ASCII.GetBytes("Test Server"); + + clientSocket.Close(); + } + + public void WaitUntilThreadsClose() + { + while (Thread.IsAlive) + { + Thread.Sleep(33); + } + } + } +} diff --git a/TestDataServer/TestDataServer.csproj b/TestDataServer/TestDataServer.csproj new file mode 100644 index 0000000..7322fb3 --- /dev/null +++ b/TestDataServer/TestDataServer.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/TestDataServer/TestDataServer.sln b/TestDataServer/TestDataServer.sln new file mode 100644 index 0000000..f3da4ca --- /dev/null +++ b/TestDataServer/TestDataServer.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29519.87 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestDataServer", "TestDataServer.csproj", "{C8E78006-51C2-4C27-AD65-F15ABD8C05DA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C8E78006-51C2-4C27-AD65-F15ABD8C05DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8E78006-51C2-4C27-AD65-F15ABD8C05DA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8E78006-51C2-4C27-AD65-F15ABD8C05DA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8E78006-51C2-4C27-AD65-F15ABD8C05DA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0722B7ED-F7FA-4DD6-B2E0-BDC3C59FA03A} + EndGlobalSection +EndGlobal diff --git a/gen_makefiles.sh b/gen_makefiles.sh new file mode 100644 index 0000000..b28ca81 --- /dev/null +++ b/gen_makefiles.sh @@ -0,0 +1,515 @@ +#!/usr/bin/env bash + +# Programs +declare -A PROGRAMS + +PROGRAMS[HelloWorld]="HelloWorld" +PROGRAMS[FizzBuzz]="FizzBuzz" +PROGRAMS[RecurringRainfall]="RecurringRainfall" +PROGRAMS[ProducerConsumer]="ProducerConsumer" +PROGRAMS[ArrayStack]="ArrayStack" +PROGRAMS[Endian]="Endian" +PROGRAMS[BreakMemory]="BreakMemory" +PROGRAMS[AddTwoNumbers]="l33tcode_addtwonumbers" +PROGRAMS[MedianOfSortedArrays]="l33tcode_medianofsortedarrays" +PROGRAMS[ReverseWords]="l33tcode_reversewords" +PROGRAMS[merge2sortedlists]="l33tcode_merge2sortedlists" + +######################### +# DON'T EDIT BELOW HERE # +######################### + +declare -A CC_EXISTS +declare -A CC_EXE +declare -A CC_OPTS +declare -A LINK_OPTS + +operating_system=$(uname) + +# Detect command line +if [ $# == 0 ] || [ $1 == 'opt' ]; then + echo "[INFO] Enabling optimizations and Enabling debugging" + ENABLE_OPTS=true + ENABLE_DEBUG=true +elif [ $1 == 'help' ]; then + echo "Usage: gen_makefiles.sh " + echo " args:" + echo " help - This message" + echo " debug - Generate makefiles with optimizations off and debugging enabled" + echo " opt - Generate makefiles with optimizations on and debugging enabled" + echo " release - Generate makefiles with optimizations and debugging disabled" + echo " If no args are provided, opt is the default" + exit 1 +elif [ $1 == 'debug' ]; then + echo "[INFO] Disabling optimizations and Enabling debugging" + ENABLE_OPTS=false + ENABLE_DEBUG=true +elif [ $1 == 'release' ]; then + echo "[INFO] Enabling optimizations and Disabling debugging" + ENABLE_OPTS=true + ENABLE_DEBUG=false +else + echo "[ERR] Unknown option, use gen_makefiles.sh help for help" + exit 2 +fi + +################### +# Detect compilers +# +# Tries to find the compilers on the host system +# If a compiler isn't found, it won't generate makefiles for that target +# +# Priority order: +# LLVM -> GCC -> Closed Source +function detect_compilers() { + + # Handy default to avoid copy/paste + INTERNAL_GCC_WARNINGS="-Wall" + + if [ $ENABLE_OPTS == 'true' ]; then + INTERNAL_GCC_STYLE_DEFAULT_OPTS="-O3" + fi + + if [ $ENABLE_DEBUG == 'true' ]; then + INTERNAL_GCC_STYLE_DEBUG="-g" + fi + + INTERNAL_GCC_STYLE_FLAGS="$INTERNAL_GCC_STYLE_DEFAULT_OPTS $INTERNAL_GCC_WARNINGS $INTERNAL_GCC_STYLE_DEBUG" + + # Ada Compiler + type -a gnatmake &> /dev/null + if [ $? == 0 ]; then + echo [INFO] Found Ada gnatmake, using gnatmake for Ada + CC_EXISTS['Ada']=true + CC_EXE['Ada']=gnatmake + CC_OPTS['Ada']=$INTERNAL_GCC_STYLE_FLAGS + else + echo [WARN] No Ada compiler found, no Ada makefiles will be generated + fi + + # C Compiler + type -a clang &> /dev/null + INT_HAS_CLANG=$? + type -a gcc &> /dev/null + INT_HAS_GCC=$? + if [ $INT_HAS_CLANG == 0 ]; then + echo [INFO] Found clang, using clang for C + CC_EXISTS['C']=true + CC_EXE['C']=clang + CC_OPTS['C']=$INTERNAL_GCC_STYLE_FLAGS + elif [ $INT_HAS_GCC == 0 ]; then + echo [INFO] No clang, found gcc, using gcc for C + CC_EXISTS['C']=true + CC_EXE['C']=gcc + CC_OPTS['C']=$INTERNAL_GCC_STYLE_FLAGS + else + echo [WARN] No C compiler found, no C makefiles will be generated + fi + + # Cpp Compiler + type -a clang++ &> /dev/null + INT_HAS_CLANGPP=$? + type -a g++ &> /dev/null + INT_HAS_GPP=$? + if [ $INT_HAS_CLANGPP == 0 ]; then + echo [INFO] Found clang++, using clang for C++ + CC_EXISTS['Cpp']=true + CC_EXE['Cpp']=clang++ + CC_OPTS['Cpp']=$INTERNAL_GCC_STYLE_FLAGS + elif [ $INT_HAS_GPP == 0 ]; then + echo [INFO] No clang++, found g++, using g++ for C++ + CC_EXISTS['Cpp']=true + CC_EXE['Cpp']=g++ + CC_OPTS['Cpp']=$INTERNAL_GCC_STYLE_FLAGS + else + echo [WARN] No C++ compiler found, no C++ makefiles will be generated + fi + + if [ $operating_system == 'Linux' ]; then + LINK_OPTS['Cpp']="-lpthread" + elif [ $operating_system == 'FreeBSD' ]; then + LINK_OPTS['Cpp']="-lpthread" + fi + + # C# Compiler + type -a mcs &> /dev/null + if [ $? == 0 ]; then + echo [INFO] Found mcs, using mcs for C# + CC_EXISTS['CSharp']=true + CC_EXE['CSharp']=mcs + + if [ $ENABLE_DEBUG == true ]; then + CSHARP_DEBUG="-debug" + fi + + if [ $ENABLE_OPTS == true ]; then + CSHARP_OPTS="-optimize" + fi + + CC_OPTS['CSharp']="$CSHARP_DEBUG $CSHARP_OPTS" + else + echo [WARN] No C# compiler found, no C# makefiles will be generated + fi + + # D Compiler + type -a ldc2 &> /dev/null + INT_HAS_LDC2=$? + type -a gdc &> /dev/null + INT_HAS_GDC=$? + if [ $INT_HAS_LDC2 == 0 ]; then + echo [INFO] Found ldc2, using ldc2 for D + CC_EXISTS['D']=true + CC_EXE['D']=ldc2 + + if [ $ENABLE_DEBUG == true ]; then + D_DEBUG="-g" + fi + + if [ $ENABLE_OPTS == true ]; then + D_OPTS="-O3" + fi + + CC_OPTS['D']="$D_DEBUG $D_OPTS" + elif [ $INT_HAS_GDC == 0 ]; then + echo [INFO] No ldc2, found gdc, using gdc for D + CC_EXISTS['D']=true + CC_EXE['D']=gdc + CC_OPTS['D']=$INTERNAL_GCC_STYLE_FLAGS + else + echo [WARN] No D compiler found, no D makefiles will be generated + fi + + # Fortran compiler + type -a flang &> /dev/null + INT_HAS_FLANG=$? + type -a gfortran &> /dev/null + INT_HAS_GFORTRAN=$? + if [ $INT_HAS_FLANG == 0 ]; then + echo [INFO] Found flang, using flang for Fortran + CC_EXISTS['Fortran']=true + CC_EXE['Fortran']=flang + if [ $operating_system == 'FreeBSD' ]; then + CC_OPTS['Fortran']="$INTERNAL_GCC_STYLE_FLAGS -lexecinfo" + else + CC_OPTS['Fortran']=$INTERNAL_GCC_STYLE_FLAGS + fi + elif [ $INT_HAS_GFORTRAN == 0 ]; then + echo [INFO] No flang, found gfortran, using gfortran for Fortran + CC_EXISTS['Fortran']=true + CC_EXE['Fortran']=gfortran + CC_OPTS['Fortran']=$INTERNAL_GCC_STYLE_FLAGS + else + echo [WARN] No Fortran compiler found, no Fortran makefiles will be generated + fi + + # Haskell Compiler + type -a ghc &> /dev/null + if [ $? == 0 ]; then + echo [INFO] Found ghc, using ghc for Haskell + CC_EXISTS['Haskell']=true + CC_EXE['Haskell']=ghc + if [ $ENABLE_DEBUG == true ]; then + HASKELL_DEBUG="-g" + fi + + if [ $ENABLE_OPTS == true ]; then + HASKELL_OPTS="-O3" + fi + CC_OPTS['Haskell']="-Wall $HASKELL_DEBUG $HASKELL_OPTS" + else + echo [WARN] No Haskell compiler found, no Haskell makefiles will be generated + fi + + # Java compiler + type -a javac &> /dev/null + if [ $? == 0 ]; then + echo [INFO] Found javac, using javac for Java + CC_EXISTS['Java']=true + CC_EXE['Java']=javac + CC_OPTS['Java']= + if [ $ENABLE_DEBUG == true ]; then + CC_OPTS['Java']="-g" + fi + else + echo [WARN] No Java compiler found, no Java makefiles will be generated + fi + + # Rust compiler + type -a rustc &> /dev/null + if [ $? == 0 ]; then + echo [INFO] Found rustc, using rustc for Rust + CC_EXISTS['Rust']=true + CC_EXE['Rust']=rustc + + if [ $ENABLE_DEBUG == true ]; then + RUST_DEBUG="-g" + fi + + if [ $ENABLE_OPTS == true ]; then + RUST_OPTS="-C opt-level=3" + fi + CC_OPTS['Rust']="$RUST_DEBUG $RUST_OPTS" + else + echo [WARN] No Rust compiler found, no Rust makefiles will be generated + fi +} + +function gen_std_program_makefile() { + declare makefile=$1 + + echo "\$(PROB): \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -o \$(PROB) \$(DIR)/\$(PROB).\$(EXT) \$(LINK_OPTS)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm \$(PROB)" >> $makefile +} + +function gen_ghc_program_makefile() { + declare makefile=$1 + + echo "\$(PROB): \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -o \$(PROB) \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm \$(PROB) \$(DIR)/\$(PROB).o \$(DIR)/\$(PROB).hi" >> $makefile +} + + +function gen_gnat_program_makefile() { + declare makefile=$1 + + echo "\$(PROB): \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -o \$(PROB) \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm \$(PROB) \$(PROB).o \$(PROB).ali" >> $makefile +} + +function gen_ldc_program_makefile() { + declare makefile=$1 + + echo "\$(PROB): \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -of=\$(PROB) \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm \$(PROB) \$(PROB).o" >> $makefile +} + +function gen_mcs_program_makefile() { + declare makefile=$1 + + echo "\$(PROB): \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -out:\$(PROB) \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm \$(PROB)" >> $makefile +} + +function gen_javac_program_makefile() { + declare makefile=$1 + + echo "\$(PROB).class: \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + printf "\t%s\n\n" "\$(CC) \$(CC_OPTS) -d . \$(DIR)/\$(PROB).\$(EXT)" >> $makefile + echo "clean:" >> $makefile + printf "\t%s\n" "rm *.class" >> $makefile +} + +function gen_Ada_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for Ada:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=adb >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_gnat_program_makefile $makefile +} + +function gen_C_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + declare link_opts=$6 + + echo [GEN] Writing makefile for C:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=c >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo LINK_OPTS=$link_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_std_program_makefile $makefile +} + +function gen_Cpp_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + declare link_opts=$6 + + echo [GEN] Writing makefile for Cpp:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=cpp >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo LINK_OPTS=$link_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_std_program_makefile $makefile +} + +function gen_CSharp_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for CSharp:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=cs >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_mcs_program_makefile $makefile +} + +function gen_D_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for D:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=d >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + if [[ $cc_exe == ldc2 ]]; then + gen_ldc_program_makefile $makefile + else + gen_std_program_makefile $makefile + fi +} + +function gen_Fortran_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for Fortran:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=f90 >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_std_program_makefile $makefile +} + +function gen_Haskell_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for Haskell:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=hs >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_ghc_program_makefile $makefile +} + +function gen_Java_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for Java:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=java >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_javac_program_makefile $makefile +} + +function gen_Rust_program_makefile() { + declare program=$1 + declare makefile=$2 + declare src_dir=$3 + declare cc_exe=$4 + declare cc_opts=$5 + + echo [GEN] Writing makefile for Rust:$program to $makefile + + echo PROB=${program,,} > $makefile + echo EXT=rs >> $makefile + echo CC=$cc_exe >> $makefile + echo CC_OPTS=$cc_opts >> $makefile + echo DIR=$src_dir >> $makefile + echo "" >> $makefile + + gen_std_program_makefile $makefile +} + +function gen_program_makefile() { + declare program=$1 + + echo [INFO] Writing makes files for $program + + cd $program + + for lang_name in *; do + if [ ${CC_EXISTS[${lang_name}]} ]; then + mkdir -p ../build/$program/$lang_name + COMMAND="gen_${lang_name}_program_makefile $program ../build/$program/$lang_name/Makefile ../../../$program/$lang_name ${CC_EXE[${lang_name}]} '${CC_OPTS[${lang_name}]}' '${LINK_OPTS[${lang_name}]}'" + eval $COMMAND + else + echo [INFO] $lang_name has no compiler, skipping makefile generation + fi + done + + cd .. +} + +detect_compilers + +for program in "${PROGRAMS[@]}"; do + gen_program_makefile $program +done diff --git a/l33tcode_addtwonumbers/CMakeLists.txt b/l33tcode_addtwonumbers/CMakeLists.txt new file mode 100644 index 0000000..7346449 --- /dev/null +++ b/l33tcode_addtwonumbers/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.10) + +#include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) +if (!WIN32) + include(${CMAKE_CURRENT_LIST_DIR}/Fortran/CMakeLists.txt) +endif() diff --git a/l33tcode_addtwonumbers/Cpp/CMakeLists.txt b/l33tcode_addtwonumbers/Cpp/CMakeLists.txt new file mode 100644 index 0000000..f158109 --- /dev/null +++ b/l33tcode_addtwonumbers/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(Cppl33tcode_addtwonumbers) +set(CURRENT_PROJECT_CODE_NAME l33tcode_addtwonumbers) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/l33tcode_addtwonumbers/Cpp/leetcode_addtwonumbers.cpp b/l33tcode_addtwonumbers/Cpp/leetcode_addtwonumbers.cpp new file mode 100644 index 0000000..b385d60 --- /dev/null +++ b/l33tcode_addtwonumbers/Cpp/leetcode_addtwonumbers.cpp @@ -0,0 +1,126 @@ +// AddTwoNumbers.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include + +struct ListNode { + int val; + ListNode* next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode* next) : val(x), next(next) {} + + void print() + { + ListNode* head = this; + while (head) + { + printf("(%d)->", head->val); + head = head->next; + } + printf("\n"); + } +}; + +class Solution { +private: + static inline void iterate(ListNode*& l1, ListNode*& l2) + { + l1 = l1->next; + l2 = l2->next; + } + + static inline void iterate(ListNode*& l) + { + l = l->next; + } + +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* left = l1, *right = l2; + ListNode* toRet = new ListNode(); + ListNode* current = toRet, *prev = nullptr; + + int carryover = 0; + + short val = (left->val + right->val); + current->val = val % 10; + carryover = val >= 10 ? 1 : 0; + current->next = nullptr; + prev = current; + iterate(current); + + iterate(left, right); + + while (true) + { + if (left && right) + { + short val = (carryover + left->val + right->val); + carryover = val >= 10 ? 1 : 0; + current = new ListNode(val % 10, nullptr); + prev->next = current; + prev = current; + iterate(current); + + iterate(left, right); + } + else if (left || right) + { + ListNode** toAdd = left ? &left : &right; + while (*toAdd) + { + short val = (carryover + (*toAdd)->val); + carryover = val >= 10 ? 1 : 0; + current = new ListNode(val % 10, nullptr); + + prev->next = current; + prev = current; + iterate(current); + + iterate(*toAdd); + } + } + else + { + if (carryover) + { + current = new ListNode(1, nullptr); + + prev->next = current; + prev = current; + iterate(current); + } + break; + } + } + + return toRet; + } +}; + +int main() +{ + ListNode num1(9, new ListNode(9, nullptr)); // 32 + ListNode num2(9, new ListNode(9, new ListNode(9, nullptr))); // 54 + + num1.print(); + num2.print(); + + Solution s; + s.addTwoNumbers(&num1, &num2)->print(); + + return 0; +} + +// Run program: Ctrl + F5 or Debug > Start Without Debugging menu +// Debug program: F5 or Debug > Start Debugging menu + +// Tips for Getting Started: +// 1. Use the Solution Explorer window to add/manage files +// 2. Use the Team Explorer window to connect to source control +// 3. Use the Output window to see build output and other messages +// 4. Use the Error List window to view errors +// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file diff --git a/l33tcode_addtwonumbers/Rust/leetcode_addtwonumbers.rs b/l33tcode_addtwonumbers/Rust/leetcode_addtwonumbers.rs new file mode 100644 index 0000000..691d1a1 --- /dev/null +++ b/l33tcode_addtwonumbers/Rust/leetcode_addtwonumbers.rs @@ -0,0 +1,25 @@ +// Definition for singly-linked list. +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} +impl Solution { + pub fn add_two_numbers(l1: Option>, l2: Option>) -> Option> { + + } +} + +fn main() { + println!("Hello, World!"); +} \ No newline at end of file diff --git a/l33tcode_medianofsortedarrays/CMakeLists.txt b/l33tcode_medianofsortedarrays/CMakeLists.txt new file mode 100644 index 0000000..7346449 --- /dev/null +++ b/l33tcode_medianofsortedarrays/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.10) + +#include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) +if (!WIN32) + include(${CMAKE_CURRENT_LIST_DIR}/Fortran/CMakeLists.txt) +endif() diff --git a/l33tcode_medianofsortedarrays/Cpp/CMakeLists.txt b/l33tcode_medianofsortedarrays/Cpp/CMakeLists.txt new file mode 100644 index 0000000..88c76b5 --- /dev/null +++ b/l33tcode_medianofsortedarrays/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(Cppl33tcode_medianofsortedarrays) +set(CURRENT_PROJECT_CODE_NAME l33tcode_medianofsortedarrays) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/l33tcode_medianofsortedarrays/Cpp/l33tcode_medianofsortedarrays.cpp b/l33tcode_medianofsortedarrays/Cpp/l33tcode_medianofsortedarrays.cpp new file mode 100644 index 0000000..19e5848 --- /dev/null +++ b/l33tcode_medianofsortedarrays/Cpp/l33tcode_medianofsortedarrays.cpp @@ -0,0 +1,79 @@ +// MedianOfSortedArrays.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include + +using namespace std; + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) + { + vector combined; + combined.resize(nums1.size() + nums2.size()); + + size_t i = 0, j = 0; + size_t index = 0, max = nums1.size() + nums2.size(); + + for (; i < nums1.size() && j < nums2.size(); ) + { + if (nums1[i] < nums2[j]) + { + combined[index] = nums1[i]; + index++, i++; + } + else + { + combined[index] = nums2[j]; + index++, j++; + } + } + + for (; i < nums1.size(); i++) + { + combined[index] = nums1[i]; + index++; + } + for (; j < nums2.size(); j++) + { + combined[index] = nums2[j]; + index++; + } + + double median; + size_t size = combined.size(); + if (combined.size() % 2 == 0) + { + median = (combined[size / 2 - 1] + combined[size / 2]) / 2.0f; + } + else + { + median = combined[size / 2]; + } + + return median; + } +}; + +int main() +{ + vector s1{ 1,2 }; + vector s2{ 3,4}; + Solution s; + + cout << s.findMedianSortedArrays(s1, s2) << endl; + + +} + +// Run program: Ctrl + F5 or Debug > Start Without Debugging menu +// Debug program: F5 or Debug > Start Debugging menu + +// Tips for Getting Started: +// 1. Use the Solution Explorer window to add/manage files +// 2. Use the Team Explorer window to connect to source control +// 3. Use the Output window to see build output and other messages +// 4. Use the Error List window to view errors +// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file diff --git a/l33tcode_medianofsortedarrays/Rust/l33tcode_medianofsortedarrays.rs b/l33tcode_medianofsortedarrays/Rust/l33tcode_medianofsortedarrays.rs new file mode 100644 index 0000000..0b4c482 --- /dev/null +++ b/l33tcode_medianofsortedarrays/Rust/l33tcode_medianofsortedarrays.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { + + } +} \ No newline at end of file diff --git a/l33tcode_merge2sortedlists/CMakeLists.txt b/l33tcode_merge2sortedlists/CMakeLists.txt new file mode 100644 index 0000000..7346449 --- /dev/null +++ b/l33tcode_merge2sortedlists/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.10) + +#include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) +if (!WIN32) + include(${CMAKE_CURRENT_LIST_DIR}/Fortran/CMakeLists.txt) +endif() diff --git a/l33tcode_merge2sortedlists/Cpp/CMakeLists.txt b/l33tcode_merge2sortedlists/Cpp/CMakeLists.txt new file mode 100644 index 0000000..75f792c --- /dev/null +++ b/l33tcode_merge2sortedlists/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(Cppl33tcode_merge2sortedlists) +set(CURRENT_PROJECT_CODE_NAME l33tcode_merge2sortedlists) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/l33tcode_merge2sortedlists/Cpp/l33tcode_merge2sortedlists.cpp b/l33tcode_merge2sortedlists/Cpp/l33tcode_merge2sortedlists.cpp new file mode 100644 index 0000000..c096c86 --- /dev/null +++ b/l33tcode_merge2sortedlists/Cpp/l33tcode_merge2sortedlists.cpp @@ -0,0 +1,111 @@ +// Merge2SortedLists.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include + +struct ListNode { + int val; + ListNode* next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode* next) : val(x), next(next) {} + +}; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* head = nullptr; + + if (l1 && l2 && l1->val < l2->val) + { + head = l1; + l1 = l1->next; + head->next = nullptr; + } + else if (l2) + { + head = l2; + l2 = l2->next; + head->next = nullptr; + } + + ListNode* newList = head; + + if (l1 && l2) + { + while (l1 != nullptr && l2 != nullptr) + { + if (l1->val < l2->val) + { + newList->next = l1; + l1 = l1->next; + newList = newList->next; + newList->next = nullptr; + } + else + { + newList->next = l2; + l2 = l2->next; + newList = newList->next; + newList->next = nullptr; + } + } + } + + while (l1 != nullptr) + { + newList->next = l1; + newList = newList->next; + newList->next = nullptr; + } + + while (l2 != nullptr) + { + newList->next = l2; + newList = newList->next; + newList->next = nullptr; + } + + return head; + } +}; + +int main() +{ + Solution s; + s.mergeTwoLists(nullptr, nullptr); + + ListNode *one = new ListNode(4); + ListNode* two = new ListNode(2, one); + ListNode* three = new ListNode(1, two); + + ListNode* one1 = new ListNode(4); + ListNode* two1 = new ListNode(3, one); + ListNode* three1 = new ListNode(1, two); + + s.mergeTwoLists(three, three1); + + std::cout << "Hello World!\n"; +} + +// Run program: Ctrl + F5 or Debug > Start Without Debugging menu +// Debug program: F5 or Debug > Start Debugging menu + +// Tips for Getting Started: +// 1. Use the Solution Explorer window to add/manage files +// 2. Use the Team Explorer window to connect to source control +// 3. Use the Output window to see build output and other messages +// 4. Use the Error List window to view errors +// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file diff --git a/l33tcode_merge2sortedlists/Rust/l33tcode_merge2sortedlists.rs b/l33tcode_merge2sortedlists/Rust/l33tcode_merge2sortedlists.rs new file mode 100644 index 0000000..e69de29 diff --git a/l33tcode_reversewords/CMakeLists.txt b/l33tcode_reversewords/CMakeLists.txt new file mode 100644 index 0000000..7346449 --- /dev/null +++ b/l33tcode_reversewords/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.10) + +#include(${CMAKE_CURRENT_LIST_DIR}/C/CMakeLists.txt) +include(${CMAKE_CURRENT_LIST_DIR}/Cpp/CMakeLists.txt) +if (!WIN32) + include(${CMAKE_CURRENT_LIST_DIR}/Fortran/CMakeLists.txt) +endif() diff --git a/l33tcode_reversewords/Cpp/CMakeLists.txt b/l33tcode_reversewords/Cpp/CMakeLists.txt new file mode 100644 index 0000000..b007f3b --- /dev/null +++ b/l33tcode_reversewords/Cpp/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.10) + +# Modify only these if one source file! +project(Cppl33tcode_reversewords) +set(CURRENT_PROJECT_CODE_NAME l33tcode_reversewords) +set(FILE_EXT cpp) +# End + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# We want all the warnings and as errors enabled +if (MSVC) + # warning level 4 and all warnings as errors + add_compile_options(/W4 /WX) +else() + # lots of warnings and all warnings as errors + add_compile_options(-Wall -Wextra -pedantic -Werror) +endif() + +add_executable(${CMAKE_PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR}/${CURRENT_PROJECT_CODE_NAME}.${FILE_EXT}) + +target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_INCLUDES} + ) + +target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC + ${EXTRA_LIBS} + ) + + diff --git a/l33tcode_reversewords/Cpp/l33tcode_reversewords.cpp b/l33tcode_reversewords/Cpp/l33tcode_reversewords.cpp new file mode 100644 index 0000000..dc8cc3f --- /dev/null +++ b/l33tcode_reversewords/Cpp/l33tcode_reversewords.cpp @@ -0,0 +1,64 @@ +// https://leetcode.com/problems/reverse-words-in-a-string/ + +#include +#include +#include +#include +#include + +using namespace std; + +static string_view findWord(const string& str, size_t &index) +{ + size_t startIndex, endIndex; + + // Start of word + while (index < str.size() && isspace(str[index])) index++; + startIndex = index; + + // Last letter + while (index < str.size() && !isspace(str[index])) index++; + endIndex = index; + + return string_view(str.c_str() + startIndex, endIndex - startIndex); + +} + +class Solution { +public: + string reverseWords(string s) { + vector words; + size_t index = 0; + do + { + string_view sv = findWord(s, index); + if (!sv.empty()) + { + words.push_back(sv); + } + } while (index < s.size()); + + string toRet; + toRet.reserve(s.size()); + + for (auto iter = words.crbegin(); iter != words.crend(); iter++) + { + toRet += *iter; + toRet += " "; + } + toRet.resize(toRet.size() - 1); + + return toRet; + + } +}; + +int main() +{ + Solution s; + cout << s.reverseWords("the sky is blue") << endl; + cout << s.reverseWords(" hello world ") << endl; + cout << s.reverseWords("a good example") << endl; + cout << s.reverseWords(" Bob Loves Alice ") << endl; +} + diff --git a/l33tcode_reversewords/Rust/l33tcode_reversewords.rs b/l33tcode_reversewords/Rust/l33tcode_reversewords.rs new file mode 100644 index 0000000..4612b55 --- /dev/null +++ b/l33tcode_reversewords/Rust/l33tcode_reversewords.rs @@ -0,0 +1,13 @@ +trait Solution { + fn reverse_words(s: String) -> String; +} + +impl Solution { + pub fn reverse_words(s: String) -> String { + + } +} + +fn main() { + println!("Hello, World!"); +} diff --git a/make_all.sh b/make_all.sh new file mode 100644 index 0000000..5f663c2 --- /dev/null +++ b/make_all.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +if [ $# == 0 ]; then + bash gen_makefiles.sh +else + bash gen_makefiles.sh $1 + if [ $? == 2 ]; then + exit 2 + fi +fi + +cd build + +for program in *; do + cd $program + for lang_name in *; do + cd $lang_name + make + cd .. + done + cd .. +done + +cd .. diff --git a/malloc/Cpp/malloc.cpp b/malloc/Cpp/malloc.cpp new file mode 100644 index 0000000..55cf854 --- /dev/null +++ b/malloc/Cpp/malloc.cpp @@ -0,0 +1,131 @@ +#include +#include + +/* + * Contains functions provided by the operating system + */ +namespace OurImaginaryOS +{ + /* + * Return 1024byte aligned page of size PAGE_SIZE * pageCount + * e.g. GetNewPage(1) returns a 32MiB page (PAGE_SIZE) + * GetNewPage(2) returns two contiguous pages, totaling 64MiB + * GetNewPage(0) is undefined. + */ + void *GetNewPage(size_t pageCount = 1); + void FreePage(void *p); + + const size_t PAGE_SIZE = 32 * 1024 * 1024; +} + +/* IAllocator interface for memory allocations. + Example Usage: + + struct Foo() { + IAllocator &mAllocator; + MyDynamicObject *mDynamicObject; + + void Foo(IAllocator &allocator) + : mAllocator(allocator) + { + mDynamicObject = new(mAllocator.Alloc(sizeof(*mDynamicObject)) MyDynamicObject(); + } + + void ~Foo() + { + mDynamicObject->~MyDynamicObject(); + mAllocator.Free(mDynamicObject); + } + } +*/ +class IAllocator +{ +public: + // size in bytes + // alignment in bytes, 0 means don't care + // alignOffset: offset to align returned pointer. E.g. alignoffset of 4: + // ptr aligned start point that matches alignment parameter. + // ^ ^ + // | 4 bytes | Rest of block of size "size - alignOffset" | + // flags - currently unused + virtual void *Alloc(size_t size, size_t alignment = 0, size_t alignOffset = 0, int64_t flags = 0) = 0; + virtual void Free(void *ptr) = 0; + + virtual ~IAllocator() = default; +}; + +using namespace OurImaginaryOS; + +class MyAllocator : public IAllocator +{ +public: + MyAllocator() + { + + } + + virtual void *Alloc(size_t size, size_t alignment = 0, size_t alignOffset = 0, int64_t flags = 0) + { + return nullptr; + } + + virtual void Free(void *ptr) + { + } + + virtual ~MyAllocator() + { + + } +}; + +int main() +{ + return 0; +} + +/*********************************************************/ +// Stuff to make coding game syntax highlighting work +// Don't worry about what's below here. + +#include +#include + +namespace OurImaginaryOS +{ + static std::mutex s_internalPagesLock; + static std::vector s_internalPages; + + void *GetNewPage(size_t pageCount) + { + void *newPage = malloc(PAGE_SIZE * pageCount); + + s_internalPagesLock.lock(); + s_internalPages.push_back(newPage); + s_internalPagesLock.unlock(); + + return newPage; + } + + void FreePage(void *p) + { + void *toFree = nullptr; + + s_internalPagesLock.lock(); + for (auto iter = s_internalPages.begin(); iter != s_internalPages.end(); iter++) + { + if (*iter == p) + { + toFree = p; + s_internalPages.erase(iter); + break; + } + } + s_internalPagesLock.unlock(); + + if (toFree) + { + free(p); + } + } +} diff --git a/solution/LanguageBasics/LanguageBasics.sln b/solution/LanguageBasics/LanguageBasics.sln new file mode 100644 index 0000000..281f4b3 --- /dev/null +++ b/solution/LanguageBasics/LanguageBasics.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30611.23 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ProducerConsumerCpp", "ProducerConsumerCpp\ProducerConsumerCpp.vcxproj", "{DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Debug|x64.ActiveCfg = Debug|x64 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Debug|x64.Build.0 = Debug|x64 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Debug|x86.ActiveCfg = Debug|Win32 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Debug|x86.Build.0 = Debug|Win32 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Release|x64.ActiveCfg = Release|x64 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Release|x64.Build.0 = Release|x64 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Release|x86.ActiveCfg = Release|Win32 + {DAD3BB7C-72DF-40DB-BFC3-F24A39E5DA1A}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F74E0D73-9C68-40B3-A717-470ACF50BA2A} + EndGlobalSection +EndGlobal diff --git a/solution/LanguageBasics/ProducerConsumerCpp/ProducerConsumerCpp.vcxproj b/solution/LanguageBasics/ProducerConsumerCpp/ProducerConsumerCpp.vcxproj new file mode 100644 index 0000000..5db92ee --- /dev/null +++ b/solution/LanguageBasics/ProducerConsumerCpp/ProducerConsumerCpp.vcxproj @@ -0,0 +1,148 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + Win32Proj + {dad3bb7c-72df-40db-bfc3-f24a39e5da1a} + ProducerConsumerCpp + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + + + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpplatest + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + \ No newline at end of file