Compare commits

..
2 Commits
45 changed files with 1458 additions and 1806 deletions

No files matched your search

-1
View File
@@ -1,3 +1,2 @@
exe
*.exe
build/
-21
View File
@@ -1,21 +0,0 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.26100.0",
"compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.44.35207/bin/Hostx64/x64/cl.exe" ,
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-msvc-x64"
}
],
"version": 4
}
-29
View File
@@ -1,29 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "C++: Run without debugging",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}\\build\\debug\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"console": "integratedTerminal",
"preLaunchTask": "C++: Smart Build (Auto-detect Compiler)"
},
{
"name": "C++: Debug with MSVC",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}\\build\\debug\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"console": "integratedTerminal",
"preLaunchTask": "C++: Smart Build (Auto-detect Compiler)"
}
]
}
-66
View File
@@ -1,66 +0,0 @@
{
"files.associations": {
"ostream": "cpp",
"atomic": "cpp",
"bit": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"exception": "cpp",
"format": "cpp",
"initializer_list": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"iterator": "cpp",
"limits": "cpp",
"locale": "cpp",
"memory": "cpp",
"new": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"utility": "cpp",
"xfacet": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xstring": "cpp",
"xtr1common": "cpp",
"xutility": "cpp",
"vector": "cpp",
"list": "cpp",
"optional": "cpp",
"algorithm": "cpp",
"deque": "cpp",
"queue": "cpp",
"stack": "cpp"
},
"files.exclude": {
"**/*.rpyc": true,
"**/*.rpa": true,
"**/*.rpymc": true,
"**/cache/": true
}
}
-97
View File
@@ -1,97 +0,0 @@
param(
[Parameter(Mandatory = $true)]
[string]$SourceFile,
[Parameter(Mandatory = $true)]
[string]$WorkspaceFolder,
[Parameter(Mandatory = $false)]
[string]$BuildType = "debug"
)
# Extract filename without extension
$FileBaseName = [System.IO.Path]::GetFileNameWithoutExtension($SourceFile)
$OutputPath = Join-Path $WorkspaceFolder "build\$BuildType\$FileBaseName.exe"
# Ensure build directory exists
$BuildDir = Join-Path $WorkspaceFolder "build\$BuildType"
if (-not (Test-Path $BuildDir)) {
New-Item -ItemType Directory -Path $BuildDir -Force | Out-Null
}
Write-Host "Building: $SourceFile"
Write-Host "Output: $OutputPath"
Write-Host ""
# Try g++ first
if (Get-Command g++ -ErrorAction SilentlyContinue) {
Write-Host "Using g++ compiler..." -ForegroundColor Green
if ($BuildType -eq "release") {
$gppArgs = @(
"-std=c++17"
"-Wall"
"-Wextra"
"-O2"
"-DNDEBUG"
"`"$SourceFile`""
"-o"
"`"$OutputPath`""
)
}
else {
$gppArgs = @(
"-std=c++17"
"-Wall"
"-Wextra"
"-g"
"-O0"
"`"$SourceFile`""
"-o"
"`"$OutputPath`""
)
}
& g++ @gppArgs
if ($LASTEXITCODE -eq 0) {
Write-Host "Build successful with g++!" -ForegroundColor Green
exit 0
}
else {
Write-Host "g++ build failed, trying MSVC..." -ForegroundColor Yellow
}
}
# Try MSVC as fallback
$VsDevCmd = "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat"
if (Test-Path $VsDevCmd) {
Write-Host "Using MSVC compiler..." -ForegroundColor Green
# Convert to absolute paths for MSVC
$AbsoluteSourceFile = Resolve-Path $SourceFile
$ObjFile = Join-Path $BuildDir "$FileBaseName.obj"
$PdbFile = Join-Path $BuildDir "$FileBaseName.pdb"
if ($BuildType -eq "release") {
$MSVCCommand = "`"$VsDevCmd`" && cl.exe /std:c++17 /W4 /O2 /DNDEBUG /EHsc /MD /Fe:`"$OutputPath`" /Fo:`"$ObjFile`" `"$AbsoluteSourceFile`""
}
else {
$MSVCCommand = "`"$VsDevCmd`" && cl.exe /std:c++17 /W4 /Zi /EHsc /MDd /Fe:`"$OutputPath`" /Fo:`"$ObjFile`" /Fd:`"$PdbFile`" `"$AbsoluteSourceFile`""
}
& cmd /c $MSVCCommand
if ($LASTEXITCODE -eq 0) {
Write-Host "Build successful with MSVC!" -ForegroundColor Green
exit 0
}
else {
Write-Host "MSVC build failed!" -ForegroundColor Red
exit 1
}
}
else {
Write-Error "No C++ compiler found! Please install g++ or Visual Studio."
exit 1
}
+25 -74
View File
@@ -1,76 +1,27 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C++: Smart Build (Auto-detect Compiler)",
"command": "powershell.exe",
"args": [
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}\\.vscode\\smartbuild.ps1",
"-SourceFile",
"${file}",
"-WorkspaceFolder",
"${workspaceFolder}",
"-BuildType",
"debug"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc", "$msCompile"],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "🚀 Smart build - auto-detects g++ or MSVC",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
}
},
{
"type": "shell",
"label": "C++: Smart Build (Release)",
"command": "powershell.exe",
"args": [
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}\\.vscode\\smartbuild.ps1",
"-SourceFile",
"${file}",
"-WorkspaceFolder",
"${workspaceFolder}",
"-BuildType",
"release"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc", "$msCompile"],
"group": "build",
"detail": "🎯 Optimized release build"
},
{
"type": "shell",
"label": "🧹 Clean Build Directory",
"command": "powershell.exe",
"args": [
"-Command",
"if (Test-Path \"${workspaceFolder}\\build\") { Remove-Item -Recurse -Force \"${workspaceFolder}\\build\\*\"; Write-Host 'Build directory cleaned! 🧹' -ForegroundColor Green } else { Write-Host 'Nothing to clean!' -ForegroundColor Yellow }"
],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"detail": "Clean up all build artifacts"
}
]
"tasks": [
{
"type": "cppbuild",
"label": "C: gcc.exe build active file",
"command": "C:\\msys64\\ucrt64\\bin\\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${workspaceFolder}\\exe\\${fileBasenameNoExtension}.exe"
// hey check this line
],
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
+47
View File
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <string.h>
typedef struct
{
int real;
int imag;
} ldaComplex;
void print(ldaComplex *lda)
{
printf("%d + %di", lda->real, lda->imag);
}
// this is the best of my ability in c: returning string is a Fucking Mess
// i would love to do this in rust
ldaComplex add(ldaComplex a, ldaComplex b)
{
return (ldaComplex){a.real + b.real, a.imag + b.imag};
}
ldaComplex multiply(ldaComplex a, ldaComplex b)
{
return (ldaComplex){a.real * b.real - a.imag * b.imag,
a.real * b.imag + a.imag * b.real};
}
int main(int argc, char const *argv[])
{
ldaComplex lda = {1, 2};
ldaComplex lda2 = {5, 2};
ldaComplex addRes = add(lda, lda2);
ldaComplex multiRes = multiply(lda, lda2);
printf("(");
print(&lda);
printf(") + (");
print(&lda2);
printf(") = ");
print(&addRes);
printf("\n(");
print(&lda);
printf(") * (");
print(&lda2);
printf(") = ");
print(&multiRes);
return 0;
}
// ass
-57
View File
@@ -1,57 +0,0 @@
#include <iostream>
#include <string>
typedef struct
{
int real;
int imag;
} ldaComplex;
void print(const ldaComplex *lda)
{
std::printf("%d + %di", lda->real, lda->imag);
}
std::string to_string(const ldaComplex *lda)
{
return std::to_string(lda->real) + " + " + std::to_string(lda->imag) + "i";
}
/**
* @brief Adds two complex numbers.
*
* @param[in] a The first complex number.
* @param[in] b The second complex number.
*
* @return The sum of a and b.
*/
ldaComplex add(const ldaComplex a, const ldaComplex b)
{
return ldaComplex{a.real + b.real, a.imag + b.imag};
}
ldaComplex multiply(const ldaComplex a, const ldaComplex b)
{
return ldaComplex{a.real * b.real - a.imag * b.imag,
a.real * b.imag + a.imag * b.real};
}
ldaComplex operator+(const ldaComplex a, const ldaComplex b)
{
return add(a, b);
}
ldaComplex operator*(const ldaComplex a, const ldaComplex b)
{
return multiply(a, b);
}
int main(int argc, char const *argv[])
{
ldaComplex lda = {1, 2};
ldaComplex lda2 = {5, 2};
ldaComplex addRes = add(lda, lda2);
ldaComplex addResadd = lda + lda2;
ldaComplex multiRes = multiply(lda, lda2);
ldaComplex multiResmul = lda * lda2;
std::cout << to_string(&lda) + " + " + to_string(&lda2) + " = " + to_string(&addRes) << " (" << to_string(&addResadd) << ")" << std::endl;
std::cout << to_string(&lda) + " * " + to_string(&lda2) + " = " + to_string(&multiRes) << " (" << to_string(&multiResmul) << ")" << std::endl;
return 0;
}
// ass
+2 -2
View File
@@ -1,15 +1,15 @@
#include <iostream>
void findMax(int *max, int a)
{
if (a > *max)
*max = a;
};
#include <stdio.h>
int main()
{
int c = 176;
int f = 10;
findMax(&f, c);
std::printf("%d, %d", c, f);
printf("%d, %d", c, f);
return 0;
}
+2 -3
View File
@@ -1,4 +1,4 @@
#include <iostream>
#include <stdio.h>
int log10intint(int n)
{
@@ -12,8 +12,7 @@ int log10intint(int n)
if (n - a < 0)
return i;
}
return ~(1 << 31);
}
};
int ten_to_the(int i)
{
if (i < 0)
+4 -2
View File
@@ -1,5 +1,7 @@
#include <iostream>
#include "sphenic.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool sphenic(int i)
{
if (i < 30)
-1
View File
@@ -1 +0,0 @@
bool sphenic(int i);
-150
View File
@@ -1,150 +0,0 @@
#include <vector>
#include <list>
#include <iostream>
#include <memory>
#include <optional>
class node
{
public:
int data;
std::unique_ptr<node> next;
node(int data) : data(data), next(nullptr) {}
node(int data, std::unique_ptr<node> next) : data(data), next(std::move(next)) {}
// ~node() {}
};
class linked_list
{
public:
std::unique_ptr<node> head;
linked_list() : head(nullptr) {}
linked_list(std::vector<int> v) : head(nullptr)
{
for (int i : v)
{
append(i);
}
}
linked_list(std::initializer_list<int> v) : linked_list(std::vector<int>(v)) {}
void append(int x) // prepend
{
auto temp = std::make_unique<node>(x, std::move(head));
head = std::move(temp);
}
/// Pops the head of the linked list and returns the value in x.
///
/// If the linked list is empty, returns false. Otherwise, returns true.
/// @param x The value popped from the linked list, if not empty.
/// @return true if a value was popped, false if the list was empty.
std::optional<int> pop()
{
if (!head)
return std::nullopt;
int value = head->data;
head = std::move(head->next);
return value;
}
/// Initialize a linked list with a vector of values
///
/// The linked list is created by prepending each item in the vector
/// to the list in order. The resulting list is a linked list where
/// each node contains one item from the vector, and the order of the
/// items in the vector is preserved in the linked list.
linked_list &add(std::vector<int> &v)
{
for (int i : v)
{
append(i);
}
return *this;
}
node *tail() const
{
node *temp = head.get();
if (!temp) return nullptr;
while (temp->next != nullptr)
{
temp = temp->next.get();
}
return temp;
}
// what did i do to my argument
void add(const linked_list &l)
{
if (!l.head) return;
node* l_tail = l.tail(); // valid cuz check above
l_tail->next = std::move(head);
head = std::make_unique<node>(l.head);
// return *this;
}
linked_list &add(std::initializer_list<int> l)
{
for (int i : l)
{
append(i);
}
return *this;
}
std::vector<int> view() const
{
std::vector<int> ret;
node *temp = head.get();
while (temp != nullptr)
{
ret.push_back(temp->data);
temp = temp->next.get();
}
return ret;
}
friend std::ostream &operator<<(std::ostream &os, const linked_list &list)
{
node *temp = list.head.get();
while (temp)
{
os << temp->data << " -> ";
temp = temp->next.get();
}
os << "nullptr";
return os;
}
};
int main(int argc, char const *argv[])
{
linked_list l;
l.append(1);
l.append(2);
l.append(3);
l.append(4);
l.append(5);
std::cout << l << std::endl;
int x = l.pop().value(); // should be 5
std::cout << x << std::endl;
linked_list l2 = {6, 7, 8, 9};
l.add(l2);
l2.add({17, 18, 19, 20, 21});
std::cout << l2 << std::endl;
std::cout << l << std::endl;
std::vector v = l.view();
for (int i : v)
{
std::cout << i << " ";
}
std::cout << "\n";
v = l2.view();
for (int i : v)
{
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}
+195
View File
@@ -0,0 +1,195 @@
#include "../common/linkedlist.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h> // reimport!!! as
#include <stdbool.h>
typedef struct CarInfo
{
int capacity;
char *id; // i follow the thing
// (0, cap]
int reserved;
} CarInfo;
typedef struct Train
{
dllda Cars;
int passengers;
} Train;
// rust is perfect for this let me tell you
CarInfo *CarInit(int cap, char *id)
{
CarInfo *c = (CarInfo *)calloc(1, sizeof(CarInfo));
if (cap > 0)
c->capacity = cap;
c->id = strdup(id);
return c;
}
int trainLength(Train *train) { return (train->Cars).size; }
int car_check(CarInfo *c)
{
if (c->reserved <= 0)
return -1;
else if (c->reserved > c->capacity)
return 1;
return 0;
}
int getPassengers(CarInfo *c) { return c->reserved; }
int getCapacity(CarInfo *c) { return c->capacity; }
// negative passengers
int CarModifyPassengers(CarInfo *car, int passengers)
{
int current = getPassengers(car);
int capa = getCapacity(car);
int added = current + passengers;
if (added > capa)
{
car->reserved = capa;
return added - capa; // added - newCurrent
}
else if (added < 0)
{
car->reserved = 0;
return added;
}
else
{
car->reserved = added;
return 0;
}
}
int TrainModifyPassengers(Train *train, int passengers)
{
if (passengers == 0)
return 0;
int len = trainLength(train);
dllda *Cars = &train->Cars;
int in_or_out = passengers > 0 ? 1 : -1;
int number = in_or_out == 1
? 0
: in_or_out == -1
? len - 1
: false;
for (int i = number;
in_or_out == -1
? i >= 0
: in_or_out == 1
? i < len
: false;
i += in_or_out)
{
CarInfo *thisCar;
dllda_query(Cars, i, (uintptr_t *)&thisCar);
passengers = CarModifyPassengers(thisCar, passengers);
// I DONT FREE cars fuckleyoos
if (passengers == 0)
break;
}
return passengers > 0 ? passengers : 0;
}
int printTheCarThing(CarInfo *c)
{
return printf("CarInfo (id: %s): %d/%d", c->id, c->reserved, c->capacity);
}
int printhere(Train *train)
{
dllda *new = &train->Cars;
int sz = dllda_len(new);
if (sz <= 0)
return 0;
printf("size: %d [", sz);
uintptr_t *c = (uintptr_t *)calloc(sz, sizeof(uintptr_t));
for (int i = sz - dllda_to_list(new, c);
printf("(%d: ", i) &&
printTheCarThing((CarInfo *)c[i]) &&
printf(")") &&
(++i < sz); // how to get value
printf(", "))
;
printf("]\n");
return 1;
}
void cartraverse(Train *train)
{
dllda *l = &train->Cars;
printf("\nthis is cars with size %d, start being uint %p, and end we do not know %p\n", l->size, l->start, l->end);
printf("array repr: ");
printhere(train) || printf("None\n");
int leng = dllda_len(l);
nodeld *someNode = l->start;
for (int i = 0; (i < leng); i++,
(i < leng) && (printf("next node is\n") == 0)) // funnily
{
printf("with find:\n");
nodeld *thisNode = adll_find(l, i);
printf("node %p at %d, ", thisNode, i);
printf("with ptr %p val ", thisNode->ptr);
printTheCarThing((CarInfo *)thisNode->ptr);
printf(", prev %p and next %p\n", thisNode->prev, thisNode->next);
printf("with node traversal:\n");
printf("node %p at %d, ", thisNode, i);
printf("with ptr %p val ", someNode->ptr);
printTheCarThing((CarInfo *)someNode->ptr);
printf(", prev %p and next %p\n", someNode->prev, someNode->next);
someNode = someNode->next;
}
printf("that is all.\n");
}
int main(int argc, char const *argv[])
{
Train train;
train.passengers = 0;
train.Cars = *initlda(); // some fuck
dllda *Cars = &train.Cars;
// cartraverse(&train);
CarInfo *Car1 = CarInit(55, "gay101");
// dllda *Cars = &train.Cars;
dllda_push(Cars, (uintptr_t)Car1);
CarInfo *Car2 = CarInit(73, "top3");
dllda_pushleft(Cars, (uintptr_t)Car2);
// cartraverse(&train);
CarInfo *Car3 = CarInit(25, "r1chk1dz");
dllda_pushleft(Cars, (uintptr_t)Car3);
// cartraverse(&train);
CarInfo *Car4 = CarInit(14, "prez");
dllda_insert(Cars, 2, (uintptr_t)Car4);
cartraverse(&train);
uintptr_t *array = (uintptr_t *)calloc(dllda_len(Cars), sizeof(CarInfo));
dllda_to_list(Cars, array);
// printhere(&train);
int pass = 183;
printf("pass in: %d\n", pass);
printhere(&train);
pass = TrainModifyPassengers(&train, pass);
printf("pass left: %d\n", pass);
// cartraverse(&train);
printhere(&train);
int out = -221;
printf("pass out: %d\n", out);
out = TrainModifyPassengers(&train, out);
printhere(&train);
printf("pass all out?: %d\n", out);
printhere(&train);
return 0;
}
+62
View File
@@ -0,0 +1,62 @@
#include "../common/arraylist.h"
// haha i will have to compile manually EVERY TIME HAHAHAHAHAHAHAHA
// gcc ./2/unboundedIntegers.c ./common/arraylist.c -o ./exe/inboundedIntegers && ./exe/inboundedIntegers
#include <stdio.h>
ldaArrayList number_to_list(long long int e)
{
ldaArrayList c;
ldalistinit(&c);
if (e < 0)
{
ldalistpush(&c, -1);
e = -e;
}
else
ldalistpush(&c, 1);
for (; e > 0; e /= 10)
ldalistadd(&c, 1, (int)(e % 10));
// SHIT IN (array rotato (it means bad))
ldalistprint(&c);
return c;
}
void displayNumber(ldaArrayList *n)
{
for (int i = 0, cur; i < ldalistlen(n); i++)
{
if (ldalistlookup(n, i, &cur) != 0)
return;
if (cur == -1)
printf("-");
else
printf("%d", cur);
}
}
long long int list_to_number(ldaArrayList c)
{
// SHIT OUT
long long ret = 0;
int e;
for (long long int f = 1; ldalistpop(&c, &e) == 0; f *= 10)
{
if (e >= 0)
ret = ret + e * f;
else if (e == -1)
ret = -ret;
}
return ret;
}
// i wont bother with add rem stuff use the list methods directly
int main(int argc, char const *argv[])
{
ldaArrayList ef = number_to_list(-276482364786342);
displayNumber(&ef);
printf("\n");
printf(" %lld ", list_to_number(ef));
return 0;
}
-129
View File
@@ -1,129 +0,0 @@
#include <vector>
#include <iostream>
#include <optional>
class queue
{
private:
static const int cap = 20;
int arr[cap];
int front = 0;
int back = 0;
int size = 0;
public:
int get_size() const { return size; }
/**
* Adds an element to the back of the queue.
*
* @param x The element to be added.
* @return Returns true if the element was successfully added, false if the queue is full.
*/
bool push(int x)
{
if (size == cap)
return false; // Queue is full
arr[back] = x;
back = (back + 1) % cap;
size++;
return true;
}
/**
* Removes an element from the front of the queue.
*
* @return Returns an optional containing the popped value, or std::nullopt if the queue is empty.
*/
std::optional<int> pop()
{
if (size == 0)
return std::nullopt; // Queue is empty
int value = arr[front];
front = (front + 1) % cap;
size--;
return value;
}
/**
* Returns a vector containing the elements of the queue from front to back.
*
* @return A vector of integers representing the queue's contents.
*/
std::vector<int> view() const
{
std::vector<int> ret;
for (int i = 0; i < size; i++)
{
ret.push_back(arr[(front + i) % cap]);
}
return ret;
}
};
int main()
{
queue q;
q.push(1);
q.push(2);
q.push(14);
q.push(2);
q.push(5);
q.push(674);
q.push(7);
q.push(5563);
q.push(9);
q.push(66666);
q.push(1111);
q.push(12);
q.push(13);
q.push(1440);
q.push(15);
q.push(16);
q.push(1778);
q.push(18);
q.push(20);
q.push(20);
std::vector<int> v = q.view();
for (const int i : v)
{
std::cout << i << " ";
}
std::cout << std::endl;
if (!q.push(21))
{
std::cout << "Queue is full!" << std::endl;
}
v = q.view();
for (const int i : v)
{
std::cout << i << " ";
}
std::cout << std::endl;
for (int i = 0; i < 12; i++)
{
auto popped = q.pop();
if (popped.has_value())
{
std::cout << popped.value() << " ";
}
else
{
std::cout << "Queue is empty!" << std::endl;
}
}
std::cout << std::endl;
v = q.view();
for (const int i : v)
{
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
-87
View File
@@ -1,87 +0,0 @@
#include <iostream>
#include <vector>
#include <optional>
class lda_stack
{
private:
std::vector<int> stack;
size_t capacity;
public:
lda_stack(size_t cap = 60) : capacity(cap) {}
/**
* Pushes an element onto the stack.
*
* @param x The element to be pushed.
* @return Returns true if the element was successfully pushed, false if the stack is full.
*/
bool push(int x)
{
if (stack.size() >= capacity)
return false; // Stack is full
stack.push_back(x);
return true;
}
/**
* Pops the top element from the stack.
*
* @return Returns an optional containing the popped value, or std::nullopt if the stack is empty.
*/
std::optional<int> pop()
{
if (stack.empty())
return std::nullopt; // Stack is empty
int value = stack.back();
stack.pop_back();
return value;
}
/**
* Peeks at the top element of the stack without removing it.
*
* @return Returns an optional containing the top value, or std::nullopt if the stack is empty.
*/
std::optional<int> peek() const
{
if (stack.empty())
return std::nullopt; // Stack is empty
return stack.back();
}
/**
* Returns the current size of the stack.
*
* @return The number of elements in the stack.
*/
size_t size() const { return stack.size(); }
};
int main()
{
lda_stack s1;
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
auto popped = s1.pop();
if (popped.has_value())
std::cout << popped.value() << std::endl;
popped = s1.pop();
if (popped.has_value())
std::cout << popped.value() << std::endl;
popped = s1.pop();
if (popped.has_value())
std::cout << popped.value() << std::endl;
popped = s1.pop();
if (popped.has_value())
std::cout << popped.value() << std::endl;
return 0;
}
+1 -1
View File
@@ -1,4 +1,4 @@
#include <iostream>
#include <stdio.h>
int calculate_iter(int n)
{
+7 -8
View File
@@ -1,7 +1,6 @@
#include <iostream>
#include <string>
#include "../1/sphenic.hpp"
using std::string;
#include <stdio.h>
#include <stdbool.h>
bool _sphenic(int num, int cnt, int pr)
{
// Base case: If we have already found 3 distinct primes, check if the number is fully divided.
@@ -41,14 +40,14 @@ bool rsphenic(int n)
int main()
{
int N = 200;
string str;
for (int i = 1; i < N; i++)
{
// printf("%d\n", i);
if (rsphenic(i))
str += std::to_string(i) + " ";
};
std::cout << str << std::endl;
printf("%d ", i);
}
return 0;
}
-117
View File
@@ -1,117 +0,0 @@
#include <iostream>
#include <vector>
#include <cmath>
class binary_tree
{
public:
binary_tree() {}
void append(int x)
{
data.push_back(x);
bubble_up(data.size() - 1);
}
void add(std::vector<int> add)
{
for (int x : add)
{
append(x);
}
}
int pop()
{
if (data.empty())
throw std::runtime_error("Heap is empty");
int ret = data[0];
data[0] = data.back();
data.pop_back();
if (!data.empty())
sift_down(0);
return ret;
}
void print()
{
int levels = 0;
for (int i = 0; i < data.size(); i++)
{
if (log2int(i + 1) == levels + 1)
{
std::cout << "\n";
levels++;
}
std::cout << data[i] << " ";
}
std::cout << "\n";
}
private:
std::vector<int> data;
int log2int(int n)
{
int log = 0;
while (n > 1)
{
n /= 2;
log++;
}
return log;
}
void bubble_up(int idx)
{
while (idx > 0)
{
int parent = (idx - 1) / 2;
if (data[parent] >= data[idx])
break;
std::swap(data[parent], data[idx]);
idx = parent;
}
}
void sift_down(int idx)
{
while (true)
{
int left = 2 * idx + 1;
int right = 2 * idx + 2;
int largest = idx;
if (left < data.size() && data[left] > data[largest])
largest = left;
if (right < data.size() && data[right] > data[largest])
largest = right;
if (largest == idx)
break;
std::swap(data[idx], data[largest]);
idx = largest;
}
}
};
int main(int argc, char const *argv[])
{
binary_tree bt;
bt.append(10);
bt.append(20);
bt.append(5);
bt.append(6);
bt.append(15);
bt.print();
int popped = bt.pop();
std::cout << "Popped: " << popped << "\n";
bt.print();
bt.add({50, 40, 60});
bt.print();
return 0;
}
+113
View File
@@ -0,0 +1,113 @@
// for printf
#include <stdio.h>
#include <stdlib.h>
#include "arraylist.h"
int CAPACITY = 24, ADDITIONAL = 16; // id rather just <<=1
#define INITIAL_CAPACITY 24
#define RESIZE_FACTOR 2
// stack list
void ldalistinit(ldaArrayList *l)
{
l->size = 0;
l->capacity = INITIAL_CAPACITY;
l->list = (int *)calloc(l->capacity, sizeof(int));
if (!l->list)
{
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
}
int ldalistlen(const ldaArrayList *l)
{
return l->size;
}
int ldalistMakeRoom(ldaArrayList *l)
{
if (l->size >= l->capacity)
{
l->capacity *= RESIZE_FACTOR;
int *new_list = (int *)realloc(l->list, l->capacity * sizeof(int));
if (!new_list)
{
fprintf(stderr, "Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
l->list = new_list;
return 1;
}
return 0;
}
int ldalistpush(ldaArrayList *l, int value)
{
// raw dogging
ldalistMakeRoom(l); // ignoring this?
// write first then increase
l->list[l->size++] = value;
return 0;
}
int ldalistadd(ldaArrayList *l, int at, int value)
{
if (at < 0 || at > l->size)
return -1;
ldalistMakeRoom(l);
for (int i = l->size; i > at; i--)
{
l->list[i] = l->list[i - 1];
};
l->list[at] = value;
l->size++;
return 0;
}
int ldalistpop(ldaArrayList *l, int *put_here)
{
if (l->size <= 0) // how would u like
return -1;
*put_here = l->list[--l->size];
// decrease to then take out
return 0;
}
int ldalistremove(ldaArrayList *l, int at, int *put_here)
{
if (at < 0 || at >= l->size)
return -1;
*put_here = l->list[at];
for (int i = at; i < l->size - 1; i++)
{
l->list[i] = l->list[i + 1]; // drag down one
}
l->size--;
return 0;
}
int ldalistlookup(const ldaArrayList *l, int at, int *copy_here)
{
if (at < 0 || at >= l->size)
return -1;
*copy_here = l->list[at];
return 0;
}
void ldalistprint(const ldaArrayList *l)
{
printf("Array with size %d (capacity %d): [", l->size, l->capacity);
for (int i = 0; i < l->size; i++)
{
printf("%d", l->list[i]);
if (i < l->size - 1) // way easier for the eyes
printf(", ");
}
printf("]\n");
};
// int main(int argc, char const *argv[])
// {
// /* code */
// return 0;
// }
+25
View File
@@ -0,0 +1,25 @@
// for printf
// stack list
#ifndef COMMON_LDAARRAYLIST_H
#define COMMON_LDAARRAYLIST_H
typedef struct LdaArrayList
{
int size;
int capacity; // size big then capacity big 2
int *list;
} ldaArrayList;
void ldalistinit(ldaArrayList *l);
int ldalistlen(ldaArrayList *l);
// int ldalistcheck(ldaArrayList *l);
int ldalistpush(ldaArrayList *l, int value);
int ldalistadd(ldaArrayList *l, int at, int value);
int ldalistpop(ldaArrayList *l, int *put_here);
int ldalistremove(ldaArrayList *l, int at, int *put_here);
int ldalistlookup(ldaArrayList *l, int at, int *copy_here);
void ldalistprint(ldaArrayList *l);
#endif
+488
View File
@@ -0,0 +1,488 @@
#include "linkedlist.h"
#include <stdio.h>
#include <assert.h>
// im not good at c!!!!! i do not use the Potential it has
// BE INCREDIBLY FR WITH NODEPTR
// am i doing it right
#define elif else if
// removehidden
dllda *initlda()
{
dllda *list = (dllda *)calloc(1, sizeof(dllda));
if (!list) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return list;
}
nodeld *nodeinit(uintptr_t ptr)
{
nodeld *new = (nodeld *)calloc(1, sizeof(nodeld));
if (!new) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
new->ptr = ptr;
return new;
}
// int dllda_init(dllda *l, uintptr_t firstValue)
// {
// l->size = 1;
// nodeld start;
// start.ptr = firstValue;
// l->start = &start;
// start.prev = NULL, start.next = NULL;
// printf("%p,%p,%p,%d,%p,%p", l, &start, start.ptr, *(int *)start.ptr, start.prev, start.next);
// return 0;
// }
// auto size--
int adll_remove(dllda *whatif, nodeld *node)
{
if (whatif->size <= 0)
{
whatif->size = 0;
return -1;
}
if (!(node->prev == NULL || node == whatif->start) &&
!(node->next == NULL || node == whatif->end)) // not a not b
{
// left of right now is left
node->next->prev = node->prev;
// right of left now is right
node->prev->next = node->next;
}
// no left.
else if (node->prev == NULL || node == whatif->start) // a
{
// start = right
whatif->start = node->next;
if (whatif->start == whatif->end)
whatif->end = NULL; // ass font
// left of right now is null
if (whatif->start != NULL)
whatif->start->prev = NULL;
}
// no right!
else if (node->next == NULL || node == whatif->end) // b
{
// end is now left
whatif->end = node->prev;
// right of left now is null
if (whatif->end != NULL)
whatif->end->next = NULL;
if (whatif->start == whatif->end)
whatif->end = NULL; // i do hate life do i
}
whatif->size--;
free(node);
// free(node);
return 0;
// how do i either know the position or know the
}
int structure_fixups(dllda *l)
{
nodeld *start = l->start, *end = l->end;
if (!(start || end))
{
printf("\nnothing\n");
l->size = 0;
return 0;
}
else if (start == NULL)
{
start = end;
int count = 1;
while (start->prev != NULL)
{
start = start->prev;
count++;
}
l->start = start;
if (count == 1)
l->end = l->start->next;
l->size = count;
return 2;
}
else if (end == NULL)
{
end = start;
int count = 1;
while (end->next != NULL)
{
end = end->next;
count++;
}
if (count > 1)
l->end = end;
l->size = count;
return 1;
}
else
return 3;
{
int cfl = 1, cfr = 1;
while (end->prev || start->next)
{
if (end->prev && start->next == 0)
{
printf("%p, %p", end->prev, start->next);
printf("%d, %d", cfl, cfr);
};
{
end = end->prev;
cfr++;
}
{
start = start->next;
cfl++;
}
}
if (cfl == cfr)
l->size = cfl;
};
}
void dllda_pushleft(dllda *c, uintptr_t ptr)
{
nodeld *new = nodeinit(ptr);
structure_fixups(c);
if (c->start != NULL)
{
new->next = c->start;
new->next->prev = new;
}
c->start = new;
c->size++;
}
void dllda_push(dllda *c, uintptr_t ptr)
{
// printf("%p %p \n", &c, c);
nodeld *new = nodeinit(ptr);
// printf("%p ", new);
structure_fixups(c);
if (c->end || c->start)
{
new->prev = c->end ? c->end : c->start;
new->prev->next = new;
c->end = new;
}
else
c->start = new;
c->size++;
}
int dllda_len(const dllda *c) { return c->size; }
nodeld *adll_find(const dllda *l, int i)
{
int len = dllda_len(l);
if (i < 0 || i >= len)
return NULL;
int attack_from = 1;
nodeld *curnode = l->start;
int from = 0;
if (i > len / 2)
{
attack_from = -1;
curnode = l->end;
from = len - 1;
}
// start is 0 end is len l - 1 aka -1
for (int cur = from; cur != i; cur += attack_from)
{
if (attack_from == 1)
curnode = curnode->next;
else if (attack_from == -1)
curnode = curnode->prev;
}
return curnode;
}
int dllda_rem(dllda *l, int pos, uintptr_t *puthere)
{
nodeld *c = adll_find(l, pos);
*puthere = (uintptr_t)c->ptr;
adll_remove(l, c);
return 0;
}
int dllda_query(const dllda *l, int i, uintptr_t *copy_here)
{
nodeld *g = adll_find(l, i);
if (g == NULL)
{
if (dllda_len(l) == 0)
return -1;
else
return -2;
};
// printf("%p, %p", g, &g);
*copy_here = g->ptr;
return 0;
}
int dllda_popleft(dllda *l, uintptr_t *puthere)
{
nodeld *startMayBeNull = adll_find(l, 0);
if (startMayBeNull == NULL)
{ // start now is No Longer Null
if (dllda_len(l) == 0)
return -1;
else
return -2;
};
*puthere = startMayBeNull->ptr;
adll_remove(l, startMayBeNull);
if (dllda_len(l) == 1)
{
if (l->start == NULL)
;
};
return 0;
}
int dllda_pop(dllda *l, uintptr_t *puthere)
{
nodeld *endMayBeNull = adll_find(l, dllda_len(l) - 1);
if (endMayBeNull == NULL)
{
int len = dllda_len(l);
if (len == 1)
return dllda_popleft(l, puthere);
elif (len == 0) return -1;
else return -2;
};
*puthere = endMayBeNull->ptr;
adll_remove(l, endMayBeNull);
return 0;
}
// no add to size, also bugs when edges (i mean this is a interceptor)
int adll_insert(nodeld *tobeplaced, uintptr_t ptr)
{
nodeld *next = tobeplaced;
nodeld *prev = next->prev;
nodeld *new = nodeinit(ptr);
new->prev = prev;
new->next = next;
if (prev->next != next || next->prev != prev)
{
free(new);
return -1;
}
prev->next = new;
next->prev = new;
return 0;
}
int dllda_insert(dllda *l, int pos, uintptr_t ptr)
{
int len = dllda_len(l);
if (0 < pos && pos < len)
{
nodeld *replaced = adll_find(l, pos);
if (replaced == NULL)
return -1;
if (adll_insert(replaced, ptr) != 0)
return -1;
l->size++;
return 0;
}
else if (pos == len) // funny you can do that
dllda_push(l, ptr);
else if (pos == 0)
dllda_pushleft(l, ptr);
else
return -1;
return 0;
}
int dllda_peek(const dllda *l, uintptr_t *copy_here)
{
return dllda_query(l, dllda_len(l) - 1, copy_here);
}
int dllda_peekleft(const dllda *l, uintptr_t *copy_here)
{
return dllda_query(l, 0, copy_here);
}
void printItOut(dllda *new)
{
int sz = dllda_len(new);
printf("size: %d [", sz);
uintptr_t *c = (uintptr_t *)calloc(sz, sizeof(uintptr_t));
for (int i = sz - dllda_to_list(new, c);
(i < sz); // how to get value
i++,
(i < sz) && printf(", "))
printf("(%d: %d)", i, *(int *)c[i]);
printf("]\n");
}
void traverse(dllda *l)
{
printf("\nthis is l with size %d, start being uint %p, and end we do not know %p\n", l->size, l->start, l->end);
printf("array repr: ");
printItOut(l);
int leng = dllda_len(l);
nodeld *someNode = l->start;
for (int i = 0; (i < leng); i++, // funnily
(i < leng) && (printf("somenode next now.\n") == 0))
{
printf("with find:\n");
nodeld *thisNode = adll_find(l, i);
printf("node %p at %d, ", thisNode, i);
printf("with ptr %p val %d, ", thisNode->ptr, *(int *)thisNode->ptr);
printf("prev %p and next %p\n", thisNode->prev, thisNode->next);
printf("with node traversal:\n");
printf("node? at %d, ", i);
printf("with ptr %p val %d, ", someNode->ptr, *(int *)someNode->ptr);
printf("prev %p and next %p\n", someNode->prev, someNode->next);
someNode = someNode->next;
}
printf("that is all.\n");
}
// return sizes
int dllda_to_list(const dllda *l, uintptr_t *arr)
{
int len = dllda_len(l);
nodeld *node = l->start;
for (int i = 0; i < len; i++)
{
arr[i] = node->ptr;
node = node->next;
}
return len;
}
int dllda_into_list(dllda *l, uintptr_t *arr)
{
int len = dllda_len(l);
for (int i = 0; i < len; i++)
{
uintptr_t *t = &(arr[i]);
dllda_popleft(l, t);
// printf("%d ", *(int*) *t);
}
return len;
}
int dllda_from_list(dllda *l, uintptr_t *arr, int size)
{
for (int i = 0; i < size; i++)
// printf("%p %d ", arr[i], *(int *)arr[i]);
dllda_push(l, arr[i]);
// printf("%d ", *(int*) *t);
return 0;
}
int main(int argc, char const *argv[])
{
dllda *nlist = initlda();
// Test empty list
uintptr_t value;
assert(dllda_pop(nlist, &value) == -1); // Should return -1
// Test one element
int item = 42;
dllda_push(nlist, (uintptr_t)&item);
assert(*(int *)nlist->start->ptr == 42); // Should print 42
assert(dllda_pop(nlist, &value) == 0); // Should succeed
assert(*(int *)value == 42); // Should print 42
assert(dllda_len(nlist) == 0); // Should print 0
// Test multiple elements
int item11 = 1, item22 = 2, item33 = 3;
dllda_push(nlist, (uintptr_t)&item11);
dllda_push(nlist, (uintptr_t)&item22);
dllda_pushleft(nlist, (uintptr_t)&item33);
printItOut(nlist); // Should print [3, 1, 2]
assert(dllda_len(nlist) == 3);
return 0;
// wow
dllda *new = initlda();
int dsa = 17;
dllda_push(new, (uintptr_t)&dsa);
// traverse(new);
printItOut(new);
int item4 = -2;
dllda_pushleft(new, (uintptr_t)&item4);
printItOut(new);
// traverse(new);
int item1 = 1;
dllda_pushleft(new, (uintptr_t)&item1);
// traverse(new);
printItOut(new);
int item5 = 9;
dllda_insert(new, 2, (uintptr_t)&item5);
printItOut(new);
// traverse(new);
int item2 = 4;
dllda_push(new, (uintptr_t)&item2);
// traverse(new);
int item3 = 13;
dllda_push(new, (uintptr_t)&item3);
// traverse(new);
int item6 = 25;
dllda_insert(new, 0, (uintptr_t)&item6);
// printItOut(new);
// traverse(new);
uintptr_t this1, this2, this3;
int code;
code = dllda_rem(new, 3, &this1);
printf(" %d ", *(int *)this1);
// printItOut(new);
code = dllda_popleft(new, &this2);
printf(" %d ", *(int *)this2);
// printItOut(new);
code = dllda_pop(new, &this3);
printf(" %d ", *(int *)this3);
// printItOut(new);
// traverse(new);
printf("\n");
int item7 = 11;
dllda_insert(new, 2, (uintptr_t)&item7);
int item8 = 42;
dllda_insert(new, 1, (uintptr_t)&item8);
int item9 = 16;
dllda_insert(new, 3, (uintptr_t)&item9);
dllda_push(new, this1);
dllda_push(new, this2);
dllda_pushleft(new, this3);
printItOut(new);
printf("\n");
int len = dllda_len(new);
uintptr_t *list = calloc(len, sizeof(uintptr_t));
dllda_into_list(new, list);
for (int i = 0; i < len; i++)
printf("%d ", *(int *)list[i]);
printf("\n");
printItOut(new);
printf("a\n");
dllda_from_list(new, list, len);
printItOut(new);
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
#ifndef LDA_LINKEDLIST_H
#define LDA_LINKEDLIST_H
#include <stdlib.h>
#include <stdint.h>
// Node structure for the doubly linked list
typedef struct Node
{
uintptr_t ptr; // Generic pointer or integer value
struct Node *prev;
struct Node *next;
} nodeld;
// Doubly linked list structure
typedef struct DoublyLinkedList
{
int size; // Number of elements in the list
nodeld *start; // Pointer to the first node
nodeld *end; // Pointer to the last node
} dllda;
// Initializes a new doubly linked list
dllda *initlda();
// Initializes a new node with the given value
nodeld *nodeinit(uintptr_t ptr);
// Fixes the structure of the list (e.g., after modifications)
int structure_fixups(dllda *l);
// Adds a value to the front of the list
void dllda_pushleft(dllda *c, uintptr_t ptr);
// Adds a value to the end of the list
void dllda_push(dllda *c, uintptr_t ptr);
// Inserts a value at the specified position
int dllda_insert(dllda *l, int pos, uintptr_t ptr);
// Finds the node at the specified index
nodeld *adll_find(const dllda *l, int i);
// Returns the length of the list
int dllda_len(const dllda *c);
// Queries the value at the specified index
int dllda_query(const dllda *l, int i, uintptr_t *copy_here);
// Peeks at the first value without removing it
int dllda_peekleft(const dllda *l, uintptr_t *copy_here);
// Peeks at the last value without removing it
int dllda_peek(const dllda *l, uintptr_t *copy_here);
// Removes the value at the specified position
int dllda_rem(dllda *l, int pos, uintptr_t *puthere);
// Removes the first value from the list
int dllda_popleft(dllda *l, uintptr_t *puthere);
// Removes the last value from the list
int dllda_pop(dllda *l, uintptr_t *puthere);
// Converts the list to an array
int dllda_to_list(const dllda *l, uintptr_t *arr);
#endif
-68
View File
@@ -1,68 +0,0 @@
#include <iostream>
#include <vector>
// Array-based list class
class ArrayList
{
private:
std::vector<int> data;
public:
ArrayList() {}
// Adds an element to the end of the list (O(1) amortized)
void push_back(int value)
{
data.push_back(value);
}
// Removes the last element from the list (O(1))
int pop_back()
{
if (data.empty())
{
throw std::runtime_error("List is empty");
}
int value = data.back();
data.pop_back();
return value;
}
// Gets the element at a specific index (O(1))
int get(int index) const
{
if (index < 0 || index >= data.size())
{
throw std::runtime_error("Index out of bounds");
}
return data[index];
}
// Prints the list (O(n))
void print() const
{
for (int value : data)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
int get_size() const { return data.size(); }
};
int main()
{
ArrayList list;
list.push_back(10);
list.push_back(20);
list.push_back(30);
list.print();
std::cout << "Popped: " << list.pop_back() << std::endl;
list.print();
std::cout << "Element at index 1: " << list.get(1) << std::endl;
return 0;
}
-54
View File
@@ -1,54 +0,0 @@
#include <iostream>
#include <vector>
#include <queue>
#include <list>
class Graph {
public:
Graph(int vertices) : adjList(vertices) {}
void addEdge(int u, int v) {
adjList[u].push_back(v); // Add v to u's list
adjList[v].push_back(u); // Because it's an undirected graph
}
void bfs(int start) {
std::vector<bool> visited(adjList.size(), false);
std::queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
std::cout << node << " "; // Process the current node
// Visit all the unvisited neighbors
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
private:
std::vector<std::list<int>> adjList; // Adjacency list representation of the graph
};
int main() {
Graph g(6); // Create a graph with 6 vertices
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
std::cout << "BFS starting from node 0: ";
g.bfs(0); // Perform BFS starting from node 0
std::cout << std::endl;
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
// feed in a pointer to a function that takes 2 and returns (just like the )
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int cmpfunc(const void *a, const void *b)
{
const int *A = a, *B = b;
return (*A > *B) - (*A < *B);
}
int _centeredCube(int num) {
int low = -num, high = num, mid, result = 0;
while (low <= high) {
mid = low + (high - low) / 2;
long long thisSum = (long long) pow(mid, 3) + (long long) pow(mid + 1, 3); // Avoid overflow
if (thisSum == (long long) num)
return mid;
else if (thisSum < num) {
result = mid; // Store the best approximation so far
low = mid + 1;
} else {
high = mid - 1;
}
}
return result; // Return the closest guess when exact match is not found
};
bool centerCube(int num) {
int n = _centeredCube(num);
long long thisSum = (long long) pow(n, 3) + (long long) pow(n + 1, 3);
printf("n = %d, thisSum = %lld, num = %d\n", n, thisSum, num);
return thisSum == (long long) num;
}
int main(int argc, char const *argv[])
{
int a[13] = {1, 2, 3, 7, 3, 9, 11, 13, 42, -1, 4, 52, 10};
qsort(a, 13, sizeof(int), cmpfunc);
for (int i = 0; i < 13; i++)
printf("%d ", a[i]);
printf("\n");
int at = 5;
int *here = (int *)bsearch(&at, a, 13, sizeof(int), cmpfunc);
if (here == NULL)
printf("no %d ", at);
else
printf("is %d ", *here);
return 0;
}
-37
View File
@@ -1,37 +0,0 @@
#include <iostream>
#include <vector>
int binarySearch(const std::vector<int>& arr, int target) {
int low = 0;
int high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // Element found at index `mid`
}
if (arr[mid] < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Element not found
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
int index = binarySearch(arr, target);
if (index != -1) {
std::cout << "Element " << target << " found at index " << index << std::endl;
} else {
std::cout << "Element " << target << " not found" << std::endl;
}
return 0;
}
-128
View File
@@ -1,128 +0,0 @@
#include <iostream>
// Define the structure for a binary tree node
struct Node {
int data; // Value stored in the node
Node* left; // Pointer to the left child
Node* right; // Pointer to the right child
Node(int value) : data(value), left(nullptr), right(nullptr) {} // Constructor
};
// Binary Tree class definition
class BinaryTree {
public:
Node* root; // Root of the binary tree
BinaryTree() : root(nullptr) {} // Constructor to initialize the root to null
// Insert a new node in the binary tree
void insert(int value) {
root = insertRec(root, value);
}
// In-order traversal (left, root, right)
void inOrder() {
inOrderRec(root);
std::cout << std::endl;
}
// Pre-order traversal (root, left, right)
void preOrder() {
preOrderRec(root);
std::cout << std::endl;
}
// Post-order traversal (left, right, root)
void postOrder() {
postOrderRec(root);
std::cout << std::endl;
}
// Search for a value in the binary tree
bool search(int value) {
return searchRec(root, value);
}
private:
// Helper function for inserting a node recursively
Node* insertRec(Node* node, int value) {
// If the tree is empty, create a new node
if (node == nullptr) {
return new Node(value);
}
// Otherwise, recur down the tree
if (value < node->data) {
node->left = insertRec(node->left, value); // Insert in the left subtree
} else {
node->right = insertRec(node->right, value); // Insert in the right subtree
}
return node;
}
// Helper function for in-order traversal (left, root, right)
void inOrderRec(Node* node) {
if (node == nullptr) return;
inOrderRec(node->left); // Visit left subtree
std::cout << node->data << " "; // Visit root
inOrderRec(node->right); // Visit right subtree
}
// Helper function for pre-order traversal (root, left, right)
void preOrderRec(Node* node) {
if (node == nullptr) return;
std::cout << node->data << " "; // Visit root
preOrderRec(node->left); // Visit left subtree
preOrderRec(node->right); // Visit right subtree
}
// Helper function for post-order traversal (left, right, root)
void postOrderRec(Node* node) {
if (node == nullptr) return;
postOrderRec(node->left); // Visit left subtree
postOrderRec(node->right); // Visit right subtree
std::cout << node->data << " "; // Visit root
}
// Helper function for searching a value in the tree
bool searchRec(Node* node, int value) {
if (node == nullptr) return false;
if (node->data == value) return true; // Value found
else if (value < node->data) return searchRec(node->left, value); // Search in left subtree
else return searchRec(node->right, value); // Search in right subtree
}
};
// Driver function to test the binary tree implementation
int main() {
BinaryTree tree;
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
std::cout << "In-order traversal: ";
tree.inOrder(); // Output: 20 30 40 50 60 70 80
std::cout << "Pre-order traversal: ";
tree.preOrder(); // Output: 50 30 20 40 70 60 80
std::cout << "Post-order traversal: ";
tree.postOrder(); // Output: 20 40 30 60 80 70 50
int searchValue = 60;
if (tree.search(searchValue)) {
std::cout << "Found " << searchValue << " in the tree!" << std::endl;
} else {
std::cout << searchValue << " not found in the tree." << std::endl;
}
return 0;
}
-26
View File
@@ -1,26 +0,0 @@
#include <iostream>
#include <vector>
void bubbleSort(std::vector<int>& arr) {
int n = arr.size();
bool swapped;
for (int i = 0; i < n - 1; ++i) {
swapped = false;
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (!swapped) break; // If no elements were swapped, the array is sorted
}
}
int main() {
std::vector<int> arr = {5, 2, 9, 1, 5, 6};
bubbleSort(arr);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-78
View File
@@ -1,78 +0,0 @@
#include <iostream>
#include <deque>
// Deque class using std::deque
class Deque
{
private:
std::deque<int> data;
public:
Deque() {}
// Adds an element to the front of the deque (O(1))
void push_front(int value)
{
data.push_front(value);
}
// Adds an element to the back of the deque (O(1))
void push_back(int value)
{
data.push_back(value);
}
// Removes an element from the front of the deque (O(1))
int pop_front()
{
if (data.empty())
{
throw std::runtime_error("Deque is empty");
}
int value = data.front();
data.pop_front();
return value;
}
// Removes an element from the back of the deque (O(1))
int pop_back()
{
if (data.empty())
{
throw std::runtime_error("Deque is empty");
}
int value = data.back();
data.pop_back();
return value;
}
// Prints the deque (O(n))
void print() const
{
for (int value : data)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
int get_size() const { return data.size(); }
};
int main()
{
Deque deque;
deque.push_back(10);
deque.push_back(20);
deque.push_front(30);
deque.push_front(40);
deque.print();
std::cout << "Popped from front: " << deque.pop_front() << std::endl;
deque.print();
std::cout << "Popped from back: " << deque.pop_back() << std::endl;
deque.print();
return 0;
}
-49
View File
@@ -1,49 +0,0 @@
#include <iostream>
#include <vector>
#include <list>
class Graph {
public:
Graph(int vertices) : adjList(vertices) {}
void addEdge(int u, int v) {
adjList[u].push_back(v); // Add v to u's list
adjList[v].push_back(u); // Because it's an undirected graph
}
void dfs(int start) {
std::vector<bool> visited(adjList.size(), false);
dfsUtil(start, visited);
}
private:
void dfsUtil(int node, std::vector<bool>& visited) {
visited[node] = true;
std::cout << node << " "; // Process the current node
// Visit all the unvisited neighbors
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}
}
}
std::vector<std::list<int>> adjList; // Adjacency list representation of the graph
};
int main() {
Graph g(6); // Create a graph with 6 vertices
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
std::cout << "DFS starting from node 0: ";
g.dfs(0); // Perform DFS starting from node 0
std::cout << std::endl;
return 0;
}
-56
View File
@@ -1,56 +0,0 @@
#include <iostream>
#include <vector>
#include <list>
#include <stack>
class Graph {
public:
Graph(int vertices) : adjList(vertices) {}
void addEdge(int u, int v) {
adjList[u].push_back(v);
adjList[v].push_back(u);
}
void dfsIterative(int start) {
std::vector<bool> visited(adjList.size(), false);
std::stack<int> s;
s.push(start);
while (!s.empty()) {
int node = s.top();
s.pop();
if (!visited[node]) {
visited[node] = true;
std::cout << node << " "; // Process the node
}
// Push unvisited neighbors onto the stack
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
private:
std::vector<std::list<int>> adjList; // Adjacency list representation
};
int main() {
Graph g(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
std::cout << "Iterative DFS starting from node 0: ";
g.dfsIterative(0);
std::cout << std::endl;
return 0;
}
-133
View File
@@ -1,133 +0,0 @@
#include <iostream>
#include <memory>
// Node structure for doubly linked list
struct Node
{
int data;
std::weak_ptr<Node> prev;
std::shared_ptr<Node> next;
Node(int value) : data(value), prev(), next(nullptr) {}
};
// Doubly linked list class
class DoublyLinkedList
{
private:
std::shared_ptr<Node> head;
std::shared_ptr<Node> tail;
int size;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr), size(0) {}
// Adds a value to the front of the list (O(1))
void push_front(int value)
{
auto new_node = std::make_shared<Node>(value);
if (!head)
{
head = new_node;
tail = new_node;
}
else
{
new_node->next = head;
head->prev = new_node;
head = new_node;
}
size++;
}
// Adds a value to the end of the list (O(1))
void push_back(int value)
{
auto new_node = std::make_shared<Node>(value);
if (!tail)
{
head = new_node;
tail = new_node;
}
else
{
tail->next = new_node;
new_node->prev = tail;
tail = new_node;
}
size++;
}
// Removes a value from the front of the list (O(1))
int pop_front()
{
if (!head)
{
throw std::runtime_error("List is empty");
}
int value = head->data;
head = head->next;
if (head)
{
head->prev.reset();
}
else
{
tail.reset();
}
size--;
return value;
}
// Removes a value from the end of the list (O(1))
int pop_back()
{
if (!tail)
{
throw std::runtime_error("List is empty");
}
int value = tail->data;
tail = tail->prev.lock();
if (tail)
{
tail->next.reset();
}
else
{
head.reset();
}
size--;
return value;
}
// Prints the list from front to back (O(n))
void print() const
{
auto current = head;
while (current)
{
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
int get_size() const { return size; }
};
int main()
{
DoublyLinkedList list;
list.push_front(10);
list.push_front(20);
list.push_back(30);
list.print();
std::cout << "Popped from front: " << list.pop_front() << std::endl;
list.print();
std::cout << "Popped from back: " << list.pop_back() << std::endl;
list.print();
return 0;
}
-41
View File
@@ -1,41 +0,0 @@
#include <iostream>
#include <vector>
void heapify(std::vector<int>& arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(std::vector<int>& arr) {
int n = arr.size();
for (int i = n / 2 - 1; i >= 0; --i) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; --i) {
std::swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
std::vector<int> arr = {12, 11, 13, 5, 6, 7};
heapSort(arr);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-24
View File
@@ -1,24 +0,0 @@
#include <iostream>
#include <vector>
void insertionSort(std::vector<int>& arr) {
int n = arr.size();
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = key;
}
}
int main() {
std::vector<int> arr = {12, 11, 13, 5, 6};
insertionSort(arr);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-58
View File
@@ -1,58 +0,0 @@
#include <iostream>
#include <vector>
void merge(std::vector<int>& arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
std::vector<int> L(n1), R(n2);
for (int i = 0; i < n1; ++i) {
L[i] = arr[left + i];
}
for (int j = 0; j < n2; ++j) {
R[j] = arr[mid + 1 + j];
}
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
++i;
} else {
arr[k] = R[j];
++j;
}
++k;
}
while (i < n1) {
arr[k] = L[i];
++i;
++k;
}
while (j < n2) {
arr[k] = R[j];
++j;
++k;
}
}
void mergeSort(std::vector<int>& arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
std::vector<int> arr = {38, 27, 43, 3, 9, 82};
mergeSort(arr, 0, arr.size() - 1);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-32
View File
@@ -1,32 +0,0 @@
#include <iostream>
#include <vector>
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; ++j) {
if (arr[j] < pivot) {
++i;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
std::vector<int> arr = {10, 7, 8, 9, 1, 5};
quickSort(arr, 0, arr.size() - 1);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-24
View File
@@ -1,24 +0,0 @@
#include <iostream>
#include <vector>
void selectionSort(std::vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
int minIdx = i;
for (int j = i + 1; j < n; ++j) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
std::swap(arr[i], arr[minIdx]);
}
}
int main() {
std::vector<int> arr = {64, 25, 12, 22, 11};
selectionSort(arr);
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
-85
View File
@@ -1,85 +0,0 @@
#include <iostream>
#include <memory>
// Node structure for singly linked list
struct Node
{
int data;
std::unique_ptr<Node> next;
Node(int value) : data(value), next(nullptr) {}
};
// Singly linked list class
class SinglyLinkedList
{
private:
std::unique_ptr<Node> head;
Node *tail;
int size;
public:
SinglyLinkedList() : head(nullptr), tail(nullptr), size(0) {}
// Adds a value to the end of the list (O(1))
void push_back(int value)
{
auto new_node = std::make_unique<Node>(value);
if (!head)
{
head = std::move(new_node);
tail = head.get();
}
else
{
tail->next = std::move(new_node);
tail = tail->next.get();
}
size++;
}
// Removes a value from the front of the list (O(1))
int pop_front()
{
if (!head)
{
throw std::runtime_error("List is empty");
}
int value = head->data;
head = std::move(head->next);
if (!head)
{
tail = nullptr;
}
size--;
return value;
}
// Prints the list (O(n))
void print() const
{
Node *current = head.get();
while (current)
{
std::cout << current->data << " ";
current = current->next.get();
}
std::cout << std::endl;
}
int get_size() const { return size; }
};
int main()
{
SinglyLinkedList list;
list.push_back(10);
list.push_back(20);
list.push_back(30);
list.print();
std::cout << "Popped: " << list.pop_front() << std::endl;
list.print();
return 0;
}
+235
View File
@@ -0,0 +1,235 @@
#include <stdio.h>
// Function to perform Cocktail Shaker Sort (Bidirectional Bubble Sort)
void cocktailShakerSort(int arr[], int n)
{
int swapped = 1; // To track if any swaps were made
int start = 0; // Starting index
int end = n - 1; // Ending index
while (swapped)
{
swapped = 0;
// Forward pass: left to right
for (int i = start; i < end; ++i)
{
if (arr[i] > arr[i + 1])
{
// Swap if the current element is greater than the next
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
// If no swaps occurred, the array is sorted
if (!swapped)
break;
// Reduce the end point since the last element is sorted
--end;
// Backward pass: right to left
for (int i = end - 1; i >= start; --i)
{
if (arr[i] > arr[i + 1])
{
// Swap if the current element is greater than the next
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
// Increment the start point since the first element is sorted
++start;
}
}
// Helper function to print the array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
// Swap function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Selection Sort function
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the current element is the minimum
// Find the index of the minimum element in the unsorted portion
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the minimum element with the first element of the unsorted portion
if (minIndex != i) {
swap(&arr[i], &arr[minIndex]);
}
}
}
int findMinIndex(int arr[], int start, int n) {
int minIndex = start;
for (int i = start + 1; i < n; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Recursive Selection Sort function
void recursiveSelectionSort(int arr[], int start, int n) {
if (start >= n - 1) {
return; // Base case: when there's only one element left, array is sorted
}
// Find the minimum element in the remaining unsorted array
int minIndex = findMinIndex(arr, start, n);
// Swap it with the first element of the unsorted portion
if (minIndex != start) {
swap(&arr[start], &arr[minIndex]);
}
// Recur for the remaining unsorted portion
recursiveSelectionSort(arr, start + 1, n);
}
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
// Swap if the current element is smaller than the previous one
swap(&arr[j], &arr[j - 1]);
}
}
}
// Helper function to insert element in the sorted portion recursively
void insertElement(int arr[], int n) {
if (n <= 0) {
return;
}
insertElement(arr, n - 1); // Sort the first n-1 elements
// Now insert the nth element into the sorted portion
for (int j = n; j > 0 && arr[j] < arr[j - 1]; j--) {
swap(&arr[j], &arr[j - 1]);
}
}
// Recursive Insertion Sort function
void recursiveInsertionSort(int arr[], int n) {
if (n <= 1) {
return; // Base case: when the array has 1 or fewer elements, it's sorted
}
recursiveInsertionSort(arr, n - 1); // Sort the first n-1 elements
insertElement(arr, n - 1); // Insert the nth element in the correct position
}
// Merge two sorted subarrays arr[l..m] and arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1; // Size of the left subarray
int n2 = r - m; // Size of the right subarray
// Temporary arrays to hold the values
int *left = (int *)malloc(n1 * sizeof(int));
int *right = (int *)malloc(n2 * sizeof(int));
// Copy data to temp arrays
for (int i = 0; i < n1; i++)
left[i] = arr[l + i];
for (int i = 0; i < n2; i++)
right[i] = arr[m + 1 + i];
// Merge the temp arrays back into arr[l..r]
int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
{
if (left[i] <= right[j])
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}
// Copy the remaining elements of left[], if any
while (i < n1)
{
arr[k] = left[i];
i++;
k++;
}
// Copy the remaining elements of right[], if any
while (j < n2)
{
arr[k] = right[j];
j++;
k++;
}
free(left);
free(right);
}
// Function to split the array and call merge on the halves
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2; // Find the middle point
// Recursively sort the first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
int main()
{
int arr[] = {5, 1, 4, 2, 8, 0, 3, 12, 11, 64, 25, 12, 22, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
// cocktailShakerSort(arr, n);
// mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
-68
View File
@@ -1,68 +0,0 @@
#include <iostream>
#include <vector>
// Stack class using std::vector
class Stack
{
private:
std::vector<int> data;
public:
Stack() {}
// Pushes an element onto the stack (O(1))
void push(int value)
{
data.push_back(value);
}
// Pops the top element from the stack (O(1))
int pop()
{
if (data.empty())
{
throw std::runtime_error("Stack is empty");
}
int value = data.back();
data.pop_back();
return value;
}
// Peeks at the top element of the stack (O(1))
int peek() const
{
if (data.empty())
{
throw std::runtime_error("Stack is empty");
}
return data.back();
}
// Prints the stack (O(n))
void print() const
{
for (int value : data)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
int get_size() const { return data.size(); }
};
int main()
{
Stack stack;
stack.push(10);
stack.push(20);
stack.push(30);
stack.print();
std::cout << "Popped: " << stack.pop() << std::endl;
stack.print();
std::cout << "Peek: " << stack.peek() << std::endl;
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
#include <stdio.h>
int arrPrinter(int *l, int sz)
{
printf("array (size %d): [", sz);
for (
int i = 0;
(printf("%d", l[i]) != 0) &&
(++i < sz);
printf(", "))
;
printf("]\n");
return 0;
}
int main(int argc, char const *argv[])
{
int l[8] = {1, 2, 4, 6, 8, 11, 42, 76};
printf("array l = [");
for (
int i = 0;
(printf("%d", l[i]) != 0) &&
(++i < 8);
printf(", "))
;
printf("]\n");
arrPrinter(l, 8);
return 0;
}
+101
View File
@@ -0,0 +1,101 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *array; // Dynamic array to store heap elements
int size; // Current size of the heap
int capacity; // Maximum capacity of the heap
} MaxHeap;
// Function to create a max heap
MaxHeap* createMaxHeap(int capacity) {
MaxHeap *heap = (MaxHeap *)malloc(sizeof(MaxHeap));
heap->capacity = capacity;
heap->size = 0;
heap->array = (int *)malloc(capacity * sizeof(int));
return heap;
}
// Function to swap two elements
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
// Function to heapify a subtree rooted with node i
void heapify(MaxHeap *heap, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child index
int right = 2 * i + 2; // right child index
// If left child is larger than root
if (left < heap->size && heap->array[left] > heap->array[largest]) {
largest = left;
}
// If right child is larger than largest so far
if (right < heap->size && heap->array[right] > heap->array[largest]) {
largest = right;
}
// If largest is not root, swap and continue heapifying
if (largest != i) {
swap(&heap->array[i], &heap->array[largest]);
heapify(heap, largest);
}
}
// Function to insert a new element to the heap
void insert(MaxHeap *heap, int key) {
if (heap->size == heap->capacity) {
printf("Heap is full, cannot insert %d\n", key);
return;
}
// First insert the new key at the end
heap->array[heap->size] = key;
heap->size++;
// Fix the max heap property if it is violated
for (int i = heap->size / 2 - 1; i >= 0; i--) {
heapify(heap, i);
}
}
// Function to display the max heap
void displayHeap(MaxHeap *heap) {
printf("Max Heap: ");
for (int i = 0; i < heap->size; i++) {
printf("%d ", heap->array[i]);
}
printf("\n");
}
// Main function
int main() {
int capacity;
printf("Enter the maximum capacity of the heap: ");
scanf("%d", &capacity);
MaxHeap *heap = createMaxHeap(capacity);
int numElements;
printf("Enter the number of elements to insert into the heap: ");
scanf("%d", &numElements);
for (int i = 0; i < numElements; i++) {
int value;
printf("Enter value %d: ", i + 1);
scanf("%d", &value);
insert(heap, value);
}
displayHeap(heap);
// Free allocated memory
free(heap->array);
free(heap);
return 0;
}
+3
View File
@@ -0,0 +1,3 @@
# DSA
this Sucks Ass