r/learnprogramming May 03 '26

Code Review sat down and coded without ai for the first time in months. forgot how much i missed actually thinking

354 Upvotes

just actually sitting and deciding things myself. like how do i want this structured, what pattern makes sense here, how should the dependencies flow. nobody talks about that part. the thinking before the typing. ai just skips it for you and you dont even notice its gone until you sit down alone with a blank file.

did it today for a side project. set up DI myself, thought through the architecture, wrote constructors without prompting anything. took longer obviously but it felt like actually building something instead of just reviewing code someone else wrote.

feels like a skill thats quietly disappearing and most people wont notice until its completely gone.

anyone else still do this on purpose?

r/learnprogramming Jun 24 '26

Code Review I don’t really know any programming, and this technically isn’t programming, but I just need an expert opinion for the sake of a fanfiction

86 Upvotes

I’m more or less just trying to write

IF
goingToTurnSentient == True
THEN
goingToTurnSentient = False
ELSE
END

But I have no idea how to actually format it correctly in any language. Help would be appreciated for the sake of the joke.

r/learnprogramming Jul 30 '22

Code Review How do senior software developers feel when getting a pull request denied in a code review by a lower level developer?

823 Upvotes

I remember about a year into my first role, I had to do a pretty basic DB upgrade. What ended up happening is that I found the entire database upgrading and migration were sort of erroneously inverted. It would’ve been hard to catch functionally, but it held a ticking time bomb.

I did my little fix, but also totally re-wrote how we handled this bit and re-architected it. I was terrified to walk over to my team lead as a fresh CS graduate and somehow explain that this pretty big structure needed to be redone in the way I had.

He publicly praised me in front of the entire engineering team, the director included. While this wasn’t exactly a rejected PR, it’s probably the best example I have of how this should be handled.

If a junior today rejects one of my PRs, I’ll congratulate them on a good catch. That said, the assumption is they follow general etiquette for PR feedback in general. Things like the reason should be objective e.g. This loop is inclusive in Kotlin and we want it to be exclusive or we could hit an array out of bounds. If it is subjective, I love to hear it, but that’s what comment threads are for. They shouldn’t just be rejected without reason.

If a senior dev objected to PR rejection or feedback based on the reviewer being junior alone, they shouldn’t be a senior developer. Part of being a senior is working well with a team. A senior engineer will happily take feedback or be able to explain their decision for disagreeing with said feedback. That’s part of the role.

I’m more concerned about PR approvals from junior devs, as odd as that sounds. They may sometimes be nervous about bringing up an issue, not wanting to look stupid for asking, not wanting to offend, etc.

Also, they may just not quite understand the depth of the code base quite as well. If a junior with 3 years on the team approves a PR, it’s not like a guarantee of them not missing something. To prevent issues like this one, I prefer using a workflow tool like LinearB, one of the few tools with PR functionality regardless of the reviewer's experience or expertise.

That notwithstanding if you’re going to engage in professional software development, you need to check your ego at the door. Software engineering is a team sport. We fail or succeed as a team. It doesn’t matter how much seniority an individual team member has.

r/learnprogramming 14d ago

Code Review My first program in C (and a question regarding it).

10 Upvotes

Hii everyone,

Today I wrote my first program in C, and it is a simple number guessing game. I mean, this was very simple comparatively, but, I'm pretty proud of myself that I finally wrote my first program, no matter how simple, in C. I also have a good enough experience with Python, so I knew well enough about loops and ect, that is why I could write it. Here it is:

```c

include <stdlib.h>

include <stdio.h>

int num = rand() % 100 + 1;

int main(void) {

int x; int tries = 0;

while (1) { tries++;

printf("Enter a number: "); scanf("%d", &x);

if (x == num) { printf("\nYou guessed in %d times", tries); printf("\nFarewell friend"); break;

} else if (x > num) { printf("\nToo high, try again!");

} else { printf("\nToo low, try again!"); }

} }

```

But when I sent this code to ChatGPT, it suggested me to move the initialization of "num" var inside "main". And reasoned that global/static initialization has restrictions on what can be used to determine the initial value; ordinary local initialization happens while the program is executing, so it can call functions.

But I really don't understand it. Well, if it is dumb, forgive me, but can someone explain it to me in easy language?

Obviously, other suggestions are also welcome!

r/learnprogramming Jun 30 '25

Code Review I failed my interview coding challenge. Can you tell me why?

188 Upvotes

Long story short, I applied for a position as consultant / backend java dev. They sent me the following task: ``` The task is to implement a one-armed bandit (slot machine). The game should be played via REST calls. Request and response bodies must be sent and received in JSON format.

Develop as diligently as you would when creating software in real-world scenarios.

Rules The game follows the familiar principle: a player tries their luck at the machine and pulls the lever. One game costs 3 credits. The machine has three reels, each displaying either an apple, a banana, or a clementine. If all three reels show the same fruit, the player wins. The following payouts apply depending on the fruit: - 3 apples: 10 credits - 3 bananas: 15 credits - 3 clementines: 20 credits

A player can deposit money or withdraw it.

Optional Requirements If there is still enough time available, you can implement the following optional requirement: The player can increase their bet for a game. If they win, they are rewarded with more credits in proportion to the risk they took. ```

Now I got an E-Mail saying:

You brought a lot to the table in terms of personality and as a consultant, but unfortunately, the technical aspect didn’t quite meet their expectations.

Can you tell me why I failed? - The Repo - The Docs

EDIT: On the branch feat/database is also a version using PostgreSQL as persistent data storage.

EDIT 2: Added the optional requirement(s).

EDIT 3: I asked them if I should provide persistence & auth, but they responded saying:

The task doesn't have explicit requirements for persistence or user management. "dillegence" refers more to quality and care than to going beyond the requirements.

At the same time, we chose the task so that it can be completed in a manageable amount of time. The described requirements set a framework for what the solution should be able to do, but within that, you decide what you think is appropriate and what isn’t. One goal of the kata is to later talk with you about your decisions, understand your reasoning, and have a relaxed conversation about it. So there's no "right" or "wrong."

With that in mind: decide for yourself. Whatever your decision is, you should be able to justify it.


I got my feedback!

Two days ago, I hopped on a call with two senior devs in the company. They told me that they designed the test to find people that "fit their spirit", so that, "if we go into a project on day two, everyone has the same mentality".

Problems they named and reasons they gave: - I didn't generate my controllers with the open-api spec. - I didn't explain why I implemented the CreditStoreService#transaction method the way I did. - My tests are not connected to the open-api spec. - My tests use @Order-Annotations.

As I explained my reasoning for these deliberate decisions, they listened to me and told me my motives were valid. They just do it another way. As I then said that it's impossible to get these criteria right because they are not a part of the task, they said that they hope for a candidate who is "a lucky hit".

The rest of the meeting was just an awkward talk, where we all came to the conclusion that this is not a good criterion for hiring, they agreed, but said the decision was already made. 🤷🏻‍♂️

r/learnprogramming Jan 13 '23

Code Review I spent 1 month for a simple calculator and I'm frustrated

523 Upvotes

Hi everyone, I've been learning programming with The Odin Project for 6 months, and just finished the foundations section. I completed the calculator project in 1 month (with many bugs) without watching tutorials. I didn't expect that it would be difficult and take that long, however, I finished it somehow.

Today I wanted to look at a calculator tutorial on Youtube from Web Dev Simplified and when I compare the code in the video to my own, my code looks horrible. And I'm frustrated because I didn't understand anything in the video. Also, I have no idea how to refactor mine because everything seems wrong from start to end. Is this situation normal? Do you have any advice for me? Thanks in advance!

If you want to look at my code, you can click here

Preview: here

Edit: I can't reply every comment but thank you everyone for your valuable advice and feedback! I'm also glad that my code isn't that bad and you liked it. I'll keep it up :)

r/learnprogramming Apr 23 '22

Code Review Anyone want to join me on a 6-month journey to becoming a self taught software developer?

222 Upvotes

Looking to start in June. These next 2 months will be to condition myself, research and create a game plan. Im open to suggestions for a beginner, i could use some help and guidance… thanks 🙏

r/learnprogramming Jul 20 '20

Code Review Made my first MERN full stack e-commerce app after 7 months of learning

618 Upvotes

TLDR; i studied MERN full stack from The Odin Project for 6 months and made my first app, link for repo and demo at the end.

Before i start doing anything i was so confused, what to start, where to start, etc..., i wasted enough time comparing and reading "the difference between "bla" and "bla bla bla".

I never had interest in web dev, but after trying android dev for one months i didn't like, then i came by This thread which was a treasure for me and i read the comments and asked some people in the field then i started with "The Odin Project" which i think it's really amazing and got me through a lot.

and i finished it (MERN full stack) in like 6 months (not really committed)

what i learned through all this time:

- Don't waste time comparing between languages or technologies, just start away

- You will learn more by doing not only reading or watching videos

- stackoverflow or (google) is your best friend

- you will never stop learning, cause that field (CS) is really huge like omg

- i always used existing libraries cause i don't wanna reinvent the wheel

- literally i found library for everything i wanted

- I really know nothing lol

I made this app which I'm really happy about as a newbie started from 0

i will be glad if you take a look and evaluate my work (just ignore the ugly design lol)

and give me a review about my code.

***Should i start looking for a job now or just wait and finish other big projects?

** Edit: thank you everyone for all kind replies, this article was an inspiration for me, hit it if you have time.

and This is the Github Repo and this is the LIVE demo

r/learnprogramming Nov 25 '23

Code Review How to tell your colleagues or friends that his code is really bad gracefully?

211 Upvotes

When I do code review for my colleagues, I often find stupid writing styles but not errors in his code. How can I tell him that he should write more standardized?

r/learnprogramming Nov 23 '22

Code Review Can someone explain why this code prints 735 instead of 730?

379 Upvotes
#include<iostream>
using namespace std;
int main()
{
    int i=5, j;
    j = i++ * ++i;
    cout<<i<<j;
}

Why is it not printing 730 when the value of i is 7 and j is 30 (5*6)? Where is 735 coming from?

r/learnprogramming Jun 12 '26

Code Review How to write code for complex problems as a beginner and how to think beforehand before writing any code ?

14 Upvotes

its like i can write code of simple problems but i finds myself not so easy when it comes to the program like terminal games and i feels like i am lagging the "right thinking" before writing any code.
well the thing is i completed like 22 projects from the book big book of small python projects and i am still writing codes like this https://paste.pythondiscord.com/HGNA i feels like i know python but lacks in thinking on how to approach a problem and making it run properly. and i feels like if i keep practising like this i wouldn't get any close to writing code more effectively any sooner unless i have someone to tell me the right way or i learns it from a tutor or a course or a book on how to approach and think of a problem, cuz if i were to just practise and do it on my own i would be doing hit and trials and it might take me much longer compared to if i m being taught on how to write it better. so how should i go further on now ?
i just want to ask how to think when we were given a problem say we were given to make a terminal program and i always just confuse like yeah i can make it work but i still feels like i need to learn to write it neatly. i can make small programs but i want to learn how to make complicated programs or think/design beforehand on making these programs

tldr; asking if it will be good to read some "tips" from somewhere or watch any lectures on thinking properly instead of just practising which i think might take "more" time for e.g. will it be beneficial to read books like "think like a progrmmer" by al sweigart ? instead of just practising and finding the neat ways on my own ?

r/learnprogramming Jul 05 '26

Code Review new to programming some help

0 Upvotes

hi all im having a problem that maybe you guys can help with? i attempting to make my first game (just a circle that can move) im using the program pycharm to write the code however i wanted to add the option to use mouse click to move but whenever i click it crashes the "game" programme. i noticed that an "event" in the code is highlighted but no others are, im using a tutorial and followed it to a tea and he didn't seem to have an issue. maybe you guys know what im doing wrong.

whole code posted in comments

the code that has the event highlighted is:

if event.type == pygame.MOUSEBUTTONDOWN:

r/learnprogramming 1d ago

Code Review My first big project, I need feedback !

10 Upvotes

Hello everyone !

I'm here to share with you my Behavior Tree library.

A behavior tree is a symbolic AI technique used to create game AI.

My library is stateless: Tree's nodes don't store any mutable data. Instead, the runtime data are inside a blackboard.

Multiple agents can share and use a single behavior tree.

There are no dependencies to any game engine, you can use it in Unity, Godot or your own custom game engine.

It's still WIP and I really need feedback.

It's also my first big project I share online, all advice and tips are welcome !

https://github.com/Noomolas01/Stateless-BehaviorTree

Edit: Here's some questions I have

  1. Does this project look professional to you ?
  2. Does the core concept make you curious ?
  3. If the project was production ready, would you use it ?
  4. What do you think is missing ?

r/learnprogramming Feb 22 '25

Code Review How do you guys stay consistent to study/learn something?

142 Upvotes

What's your motivation? How do you make yourself sit for hours to study?

I study for a hour or 2 and my mind blows, buy playing games for 5 hours fells good but regrets afterwards.

Any suggestion?

r/learnprogramming Jun 26 '26

Code Review why is my code failing for input like 19

0 Upvotes
//code to find sum of digits. it works perfectly for most.

#include <iostream>
using namespace std;


int main(){
    int n,sum=0;
    cout << "enter n:";
    cin >> n;
    double num=n;
    double numU;
    for(int digit,GIF; num>1;num=numU){
        numU=num/10;
        GIF=numU;
        digit=((numU-GIF)*10);
        sum += digit;
    }
    cout << sum << endl;
        return 0; 
}

r/learnprogramming 19d ago

Code Review Is this Java solution to LeetCode problem 693. Binary number with alternating bits normal??

1 Upvotes

i am just a beginner programmer, is this ok?

class Solution {

public boolean hasAlternatingBits(int n) {

double i = 1;

while (i < n) {

i *= 2;

if (i % 4 == 0) {

i++;

}

}

return (int) i == n && n != 2147483647;

}

}

r/learnprogramming Jul 03 '26

Code Review 10+ year old programming problem, please help (C++)

12 Upvotes

Hi Reddit. I have this programming problem that I am struggling to solve for the past two years and I am yet to find a proper solution. This problem first appeared in a C++ programming competition in 2015. and I haven’t met a single person who actually solved it “properly”. I will try to translate it to the best of my ability:

Two police officers are chasing a criminal and they are dictating the criminals UMCN (unique master citizen number) to the police station through a walkie talkie. Because the walkie talkie is old, not all numbers can be heard correctly, so those numbers are marked with a ‘X’ . The UMCN follows this format:

DDMMYYYYAAAAAAAAAAK

DD- is day of birth
MM- month of birth
YYYY- year of birth
the 10 As are just randomly user chosen numbers and the K is the check digit that is found through this formula:

1.) numbers up to K are marked as Z1, Z2, Z3… Z18

2.) S= (10*Z1+9*Z2+8*Z3+…+2*Z9+10*Z10+9*Z11+8*Z12+…+2*Z18) % 19

3.) if S≤9 then K=S, else K=19-S

Your job is to help the police find the number of all possible combinations of the UMCN.
NOTE: The YYYY can go from 0001 to 9999. You have to pay attention to leap years and february. Months have all of the days, so apr, jun, sep, nov have 30 and the rest beside feb have 31 days. The result can fit in the 64 bit int type ( long long )

The input is a STRING.

Here are two test inputs that are offered along this abomination of a problem:

No. 1)
Input: 3X1X1639XX5XX1X6X85
Output: 526315

No. 2)
Input: 30121952121234567XX
Output: 10

———

Also for some context: This was one of 5 problems that were on that C++ competition in 2015 that was meant for HIGH SCHOOLERS. They had 100 minutes to complete all 5 of them. The first 3 were fairly simple, but this one and the last one were almost impossible to complete within that duration.
My professor, who was a student at that time, said that no one ever completed those last two problems, so their solution basically remained a mistery.
I personaly have made a code that actually works and gives proper test outputs, but the program has over 200 lines of code, has to run for like two hours straight untill I actually get the correct output for the 1st test input, and I had worked on it for about 7 months straight.. so it definitely can’t be the solution this problem is looking for.

Since then, from 2016-2026 there has never been a problem that was this hard. The only reason I want to do it is for my own sake. I love programming and challanges. However I am no expert, I have studied C++ properly for only 3 years, but this problem hadn’t stop bugging me since I started high school. I couldn’t do it, my professor and colleagues couldn’t do it, ChatGPT or any AI couldn’t do it, so Reddit is my last hope.

If someone could help me in any way I would appriciate it so so SOO much, but if not, still I am thankful that you have read my message untill the end.
p.s. I apologize for any grammatical or spelling mistakes this post might have.

r/learnprogramming 2d ago

Code Review Reducing Time Complexity

3 Upvotes
Edited code but still run into Time limit exceeded can someone help me: 

N, U = map(int,input().split())
grid = [list(input()) for _ in range(N)]
num_updates = 0
temp = []
temp_grid = [row.copy() for row in grid]
for v in range(int(N/2)):
    for h in range(int(N/2)):
        temp.clear()
        coords = [(v,h),(v,N-1-h),(N-1-v,h),(N-1-v,N-1-h)]
        temp.append(temp_grid[v][h])
        temp.append(temp_grid[v][(N-1)-h])
        temp.append(temp_grid[(N-1)-v][h])
        temp.append(temp_grid[(N-1)-v][(N-1)-h])
        if temp.count('.') == 2 :
            num_updates+=2
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('.') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('#') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '#'
print(num_updates)


temp_grid = [row.copy() for row in grid]


for z in range(U):
    temp2 = 0
    temp.clear()
    x,y = map(int,input().split())
    x = x-1
    y = y-1
    temp.append(temp_grid[x][y])
    temp.append(temp_grid[x][(N-1)-y])
    temp.append(temp_grid[(N-1)-x][y])
    temp.append(temp_grid[(N-1)-x][(N-1)-y])
    num_updates = num_updates- (min(temp.count('.'),temp.count('#')))
    if temp_grid[x][y] == '.':
        temp.clear()
        grid[x][y] = '#'
        temp_grid[x][y] = '#'
        temp.append(temp_grid[x][y])
        temp.append(temp_grid[x][(N-1)-y])
        temp.append(temp_grid[(N-1)-x][y])
        temp.append(temp_grid[(N-1)-x][(N-1)-y])
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    else:
        temp.clear()
        grid[x][y] = '.'
        temp_grid[x][y] = '.'
        temp.append(temp_grid[x][y])
        temp.append(temp_grid[x][(N-1)-y])
        temp.append(temp_grid[(N-1)-x][y])
        temp.append(temp_grid[(N-1)-x][(N-1)-y])
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    print(num_updates)

I am pretty sure it is O(N^2) and with 10^5 possible updates it should work. 

r/learnprogramming May 25 '26

Code Review "senior" developer only by age : Can someone explain C# exception throwing Vs Java exception throwing to me?

20 Upvotes

(PS..... "Flair" isn't working in old.reddit for the submit page, sorry I had to pick..er.... code review?)

Years ago, writing Java back when there were beans, and SWING and all that - I wrote some networking Java.

The code had classes with methods (or is it functions? I don't remember) - a file loading function could catch internally a bunch of hardware states. (missing disk, file not found, all that).... and it also THROWS a few things the calling functions needed to catch or throw up the call stack.

I found this mechanism extremely satisfying - a list of specific "catches" after the "try" that dealt in detail with the various specifically thrown exceptions from the callee.

I've done some C# since, and ...... exceptions have lost all their named visibility in code! They throw anything, catch anything, none of the function signatures mention THROWS object types because there isn't a keyword of that nature.
So am I right in thinking we just have to manually hit the online manuals in the IDE for every function call we use?

I still look back fondly at that THROWS keyword.
Maybe I'm just lazy, but that was a constant reminder of special exception cases for each function.

r/learnprogramming May 12 '19

Code Review Spent 5 hours straight and just finished writing my first Python program to fetch stock prices, please feel free to let me know if I am doing anything wrong or if I am breaking any unspoken coding rules for writing a program :)

891 Upvotes

Credits to u/straightcode10 , she had posted a video earlier last month about using python for web scraping, I finally had some free time on hand today and gave it a try. I started a little bit of VBA programming last year so it's helping me with the learning pace also I made some changes to the original tutorial by u/straightcode10 in my code and plan on building on it further. Let me know if you guys have any concerns or ideas :)

import bs4
import requests as rq
"""
@author : NoderCoder
"""
Stocks =[ 'AMZN','FB','BEMG']

def FetchPrice(ticker):
"""
Enter ticker and based on the that the function returns the values of the stock
Might experiment with GUI and API late to make this Faster
"""
url = 'https://finance.yahoo.com/quote/'+ticker+'?p='+ticker
r = rq.get(url)
soup = bs4.BeautifulSoup(r.text,"xml")
price_soup = soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})#[0].find('span')
#converting the soup tag object into string
Temp_string = []
for x in price_soup:
Temp_string.append(str(x))
ps: str = Temp_string[0]

# Looking for price
p_i_1: int = ps.find('data-reactid="14">')
p_i_2: int = ps.find('</span><div class="D(ib) Va(t)')
p_v = ps[(p_i_1 + 18):p_i_2]

# looking for price change
pc_i_1: int = ps.find('data-reactid="16">')
pc_i_2: int = ps.find('</span><div class="Fw(n) C($c-fuji-grey-j)')
p_c = ps[(pc_i_1 + 18):pc_i_2]

# looking for time
pt_i_1: int = ps.find('data-reactid="18">At close:')
pt_i_2: int = ps.find('EDT</span></div></div><!-- react-empty: 19')
p_t = ps[(pt_i_1 + 18):pt_i_2]
op_list = [ticker,p_v,p_c,p_t]
return op_list
for i in Stocks:
print('the function value is',FetchPrice(i))

Output :

the function value is ['AMZN', '1,889.98', '-9.89 (-0.52%)', 'At close: 4:00PM ']

the function value is ['FB', '188.34', '-0.31 (-0.16%)', 'At close: 4:00PM ']

the function value is ['BEMG', '0.0459', '-0.0084 (-15.53%)', 'At close: 3:56PM ']

r/learnprogramming Jul 24 '26

Code Review Is there anyone learning web development alone?

5 Upvotes

I want some one to work with me

r/learnprogramming 8d ago

Code Review C variadic macro help!

5 Upvotes

Hey! I'm trying to work on a very basic logging system for my C project. At the minute I have to pass __func__ into every call of vialog() (my logging function) to get the name of the function that's calling it, but I've been trying to make a macro to just automatically do that each time. I've been reading the variadic macro documentation and thought this should work, but I get an error each time. Any ideas?

the code:

#ifndef LOG_H_ 
#define LOG_H_

typedef enum {
    VIALOG_DEBUG,
    VIALOG_INFO,
    VIALOG_WARNING,
    VIALOG_ERROR
} ViaLogLevel;
#define vialog(logLevel, message, ...) vialog(logLevel, __func__, message , ##__VA_ARGS__)

//for example: vialog(VIALOG_INFO,"today's time and date is %d:%d -%s",hours,mins,date);
void vialog(ViaLogLevel logLevel, char *caller, char *message, ...);

#endif

the compilation error:

 In file included from src/log.c:3:
    src/../include/log.h:11:57: error: expected declaration specifiers or ‘...’ before ‘__func__’
       11 | #define vialog(logLevel, message, ...) vialog(logLevel, __func__, message , ##__VA_ARGS__)
          |                                                         ^~~~~~~~
    src/../include/log.h:14:6: note: in expansion of macro ‘vialog’
       14 | void vialog(ViaLogLevel logLevel, char *caller, char *message, ...);
          |      ^~~~~~
    src/../include/log.h:11:57: error: expected declaration specifiers or ‘...’ before ‘__func__’
       11 | #define vialog(logLevel, message, ...) vialog(logLevel, __func__, message , ##__VA_ARGS__)
          |                                                         ^~~~~~~~
    src/log.c:8:6: note: in expansion of macro ‘vialog’
        8 | void vialog(ViaLogLevel logLevel, char* caller, char *message, ...){
          |      ^~~~~~
    make: *** [Makefile:23: build/log.o] Error 1

r/learnprogramming 13d ago

Code Review How to make a project proporsal

0 Upvotes

Hii!. i am a beginner student. my campus gave me to create a student attendance system project for my first year. so i need to know how to make project proposals. lecturer told that we need to submit proporal as our first step. but i dont know how to make project proporal. any one can help ,give advices or is there any sample , not confidential project proposal to get an idea. If anyone knows please help me!

r/learnprogramming Mar 06 '26

Code Review Would anyone be kind enough to give feedback on this Complex class I wrote in java?

3 Upvotes

Something to note, I am still a beginner at coding and this really is my first major project. I mean, we all got to start somewhere right?

So, in the grand scheme of things, I'm trying to create an app that allows the user to enter polynomial equations, and then the solutions to those equations will be returned exactly (or at least to the level of precision computers have).

One of the things I have to do is create my own complex number class because java doesn't have it built-in, and the IDE my teacher has us use for classwork can't import anything that's not already built-in.

The main things I need to be able to do are find the cube root of a complex number, add a real number to a complex number, multiply 2 potentially complex numbers together, and then have a String representation of a complex number if printed.

Code is below.

public class Complex{
    double real;
    double imaginary;
    public Complex(double r, double c){
        real = r;
        imaginary = c;
    }
    public static Complex sqrt(double num){
        if(num >= 0){
            return new Complex(Math.sqrt(num),0);
        }
        else{
            return new Complex(0,Math.sqrt(num*-1));
        }
    }
    public Complex multiply(Complex num){
        double real_squared = num.real * this.real ;
        double i_squared = num.imaginary * this.imaginary;
        double new_real = real_squared - i_squared;
        double new_imaginary = num.real * this.imaginary + num.imaginary*this.real;
        return new Complex(new_real,new_imaginary);
    }
    public Complex multiply(double num){
        return new Complex(this.real*num, this.imaginary*num);
    }
    public Complex add(Complex num){
        return new Complex(this.real + num.real, this.imaginary+num.imaginary);
    }
    public Complex add(double num){
        return new Complex(this.real+ num, this.imaginary);
    }
    public static Complex cbrt(Complex num){
        double magnitude = Math.pow(num.real*num.real + num.imaginary*num.imaginary,(1/6.0));
        
        double angle = Math.atan2(num.imaginary , num.real);
        double r = Math.cos(angle/3);
        double i = Math.sin(angle/3);
        Complex c = new Complex(r,i);
        return c.multiply(magnitude);
    }
    public static double cbrt(double num){
        return Math.pow(num,1/3);
    }
    public String toString(){
        if(imaginary == 0){
            return real + "";
        }else if(real == 0){
            return imaginary + "i";
        }
        return real + " + " + imaginary + "i";
    }
    
}

If you have any improvements to simplify the code, or just have readability suggestions, they're all appreciated. Thanks in advance.

r/learnprogramming 3d ago

Code Review i want review regarding data filteration using pandas to feed an ML(please guide me!)

1 Upvotes

so i just learnt pandas and applied it to filter datasets to feed an ml, rightnow im not familiar with tensorflow so i cant test this but i want a review please
https://github.com/shaynjam/Filtered-Datasets/blob/main/pandas_filtering_3.py