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

351 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 • • Sep 23 '26

Code Review In phython why does ( int/int ) results in float value. for example 100/25 gives us 4.0 and not 4

5 Upvotes

want to know. thank you

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?

822 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 • • 22d ago

Code Review How Do I Make My 'For' Loop Do Something Else If It Can't Give Results

63 Upvotes

I apologize if the title is confusing, I'm new to reddit + programming as a whole and just started school for it LOL.

In my programming class we need to make a number game where the goal is to make it to 100. The game play loop consists of alternating turns between the user and a computer picking numbers between 1 - 10. In our current assignment I need to include a 'for' loop and decided to make it so within the first half of the total the computer will always try to make the second digit of the total be 9 (ie. If the total = 23 it will add 6 to make total = 29, or if the total is 10 it will add 9 to make total = 19). My code works, for the most part, but if the player inputs something making the total end with a 9 as well the computer skips its turn. I've been trying for 2 1/2 hours now to figure this out but most of my outputs result in the computer spamming inputs without switching turns or else the computer ignoring the rule I'm trying to place in the first place and just inputting random numbers like usual.

FULL CODE

import random

#Rules#
def display_rules():  # Instructions / Rules Function
    print("\nLets play a game of 100!")
    print("In a game of 100 you start with a total of 0")
    print("and we take turns adding 1-10 to that total.")
    print("First to 100 wins!")
    menu()

#Gameplay#
def play_game(): # Game Play function
    play = 1
    total = 0
    print("Let's play a game of 100!")

    while play == 1:
        #!Defines End Game Loop!#
        def end_game():
            play = int(input("Do you want to play again, 1 for 'yes' or 2 for 'no'? "))  # Ask to play again
            if play == 1:
                play_game()
            elif play == 2:
                menu()
            else:
                print("Error! Error! Error!")
                end_game()

        #Asks Who Goes First#
        turn = int(input("Who goes first? (1 = you, 2 = computer): "))

        #Game Play Loop#
        while total < 100:
            if turn == 1:  # Player turn loop
                player_num = int(input("Number you want to add (1 - 10): "))
                if 1 <= player_num <= 10 and total + player_num <= 100:
                    total += player_num
                    print(f">You added {player_num}! Total is now {total}")
                    turn = 2
                else:
                    print("Error! Error! Error!")

            elif turn == 2:  # Computer turn loop
                if total < 90:
                    com_num = random.randint(1, 10)
                    if total < 50:
                        for num in range(1,11):
                            if (num + total) % 10 == 9:
                                    total += num
                                    print(f">Computer added {num}! Total is now {total}")
                    else:
                        total += com_num
                    turn = 1
                else:
                    com_num = 100 - total
                    total += com_num
                    print(f">Computer added {com_num}! Total is now {total}")
                    turn = 1
            else:  # Error messaging
                print("!Error!")
                print("Enter 1 for player or 2 for computer")
                turn = int(input("Who should go first?: "))

        if turn == 2:  # if player reached 100
            print("You win!")  # Display winning message
        else:  # Computer reached 100
            print("Bummer, you lost!")  # Display losing message
        end_game()

#Menu#
def menu():  # Menu function
    print("\nMenu:")
    print("1. Display Rules")
    print("2. Play Game")
    print("3. Exit")
    choice = int(input("Enter your choice (1, 2, or 3): "))
    if choice == 1:
        display_rules()
    elif choice == 2:
        play_game()
    elif choice == 3:
        print("Thank you for playing!")
        exit()
    else:
        print("Invalid choice! Please enter 1, 2, or 3")

#Starts Game#
menu()

com_num = random.randint(1, 10)
if total < 50:
    for num in range(1,10):
        if num + total % 10 == 9:
                total += num
                print(f">Computer added {num}! Total is now {total}")

FOR LOOP / COMPUTER TURN

elif turn == 2:  # Computer turn loop
    if total < 90:
        com_num = random.randint(1, 10)
        if total < 50:
            for num in range(1,11):
                if (num + total) % 10 == 9:
                        total += num
                        print(f">Computer added {num}! Total is now {total}")

        else:
            total += com_num
        turn = 1
    else:
        com_num = 100 - total
        total += com_num
        print(f">Computer added {com_num}! Total is now {total}")
        turn = 1

This is also for a project that is due tomorrow so if I can get a good shove in the right direction that would be very awesome T-T

r/learnprogramming • • Jun 30 '25

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

182 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

525 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 • • Aug 11 '26

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

9 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 • • Apr 23 '22

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

223 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

616 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?

206 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?

378 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 • • 12d ago

Code Review PR Reviews

14 Upvotes

Been getting tasked with reviewing PRs more and more at work. Happy to have that responsibility and grow in that fashion. However, i'm also nervous about doing it properly.

Atm i have a process of sorts to work through things. Understand the change being made (filtering out a column value, combining datasets, manipulation etc). Approach to the change (drop nulls, join v union etc, creating an additional column from scratch or something). Execution of the change. Was it overly verbose and wasteful. Were certain downstream effects not properly accounted for etc

If it all looks good to me. Then I approve. Sometimes I might meet with the programmer to ask questions based on notes as I go through the PR. Other times I don't as it's not needed and I get things clearly.

Would like to know what approach some of you use? Why/how you it? Do you have different tactics for different situations?

Any advice/tips will be appreciated. Just looking to improve and get better at this process as I think it'll also help me get a better understanding of system design and large scale architecture which is something I want/need to get better at

r/learnprogramming • • Sep 23 '26

Code Review Can someone explain this simple code to me?

0 Upvotes

import requests

response = requests.get("https://randomfox.ca/floof")

print(response.status_code)

print(response.text)

So this code will give the status_code wich I understand and than give the text version of the photo of the fox in the site, and the link to the site RandomFox.

What I dont understand is why does it only give info about image and link, and not like other stuff for ex. logo, text, ect.

I suppose its because when you click the api in the site, it gives you the same exact thing wrote down wich I assume to be the info the site allows you to dig, hypotheticaly could one be given extra and alot of info if the site permits it, or false information about the site?

r/learnprogramming • • 5d ago

Code Review What order should I learn JavaScript topics as a beginner who builds real pages?

6 Upvotes

Beginner here. HTML and CSS are solid for me now I've built a link-in-bio page and portfolio pieces. JavaScript topic lists are overwhelming: variables, functions, arrays, loops, objects, DOM, events, fetch.

For someone who learns by building real pages, what order actually works? Deep core JS first, or DOM early so I can see things change?

What tripped you up most when starting JS?

r/learnprogramming • • Feb 22 '25

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

137 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 12 '26

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

15 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 • • 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 :)

897 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 • • Aug 24 '26

Code Review My first big project, I need feedback !

9 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 • • 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 • • 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 • • Aug 06 '26

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 • • 1d ago

Code Review Please help me find out why formState goes stale in React Hook Form

0 Upvotes

I recently dabbled in react forms and got React Hook Forms setup to be used with my Zod schemas, it all works perfectly... that is until I reset the form. The reset causes the formState (to my knowledge) go stale as validation messages show that the title input is empty, but inspecting its value property through code and looking at the display of typed characters on the screen proves otherwise.

I tried multiple stuff and went through the React Hook Form docs, but tbh the docs were utterly useless as I couldn't make heads or tails of any of it. Interestingly tho, using watcher to re-render the react component causes all of it to work so I suspect its a synchronization issue, but I'm still starting out so I don't know for sure...

Schemas:

const PLAIN_DATETIME_REGEX =
  /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,9})?$/;


const DISPLAY_TIME_REGEX = /\bMoments\b|[hm]$/;


export const taskSchema = z.object({
  id: z.uuid().default(() => crypto.randomUUID()),
  status: z.literal(["complete", "incomplete"]).default("incomplete"),
  title: z
    .string()
    .trim()
    .min(1, "Title cannot be empty")
    .max(100, "Title cannot exceed 100 characters"),
  description: z.preprocess(
    (raw: string) => raw?.trim() || undefined,
    z
      .string()
      .max(2000, "Description cannot exceed 2000 characters")
      .optional(),
  ),
  createdAt: z.iso.datetime().default(() => Temporal.Now.instant().toString()),
  deadline: z.preprocess(
    (raw: string) => raw?.trim() || undefined,
    z
      .string()
      .regex(
        PLAIN_DATETIME_REGEX,
        "Deadline must be a valid ISO 8601 plain date and time",
      )
      .optional(),
  ),
  priority: z.literal(["low", "medium", "high"]),
});


export const taskFormSchema = taskSchema.omit({
  id: true,
  status: true,
  createdAt: true,
});


export const taskViewSchema = taskSchema.transform(
  ({ description, createdAt, deadline, ...rest }) => ({
    ...rest,
    description: description,
    createdAt: formatDateTimeSince(createdAt),
    deadline: formatDateTimeUntil(deadline),
  }),
);


export type Task = z.infer<typeof taskSchema>;
export type TaskForm = z.infer<typeof taskFormSchema>;
export type TaskView = z.infer<typeof taskViewSchema>;

Form Component:

export default function TaskSaver() {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<TaskForm>({
    resolver: zodResolver(taskFormSchema),
    mode: "onChange",
    defaultValues: {
      title: "",
      description: "",
      deadline: "",
      priority: "low",
    },
  });


  const addTask = useTasksStore((state) => state.addTask);
  const id = useId();


  const onSubmit: SubmitHandler<TaskForm> = (data) => {
    const result = taskSchema.safeParse(data);


    if (!result.success) {
      console.error(result.error);
      return;
    }


    addTask(result.data);
    reset();
  };


  return (
    <form onSubmit={handleSubmit(onSubmit)} className={styles.root}>
      <div className={styles.group}>
        <label htmlFor={`title-${id}`} className="sr-only">
          Title
        </label>


        <input
          type="text"
          {...register("title")}
          id={`title-${id}`}
          className={clsx(styles.input, styles.inline)}
          placeholder="Title"
        />


        {errors.title && <p className={styles.error}>{errors.title.message}</p>}
      </div>


      <div className={styles.group}>
        <label htmlFor={`description-${id}`} className="sr-only">
          Description
        </label>


        <textarea
          {...register("description")}
          id={`description-${id}`}
          className={clsx(styles.input, styles.multiline)}
          placeholder="Description"
        ></textarea>


        {errors.description && (
          <p className={styles.error}>{errors.description.message}</p>
        )}
      </div>


      {/* Needs to be worked on: below */}
      <div className={styles.group}>
        <label htmlFor={`deadline-${id}`} className="sr-only">
          Deadline
        </label>


        <input
          {...register("deadline")}
          id={`deadline-${id}`}
          className={clsx(styles.input, styles.inline)}
          placeholder="Deadline"
        />


        {errors.deadline && (
          <p className={styles.error}>{errors.deadline.message}</p>
        )}
      </div>


      <div className={styles.group}>
        <label htmlFor={`priority-${id}`} className="sr-only">
          Priority
        </label>


        <select
          {...register("priority")}
          id={`priority-${id}`}
          className={clsx(styles.input, styles.dropdown)}
        >
          <option value="low">Low</option>
          <option value="medium">Medium</option>
          <option value="high">High</option>
        </select>
      </div>


      <div className={styles.group}>
        <button type="button" className={clsx(styles.button, styles.reject)}>
          Cancel
        </button>


        <button type="submit" className={clsx(styles.button, styles.accept)}>
          Save
        </button>
      </div>
    </form>
  );
}

r/learnprogramming • • Jul 03 '26

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

11 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 • • Sep 28 '26

Code Review Study friend

4 Upvotes

Hey I'm a computer engineering student and I want to help anyone in learning to program mostly in c++ since it's my language we will review and help eachother to reach advance level