#development
1 messages · Page 172 of 1
I mean, you still have to write the logic yourself, antlr simply identifies and iterates the elements
I don’t think antlr is used too much in many spots nowadays
It’s cool to learn how it works but I think it’s important to know how to write both a lexer and parser by hand
antlr is surely used nowadays wdym
bank account goes from -$200.00 to $42,949,472.96 overnight
stonks
Tryna slide?!
Honestly making a lexer and parser with my current knowledge would be ludicrous
I still yet to fully grasp language specific features like classes, pointers, references, and anything else beyond basic datatypes and rudamentary knowledge on functions (as I am pretty sure functions are not entirely like what I am used to in languages like js)
I am severely lacking
It’s not as hard as you think tbh
Lexing is basically just a fancy word for “loop over characters to see if I recognize something”
And attaching metadata to each of those characters (line number, column number, if they are a keyword, etc)
I mean yea it might not be hard, but I also am not confident to tackle something like that, nor do I know where to start. I understand it would give me valuable knowledge and a learning experience.
Parsing is a bit more complex but for basic math expressions it’s quite simple
Fair
Well if you end up finishing that calculator thingy lmk if you want a little code review 😉
(Or if you need help with the “correct” approach)
Honestly I am stuck on where to proceed so I dont see myself getting far right now.
What are u stuck on
I also have work in 18 minutes
Right now I am stuck on how to even evaluate the expression
Ophidian gave some helpful advice
but I don't really know how to actually implement something like what he suggested with C++
Are you looking to be accurate for order of operations?
Or do you just want to evaluate sequentially
Order of operations is the hardest thing to do in a calculator like this, but if you don’t care about order of operations then it should be pretty trivial
I'd like to eventually implement following pemdas
Pemdas is likely going to need a proper parser or something like the shunting yard algorithm to implement
Not too good of a way around it
Antlr is cheating if he wants to learn C++ with this project tho :c
but the syntax is quite simple to understand
not what I mean
I'd rather stick to do it my own
the matcher declaration, can help giving an idea on how to sequence your matches
not to use antlr or anything
after u have an image of the chain you're trying to build, u can focus on implementation
If you want a good bit of practice you can make a RPN evaluator with a simple std::list and looping over characters
That way PEMDAS isn’t a giant barrier since there is no order of operations for RPN
2 2 3 + * is equal to 10 for example
3 + 2 = 5
5 * 2 = 10
Never seen an eqaution like that
It’s called reverse Polish notation
It can be trivially evaluated with a stack of operands and operators
So basically all the numbers come first and the operators go after
and it evalutates whatever two numbers are closest to the first operators
then continues down the list?
Basically
If you encounter a number, push it on to the operand stack
If you encounter a operator, pop 2 numbers from the operand stack and push the result back on to the operand stack
It’s easy to implement but still lets you learn a bit before going into evaluating “normal” notation
I will try and implement something of the sort after work
bump 😁
This is my code: https://haste.reversed.dev/p/lVW8XC.js
I get this error;
DiscordAPIError[50035]: Invalid Form Body
8[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names must be unique
Why?
You already have a command with this name
The command has 2 sub commands though in the same file.
But this most likely has nothing to do with this exact command. Check where exactly this error comes from, I assume it's when registering commands. If you have two of the same commands with the same name, change them to something else
why are you checking twice for every subcommand?
i'm curious too
I guess I forgot to remove that part when I was moving both files to one, but still gives the same error.
lemme guess, there's a missing '}'
I initially didn't think of adding a reminder list command until after
yeah you have a duplicate sub command
The list one just doesn't register only the add sub command does
the problem is that you have a duplicate command somewhere in your index.js file
that's what it's saying
Ahhhhh I found that
When I remove the reminders file I get no problems when I add it, then I get the error.
It ended up being because I forgot to delete the old files from the my repo before making the new one.
Wherer should I store one time password? Should I use redis for that?
wdym one-time password?
if you're going to use it once and never again, dont store it
I mean like a email confirmation code
so I need to store the generated code somewhere to check it
hm, I was going to say "you dont store those", but technically u do need to keep it for a while
you can keep it in memory for a while and then discard afterwards
you think? it sounds like unefficient tho
it's the other way around
you'll be storing what, 5 characters per verification request?
yes
a simple map/dictionary will do
and user id
with userid-code pairs
once the time elapses, or the user verifies successfully, u remove the entry
there are expiring-map libs out there, redis has this too iirc
map
okok
maps are O(1) for key accesses
since you'll be retrieving the entry based on userid, it'll be the best option
Ok understood, thank you
yw
I added my bot but its not showing up, i did it yesterday
Its likely still in queue then
Im also trying to get the token for my Topgg thing
You have to wait until they approve your bot
If your bot is accepted, you will find your token in the "webhook" tab when editing your bot
@wheat mesa So here's my thought process on how to achieve this using reverse polish notations. I have 2 lists, one for operands, and the other for operators. Then I will evaluate that by taking the last two entry in the operands and the first in the operators and evaluating it then assigning it to a temp variable. Now if there are no operands left, then it stops evaluating and gives the final result.
yes, this works
Yup that’s pretty much the algorithm
The only reason stacks are used is because it’s more efficient than vectors
(But if by list you mean std::list then that’s a linkedlist so it works as a stack for this impl)
Oh I was using std::vector

I mean it still works, it’s just a little more inefficient
just use int * for lists 
@wheat mesa @radiant kraken @earnest phoenix
std::string expression;
std::cout << "What would you like to evaluate?\n";
std::getline(std::cin, expression);
std::vector<std::string> tokens;
std::istringstream stream(expression);
std::string token;
std::vector<int> operands;
std::vector<std::string> operators;
while (stream >> token) {
tokens.push_back(token);
}
char* endPtr;
for(const std::string& token : tokens) {
long operand = std::strtol(token.c_str(), &endPtr, 10);
if (*endPtr == '\0') {
operands.push_back(operand);
} else {
operators.push_back(token);
}
}
How do you like my code for parsing the input into ints. I don't think I can use strings for operators but for now idc.
looks really good for a beginner
stackoverflow was not giving me proper answers
it was only giving int -> string not string -> int
oh well
I also don't really understand how strtol works
it looks good enough
I have a vague understanding on what it does
strtol stands for string to long
but no idea why I have to use a char pointer
gotcha
OH okay
so if endptr is not a nullptr it will set the value of endptr to the first character after the number
which is why I check for \0
to see if its successful
exactly
So what exactly is a nullptr then
Cause reading on it I don't quite get it
I understand its better than using 0 or NULL
so when is the appropriate time to use nullptr?
in strtol?
Should I use it there?
I figured it'd be good to not use it since I need to verify if the conversion was successful
and if it fails to convert something wont it error if nullptr is used?
no
you pass in nullptr/NULL to the second argument (endptr) if you don't need to parse the next integers following the current one
it's only useful when you want this:
char a[] = "69";
long sixtynine = strtol(a, NULL, 10);
I see
On another note
What would be the best way to get the last x elements of a vector
for example say I wanted the last 2
std::vector<int> a = ...;
std::vector<int>::size_type length = a.size();
// a[length - 1];
// a[length - 2];
```?
this?
I could do that
hm
I just need to use a loop of some kind so it always gets the last two if possible and keeps evaluating the expression until it reaches the end
I was thinking of using a while loop
yup
Oh wait this isn't going to work
Because if it gets down to there only being operand left then it could cause errors or UB
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
std::string expression;
std::cout << "What would you like to evaluate?\n";
std::getline(std::cin, expression);
std::vector<std::string> tokens;
std::istringstream stream(expression);
std::string token;
std::vector<int> operands;
std::vector<std::string> operators;
while (stream >> token) {
tokens.push_back(token);
}
char* endPtr;
for(const std::string& token : tokens) {
long operand = std::strtol(token.c_str(), &endPtr, 10);
if (*endPtr == '\0') {
operands.push_back(operand);
} else {
operators.push_back(token);
}
}
int result = 0;
for(int i = 0; i < operands.size(); i++) {
int op = operands.back();
if(operators.front() == "+") {
result += op;
} else if(operators.front() == "-") {
result -= op;
} else if(operators.front() == "*") {
result *= op;
} else if(operators.front() == "/") {
result /= op;
}
}
std::cout << result << std::endl;
// std::copy(operands.begin(), operands.end(), std::ostream_iterator<int>(std::cout, " "));
// std::copy(operators.begin(), operators.end(), std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}
in theory this seemed fine, in practice not so much
Then I remembered for the reverse polish notation to work, I need to take the last two numbers and not just the first one
😔
switch cases work on characters tho
Honestly
I am just dumbfounnded on what to do
Cause I can easily get the last two, but on how to actually do the evaluations is beyond me
wdym?
Like I can get the last to operands
but on how to evaluate them based on the first operator I have no idea
I cant seem to figure it out
i have an idea in mind
but i dont really have the time to code it rn 
You could explain it instead
wait
something like this @sharp geyser
char * input = ...;
char * endptr = input;
bool first = true;
long last;
while (1) {
long a = std::strtol(endptr, &endptr, 10);
char Operator = get_next_operator(&endptr);
if (first) {
first = false;
long b = std::strtol(endptr, &endptr, 10);
last = execute(Operator, a, b);
} else {
last = execute(Operator, last, a);
}
if (*endptr == '\0') break;
}
// result is `last`
its a bit hard to explain
Also
I wasn't stuck on getting the last two I was stuck on actually how to execute it
why is that?
Because I dont see how I can execute the equation?
its a reverse polish notation. I use push_back to add the operands to the vector
so I get the last 2 and take the first operator
Basically it goes
2 2 3 + *
2 + 3 = 5
5 * 2 = 10
hmmmmmmm
Use of undeclared identifier 'evaluate'
obviously it was a prototype
clearly exists
Oh I know
but I made my own evaluate function
but it is saying it no exist
Wait
do I have to put the function before the main function
is that how C++ work
maybe something like this? ```
first = true
length = operands.size()
for i = 0; i < length; i++
b = operands.back()
operands.pop_back()
a = operands.back()
operands.pop_back()
operator = operators.front()
operators.pop_front()
operands.push_back(execute(operator, a, b))
result = operands.back()
I never thought about just overwriting what the operands vector is
That is actually genuis

i'm so sorry that it took me a while to understand your problem lmao
@earnest phoenix what do you think?
Good enough, note that your const std::string& token declaration shadows the previous declaration
C++ is harmful
@real rose fix automod
to me at least

uh oh spaghettio
What exactly is going on?
Instead of making a normal math calculator
I am using reverse polish notation
:D
Which has really simple rules

what do u think of my pseudocode?
Why would you do that?
to suffer ig
In theory it sounded okay
tho its really good for learning about stacks
It made sense to me, probably not the best way to do it but hey
if it works it works
I wonder why its exiting tho
Apparently a seg fault or access violation

could be a problem on how you're getting the operands and operators
or was it working before?
It's not entirely horrendous, just very inefficient to handle actual compound equations and such, the proper way to handle the discovery of operands and their relative binary expressions is to peek through the characters in the token stream, and going by the rules of operator precedence, construct the structure of the equation from either the left or the right side
And if nothing fits in there, throw a syntax error
wait what's ur code
Use the LLDB debugger
I was going to but I couldn't figure out how to get it to use that one
Is it not this one?
Open C:\Program Files\LLVM\bin, what do you see?
yes
Try running lldb --version in the console
Well there you go, you need to install Python since LLDB uses it
@sharp geyser
one sec
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Damn Hastebin has changed a lot
hmmmm reinterpret_cast<const char *>(token)
this rings a red flag to me
wait
nvm
before the for(int i = 0; i < operands.size(); i++) loop, what does std::cout << operands << '\n' << operators << std::endl; yield?
does it work as expected
well you can't print vectors like that
Did you install Python yet? 
What does it say?
Now then to answer null's question, same shit happens even before the for loop
Same thing
then the problem is not on the last for loop
Its likely the casting to char *
thats the only thing I can think of that i've done differently
but strtol takes in a std::string or char* not char
as i said before, maybe it's something wrong with this ```cpp
for(const char& token : tokens) {
long operand = std::strtol(reinterpret_cast<const char *>(token), &endPtr, 10);
i'm not really that big into C++, is there anything wrong with this? @earnest phoenix
thats what I am thinking
i'm more of a C dev than C++ 
@earnest phoenix So I can't even install python 3.10 anymore its in a security release only stage
and the security release doesn't even have the python310.dll
imo it's better to just try to solve the segfault ourselves without a debugger first
the problem is most likely on that for loop
Can you open the directory Python was installed to?
Already have it open
So yea it was the casting
I did something that was probably worse and got it to work
What is in there?
what was it?
char myCharArray[2];
myCharArray[0] = token;
myCharArray[1] = '\0';
for(const char& token : tokens) {
long operand = std::strtol(myCharArray, &endPtr, 10);

no idea what it does
but did it to see if it would fix the problem
Use the "Windows Installer (64-bit)"
https://www.python.org/downloads/release/python-31010/
ayyy that's actually a really good way to fix the problem
I'm not exactly sure why LLDB doesn't use the latest Python DLL, but eh
I bet
is the result as expected?
I just don't know what it does
Nope
new error
it aborts because back is called on an empty vector
lmao
probably the operators vector
Note that you were casting a reference to a pointer, this is not entirely valid
As there is 3 in the operands 2 in the operators
so its trying to pull a 3rd from the operators when it doesn't exist

not really sure what this does```cpp
std::vector<char> tokens;
std::istringstream stream(expression);
while (stream >> token) {
tokens.push_back(token);
}
what is tokens?
does it just split by whitespace
yea
or
it splits it based on whitespace iirc
is it just the characters for the string
tokens is just the operands and operators
it splits based on whitespace
and then I split them off into their own vectors
so "2 3 +" -> '2', '3', '+'
i see where that would work, not sure when you do 23 59 + tho
I am not accounting for the fact that there will be more operands than operators
It works the same, the extraction operator (>>) of std::istringstream only stops at a whitespace
It's undefined behavior
That's the proper way
there we go
Ah wait I realize now
I think you should prioritize setting up the debugger, it'll help you fix them much faster
nah
bruh
it'll be better if we can get misty to make his calc app working
Funnily enough this is what it showed for the initial error, note the arguments
Okay
changing tokens to std::string caused a lot of problems
and my brain is having issue solving em
You can use it through the command-line
Just lldb path/to/executable, and r (shortcut to process launch)
for(const std::string& token : tokens) {
long operand = std::strtol(token.c_str(), &endPtr, 10);
if (*endPtr == '\0') {
operands.push_back(operand);
} else {
operators.push_back(token);
}
}
``` try this
yea that is what I was doing
but operators is a char vector
because I use a switch/case in the evaluate function to make my life easier when doing the math

yep
brain officially hurty
C++ is so strict with everything js would just be like "ok yep makes sense"

I'm a bit lost, can you show the current code and the behavior?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i'm in the middle of a math exam right now 
its having issues cause at L 59 operators is a char vector and I am trying to push a std::string
I am using chars for the operators because it makes no sense imo for it to be a std::string and it allows me to use a switch/case to do math evaluations easier
tho that might just be my brain being wonky
1:11am
I usually sleep at 2am and wake up at 10am
perks of graduating
and having a job that is a closing shift

sleep smh
Simply access the first character of the string when pushing the operator
It's a single char, nothing else
Those equations 
Wait no
its doing 3 + 2 = 5 and then doing something with the remaining2
I guess adding it
but it should be multiplication
Just implement the ordinary syntax 

Okay now what the fuck is happening
the result is 8 now
OKAY WAIT
VOLTREX
I GOT IT
@wheat mesa hey buddy I got it to work
thru trial and error

I actually learned a lot here
Now I know how to convert a string to an int at least

with the help of me 
not only that I understand more on how vectors work
poggers
Ima move this code to another file
Okay now time to make a discord bot 
wdym?
he in my friends list
damn i didnt know he accepts friends
I was shocked he even accepted it
lmao
Turns out installing the dpp library is a process
a long one at that
Hi
or installing any other C++ library

good luck on that
I got it installed, but doing the cmake stuff for it

Not ready for cmake
it is pain
so ima stick with projects that dont require a package for now
this took way longer than it shouldve https://fs.rjns.dev/v/uqTarusAqeGQRewOJM

Hello, my bot is now have 7.5K servers its not count as very very big bot buts its big enough to create spam!
I need to check server language on all of commands or for example for any message sent on any server I need to check is that message.channel seted up as media only channel or not. so as a result of it I have to send a request to mongoDB to access to my Data Base and check it what should I do?
cache db response with redis or something
doesn't most reputable database libraries already cache data?
I think that if mongodb had a problem with handling a bot that is on 8,000 servers, it would not be such a popular database 
Of course, mySQL probably seems faster, but your database won't fall apart
depends kinda, mongo will be faster for arbitrary data access, regular sql will be faster for structured data
I didnt say mongodb cant handle it
int CheckingAccount::ChangeBalance(int new_balance) {
return this->balance = new_balance;
}
Would this return the value of balance after its set or would it return the old balance.
but I just dont want to request data all time
ok tnx
and also which one is better for sharding? own djs shardingManager or discord-hybrid-sharding?
just use the djs sharding manager ngl
with how djs is now the hybrid sharding one is obsolete imo
Not to mention if you really wanted, you could just turn on auto sharding and call it a day.
so why many devs still use it? 
If you want something easier though, you would wanna go with discord-hybrid-sharding
it has built in stuff to make it a little easier than just turning auto on
which uses your recommended shard count.
no I guess Im gonna try DJS Sharding
iirc should return the new balance value
thanks
ALSO
didn't know if I told you
but I got the RPN thing to work
:D
Nice!
null and voltrex helped me in the end
Good little exercise for learning how istringstream works too
but I managed to figure out the general idea
Now I am working on a mock bank app
So I can learn about classes and headerfiles
Always fun stuff
yessir
You should also learn about pointers and such sometime
Perhaps try implementing your own vector class (but without templates, just for ints or something)
Im sure I can make use of them in this somehow
That’ll be good for pointers
I can try
That’ll teach you the basics of allocation and deallocation
Isn't vector just a dynamic array
Yes
I'll try it out after this mock bank app
Okey
its time 🙏
I finally got myself a proper pc
got it free actually
ordered a rtx 4060 for it
Make sure not to bottleneck it with a bad cpu or power supply
I dont remember how to check bottle necks
I think this is accurate
not terrible
I do want to eventually upgrade my cpu
just not sure what to
and if I do that, I might as well upgrade my mb as well so I can utilize ddr5 ram
I get 500MB more usage just in the start
?
DJS Sharding is heavier
when I start my bot with Hybrid Sharding it takes 1GB ram
and now
with same amount of shards
it takes 1.5GB
yup
normal djs starts with 500mb more
Damn I thought they made it better
as it start 8 different shard and everything work 8 times for example 8 ready.js but in hybrid it was only 2 ready.js as I had 2 Cluster and 4 shard in each cluster so there was same shard count but different usage
i3 with a 4070? That’s definitely gonna bottleneck
You wont get full performance out of your gpu
well which one is better now? hybrid or djs?
If you want clustering hybrid
unless you want to do it yourself with djs
I forgot djs has yet to implement such a thing
Which is surprising considering how much they hold bot dev's hands anyway
no I dont want to do it by my self
splendid
let me know if you have any questions

Same C:
is there someway to check if a guild has a Premium App Subscription for my bot? I dont see it in the guild object.
https://discord.com/developers/docs/resources/guild#guild-object
Ah
if you respond with DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE can you follow up with PREMIUM_REQUIRED?
https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type
can someone explain to me whats a normal? (in vector)
have googled the term still dont understand it
Imagine you have many values with arbitrary values
Normalizing them is simply converting them to 0...1 range
Like 40, 100, 10 would become 0.4, 1, 0.1
@civic scroll @radiant kraken @sharp geyser was bored so made an entire pure parser for the calculator we were talking about 
https://gist.github.com/VoltrexKeyva/b8e91900fb0daaaed799d28d3ea4ef6e
... on a phone
love are you out of your mind
but why must he torture himself like that
What in the fuck
Almost 800 lines on a phone
Buddy, thats not just being bored
Dedication 
Also just want to point out
I never would of been able to do something like that with my current knowledge
@earnest phoenix @radiant kraken sayulang 
oh shit to is supposed to be a keyword
fixed
how did u work on the vscode syntax highlighting
what's that
syntax highlighting engine for vscode i think
What I made is a pure recursive descent parser, one of the hardest and most capable parsers out there (used in basically every mainstream programming language implementation)
What I was suggesting to you wasn't that, there are many many types of parsers that are much simpler but not as powerful or flexible
It looks pretty close to what I made in C#
Granted I based it off of the crafting interpreters implementation
Show 👀
This was one of the first projects I did when I was getting into parsing, pretty proud of adding the whole “MathLibrary.cs” file to it, it feels easy to use and extensible
That's pretty nice
As much as I like the visitor pattern, it's incredibly hard to implement in programming languages that have extremely strict type systems like C/C++ and Rust
Yeah
It’s really annoying, which is why I much prefer rust’s type system for interpreters and such
Versatile pattern matching + a flexible type system for representing recursive structures = a beautiful interpreter
Here’s the same thing implemented in rust (without functions) https://github.com/Jwaffled/math_parser_rs
hey guys i have written my own algorithm for a school project where we had to return the minimal amount of boxes by fitting each and one other
anyways
i ran my code through an online "chat gpt detector"... it returned me fucking 55%
i didn't even copy code from chatgpt, only asked questions about what some issues were and how to fix them lmao
That's awesome
Btw what's the 10 here supposed to be?
https://github.com/Jwaffled/math_parser_rs/blob/master/src/scanner.rs#L114
as long as your can explain ur code it doesnt really matter
my university really bitches on that type of stuff
but the thing is, i literally coded everything myself
so why the fuck is chatgpt zero highlighting me as 54% ai generated?
the stuff it highlighted are really strange as well, such as importing packages, variable names, function signatures..?
ChatGPT Zero is really bad at detecting AI vs hand-written code
because code doesnt have as much possible variation as normal text
i see, i hope that my school isn't using that then..
they are probably using moss of stanford
heard it's a good one
h
It’s the radix of the character, for some reason there’s no overload that assumes it’s base 10, so I have to specify that I’m parsing a base 10 number
Oh, yeah I would assume that there would be a default base 10 radix as well
Or maybe there is a version that assumes base 10 and I just didn’t see it when I wrote that
I hate this https://fs.rjns.dev/v/rlzuCGNuyqiQfJnVWy
Looks fun to me
yea especially the part where it takes 3 hours
Does anyone have recommendations on how to efficiently store and process objects in a physics simulation? Last time I used an ECS, but I felt like I had difficulty achieving flexible behavior
Not sure if I should go after that again, or if I should try some other structure
hey guys
has anyone any recommendations on how to make this look better
idk the products are looking dookie for some reason but i can't place it.
Usually it's better not to center the text, left align is cleaner and easier to look at/follow.
To me the images feel a little too wide?
You could also consider adding a container with a box shadow around each product
i see, thank you for the help!
the search bar is too short
Actually, wouldn't it be better to move this black stripe with stars to the footer? It's probably a matter of taste, but I feel strange when there is a number of stars in the upper right corner, the footer seems to me a better place for such information than the very top of the page
How do i add the feature of sending voice messages to my discord bot
Like just send an mp3 file as voice message
its average
i mean it's okay if it's for the mobile version but
imo it needs to be a bit wider
hey java gurus, i have a question:
I am creating an algorithm to return the minimal amount of boxes needed. One box can fit in another box based on permutations. So suppose a box has dimensions [x,y,z], then you must check all permutations of the box as:
A box fits if there exists a permutation such that x > x of other box, y > y of other box, z > z of other box.
Right now this is my output of my FIRST box splitter:
[[[0.747756, 0.642319, 0.569011], [0.514339, 0.583412, 0.660649]], [[0.556423, 0.772266, 0.755868], [0.675496, 0.705229, 0.544096]], [[0.678271, 0.663318, 0.571389]], [[0.842022, 0.73891, 0.698524], [0.622235, 0.8074, 0.632252], [0.673077, 0.708456, 0.570999], [0.757113, 0.634282, 0.610887]], [[0.605403, 0.879344, 0.840328]], [[0.796699, 0.95473, 0.81393], [0.579564, 0.879689, 0.736052], [0.571137, 0.532766, 0.936874], [0.932276, 0.591703, 0.658759], [0.945931, 0.652785, 0.737563], [0.88937, 0.538176, 0.534113]], [[0.871447, 0.690473, 0.88035]], [[0.777473, 0.892142, 0.962822], [0.579407, 0.848634, 0.925978]], [[0.803432, 0.860415, 0.956237]]]
However, in my recursive call it goes horribly wrong:
public static void boxFitter() {
boolean hasChanged = false;
for(int i = 0; i < boxPartitions.size(); i++){
for(int j = 0; j < boxPartitions.size(); j++){
if(isSmaller(boxPartitions.get(i).get(0), boxPartitions.get(j).get(0))){
boxPartitions.get(i).addAll(boxPartitions.get(j));
result.add(boxPartitions.get(i));
boxPartitions.remove(boxPartitions.get(i));
boxPartitions.remove(boxPartitions.get(j));
i= 0;
j= 0;
hasChanged = true;
}
}
}
if(boxPartitions.size() > 1 && hasChanged){
boxFitter();
}else if(boxPartitions.size() == 1 && hasChanged){
Vector<Double> toCheck = boxPartitions.get(0).get(0);
for(int i = 0; i < result.size(); i++){
if(isSmaller(result.get(i).get(0), toCheck)){
result.get(i).addAll(boxPartitions.get(0));
boxPartitions.remove(boxPartitions.get(0));
} else if(boxPartitions.size() == 1 && isSmaller(toCheck, result.get(i).get(0))){
result.get(i).addAll(0, boxPartitions.get(0));
boxPartitions.remove(boxPartitions.get(0));
}
}
}
}```
it returns me fucking 4 instead of 9 for the minimal boxes. i just need any help on how to progress further and if someone sees the issue..
I...have no idea of what you asked
but a thing is for sure, you need to optimize those accesses
One message removed from a suspended account.
We get a vector of boxes as inputs
They want you to fit boxes inside each other if they fit, meaning that there’s a permutation of the 2 boxes where the dimensions of one box are all bigger than the other.
But for some reason the above method isn’t really doing the job correctly. It partitions the boxes the wrong way
@wheat mesa when it comes to making my own vector implementation, how do you advise I start off?
My thought process is a bit flawed
@earnest phoenix what’s your thoughts on this? I want to try and implement my own vector class, but only supporting ints. Waffle said it’d help with learning pointers and references as well as allocation and deallocation
I just simply don’t know where to start. I was going to treat it like a dynamic array that can take an endless amount of values but I don’t know how to achieve this without actually using vector itself.
Which defeats the purpose if I use the built in vector
I know arrays work by doing type[size] but I don’t know how I’d make that dynamic
usually whats done is you allocate x amounts of ints in your case as an array with an allocator to start off with so you have a plain c array to work with
idk what language youre using but you can make that dynamic aka allocate it using an allocator then deallocate that array once you dont need it anymore with new so something like int* array = new int[x]; in c++ which makes an array of size x
then array references the start of the first int so you can set data on it at specific indexes as usual
theres no boundary checks tho thats for you to implement in a custom vector
or you can simply use a c++ array (std::array) which is a bit more intuitive and safer to work with to make the array 🤷♂️
I see
Yea I’m quite new to c++ so allocation and deallocation are foggy subjects for me
Would x be something that has to be provided when using the custom vector class or would it be any number?
you can make the user provide the initial size of the internal array but whats usually done is c++ starts with some number (it can be anything) as the initial size for the vector array and then grows it once more elements are inserted
you should focus on setting/deleting/initiating the vector first though leave growing/shrinking the internal array for last
So it has a default size but its size can be modified depending on what’s allocated to the array?
essentially yeah
the initial size is usually something that balances the performance of inserting the first few elements and not having too excessively big of an array for no reason
Makes sense
but it really doesnt matter too much can be something on the top of your head like 5 or something or whatever you like
Yea in reality it just needs to be something to start the vector off with
Well thanks a lot for your advice
I’ll try and see if I can get something started
yeah try keep it stupid simple at first so you dont get too ambitious without knowing how to do certain stuff
one thing at a time!!
You implement a capacity and a tracker of vector size, always start with a capacity of one, and allocate an array of the given type with a size of 1
Every time you reach the capacity you basically allocate a new array and move the elements of the previous array to the new one, deallocate the old one, and use the newly allocated array, and increase the capacity on a scale of power of 2
Pretty much every compiler that implements vectors does this
@sharp geyser ```cpp
const int size_of_each_element = sizeof(int);
int * pointer = (int *)std::malloc(initial_capacity * size_of_each_element);
// pointer[0], pointer[1], etc...
if (pointer == nullptr) {
// system out of memory
}
// resize the vector to a new capacity
pointer = std::realloc(pointer, new_capacity * size_of_each_element);
// deletes/frees the memory back to the OS. this MUST be called once you're done with the vector, otherwise you have a memory leak
std::free(pointer);
I see
Ima try and implement something similar tomorrow later today after I wake up
Since its my day off

I wasn't too sure how to free the block of memeory
I'd recommend not calling std::malloc() and then check if it failed, just implement a capacity check instead
but then I remembered there was delete keyword
Because std::malloc() has a much higher overhead than just a simple check
what is the difference between using malloc and just new
new automatically checks if the pointer is nullptr or not for you
both basically does the same thing
so is it better to use new over malloc?
no imo
or for learning purpose is it better to use malloc
new calls the constructor where malloc() does not
^ new is good for classes
so with malloc i'd have to do a lot more checks myself.
right right
wdym
if you're using raw C structs (without constructors) or primitive types (pointers, ints, chars, etc) go for std::malloc, otherwise if you're going for classes/structs with constructors go for new
So when implementing my own custom class, it entails a headerfile as well. I am still not used to what to do in those. I know I should be outlining what is included int he cpp file but when it comes to outlining what a class is I am clueless.
so are you working on a library of some sort
Not really
e.g you want to keep things in separate C++ files
std::malloc() has multiple steps and branches that it goes through before bailing out and returning a nullptr indicating failure, whereas you can know ahead of time that it goes beyond the capacity so you can optimize it further with a simple capacity check
Just messing around in c++ and waffle recommended to make a vector implementation
ah
so I thought i'd just make it a class so I can mess with headerfiles as well
then since you're still a beginner then i recommend write the class definition in a C++ header file
wdym? Isn't that what I was asking about
You basically just only write the types of what the class contains (declaration), not the bodies (definition)
that should be for later imo, linking can get a bit complicated for a beginner
unless his IDE got his back or something
voltrex writing a long essay 
He on phone
Example:
foo.h:
#ifndef FOO_H
#define FOO_H
class Foo {
public:
int foo;
Foo(int foo);
int bar(int baz);
};
#endif // FOO_H
foo.cpp
#include "foo.h"
Foo::Foo(int foo) : foo(foo) {}
int Foo::bar(int baz) const { return foo + baz; }
not main.cpp
foo.cpp
main.cpp should be for the main function/program startup/shutdown
Did you look at the bottom?
It's an example, but yes it should be separated
There
also, why not ```cpp
#include "foo.h"
Foo::Foo(int foo): foo(foo) {}
int Foo::bar(int baz) { return foo + baz; }
i've seen some examples do this
Yes that is correct way actually
The LLVM Project is a collection of modular and reusable compiler and toolchain technologies. - llvm/llvm-project
not as blazingly fast as Rust's Vec tho

@earnest phoenix @radiant kraken so what does int* array; do?
I notice that when messing with it in code, it seems to create a one dimensional list/array/something
as I can do array[1] and assign stuff to it
but I am not sure if I am mistaken
wdym?
I don't know how to really explain it any better
I simply don't understand what int* array is.
like int array obviously means that array will hold a number
yes
but adding an asterisk and what the end behaviour is I don't know
I guess thats as simple as I can get my question
int * array is a pointer to an int in memory
I see
If you think about it arrays in C/C++ are just pointers to the first element
array[1] is the memory address array + index * the size of each element in array, in this case sizeof(int)
I am just trying to figure out the best method of holding onto the array once its been allocated
It creates a pointer to an int, the * in types denotes a pointer, meanwhile in body it denotes deferencing a pointer (accessing its value), if you read the declaration from right-to-left, it is a * (pointer) to int
Pointers are the addresses of values separated by value size in memory, which can be assigned either the value itself or an array of it
int* p can hold either an integer or an array of integers, but when the latter, it'll decay to the first element of the array, and you can access the others using the subscript operator ([]) or by pointer arithmetic (p++ = shift by sizeof(int))
However, int (*p)[5] is a pointer to a whole array of 5 integers (not just the first element), so it can't hold just an integer, and doing pointer arithmetic on an this will shift the array by sizeof(int) * 5
I see
int *
int thing[] is only for array literals
not dynamic arrays
^
volt u dont really need long essays for everything 
I do for explaining things in detail
So for my vector implementation I want to have an internal array correct? So would in my headerfile would I do something along the lines of
class {
private:
int* array;
public:
Vector();
}
Vector::Vector(){
this->array = new int[1]
}
or something along these lines
it's better to explain things in simpler terms
new int[initial_capacity]; yes
I'm explaining it in simpler terms in more detail
well the initial capacity would be 1
and with each new element the capcity changes as a new array is made
sure
i've never seen someone use int (*p)[5] before
Make a capacity field that keeps track of the capacity so you can easily check it on push
ngl sounds like a useless feature
Don't forget a length field, for the current amount of populated elements in the array
public static void createBoxPartitions() {
while (!inputBoxes.isEmpty()) {
Vector<Vector<Double>> currentBox = new Vector<>();
Vector<Double> firstBox = inputBoxes.remove(0);
currentBox.add(firstBox);
for (int i = 0; i < inputBoxes.size(); i++) {
if (isSmaller(firstBox, inputBoxes.get(i))) {
currentBox.add(inputBoxes.get(i));
inputBoxes.remove(i);
i = 0;
} else if (isSmaller(inputBoxes.get(i), firstBox)) {
currentBox.add(0, inputBoxes.get(i));
inputBoxes.remove(i);
i = 0;
} else {
Vector<Vector<Double>> distinctBox = new Vector<>();
distinctBox.add(inputBoxes.get(i));
inputBoxes.remove(i);
boxPartitions.add(distinctBox);
i = 0;
}
}
}
}
For some reason my algorithm partitions all boxes in 4 boxes rather than 6. Would anyone know why?
This is the isSmaller function:
public static boolean isSmaller(Vector<Double> largerBox, Vector<Double> smallerBox) {
Vector<Double> sortedLargerBox = new Vector<>(largerBox);
Vector<Double> sortedSmallerBox = new Vector<>(smallerBox);
Collections.sort(sortedLargerBox);
Collections.sort(sortedSmallerBox);
for (int i = 0; i < 3; i++) {
if (sortedLargerBox.get(i) <= sortedSmallerBox.get(i)) {
return false;
}
}
return true;
}```
Who doesn't like getting the size of the internal array each time you need the size of it

idk man im tired
you cant
its 3am
go to bed then
Where there is a will there is a way
gl finding a way
It's a way to let the compiler enforce the size of array that the pointer is pointing at, a plain array or pointer does not hold its size information across function passes so the compiler cannot enforce it
int* Vector::insert(int element, int index = 0) {
int* temp = this->array;
this->capacity += 1;
for(int i = this->length; i >= index; i--) {
temp[i] = temp[i - 1];
}
temp[index - 1] = element;
int* newArray = new int[this->capacity];
newArray = temp;
delete this->array;
this->array = newArray;
return this->array;
}
Okay this is my shitty implementation of inserting an element into the vector at a specific index.
Please tell me I am at least close
😩
because its much more efficient and faster
and doesnt have to delete and make a new array
I see
Enforcing good memory management practice
#include <cstring>
void print_p(int* arr) { // no size information
}
void print_a(
int arr[5]) { // the `[5]` is redundant here and is not enforced as the
// array decays to a pointer, losing size information
}
void print_pa(int (*p)[5]) { // size information is not lost
}
int main() {
int* p = new int[10];
memset(p, 0, 10 * sizeof(int));
print_p(p); // OK, unexpected
int a[10];
memset(a, 0, 10 * sizeof(int));
print_a(a); // OK, unexpected
int(*pa)[10] = &a;
print_pa(pa); // compiler error, expected
}
People do, a lot actually
where?
I'm not gonna go through lots of repositories to find where exactly they are used but they're used in critical places, such as mission-critical projects
mission-critical?
Okay so wait
I would use realloc to change the size of this->array and then I would then change what this->array is
A mission critical factor of a system is any factor (component, equipment, personnel, process, procedure, software, etc.) that is essential to business operation or to an organization. Failure or disruption of mission critical factors will result in serious impact on business operations or upon an organization, and even can cause social turmoil ...
I am just basing this off of reading cppreference
int* newArray = (int*) std::realloc(this->array, this->capacity);
if(newArray != nullptr){
this->array = temp;
}
so something like this
well you just assign that to this->array
exactly

So I ended up doing it correctly

Now next question
actually no
let me test first
before asking
I gotta try and learn
so I wont ask a question until I am truly stuck
Though actually I do have a question
does c++ have the concept of optional arguments
yes
Cause I notice despite giving index a default of 0
look up std::optional<thing>
when using said method it still expects 2 arguments
Ah
Gotcha
thanks <3
now to truly test
<3
@sharp geyser oh besides did you know something about ```cpp
Class::Class() {
// size zero
}
Class::Class(int size) {
// with size
}
afaik that is also possible
Wait what
@earnest phoenix afaik there's default constructors and all that, what are they for?
Oh right just realized something
I can't treat this like it is an array
as its a class
I just tried doing vec[0]

That's called overloading if you're interested
Both C and C++ have it
so I could technically make it so they can supply a size themselves?
C does not have operator overloading???
afaik it's ```cpp
int Class::operator[](int index) {
}
There's the default constructor and destructor, copy constructor and copy assignment, move constructor and move assignment
Vector::Vector() {
this->capacity = 1;
this->array = new int[1];
this->length = 1;
}
Vector::Vector(int size) {
this-> capacity = size;
this-> array = new int[size];
this-> length = size;
}
yuhh
Okay
So another thing
Is there anyway I can make Vector vec; be treated like an array
so once I make a new vec instance
I can do vec.insert(199) -> vec[0]
to get the first element
this
Overloading in C can be achieved using C11 _Generic, but yeah it doesn't built-in support for it
oh if you want for the values to be modifiable, return a int &, (int reference)
@earnest phoenix how is this possible, afaik pointer to reference is impossible in C++
I don't quite get it
which part do u dont get?
How it is supposed to work
array[3]
void Vec::operator [] (int index) {
index // 3
}
sis this is not rust
wait whay
What you suggest is only possible with global variables, pointer to reference is indeed invalid
pointer + offset
array is a vector class
Hm?
oh wait
it's still continuous memory reason
is it just void Vec::operator[](int index, int value) {} ?
nope
in this case it would be a pointer deref
// in Vector.h
int operator[](int index) const;
//in Vector.cpp
int Vector::operator[](int index) const {
return this->array[index];
}
so something like this?
yes
my IDE pushed the const onto it
thats good
I assume I don't want it modifiable
but why would you not declare the method inside the class?
because it detects that ur function does not modify the class's properties
Wdym
so he can write one in a separate C++ file?
it's the convention if you don't want to create a single-header library
like
class Vector {
public:
int operator [] (int index) const { ... }
}
in the cpp side
that's if you want to make a header-only library
wym?
the convention is to separate the class definition and the class method bodies
it also has the implementation there, how come it only generates headers
In file included from C:/Dev/Vector/main.cpp:2:
C:/Dev/Vector/Vector.h:19:32: error: no template named 'optional' in namespace 'std'
19 | int* insert(int element, std::optional<int> index);

can i just use something else to automatically generate headeds from my class
#include <optional>
You need to include the <optional> header
I did
L
rust has that built-in
smh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
see?
it is included
wait...
lol
you didn't do any checks for array accessing?
Go for it
if (index >= this->length) { yeet }
insane i know
What C++ version are you using?
std::optional requires C++17 or higher
what ide you in
I think c++ 20
you think?
Well tbh sayu
he's in CLion
CLion
open settings
it standard was set to C++ 20








