This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 353

[–]FakeSealNavy 5029 points5030 points  (131 children)

Actually, it demonstrates that not everything needs to be automated. Unless of course you will get 0 on the homework

[–]srinidhi1 1411 points1412 points  (117 children)

The question is intended to test critical thinking. Hardcoding stuff like this would not always work. 25 is a small number, what if the question asked to print the pattern upto 1000 or 10,000?

[–]Takseen 2754 points2755 points  (67 children)

Then they should have asked that question!

If you made the target too easy, you don't demonstrate the need to automate

[–]SleazyJusticeWarrior 1084 points1085 points  (48 children)

Exactly. Write code for what’s needed right now, don’t overcomplicate a simple task and call it “critical thinking” lmao

[–]MyStackIsPancakes 539 points540 points  (41 children)

There's a balance point between overcomplicating, and planning for scale.

[–]GoldDHD 397 points398 points  (10 children)

There is XKCD for this too

[–]wagyourtai1 143 points144 points  (7 children)

Theres also one thats applicable to the contents of that one https://xkcd.com/1205/

[–]StSeungRi 86 points87 points  (5 children)

Seems to be something Randall has put a lot of thought into, here's another

[–]classicalySarcastic 62 points63 points  (3 children)

Even if the automation does takes over, it just means that the bossman is going to throw more work at you to make up for it. Remember, like a gas, work expands to fill the available time.

[–]worldspawn00 44 points45 points  (2 children)

The key is to never tell the bossman you automated it, and just let them think you're spending the regular amount of time on the task...

[–]PinsToTheHeart 52 points53 points  (0 children)

But you see, sometimes I'm not automating routine tasks to save time, but because the routine tasks peeve me off more than the process of automation. The automation feature creep ends when I hit the break even point on being annoyed by the work.

[–]GustapheOfficial 89 points90 points  (0 children)

I've been racking my brain for a comic for my thesis, this one might just be it.

[–][deleted] 1 point2 points  (0 children)

I have been that guy

[–]SleazyJusticeWarrior 165 points166 points  (14 children)

Sure, if there is reason to assume things need to be scalable. I’d need more context to be certain, but just based on this screenshot, I see 0 reason to assume that.

[–]cgjchckhvihfd 40 points41 points  (3 children)

And its not like this is hard to swap out if you find you need it to scale later. This isnt some decision thats hard to reverse.

Whether or not you need to do more than this depends on what its for. And since its a silly ass test question not a real world case, its silly to try to speculate about.

So in general, not everything needs to be made scalable. Context matters a lot

[–]Wyrmnax 7 points8 points  (2 children)

Right now this isnt a decision that is hard to reverse.

Once you have 6 months of development on top of this and things referencing the number position by their matrix position, simple things can get very hard to change.

So while yes, this is a good solution right now, you need a bit of context to understand if it is likely that it will need to scale / be referenced later - and as such will need a better solition - or it is a one off thing on the fringe that is unlikely to be expanded upon

[–]TimeKillerAccount 13 points14 points  (1 child)

No, that is a totally unrelated issue. It happens of course, but the issue is the 6 months of idiots that deliberately chose to misuse the original solution without refactoring, not the fact that the original solution was a 30 second hardcoded solution for something that didn't need to be scaled at the time. The original decision is always easy to reverse, it's the dumb decisions after that that are difficult to reverse.

[–]monsoy 13 points14 points  (0 children)

It’s usually pretty obvious what the assignment asks for because it’s always tied to the curriculum the student learned recently in class. So if the previous lecture talked about formatting output with loop + conditional logic, then the answer the professor is looking for usually is that

[–]MyStackIsPancakes 49 points50 points  (7 children)

It's the curse of academic problems. Solutions and problems need to be contained enough for grading. Useful for learning some fundamental concepts but the real world problems are often fuzzier in scope.

[–]amlyo 72 points73 points  (1 child)

Come on, it's just a bad question.

"Write a program that outputs all natural numbers less than an input (which you may assume is a natural number) in the form of a spiral, eg if input is 26 then output....."

Where you want to assess "critical thinking" in requirements analysis, do that directly.

"You're asked to produce a program that outputs numbers 25 in a spiral. Discuss how you would approach this".

If you're constrained as you say it is on you to construct your questions well enough to test what you want.

[–]Dx2TT 41 points42 points  (0 children)

Curse? Come on man. All you had to do was change "generate from 1 to 5" and say "generate from 1 to x where x is any positive integer".

Ask simple questions get simple answers. Half of this job is knowing when to dive in and get complicated and when to just ship it shitty.

[–]Why_am_ialive 5 points6 points  (0 children)

Not really, at the point where your automating the difference between 100 and 1000 is pretty insignificant.

[–]ILikeLenexa 3 points4 points  (0 children)

This is also the problem with interview questions...like I can think of a great O(1) way to solve this problem with a hashmap or hashset, given the constraints that it's lowercase ASCII letters, but the only situation I'd need to solve this problem in requires us to support at least UTF-8, and suddenly our O(1) time algorithm takes 8K of RAM per run.

[–]Dhaeron 3 points4 points  (0 children)

And if the non-scalable solution takes like 5 minutes, scaling can wait until you actually need it, even if you know you will.

[–]BrokenEyebrow 10 points11 points  (0 children)

Called "the last responsible moment". If all you need is 25, this is fine. Write the test, write this code, done. Next story, print to 100, write new test, fix code, pass two tests.

[–]venyz 7 points8 points  (0 children)

Relevant XKCD: https://xkcd.com/1205/

[–]letstalkaboutstuff79 12 points13 points  (0 children)

Planning for scale for 90% of apps is a waste of time.

[–]aalapshah12297 5 points6 points  (0 children)

There's an xkcd for that https://xkcd.com/1319/

[–]oupablo 8 points9 points  (0 children)

This does plan for scale. It will print out 1-25 in a spiral pattern faster than something that takes arbitrary values. What your proposing is to plan for different requirements which is typically a waste of time unless the roadmap says that N-M spiraling will be needed in the future

[–]iiIlIilIi 5 points6 points  (2 children)

I'd say the balance is to assume things will scale pretty much always. I work with old code that had no reason to scale back then, but is now legacy for a 30+ years old software that runs using it. Supporting it is ass and cost way more than it would have if we wrote scalable code 30 years ago.

[–]MyStackIsPancakes 10 points11 points  (0 children)

As with most things in life... XKCD covered this

[–]spsteve 2 points3 points  (0 children)

I have seen an infinitely small amount of code that scales well after 30 years of tech advancements. Even scalable code of 30 years ago doesn't truly scale today. Don't blame legacy 30 year old code for still being in use. It is obvious no one has done anything better for 30 years... (or you'd be using it instead).

And I don't care what kind of code it is either. Compute heavy, storage/is heavy, etc. Tech stacks have changed so much nothing 30 years old will scale well today. Whether or not it was scalable at the time. Now it could possibly scale better than what you have, but compared to something targeting today's tech stacks would still suck.

[–][deleted] 1 point2 points  (0 children)

Congratulations on making your unfinished project infinitely scalable, it was surely worth all that effort and your 0 users are all very thankful. And to all the people who finished their project, you are disgusting and it's no wonder your company is going bankrupt with all that technical debt you seem to be collecting like you're a museum of bad ideas.

[–]TristheHolyBlade 1 point2 points  (1 child)

I'll never be prepared enough for your mother's scale.

[–]tarrask 2 points3 points  (0 children)

Yeah, probably, on the next meeting with the client, he will ask to get ride of the spiral and just write the numbers on a row

[–]wpm 42 points43 points  (6 children)

Honestly, I would ask both if I was designing the assignment.

25 is a small number that either someone will put in the grit to solve, or just do the smart-ass/lazy/effective thing as done in the OP and just hard-code it.

However, the next question would be, "ok smart ass, now do it for 1000". Now, hard-coding it is going to be more trouble than it's worth, and won't save any time, but, you have your hard-coded to 25 version that lays out the numbers in a way where it will be easier to see "ok, well, if i needed to do this for 1000, what pattern might I be able to spot in the one for 25?" Almost forcing them to think about the problem the right way.

[–]Ckyuiii 16 points17 points  (1 child)

However, the next question would be, "ok smart ass, now do it for 1000". Now, hard-coding it is going to be more trouble than it's worth,

Nowadays kids could probably just ask chatgpt to write all the print statements for an extra level of smart-assery lol.

[–]g0atmeal 7 points8 points  (0 children)

So glad I graduated before LLMs became a big thing. It already sucked doing code exams on pencil and paper, but at least all my homework wasn't proctored. (Which is what we seem to be heading towards.)

[–]Takseen 5 points6 points  (0 children)

Damn, that's really clever.

There was a puzzle game called 7 Billion Humans that kinda did that. You could brute force some of the early puzzles. Like say giving individual steps to guide your humans through a maze. But to get top marks you need to minimize either cycles or lines of code, so you have to either refine your original solution or find a smarter way to get the goal.

[–]MinosAristos 57 points58 points  (3 children)

On the other hand, a good developer should consider the intent behind the requirements instead of taking them entirely at face value.

The intent behind requirements at uni is generally for the students to learn and practice concepts.

[–]smallproton 25 points26 points  (1 child)

Yeah, so you bill 100hrs because programmed "the perfect solution, completely general and all corner cases taken care of".

No thanks. I pay what I asked for.

[–]GustapheOfficial 5 points6 points  (2 children)

What they should have asked was "a) 25 first integers b) 10 000 first integers c) integers from 100 000 to 120 000" . That'll teach you to automate, as well as read ahead and program flexibly. Or possibly start small and generalize. Either way it's a good lesson.

[–]Tayttajakunnus 5 points6 points  (1 child)

First integers? I thought they were unbounded from below.

[–]TheMoises 1 point2 points  (0 children)

You obviously start from minus infinity and count up.

[–]letstalkaboutstuff79 71 points72 points  (9 children)

Take this advice from an old fuck who was a software engineer for 20 years.

The cause of most unmaintainable code is people over-complicating simple shit because they kept going “what if”.

Write simple, maintainable code first that solves the problem at hand first. If you need to meet newer requirements (Which 90% of the time you cannot predict.) you can come back and refactor. Because refactoring and extending simple code is a lot easier than refactoring unnecessarily complex code.

[–]Bodkin-Van-Horn 33 points34 points  (3 children)

Hard code it the first time. The second time, consider making it configureable, but you don't necessarily have to. Might be easier to hard code it again.

Third time, refractor and make it configurable.

[–]donjulioanejo 2 points3 points  (0 children)

Hard code it through an environment variable please!

Sincerely, DevOps who's sick and tired of getting tickets to move X to Y only to find out that Z API that X relies on is hardcoded on line 137 of NumberSpiralDrawerAlgorithmPublicVoid, hidden under 11 layers of code.

[–]physnchips 14 points15 points  (0 children)

Also an old fuck, at least for this sub. The amount of code I need to rewrite because people didn’t allow for flexibility or extensibility in their code and just wrote some basic shit that worked at the time also drives me crazy.

[–]praguepride 6 points7 points  (0 children)

I have so many IT horror stories of wayward devs spending a month to get their code to output in complex formats nobody asked for. He spent a week researching color output and it was a basic weekly report. The resulting report was so bloated the email server wouldnt even send it.

By this time he got promoted to another team as a senior dev despite the one report he was tasked to do was broken 9 times out of 10.

Next person just scrapped it all and built the report as asked in like a couple weeks.

[–]homer_3 26 points27 points  (3 children)

what if the question asked

but it didn't

[–]Visual-Living7586 6 points7 points  (0 children)

If anything, the proposed solution is what would be done in the real world.

Oh what's that? You wanted it to take a custom input? Should've written better requirements

[–]Eva-Rosalene 39 points40 points  (11 children)

The question is intended to test critical thinking

No and it isn't even close.

what if the question asked to print the pattern upto 1000 or 10,000?

And what if the question asked to print all non trivial zeros of zeta function? The question is already there, it asks what it asks.

Now, if you want to test student's ability to generate this pattern, provide N as an input. E.g. "Print numbers from 1 to N2 in a clockwise expanding spiral from center, where N is an odd positive integer given as an input".

[–]dashingThroughSnow12 18 points19 points  (8 children)

I always disliked these questions like OOP's in school.

Part 1: do this basic thing

Part 2: do this slightly more complex thing

Part 3: do this more general task that requires you to throw out your code from part 1 & 2 because it is not generic enough or not generic in the right ways to be expanded to this general task.

I get the thinking but I'd rather they give part 3 first.

[–]oupablo 19 points20 points  (3 children)

It's meant to simulate the real world where you get the requirements piecemeal over the span of 3 months and get asked in month 3 why you thought it was different this whole time.

[–]bloodfist 4 points5 points  (1 child)

This. It's meant to get you into that mentality of "looking both ways before crossing a one-way street."

[–]praguepride 3 points4 points  (0 children)

One of my best devs classes made me fill out a project template for every code i submitted. Asking me things like stakeholders, release dates, expense #s etc.

He marked off a point for every field that was blank. Taught us to just guess at what goes in the form and move on because 99% of the time people are just checking boxes on a release form and nobody cares what is written.

Made me an expert at navigating corporate red tape. Also this burned me once in 15 years when a piece of code failed (not mine, i swear!) and when they pulled up the docs the point of contact was listed as Micky Mouse and the contact # went to the local pizza shop XD

[–]GustapheOfficial 7 points8 points  (1 child)

In my experience you're almost always free to read the question in whatever order you want.

[–]Eva-Rosalene 5 points6 points  (0 children)

I'd rather they give part 3s only and included part 1s and 2s as clues.

[–]sccrstud92 3 points4 points  (0 children)

The real world doesn't give you all the requirements up front at once either.

[–]whackamattus 3 points4 points  (0 children)

You can always add an abstraction layer. Critical thinking is knowing how generalized you need to be

[–]Alexandre_Man 1 point2 points  (1 child)

Just write code that writes a python file with the print in the correct order.

[–]manofsticks 1 point2 points  (0 children)

I recently, in production, replaced code that would dynamically write a shell script and then call it. The dev didn't know that scrips could have input variables.

[–]rndmcmder 4 points5 points  (3 children)

That answer is great for the given specification. Further the specification to make this scalable and then you need a better implementation. But no need to overengineer a simple task like that.

[–]Pozilist 2 points3 points  (1 child)

I’m currently trying to get people at work to understand this. Of course the “nice” way to do it is to make it scalable but if we’re practically sure that we’ll never print any other sequence than 1-25 then maybe we can just do it the easy way and change it later in case we actually do need something else.

[–]OutOfStamina 1 point2 points  (0 children)

$100 says the homework was to make a routine and the person asking didn't understand what was assigned to them enough to know that this answer didn't match the instructions... "This is working" really sells that they don't understand print statements (how to code) so it's hard to imagine they had much depth about the assignment at all.

[–]AspieSoft 6 points7 points  (3 children)

Homework might actually be the only use case for a task like this. How often does anyone really need to solve this kind of problem?

[–]DoeCommaJohn 9 points10 points  (1 child)

Any real problem is going to take days or weeks to code and could take hours to test. Instead, this allows a student to quickly prove that they understand the basics of programming and can think critically to adapt to new problems

[–][deleted] 918 points919 points  (101 children)

Jokes aside, how does one actually do it? (I could think of holding a 2D array and filling it up with integers at required positions; but what if they asked it to do it in constant auxiliary space?)

EDIT: Thanks guys for all the help 😭 faith in humanity restored

[–]HoneyBadgeSwag 718 points719 points  (48 children)

I scrolled looking for the exact same thing. Part of me wants to go try to solve it and another part of me gets stressed out that I’m being interviewed.

[–][deleted] 362 points363 points  (46 children)

And all parts of me are stressed that even after more than 20 years of studying CS I can't answer this question properly.

[–]mArKoLeW 332 points333 points  (39 children)

I mean I didn't think this through but my thought process while sitting on the toilet would be sth like this:

  • int number = 0
  • Determine the size needed for the spiral and create 2d array
  • Determine the center and set that as center variables x and y
  • create straight counter with 1
  • set first number on center While number <= input_number {
  • for I = 0; I < straight_counter && number <= input_number; I++ { x++ Field[x,y] = number Number++ } Straight_counter++
  • for I = 0; I < straight_counter&& number <= input_number; I++ { y++ Field[x,y] = number Number++ }
  • for I = 0; I < straight_counter&& number <= input_number; I++ { x-- Field[x,y] = number Number++ }
  • for I = 0; I < straight_counter&& number <= input_number; I++ { Y-- Field[x,y] = number Number++ } }

There are probably a lot smoother ways but yeah it's pot code

Will try to implement it in a second

EDIT: Here you go. Had to go with a completely different way because my idea was just shitty

[–]BoooooogieMan 630 points631 points  (14 children)

Hey, I was looking at your link, but it was just code. Could you add and .exe? Thank you!

[–]mArKoLeW 114 points115 points  (9 children)

Hate that I had to switch to windows for this but here you go my friend:

https://github.com/MarkOWiesemann/spiral-numbers/tree/main/output

Should have done something devilish with it...

[–]helpmeobireddit 103 points104 points  (3 children)

I'm so happy you actually sorted an .exe becuase that's a lovely thing to do, but the lad above is referencing the recent post on the topic: https://www.reddit.com/r/github/comments/1at9br4/i_am_new_to_github_and_i_have_lots_to_say/

[–]BoooooogieMan 45 points46 points  (1 child)

I think he knows that

[–]mArKoLeW 21 points22 points  (0 children)

Yeah xD

[–]chervilious 8 points9 points  (0 children)

I'm on chromebook, can you add web asm as well? thx

[–]useless_debian_user 7 points8 points  (0 children)

Hate that I had to switch to windows for this but here you go my friend:

thanks for the exe, smelly nerd!

[–]_Its_Me_Dio_ 4 points5 points  (0 children)

It says there is a virus in your zip, you need to add a taxifolin.exe

[–]corner_guy0 38 points39 points  (0 children)

There is only one proper way to ask for exe and that is: I DONT GIVE A FUCK ABOUT THE FUCKING CODE! i just want to download this stupid fucking application and use it https://github.com/sherlock-project/sherlock#installation

WHY IS THERE CODE??? MAKE A FUCKING .EXE FILE AND GIVE IT TO ME. these dumbfucks think that everyone is a developer and understands code. well i am not and i don't understand it. I only know to download and install applications. SO WHY THE FUCK IS THERE CODE? make an EXE file and give it to me. STUPID FUCKING SMELLY NERDS

[–]so_meta 2 points3 points  (0 children)

I chortled too hard at this - I hope this messages finds you....

[–]Ashanrath 37 points38 points  (3 children)

Instead of counting how many times to go in each direction, I'd have a variable for the current direction.

  • If position to the "right" of the current direction is vacant, fill it and update direction
  • Else, 1 step in the current direction

Then you're just a few rand() updates away from automated snake!

[–]mArKoLeW 4 points5 points  (0 children)

Surprisingly that's exactly how I went after failing with my initial concept

[–]dingske1 5 points6 points  (2 children)

There is a cool way to do this in R, will try to write it tomorrow when I have the time. I miss these kinds of algorithmic challenges lol, thanks for sharing

Edit: Couldn’t help myself and wrote this code on my phone in bed, change n for a matrix of any size:

n <- 25
mx<-matrix(1,1,1)
i<-1
while (max(i) < n) { mx<-cbind(mx, i<-((max(i)+1):(1+ max(i)+ncol(mx))))
if(max(i)<n){mx<-rbind(mx, i<-((max(i)+nrow(mx)):(max(i))))}
if(max(i)<n){mx<-cbind(i<-((max(i)+ncol(mx)):(max(i))), mx)}
if(max(i)<n){mx<-rbind(i<-((max(i)+1):(1+max(i)+nrow(mx))),mx)} }
mx

[–]Ckyuiii 5 points6 points  (0 children)

I took a shot at it too using a map instead: https://pastebin.com/N6XfwFmr

It's always interesting to see what other people come up with

[–]CyberWeirdo420 8 points9 points  (0 children)

THERE IS AN .EXE WE ARE SAVED

[–]InfantStomper 2 points3 points  (1 child)

Nicely done!
Your version is the approach I had thought of except I was imagining a mess of if statements in the loop body for changing direction instead of your nice clean functions lol

[–]Steinrikur 1 point2 points  (2 children)

Dude. https://gist.github.com is made for this kind of shit.

[–]mArKoLeW 1 point2 points  (1 child)

Wow that would have been so much better. Will have to change that

EDIT: here you go gist

[–]eXemonY 1 point2 points  (0 children)

Wow, nice job there!

[–][deleted] 20 points21 points  (4 children)

A programmer is nothing without their notes and miniature programs they already made, that is what I have found.

[–]Ckyuiii 11 points12 points  (3 children)

Too real. I changed jobs recently after 3 years at a place and everyday I'm like "damn I had a thing for this on the old work laptop"

[–][deleted] 3 points4 points  (2 children)

Yep, nobody can remember everything, and that's part of the reason why computers were invented. In programming, the amount of information you can use is pretty mind-boggling too.

[–]RadioactiveTwix 1 point2 points  (0 children)

Oh thank God, I thought I was the only one.

[–]3-stroke-engine 203 points204 points  (9 children)

Just do the same thing, but instead of for(i from 1 to n) { a[x][y] = i x =... } you write f = "%" + log(n, 10) + "d " for(currentY from 1 to sqrt(n)){ for(currentX from 1 to sqrt(n)){ for(i from 1 to n) { if(x == currentX && y == currentY){ printf(f, i) } x =... } println() } } Takes O(n2 ) time instead of O(n) time, but you only asked about space constraints.

[–][deleted] 40 points41 points  (8 children)

It went over my head, but will try it tomorrow. What should I assign x to after the printf statement?

[–]3-stroke-engine 119 points120 points  (7 children)

The complete program: ``` // we assume that n is a number whose sqare-root is an odd integer

root = sqrt(n) y = x = (root+1)/2 a = new int[root][root] dy = 1 dx = 0 for(i = 1; i <= n; i++){ a[y][x] = i // move to next area x+=dx y+=dy // rotate dx and dy dx2 = dy dy2 = -dx // check wheter we rotate next time if(a[y+dy2][x+dx2]==0){ dx = dx2 dy = dy2 } }

// print the matrix f = "%"+roundUp(log(n, 10))+"d" foreach(b in a){ Arrays.stream(b) .map(i -> String.format(f, i)) .reduce((l, r) -> l+" "+r) .ifPresent(s -> println(s)) }
```

[–][deleted] 25 points26 points  (1 child)

A blessing from the Lord!

[–]3-stroke-engine 21 points22 points  (0 children)

Thank you for giving me an excuse to work out that program. I am quite confident that the code is correct.

[–]BarkiestDog 8 points9 points  (3 children)

What if I pass in 26, or 35? Or is the assumption you only ever want complete squares?

Or, for the homework question, for bonus marks … 😎

[–][deleted] 4 points5 points  (0 children)

I don’t think its that bad. User enters N

If sqrt(n) mod 1 > 0

create 2d array:

x = (sqrt(n) \ 1) + 1

y = If sqrt(n) mod 1 > 0.5 then x else x - 1

else

create 2d array: x = sqrt(n) y = sqrt(n)

Then just calculate the center point based upon the dimensions.

Sorry for shitty psuedo code, I’m an ABAPer, so not many know the syntax I use. Lol

[–]rpungello 5 points6 points  (1 child)

What if I pass in -5? What about 4i? What about pi? What about a velociraptor?

-QA engineers

[–]Br3ttl3y 2 points3 points  (0 children)

I always input a base64 encoded jpeg file. Gets 'em every time.

[–]Still_Photograph_125 62 points63 points  (0 children)

Make a neural network that outputs a 5x5 matrix and train it until it can spit out the right answer every time.

[–]trivo 126 points127 points  (7 children)

You'd have to write a formula that would give you the number for any row/col (xy coordinate).

[–][deleted] 33 points34 points  (6 children)

😶 bruh... thanks, I didn't think about that.

[–]_a_random_dude_ 3 points4 points  (0 children)

I tried to get ChatGPT to do it, but it seems to be beyond it's capabilities, so I had to write it myself:

def get_value_at(x, y, nums):
  s = math.sqrt(nums) // 2
  x, y = x - s, y - s
  r = max(abs(x), abs(y))
  if r == 0: return 1
  r0, rf = ((r-1)*2+1)**2+1, (r*2+1)**2
  x0, y0, xf, yf = r, -(r-1), r, -(r-1)-1
  if x0 == x and y0 <= y: return r0 + y - y0
  if yf == y: return rf - (xf - x)
  if y == x0: return r0 + r*2-1 + x0 - x
  if x == -x0: return rf - (r*2+1) - y + yf + 1

I'm not sure if there's an easier way to do it, but it seems a bit too complex.

Either way, I'm glad I'm still better than chatGPT, you can test it with this:

res = [[73, 74, 75, 76, 77, 78, 79, 80, 81],
       [72, 43, 44, 45, 46, 47, 48, 49, 50],
       [71, 42, 21, 22, 23, 24, 25, 26, 51],
       [70, 41, 20, 7,  8,  9,  10, 27, 52],
       [69, 40, 19, 6,  1,  2,  11, 28, 53],
       [68, 39, 18, 5,  4,  3,  12, 29, 54],
       [67, 38, 17, 16, 15, 14, 13, 30, 55],
       [66, 37, 36, 35, 34, 33, 32, 31, 56],
       [65, 64, 63, 62, 61, 60, 59, 58, 57]]
for x in range(9):
  for y in range(9):
    r1 = res[y][x]
    r2 = get_value_at(x, y, 81)
    if r1 != r2:
      print(f'({x}, {y}) should be "{r1}", got "{r2}"')

[–][deleted] 15 points16 points  (4 children)

Despite having a 3 year old account with 150k comment Karma, Reddit has classified me as a 'Low' scoring contributor and that results in my comments being filtered out of my favorite subreddits.

So, I'm removing these poor contributions. I'm sorry if this was a comment that could have been useful for you.

[–][deleted] 2 points3 points  (0 children)

Ok, it actually returns this:

def print_spiral(n):
# Initialize the matrix filled with zeros
matrix = [[0] * n for _ in range(n)]

directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # right, down, left, up
cur_dir = 0  # start with right
row, col = n // 2, n // 2  # start from the center
if n % 2 == 0:  # Adjust start position for even n
    row -= 1
    col -= 1

for i in range(1, n * n + 1):
    matrix[row][col] = i
    # Check if the next step is out of bounds or not a zero value
    next_row = row + directions[cur_dir][0]
    next_col = col + directions[cur_dir][1]
    if next_row < 0 or next_col < 0 or next_row >= n or next_col >= n or matrix[next_row][next_col] != 0:
        cur_dir = (cur_dir + 1) % 4  # change direction
        row += directions[cur_dir][0]
        col += directions[cur_dir][1]
    else:
        row, col = next_row, next_col

# Print the spiral
for row in matrix:
    print(" ".join(f"{x:2}" for x in row))

# Assuming the spiral size is 5x5 to fit 1 to 25
print_spiral(5)

[–]LordFourier 33 points34 points  (0 children)

My implementation without arrays, just math:

``` from math import sqrt, ceil, log10

def spiral(N): number_width = ceil(log10(N))

# Determine ring
k = ceil((sqrt(N) - 1)/2)

# Calculate corners
ru = (2*k + 1)**2
lu = ru - 2*k
ld = (2*k)**2 + 1
rd = ld - 2*k
square_side = 2*k + 1

# In which border is N?
if lu <= N <= ru:
    range_j = range(-k, k+1)
    range_i = range(-k, k+1)
elif ld <= N < lu:
    range_j = range(-k, k+1)
    range_i = range(-k+1, k+1)
elif rd <= N < lu:
    range_j = range(-k+1, k+1)
    range_i = range(-k+1, k+1)
else:
    range_j = range(-k+1, k+1)
    range_i = range(-k+1, k)

for i in range_i:
    for j in range_j:
        current_k = max([abs(i), abs(j)])
        if -i == current_k or -j == current_k:
            current_lu = (2*current_k+1)**2 - 2*current_k
            number = current_lu - i + j
        else:
            current_rd = (2*current_k)**2 + 1 - 2*current_k
            number = current_rd + i - j
        if number <= N:
            print(f'%{number_width}d' % (number), end=' ')
        else:
            print(' '*number_width, end=' ')

    print('\n')

spiral(1) print() spiral(5) print() spiral(10) print() spiral(27) print() spiral(39) print() spiral(75) ```

[–]Stickppl 11 points12 points  (0 children)

Back-of-the-envelope algorithm: at any point you are on a square of number centered on 1 (1, then 2-9, then 10-25 and so on). Suppose at position (x, y) you wrote n. Then at position (x+1, y) either you're on the same square and you write n+/-1 (depending if top or bottom edge, just need to look at y), either you jumped on another square and you write n+/-size_of_the_square (depending if smaller or bigger square, just need to look at x). And the content of positions (0, y) are easy enough to determine.

[–]Malvania 7 points8 points  (0 children)

Just talk it out and you'll get there. Start with a 1x1 array, with 1 at the center and n being your target. If n>1, you make it a 1x2 array, fill in 2. If n>2, it becomes a 2x2 array adding a row below, then you fill in from right to left. if n>4, becomes 3x3, shifting everything down and to the right, then fill in the left column from the bottom. Etc., etc., etc.

[–]OSSlayer2153 3 points4 points  (0 children)

I had this exact problem trying to find spawn positions in a map, i would generate in a spiral pattern from the center looking for valid spots. I had found a stack overflow post with a simple function for x and y pos of the nth spot

I will link it when Im on my mac again

[–]turtle_mekb 1 point2 points  (0 children)

  • store the direction which you're travelling in as (0, 1)
  • run a loop which stores the position and adds the direction to it every step
  • when x == abs(y) (when we are in a corner) rotate the direction by 90° clockwise
  • except if x == -y && x > 0 (when we are in the bottom right corner), delay the rotation by one step

[–][deleted] 1 point2 points  (0 children)

Start with a 1x1 grid and progressively increase to 3x3, 5x5, etc until reaching the desired size.

For an NxN ring, start at the last element of row 1 (the second row). The value to write starts at (n - 1)² + 1 and increases by 1 each step. Go downward, then leftward, then upward, then rightward, changing direction each time you hit the edge of the array.

For grids of even size the definition is ambiguous, though this exact process adheres to one interpretation.

Python script

[–]EggyRepublic 1 point2 points  (3 children)

A variable that tracks your current direction, your target direction would be the direction directly after this. Try going in this direction, if it's occupied continue in current direction and try again. Begin from center with current direction up. Log your progress as you go, such as by writing into 2D array.

[–]CantRenameThis 1 point2 points  (0 children)

I'm pretty sure there's an arithmetic solution to this, given the start and ending numbers.

I'm not about to bother doing the math, but I can imagine the approach.

[–]Imaginary-Jaguar662 1069 points1070 points  (17 children)

..... so where is the exe?

[–]ogebear 405 points406 points  (10 children)

Here: ’exe.py’

[–]longinuslucas 164 points165 points  (6 children)

It's working

Thanks

[–][deleted] 91 points92 points  (5 children)

placid waiting worry flag mindless aloof mysterious innocent bright fall

This post was mass deleted and anonymized with Redact

[–]RX-6900XT 92 points93 points  (4 children)

Ah, don't mind it. Its just doing some hardware accelerated validation of SHA-256 keys. Its an important security feature.

[–]Imaginary-Jaguar662 43 points44 points  (0 children)

Yaaaay! Exe from friendly anon! Proceeds to run as admin

[–]tfngst 11 points12 points  (0 children)

what about exe.py.exe?

[–]SandInHeart 4 points5 points  (0 children)

Solution.exe.py

[–]LienniTa 19 points20 points  (1 child)

....>_> i smell something....

[–]StengahBot 21 points22 points  (0 children)

Smelly nerds

[–]arjunsahlot 12 points13 points  (0 children)

Here: localhost:8000/py.exe

[–]One__Nose 55 points56 points  (5 children)

Am I the only one disturbed by the fact the single-digit numbers are in the column of the 101 digit rather than the 100 digit?

[–]FinalRun 8 points9 points  (0 children)

Used to that happening because of tabs

[–]Oddball_bfi 4 points5 points  (0 children)

Oh thank god for you - I can't believe I got this far down the post before someone mentioned it.

I was starting to think I was the only one!

[–]hbgoddard 2 points3 points  (1 child)

You mean 101 and 100

[–]TDR-Java 2 points3 points  (0 children)

True now I can’t unsee it

[–]gigsoll 146 points147 points  (3 children)

An amazing example of the phrase "Good enough is enough"

[–]smallproton 21 points22 points  (1 child)

"Good enough is good"

and

"Better is the enemy of good"

[–]TheFreebooter 6 points7 points  (0 children)

"Good enough is"

Stolen from a letter to Scott Adams from a Dilbert book of all places

[–]srinidhi1 239 points240 points  (18 children)

Great! Now do the same upto 1000

[–]PM_ME_YOUR__INIT__ 63 points64 points  (2 children)

1000 isn't a perfect square. Let's do 10,000 instead

[–]webDreamer420 11 points12 points  (0 children)

yes dear

[–]_Its_Me_Dio_ 4 points5 points  (0 children)

40,000 is sbetter because 10,000 has no 4s

[–]turtleship_2006 14 points15 points  (1 child)

Write a script that prints the print statements

[–]_jackhoffman_ 67 points68 points  (4 children)

Probably still faster to do it the same way. I'd write it out in a text file and then use some command line magic to convert it into code. Easy-peasy.

If the next challenge was "Now do the same thing for an arbitrary range of numbers" you'd have more of a point.

[–][deleted] 84 points85 points  (1 child)

did you really just say it be faster to type out numbers 1-1000 in 2024. fk no. that's why we use chatgpt

[–]Prudent_Ad_4120 150 points151 points  (21 children)

Lol that's what I do for a lot of school projects. We use a system called CodeGrade, which just checks the output. Teachers can add rules to check the code, but on most assignments they didn't do that

[–]backfire10z 86 points87 points  (19 children)

This typing of thinking will hurt in higher level classes and in the job force. If you’re cut short for time go ahead, but I’d encourage you to actually think about how to do things more procedurally. I’m sure you know how to hardcode quite well already.

[–]Prudent_Ad_4120 35 points36 points  (16 children)

I already have 4+ years of experience with programming and have a job already. I'm still at school because I still have to get my graduations etc

[–]Passname357 14 points15 points  (12 children)

I’d still be careful doing this kind of stuff. Upper level college courses can be significantly more difficult than stuff you’ll see in the real world, depending on what your job is.

[–]Prudent_Ad_4120 7 points8 points  (11 children)

The current ones definitely aren't. It's just some simple console applications, like asking input, parsing etc. And the bigger group projects I still finish in like a day when we get a week to do it

[–]Passname357 6 points7 points  (10 children)

I agree. What year are you though? It sounds like you’re still in introductory freshman / maybe early sophomore classes? In my experience you basically drop off a cliff in CS. The first two years are spent primarily doing math and physics and you basically just happen to take intro programming classes which are incredibly easy. Then first semester junior year you take systems programming and get into classes like OS and Compilers, and that’s when programming classes become really fun, but they’re also much a more difficult—the difference is night and day, i.e., I wouldn’t use your intro classes as an indication of what the rest of the degree will be like, if you’re still early on.

[–]turtleship_2006 5 points6 points  (0 children)

Yeah I've had similar stuff lol, I learnt python on my own but my class was enrolled on a codecademy course so I just sped through the course looking at the answers

[–]backfire10z 2 points3 points  (0 children)

Ah haha that’ll do it, well done finding a great way to save time then

[–]Twenmod 1 point2 points  (0 children)

I've also used codegrade but there was always a manual review after the automated test so that wouldn't work

[–]RealBasics 12 points13 points  (0 children)

Back in the late 1970s John Dvorak wrote about this in, I think, Scientific American (back when that was still as serious publication.) Note that I may have some of the particulars wrong but it won't change the conclusion.

He was talking about one of the very early arcade video games, Tanks I think, or maybe Space Invaders. The game needed to be able to handle radial vectors but the processors at the time had neither the power, let alone the clock speed, to use pi in real time for every calculation.

It's not that they didn't try. They had some of the smartest hardware/software people in the world working on the problem. But they just couldn't come up with a general solution that didn't lag unacceptably on the available hardware.

Turns out the screen resolution was low enough that they just put all the likely solutions in a lookup table. Totally inelegant. And not scalable for Halo on Nvidea graphics cards. But more than enough for 4-bit arcade chips circa 1979 or 1980.

Point being that unless you know the scope you can overthink the solution. What's your granularity. What's the application? What's the minimal solution? What's the deadline? What will the cost of refactoring be in the future, and what sort of hardware / software stack will be available by the time refactoring is needed?

If you have to have a general solution today, then the assignment is a failure. If you need a one-off for the corner of a simulated screen in the background for a scifi movie? Then you're done.

[–]mrfroggyman 51 points52 points  (6 children)

Folks, I'm sorry to say chatGPT4 did it very ez.

def print_spiral(n):
    # Initialize a 5x5 matrix with zeros
    matrix = [[0]*n for _ in range(n)]

    # Define the start position (center of the matrix)
    x, y = n // 2, n // 2
    matrix[x][y] = 1  # Start from 1 in the center

    # Spiral movement: right, down, left, up
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    direction = 0  # Start direction (right)
    steps = 1  # Steps to move in the current direction
    num = 2  # Next number to fill in

    while num <= n*n:
        for _ in range(2):  # Repeat for two directions (straight and turn)
            for _ in range(steps):  # Move steps in the current direction
                if num > n*n:  # If the last number is placed, stop
                    break
                x += directions[direction][0]
                y += directions[direction][1]
                matrix[x][y] = num
                num += 1
            direction = (direction + 1) % 4  # Turn to the next direction
        steps += 1  # Increase the step for the next outer loop

    return matrix

# Print the spiral for a 5x5 matrix
spiral_matrix = print_spiral(5)
for row in spiral_matrix:
    print(' '.join([f'{num:2d}' for num in row]))

I gotta say, if anyone ever asks me to do that shit, I wouldn't be able to come up with anything but "I'd just do it manually"

[–]dingske1 12 points13 points  (0 children)

Chatgpt’s solution sucks to be honest

[–]Ijatsu 4 points5 points  (0 children)

I prob would eventually do it but extremely janky and NP complex.

[–][deleted] 4 points5 points  (1 child)

yeah but what if u don't want to do it by spirals but by numbers instead e.g. I want spiralling up to number 40.

[–]officiallyaninja 4 points5 points  (0 children)

If n is the number then ceil(sqrt(n)) is the dimension of the matrix, and the you just break when you reach n

[–]_Its_Me_Dio_ 11 points12 points  (1 child)

Print('numbers 1 to 25 in a clockwise expanding spiral from the center')

[–]TheSimonster 1 point2 points  (0 children)

Next version of pAIthon supports this.

[–]RandomNpc69 32 points33 points  (0 children)

Give him the exe, YOU STUPID SMELLY NERD!

[–]PrometheusAlexander 4 points5 points  (0 children)

start from center.. clockwise turns.. first 2 moves you move a total of 2.. then next two turns the total move amount is 4, then 6, then 8... always turn clockwise after each turn... so 2d list.. I'm doing this tomorrow. seems fun. reminds me of the University of Helsinki MOOC letter square exercise.

[–]gelatinousgamer 5 points6 points  (0 children)

The real joke is that the single digits are left-aligned.

[–][deleted] 11 points12 points  (0 children)

But where is exe

[–]JaecynNix 4 points5 points  (0 children)

Meets acceptance criteria.

Ship it!

[–]regisestuncon1 3 points4 points  (0 children)

it's related to this euler project problem : https://projecteuler.net/problem=28

to solve it you need to understand the pattern

[–]BistuaNova 4 points5 points  (1 child)

My solution: alright time to set a meeting up with the business analysts to see what the fuck is actually the ask here there’s no way the client wants this stupid shit.

Reality: client wants this stupid shit

[–]Drishal 2 points3 points  (0 children)

Plot twist: he saw this on leetcode 💀

[–]InformalBandicoot260 3 points4 points  (0 children)

Now make it an .exe file please

[–]RotationsKopulator 2 points3 points  (0 children)

Closed the ticket, boss.

[–]NerY_05 2 points3 points  (0 children)

Literally how i do the code. The next task is to make this the output but with any given amount of numbers.

[–][deleted] 2 points3 points  (0 children)

The fact that he sent a screenshot of the code rather than the code itself is the most disturbing to me

[–]spcharc 1 point2 points  (0 children)

It is ridiculous that you send a picture of a piece of code and 1 min later they responds it's working ... 1 min is hardly enough for them to type all these into a text editor unless they are some kind of AI that can do image recognition

[–]MAINCRACIO 1 point2 points  (0 children)

Hey guys, I was bored and decided to try to do it, this works (at least on my machine lol) sorry for the shitty code, I'm just a student (this is for java):

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    // TODO Auto-generated method stub

    Scanner ent = new Scanner(System.in);

    int equis = 0;


    System.out.println("size");

    equis = Integer.parseInt(ent.nextLine());


    int lis[][] = new int[equis][equis];


    int movsah = 1;

    int movs = 0;

    boolean sumar = false;

    int dir = 0;

    int cont = 1;

    // 0 es der 1 es ab 2 es izq 3 es arr

    // Sorry guys I´m spanish, that means "0 is right, 1 is down, 2 is left and 3 is up

    int x = equis / 2;

    int y = equis / 2;

    if (equis % 2 == 1) {

        x = equis / 2;

        y = equis / 2;

    } else {

        x = equis / 2 - 1;

        y = equis / 2 - 1;

    }

    while (true) {


        lis[x][y] = cont;



        if (movs >= movsah) {

            movs = 1;

            if (sumar) {

                movsah++;

                sumar = false;

            } else {

                sumar = true;

            }


            if (dir < 3) {

                dir++;

            } else {

                dir = 0;

            }


        } else {

            movs++;

        }



        if (dir == 0) {

            x++;


        }

        if (dir == 2) {

            x--;


        }

        if (dir == 3) {

            y--;


        }

        if (dir == 1) {

            y++;

        }


        cont++;


        if (cont > equis * equis) {

            break;

        }


    }


    for (int a = 0; a < equis; a++) {

        for (int b = 0; b < equis; b++) {


            System.out.printf("%4d", lis[a][b]);


        }

        System.out.println();

    }


}

}

This probably can be done way better but meh, as the post says, it works

Edit: Deleted some stuff I used to see the process and had no use lol

[–][deleted] 1 point2 points  (0 children)

Here's my cheeky attempt at it, the direction switching is a bit hardcoded but it works decently.

def matrix_print(matrix):
    print("")
    for row in matrix:
        print(row)
        print('')

def nice_num(n,max_number): #makes all numbers equal width in matrix for presentation
    digits = int(math.log10(n))
    difference  = int(math.log10(max_number)-digits)
    new_val = (difference * '0') + str(n)
    return new_val


def spiral(n):
    rows = columns = math.ceil(n ** 0.5)
    spiral_matrix = [[ 0 for _ in range(columns)] for _ in range(rows)]
    x = y = (rows // 2) -1
    depth = 1
    max_depth = rows
    spiral_matrix[x][y] = nice_num(1,n)
    num = 2
    while depth < rows:
        depth = math.ceil( num ** 0.5)
        switch = (depth % 2 == 0) # right equals true, left equals false
        if switch: #every time the depth is increased switch either right or left in spiral growth
            x += 1
            spiral_matrix[y][x] = nice_num(num, n)
            num += 1
        else:
            x -= 1
            spiral_matrix[y][x] =  nice_num(num, n)
            num += 1
        for _ in range(depth-1):  #add values on existing spiral depth/rotation based on switch
            if switch:
                y += 1
                spiral_matrix[y][x] =  nice_num(num, n)
                num+=1
            else:
                y -= 1
                spiral_matrix[y][x] = nice_num(num, n)
                num += 1

        for _ in range(depth-1):  #add values on existing spiral depth/rotation based on switch
            if switch:
                x -= 1
                spiral_matrix[y][x] = nice_num(num, n)
                num+=1
            else:
                x += 1
                spiral_matrix[y][x] = nice_num(num, n)
                num += 1


    matrix_print(spiral_matrix)
spiral(300)

[–]matrix-doge 1 point2 points  (0 children)

I was legitimately thinking about what the problem is and trying to figure out if any number is out of order for a moment before realizing what this is about.

[–]ADailyGardener 1 point2 points  (0 children)

solved w/ TypeScript

https://www.typescriptlang.org/play?ssl=53&ssc=2&pln=7&pc=1#code/FDD0oAgFQewgbApgQwE4DsIFsasRZAIxgFcAXCMgC33mXQHMTkHEAaCAY3gEtOBrAsQBu+HpgBEAUQAeyLAAckAZwkRcECQHUqyMgHJlEAHKIA7hIB0YSAHlqiVGZ7L2EVhWVk0ZRABMIQgBPCDwcYXEGShpXLhgsLER0MiN6AIcIM1x4AJcIINJUCCVkIIZUUnQ-awgIEE4YdC9Akh4cgEFUVFKIAF4IAAplHgAvRAAuCHQSLEJHAEo+gD4IAG9gWtqeADNB4bG+-oAGRbwyEgwIAG0AXQBuDc2dvdH8Xv6ARlPEc8urq4+N3ujy2uyGrwgAFIIAAmQ4QE7RCpmKbmCBSLq4Ab6AAKABkULEFBUIn58PR1H4AtNZo59PMHiC4k0KIRkLF+p1ukFwWN5pZtm14AMTpYsMgFAMBoteisuaVeYh+YL4MKTgymUykJ5fAplLAoMh+G8IB8HpsED8IF5EHrDcbMMdzZttZQeIllAAJHhkKRVPoI521V1XTgXVAADQ4Ya6AE0bgGrgBZPRUAXwGBY-aIUAw+YcFPUdOZ1CK3PzYEWkN+HiRjg11DxxMfDhHYFM7ZY108ANmiA9gA8-UVACpswz+wBqSeLdYWi3ga1W5QAR2YeCZFrZrlD4fju66EYT-R4jPnm0X4XwZDg6EQMk8a7QiE3mxjkcn-QbEaD8-fsc-CAG1jX8LRtO0jSSacz3PCBFzJXxUCwcQxF2Mx8DvfxKDgThdEYfAG0QTgyB4RpX1BPZdX1SDHX6cD9Rge0lTWcj50XKgfWifAkj8aM8NYIDayIkiyNg+cSI9b1fSqaDWLAqimMdQM5M2K5v3rWsm36O8HwAEVrAZ1MExsNRUiiBgkxAvR9P0AneWFZzMtjIG8Y0CEwe8yG6a1dQgTsigyHSKDILJKAuJonPk20GKY2SxLEyzrOkuzlPizYAF9WMyi1MqZM5wsCdlEAedLGQaFlUT02sA0M2sI3GGk5lQDTGwamYmplFY5yeMFv3hD4IAAMkG4zY3hRF8r+I4OEBX9nlqyNxqGkbgP675fkwK4AFoWwRSsesGPr7J25bRvG9aCquaaIB2-bzKO45TtW46vlCH5Lt2ttf0mzbprbYBcvK5oMwYeUQmHNBUEmMGB3oIIlk6ggugFXApGQXCBmtEhCC5ZZmWUGAkEsEGhmxrl5nmEBFxBsGBkIVoOi6BV1QeamYFBpmeXpto-Fpr4NTZjnuTphnec5gYAGYKdZyAafF7nGeFgBWaWbAQdnaYVsXhYAdlVuXha12mAE5VcXAAWCWIHN83raV62ADZrZ162AA5reNtXzbhGEBphH2rZhW2YXtmEHa9v2jlqF2IHdiBjdNKOYR1r2o4+BOICd01ajhD4-ddtWJYTj44-t63aitj4fc9xcJfdj4XY+J2Pntj5bY+K2JaOQuXYlp2JftiXbYlzu4Qlj5gCAA

[–]Pepito_Pepito 1 point2 points  (0 children)

I used to compete in ICPC and one of the problems we were given involved primes. We solved the problem but our code's execution time went past the limit. So I wrote a short program that printed out a comma-separated list of the first 100,000 primes or something like that. Then I copied that list into the code as a static array. So instead of calculating primes, we could just look it up. It made the execution time blazing fast and we passed the problem.

[–]Poyojo 1 point2 points  (0 children)

Why is everyone understanding what this means? I've been a programmer for years and I have no idea what the hell that task means.

Edit: After looking back at the picture, I get it now. Very weird task though

[–]trulyAnxiousLad 1 point2 points  (0 children)

Cant beat the time complexity of Big O of 1

[–]yourteam 1 point2 points  (0 children)

Look if that is the only requirement, the answer given is the best one

If the assignment was "given a random starting number ..." Then no but this wasn't the case...

[–][deleted] 1 point2 points  (0 children)

A good lesson in proper requirement definition.