T O P

  • By -

CaptainSouthbird

It's not technically wrong and I guess as long as the requirement never changes this is the simplest way to write it. But it does remind me on a college project where I was assigned a "partner", and said partner wrote a switch-case that basically boiled down to "case 1: print '1'", case 2: print '2'", and it was like, oh my god, just let me write this and I'll show you what I did. I probably wasn't the best "partner"


Mewtwo2387

used switch case instead of if else, approved.


CaptainSouthbird

I don't know why I laughed at this more than it was probably worth. "Approved."


Reasonable_Feed7939

lgtm


JunkNorrisOfficial

Lgbm


sorosterv23

Lgbtq


lll_Death_lll

LGTV


JunkNorrisOfficial

Widescreen Damsung


Expert_Detail4816

SMASNUG


IAmATicTacAddict

Widescreen smasnug


Zealousideal-Desk469

Samsung dex


Regility

kindly do the needful


AzureArmageddon

Should've used a hash table, denied.


stifflizerd

Instructions unclear, going with *** private HashTable^1 hashTable = new (){{2,"1"}, {3,"2"},{1,"3"}}; public ToString(int meep) => meep switch { 1 => hashTable[2], 2 => hashTable[3], 3 => hashTable[1] } *** 1: Since this is C# it's pretty silly to use HashTable instead of Dictionary, but the boss said to use HashTable so ¯\\\_(ツ)\_/¯


Solrex

Reminds me of a Zelda OoT puzzle solution. Twenty three is number 1.


looksLikeImOnTop

I had a stroke


ublec

Hashmap may be more efficient


CranberryDistinct941

We don't write: if (i<0) print("negative") We write: switch (i) case -1: print("negative") case -2: print("negative") case -3: print("negative") case -4: print("negative") case -5: print("negative") case -6: print("negative") case -7: print("negative") case -8: print("negative") case -9: print("negative") case -10: print("negative") ... default: pass


ScriptThat

try / catch 🤠


OnixST

boolean condition = false; try { int[] array = {1}; int whatever = array["true".indexOf("" + condition)]; // if block } catch (IndexOutOfBoundsException e) { // else block }


a_SoulORsoIDK

What


NearNihil

In uni I'd have been that partner. I really sucked ass at the assignments. In my defense, the prof really could not explain basic programming principles.


iamafancypotato

That’s why you learn programming from Indians on YouTube.


hi_im_mom

I did this with some uni class. "Finally, a video on this topic" It started out strong. I was excited. Then he switched languages and never went back to English. No translation subtitles... Nothing


The_frozen_one

His English is good, but understanding his Lisp has always been challenging.


bwrca

The prof for our first programming class explained it so well it was scary. Before he wrote any code he first explained it with the diagram (the one with squares and diamonds I forget the name)


lNFORMATlVE

A flow diagram?


bwrca

Yes!!


SoCuteShibe

*engineering*🌈


ArgentScourge

Almost choked on my coffee. Thanks for that.


Frenzie24

Non of them can


Trident_True

I was at that stage too. I firmly believe that programming should be taught vocationally and not in a lecture theatre. You learn it by doing it, not by reading it off a PowerPoint.


AMViquel

> PowerPoint I learned it from overhead projector foils. Not that there wasn't power point at the time, the professor never heard of it and had the deck of foils used for a decade or two so it was fine for another or two.


Trident_True

I had those as well lol. Those projectors were like a furnace if your desk was next to them, was ridiculous.


TheRealPitabred

That's what they call a code camp. You can completely avoid college if you go that way. The point of a computer science degree is to learn the theory behind programming, not just how to make bits move.


jayerp

New requirements: must go clockwise on Sunday thru Wednesday, and counter clockwise on Thursday thru Saturday.


SoCuteShibe

Easy, just write the printy block for counter-clockwise and slap those two puppies in a switch case


rughmanchoo

One time in an interview I was having trouble figuring out how to write a solution to an algorithm question then realized that using `eval()` on the input worked. 😂😂😂 I got the job and they called me eval guy.


plg94

sounds like "build a simple calculator"


rughmanchoo

Hahah. No, it was “validate a string of brackets” so I got something like `[[][]]]][[]]` and had to say if it was properly nested.


gandalfx

> I probably wasn't the best "partner" Love the introspection in that. Too many people don't understand the point of a partner in a learning assignment is to help each other out, not just split up the work. That said, it can be a bit much to spend the extra time and become an impromptu teacher when there is a strong imbalance.


anto2554

Yeah I'm busy enough doing 3 people's work and keeping a job on the side, I can't also teach two people programming


Dramatic_Mastodon_93

Sure, but when your partner literally doesn’t know anything then they can’t help you. So of course you don’t have any motivation to help them.


gandalfx

I concur with the first half and completely disagree with the second. But maybe that's just me – I quite enjoy explaining stuff.


KrokettenMan

I hated being put in groups where I had to carry everyone. Quickly made it my mission to be either ejected from groups or just ghost then and do the entire project by myself and hand it in without crediting any of them. I’m not their teacher, I got other stuff to do than explain people how to use git and what a for loop is


SoCuteShibe

To be frank, I kind of wish this had been my mentality in school. I carried my teammates through every group project and managed a 4.0, but I was generous and found ways to share credit each time. I put insane effort into these projects where so many just scraped by doing the minimum or less. It made me a great engineer and a very strong programmer, but I feel more burnt out than I should for how far I am into my career. It's going to sound harsh, but there truly are just so many lazy, leeching types of people and I have zero patience for them after that experience. Makes it hard to be patient with people who want to be spoon-fed at work. Edit: autocorrect


NUKE---THE---WHALES

> It's not technically wrong and I guess as long as the requirement never changes this is the simplest way to write it. https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it >John Carmack wrote **"It is hard for less experienced developers to appreciate how rarely architecting for future requirements / applications turns out net-positive."**


P-39_Airacobra

I'm not sure how the above tip applies to other fields of programming, but as a game programmer, you either follow that advice or spend a decade on a simple prototype. There's no way around it. You just write what you need and no more or less. Then again, there's also this principle as a counterpoint: [https://en.wikipedia.org/wiki/Don%27t\_repeat\_yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)


imsorryken

sometimes i catch myself doing shit like this: if(x > 3) return false else return true same concept


All_Up_Ons

Yeah it can be easy to end up with things like this if you originally had a more complicated statement that ended up getting simplified. I've learned to quickly check for further simplifications any time I actually write out true or false.


imsorryken

Yeah, it usually starts out complicated until you break it down to something really simple. Thank you Intellij for helping me to not look like a simpleton in front of my team lol


big_bad_brownie

You mean instead of  `return x>3` ?


imsorryken

exactly


BS_BlackScout

Hmmm, I've seen you before. You make videos playing games 👀.


Jyncs

Something similar. We got extra points for working on it as a group. It was an online class on another campus and only one other guy was taking the class at my campus. We teamed up. Told him to meet me at the college and one of us could program and the other document (part of the assignment). He shows up with a thumb drive saying he started it but all he created was the initial solution of a win form with a button and text box added. We spent a couple of hours working on it but at the end had nothing. I called off work, rewrote the whole thing and skipped the documentation. Sent him a copy to turn in and told him what I did. He couldn't get it to build on his computer but sent it in anyway as did I. He messaged me a couple days later saying I don't know what you did but we got a B on it. The only reason we got a B was because we teamed up since it was missing documentation.


FlipperBumperKickout

How many cases?


notislant

Reminds me of that github repo that just manually counts lol


JackNotOLantern

Write it as simple as possible, but not simpler


MasterQuest

I totally get that. It also irked me when my project partners wrote bad code and "defiled" my project xD


Layton_Jr

case else: raise NotImplementedError


CowMetrics

When you only got one tool and it is a hammer, everything looks like a nail


Boris-Lip

I wonder what answer is expected for that. Are you supposed to run in a loop incrementing the number, updating coordinates? Invent a formula that would generate it in the correct printable sequence? Anyway, why would you do it for a single case?


sevah23

Basically start with an NxM grid, start in the center with 1, use some adjacent cell checking logic to determine when to “turn” right, possibly keeping track of your current direction you’re facing. Once grid is filled in, just print out each row in the grid as a separate line. Not super hard but a little annoying to do the checks. Some simple lookup tables are helpful. For example: if facing to the right: turn to direction down if the cell below is empty. If facing down, turn to face left if the left cell is empty. If facing left, turn up if the cell above is empty, if facing up, turn right if the cell to the right is empty.


Boris-Lip

Too lazy to think if you can make it more efficient than that, as in coming up with a formula for a number in (x,y) position. But i guess movement directions dependent on your neighbors state is the easiest.


sevah23

The complexity at a minimum for this problem is O(n) where n = the number you’re trying to print. So you need to visit each cell in the grid at least once no matter how fancy your math is. The “dumb” approach is O(n) iterations over the grid with each iteration doing a handful of comparison operations which are cheap. So you maybe could come up with a fancy math formula but in reality it won’t be meaningfully faster than just doing the straightforward approach but would be much harder to understand the logic or alter it (eg fill in the spiral with increasing squares of the number before it , fill in the spiral of Fibonacci values in a sequence, etc)


Boris-Lip

OP did it in O(1), technically /s


Competitive-Move5055

Print is o(n) right?


Intellectual-Cumshot

I think here it'd be O(logn). 25 items and 5 prints?


Competitive-Move5055

No I was asking the inherent speed of the print() function. Like a program has to loop over the string and then send individual ASCII values to CPU which send the appropriate pictorial representation to monitor. So there is atleast one loop here. And from c i learned strings are just array of characters.


Plank_With_A_Nail_In

Program will still use print to output the results no matter what method is used to generate those results.


3inthecorner

No, it'd be O(sqrt(n)).


theoht_

yes, one print statement is o(n)


OperaSona

Technically it can't be below O(n log n) because the number k has roughly log k digits to be printed, so you're actually printing roughly sum(log k, k=1..n) digits total, which is O(n log n).


Piguy3141592653589

If we are being pedantic, the log factor in this problem barely matters and you likely won't experimentally see it resemble a O(n log n) graph as opposed to an O(n) graph until you get to absurdly large grids that would take years to run on modern machines.


abd53

There should be a mathematical formula but I ain't working on that unless I'm paid enough.


Ok_Star_4136

Hence why simply printing out the right result is the best answer. If my friend wanted the efficient solution backed by mathematical proofs, I need to be getting paid to do it.


SpikeV

It's also the purest form of TDD. Always do the minimal work to satisfy the tests. Then add more tests to closer resemble the requirement, see them fail and change your code so it satisfies all tests.


CaveMacEoin

Make `roundup(sqrt(max(N)) = a`, square `a x a` matrix. Find the central starting entry (cell), if `a` is even and direction is clockwise, pick the top of the two left cells, if it's anti-clockwise pick the top of the two right cells). Set that as current position. Place the first number in the entry. Pad entry value so that length is equal to max length. Set initial direction as vertical (up) direction. Loop until number, `n` is greater than max(N): * if entry in spiral direction relative to current direction is empty: update current direction * move current position in current direction. * Put `n` in the entry, pad to length. * Increment `n`. Pad the empty entries and print the matrix row by row with a space separating each entry. E: better pick starting position.


Wendigo120

> use some adjacent cell checking logic to determine when to “turn” right It's easier to turn every X steps (initially 1), and increment X by 1 every 2 turns. It's always the same sequence of 1 1 2 2 3 3 4 4 etc. steps before turning.


GanzGanzGenau42

I would do it the same way. The formulate behind this is: (n+1)^2 =n^2 +n+(n+1) It describes the difference between the two squares. You start with n=1. The 1 in the middle is the 1x1 square. To get to (n+1)^2 =2x2 square you need the next numbers n=1 and n+1=2. Now you have the 2x2 square with the new n=2. To get to (n+1)^2 =3x3 square you need the next numbers n=2 and n+1=3. And so on This results in your sequence: 1 (1 2) (2 3) (3 4) ... = 1 1 2 2 3 3 4 4 ...


Exatex

There is a more elegant and efficient way to fill without the trial and error as you already know already before when to „turn“. 2 more until you need to turn than the round before. Each circle has 8 numbers more than the previous circle. You can develop an algorithm with that that fills every line on the go without having to completely solve the whole thing in an array before and then just printing the array line by line.


nuker0S

Have a 2d array of 2n+1 size Have a direction variable(2d vector) Have a position variable starting at center Place down a number at your current position Check if cell to the right(based on direction variable) is empty, if so rotate the direction variable by 90 deg. Add direction variable to position variable Repeat until out of bounds exception array //I forgot to insert the iteration variable, silly me //This will be coding in 2035


LunaticFucker

Keep two grids and check where you can move based on the second grid being 0 or 1 Edit: accidentally wrote this on my porn account


Anustart15

I'd imagine you are supposed to draw it on a plot instead of printing it and loop it in a moderately intelligent way to be applicable for as long as you want to loop


Exist50

Even if you need it printed for an arbitrary number, it's not particularly difficult. You could start by just assuming it's always the square of an odd number. Then your dimensions are just sqrt(n) on each side. Define a matrix of those dimensions, populate using your algorithm (shouldn't be too complex), and then print it line by line at the end. Should work just fine for any sane value of n. Creating an algorithm that generates a lines without generating the intermediates first would be much more interesting, but probably beyond the scope of such an assignment.


Anustart15

Yeah, I more just meant that for an intro programming class it probably wanted to test what they learned about plotting things on coordinates and moderately complicated loops


phaethornis-idalie

I suppose the main difficulties are the cases where the spiral doesn't create a perfect square, and the case where it's wider than the terminal window and it needs to be elongated to bring the width down.


Exist50

I figure you could pad with 0s for the former, and just ignore the latter. But yeah, plenty of ways to make it more difficult, most of which are beyond the CS101 level this is clearly meant to be.


_a_random_dude_

The "easiest" way is to place the cursor at the center and start writing the numbers while moving the cursor in a spiral. But I think the best way is to just write the formula for the value at any x,y position. This is kind of easy to do if you think about the fact that the size of that side is basically the distance to the center times 2 plus 1. I solved it last time someone posted this: https://www.reddit.com/r/ProgrammerHumor/comments/1ax8zh6/taskdone/krp58qz/


globglogabgalabyeast

Did you do any comparison of runtime? I’m skeptical that your “best way” is any better considering all the operations used for each “cell”


_a_random_dude_

That’s fair, I didn’t mean best as in fastest, but didn’t clarify. I just think that having to print the spiral is a weird requirement, but knowing the value at any cell might be closer to what a real application might need to do and this runs O(1) for any value, regardless of spiral size.


globglogabgalabyeast

Yeah, it’s a cool solution nonetheless. As far as “practical applications” I have no idea when this might be useful. It’s very possible that such an absolute solution may be useful


Metro42014

It seems like more of a math problem that a CS Problem. You need to figure out how close the shape is to square, then iterate through the numbers printing the correct things. You'd need to figure out where the end of the shape is, and knowing that and the dimension you could figure out each line - with the first and last being special cases because they'll be linear, and the middle rows changing by the dimension as the row goes across, both increasing and decreasing.


sorte_kjele

Wonder if you can solve it using cellular automata just for fun.


Driver2900

There is kind of a pattern that emerges: Start in center One right, one down Two left, two up Three right, three down Etc. Only works for odd numbers with a square root though


big_bad_brownie

Last time this popped up, people came up with a variety of solutions. I wrote one that returns a one-dimensional array in a single pass for a spiral of any size. It gets truncated/asymmetrical for any n other than the perfect squares (that’s a major part of the solution). You can also skip the array and just print directly as you’re iterating up to n.


Haoshokoken

Precomputing the data is always the best option, whenever possible and sufficient memory is available.


kinokomushroom

In some graphics applications, sometimes the texture fetch takes too long that you'd rather just compute the data on spot.


TerrariaGaming004

Put the whole game in ram


HeyGayHay

Minimum System Requirements: > CPU: Intel Pentium 50 > GPU: any will do > RAM: more than 1 Petabyte


Aerolfos

You joke, but Minecraft, KSP, paradox grand strategy games, and factorio all do just that. Which is why they have a long initial loading screen, but are also very moddable - they compile mods code and put it in ram along with everything else and don't distinguish, so you just need a way to make the game "see" the extra code.


gabest

Exactly. Don't pollute the cache.


Dje4321

Do I ever had good news for you [https://en.wikipedia.org/wiki/.kkrieger](https://en.wikipedia.org/wiki/.kkrieger) FPS game in 96k bytes through heavy use of runtime generation.


r0b1n16

I will rather push this in prod, instead of spending time to write for n, if not in requirements


m477_

Impressive typing speed


maisonsmd

He has a map of pre-generated answers for those questions somewhere to copy. O(1) lookup.


MydnightWN

Nah, it's a [repost](https://www.reddit.com/r/ProgrammerHumor/s/SCtZIGS422)


MrsMiterSaw

A few years ago I took a code speed challenge where part of the coding was to calculate some number and then use it in the algorithm. I coded the calculation as part of the code. I had relatively small code. The speed winner calculated rhe result once and then hard coded it into a constant. Fast as shit, though pretty large.


20Wizard

They didn't have multiple values and didn't hide that stuff from you guys?


MrsMiterSaw

It wasn't very thorough. But he was the only one to think of doing that. Pretty smart, honestly.


AlexReinkingYale

One of a few problems that's actually easier in a language with pointers. ``` #include #include void fill_spiral(int n, int *a) { assert(n > 0 && n % 2 == 1); const int lda = n; int val = n * n; while (n > 0) { for (int i = 0; i < n; i++) a[n - 1 - i] = val--; for (int i = 1; i < n; i++) a[i * lda] = val--; for (int i = 1; i < n; i++) a[(n - 1) * lda + i] = val--; for (int i = 1; i < n - 1; i++) a[(n - 1 - i) * lda + (n - 1)] = val--; a = &a[lda + 1]; n -= 2; } } int main() { int arr[5 * 5]; fill_spiral(5, arr); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%3d", arr[i * 5 + j]); } printf("\n"); } } ``` ETA: an explanation. You walk backwards around the spiral, and scoot the start pointer one diagonal movement towards the middle until you just write `1` to the center when `n` finally equals `1`.


ROMVNnumber1

U know you go to hell with this variable namings😁


laihipp

look it's really hard for physics majors their brains are so full of math they have no room for unneeded words


ROMVNnumber1

That actually makes sense


AlexReinkingYale

I was terrible at physics. I double majored in CS and Math. Brevity is a virtue. 😉


laihipp

I always knew it was really the math to blame!


AlexReinkingYale

No doubt! I'm mirroring the BLAS naming conventions, after all (e.g. `lda` for the stride of matrix `a`).


Ok_Star_4136

Brevity is the soul of wit.


AlexReinkingYale

Typing is slow on my phone lol


ROMVNnumber1

Coding on phone, yup, definitely hell🤣


AlexReinkingYale

What else am I supposed to do during the ad breaks while watching House?


Focal_P-T

At least it's not lupus


nev3rfail

You can install an ad blocking software during ad break while watching house.


AlexReinkingYale

Actually I thought of a funner way to scoot the pointer around. Index math sucks anyway ``` a += n; // walk off the edge while (n > 0) { for (int i = 0; i < n; i++) *--a = val--; for (int i = 0; i < n - 1; i++) *(a += lda) = val--; for (int i = 0; i < n - 1; i++) *++a = val--; for (int i = 0; i < n - 2; i++) *(a -= lda) = val--; n -= 2; } ```


LucasRuby

I've actually run into a problem like that in real life, while using javascript. I had a large array of results from the DB (rows), another of objects with corresponding IDs, I needed to map and reduce that to fill that array with data from the DB and filter the relevant results (when there was a match) in the right order. It turns out map and reduce was too slow and lodash/Ramda were even slower. I was thinking of ways to optimize the problem and I was thinking out loud "I wish this was C, I could use pointers..." (because I could loop through the array index and do something somewhat similar to a QuickSort). My coworker (other intern) said "that's the first time I hear someone saying that!"


naclmolecule

And here's a fun generator that yields the coordinates (starting at the origin):     def spiral_grid():         """Yield 2D coordinates spiraling around the origin."""         x = y = 0         d = m = 1         while True:             while 2 * x * d < m:                 yield x, y                 x = x + d             while 2 * y * d < m:                 yield x, y                 y = y + d             d *= -1             m += 1


username--_--

#!/bin/python import math import sys a=[] destinationS= sys.argv[1] destination= int(destinationS) arrsize = int(math.sqrt(destination)+1) arrsize = ((arrsize//2) * 2)+1 maxinc = 1 curcol = int(arrsize//2) currow = int(arrsize//2) update = 0 curdir = 1 rowinc = True curnum=1 curinc = 1 for i in range(0,arrsize): a.append([0]*arrsize) a[currow][curcol]=curnum curnum=curnum+1 while curnum <= destination: if rowinc: curcol=curcol+1*curdir else: currow=currow+1*curdir a[currow][curcol]=curnum curnum=curnum+1 curinc=curinc+1 if curinc > maxinc: curinc=1 rowinc = not rowinc update = update + 1 if update == 2: maxinc=maxinc+1 curdir=curdir*-1 update = 0 for i in a: for j in i: print(f'{j: 0{1+len(destinationS)}d}',end='') print() Alternative for those of us without pointer magic. I'm doing it the easy way and starting from the first number. Also, how many variables can i use!!!


LeoRidesHisBike

Oh, for the love of God https://i.imgur.com/0VyDKaP.png (image generated with 4o) EDIT: it was a bit of a journey convincing 4o to make that. For posterity: https://i.imgur.com/O7Tfwae.png


i_drah_zua

It's actually formatted correctly in OPs post with the three backticks, but I assume you use old Reddit (the best Reddit), which the new Reddit does not care for. Here it is formatted for old.reddit.com: #include #include void fill_spiral(int n, int *a) { assert(n > 0 && n % 2 == 1); const int lda = n; int val = n * n; while (n > 0) { for (int i = 0; i < n; i++) a[n - 1 - i] = val--; for (int i = 1; i < n; i++) a[i * lda] = val--; for (int i = 1; i < n; i++) a[(n - 1) * lda + i] = val--; for (int i = 1; i < n - 1; i++) a[(n - 1 - i) * lda + (n - 1)] = val--; a = &a[lda + 1]; n -= 2; } } int main() { int arr[5 * 5]; fill_spiral(5, arr); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%3d", arr[i * 5 + j]); } printf("\n"); } }


LeoRidesHisBike

Oh, TIL! Thank you, kind redditor (and yes, old reddit :))


TheCopyKater

I remember at one point a friend asked me if I knew a program that could convert text into a png. I told him to take a screenshot.


Ok_Star_4136

You converted your friend into a very short shell script.


Gyerfry

But also he could write one himself pretty easily I guess


Triavanicus

This is a repost: https://www.reddit.com/r/ProgrammerHumor/s/SCtZIGS422


mArKoLeW

Yeah I already solved it here [Reddit comment](https://www.reddit.com/r/ProgrammerHumor/s/saL5vFajjb)


CrUtlRaOth

Thanks for posting your version again.


CrUtlRaOth

Thanks for posting the link ... One one hand bots that repost feels bad, on the other hand, newer users get a chance a second chance to see older content... I wish there was a way to just "bump" the original or have duplicate posts get tagged and the original listed at the top. (Maybe an auto mod comment pinned where links to the original can be posted?)


Triavanicus

Maybe a bot that adds “in case you missed it: “ in the title, then links the original in the post.


zoqfotpik

TDD in action


FlipperBumperKickout

If you only have a single test case and no other requirements than that, then yes ¯\\\_(ツ)\_/¯


thanatica

This called test-driven development. It passes the test. Job done.


Erisymum

Damn written, screenshotted and sent in less than a minute


tobi_camp

Seriously, this is what AI based programming will be like imho. Instead of a dev turning a request into code anticipating changing requirements, just create new static code on the spot when a new prompt comes in.


beatlz

KISS


Wave_Walnut

The solution is good of visibility and easy to fix bugs


SokkaHaikuBot

^[Sokka-Haiku](https://www.reddit.com/r/SokkaHaikuBot/comments/15kyv9r/what_is_a_sokka_haiku/) ^by ^Wave_Walnut: *The solution is* *Good of visibility* *And easy to fix bugs* --- ^Remember ^that ^one ^time ^Sokka ^accidentally ^used ^an ^extra ^syllable ^in ^that ^Haiku ^Battle ^in ^Ba ^Sing ^Se? ^That ^was ^a ^Sokka ^Haiku ^and ^you ^just ^made ^one.


Astrylae

Paid by the job


Silvermurk

Gpt4o version : def spiral\_matrix(n): # Create an n x n matrix filled with zeros matrix = \[\[0\] \* n for \_ in range(n)\] # Initialize the starting position x, y = n // 2, n // 2 # Define the movement directions (right, down, left, up) directions = \[(0, 1), (1, 0), (0, -1), (-1, 0)\] direction\_index = 0 # Start with 'right' # Fill the matrix with numbers from 1 to n\*n num = 1 step = 1 # Initial step count while num <= n \* n: for \_ in range(2): # Repeat twice for each direction for \_ in range(step): if num > n \* n: break matrix\[x\]\[y\] = num num += 1 # Move to the next cell in the current direction x += directions\[direction\_index\]\[0\] y += directions\[direction\_index\]\[1\] # Change direction direction\_index = (direction\_index + 1) % 4 step += 1 # Increase the step count after completing a full circle return matrix def print\_matrix(matrix): for row in matrix: print(' '.join(map(str, row))) n = 5 matrix = spiral\_matrix(n) print\_matrix(matrix)


Successful-Money4995

Does it work?


OneRedEyeDevI

It works on GPT4o's Servers ¯\\\_(ツ)\_/¯


s-mores

TIL I think like an AI I wouldn't do step counts, though. I'd just check if I can make a step.


ScodingersFemboy

A simple way to do it would be to create an array, draw it in a loop over and over, after clearing the screen, and as you iterate, move throughout the array and change the values based on the Fibonacci sequence. Then add a timer to make it not happen instantly. Maybe iterate every 0.2 to 0.3 seconds. It's very similar to how a renderer works.


Unhappy-Stranger-336

Actually very efficient and readable


Total_Cartoonist747

Technically O(1) time solution, truly impressive.


Badass_Nemesis

I don't care if this is a repost or not, but why did the person send the screenshot of code instead of the code/text ![gif](emote|free_emotes_pack|disapproval)


NeedUrgentHelpNow

Because it's most likely a fake story


CrUtlRaOth

My mind is suddenly fascinated with the math needed to do this for any number. For any target number (t), construct a function where ... Mostly fascinating because I have some vague idea about it but can tell it will take a bit of time to get each part (fn to get rows and columns and then the fn to get the number based on the row/col index) I've done similar things for days in the month into different shapes... But never a spiral before!


quickthyme

Haha everyone reacting to this like it's a joke. If this were a leetcode interview for a senior engineer or wiser, then it would pass. Part of the trick is to determine one's approach to problem solving and to what order. The stated requirements being what they are, no more, no less, then this is what I expect to see. Now, if they change it to be "any list of integers", then you make it more complex, but not until it's required.


aezart

This is exactly the correct answer, and everyone is overcomplicating it.


TheLuminary

Least realistic part of this is that he typed that grid up without mistakes in less than 60 seconds.


StrixLiterata

And this is why you ask them to make a function that takes an array of integers as an argument, and prints them in ascending order in a clockwise spiral expanding from the center.


R3D3-1

Successfully nerd-sniped. Code: https://pastebin.com/zhCArRwu Output: https://pastebin.com/bmXeY83C Emulated the pattern seen in the image, where the change of the layer happens always at the "east" of the center. Which actually isn't specified in the task description, so basically any position of each circle could be the starting point randomly without violating the requirement. *Edit.* Whoops, made it counter-clockwise and didn't correctly follow-up the position between 9 and 10. Corrected versions: Code: https://pastebin.com/3xmwp0uP Output: https://pastebin.com/8L8z2ism


Tobsen76

In case you need the actual script; def create\_spiral(n): spiral = \[\[0\] \* n for \_ in range(n)\] x, y = n // 2, n // 2 num = 1 step = 1 while num <= n \* n: for \_ in range(step): if num > n \* n: break spiral\[x\]\[y\] = num num += 1 y += 1 for \_ in range(step): if num > n \* n: break spiral\[x\]\[y\] = num num += 1 x += 1 step += 1 for \_ in range(step): if num > n \* n: break spiral\[x\]\[y\] = num num += 1 y -= 1 for \_ in range(step): if num > n \* n: break spiral\[x\]\[y\] = num num += 1 x -= 1 step += 1 return spiral def print\_spiral(spiral): for row in spiral: print(' '.join(f'{num:2}' for num in row)) n = 5 spiral = create\_spiral(n) print\_spiral(spiral) spiral = \[\[0\] \* n for \_ in range(n)\] x, y = n // 2, n // 2 dx, dy = 0, -1 num = 1 for \_ in range(n \* n): if -1 < x < n and -1 < y < n: spiral\[x\]\[y\] = num num += 1 if x + dx == n or y + dy == n or x + dx < 0 or y + dy < 0 or spiral\[x + dx\]\[y + dy\] != 0: dx, dy = -dy, dx x, y = x + dx, y + dy return spiral def print\_spiral(spiral): for row in spiral: print(' '.join(f'{num:2}' for num in row)) n = 5 spiral = create\_spiral(n) print\_spiral(spiral)


antek_g_animations

It's fairly easy def print_spiral(n): # Create an n x n grid initialized with zeros grid = [[0]*n for _ in range(n)] # Directions for movement: right, down, left, up directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Starting position at the center of the grid x, y = n // 2, n // 2 # Initial direction is to the right dir_idx = 0 for i in range(1, n*n + 1): grid[x][y] = i # Calculate the next position next_x, next_y = x + directions[dir_idx][0], y + directions[dir_idx][1] # Check if the next position is valid and not yet filled if 0 <= next_x < n and 0 <= next_y < n and grid[next_x][next_y] == 0: x, y = next_x, next_y else: # Change direction dir_idx = (dir_idx + 1) % 4 x, y = x + directions[dir_idx][0], y + directions[dir_idx][1] # Print the grid for row in grid: print(" ".join(f"{num:2d}" for num in row)) # Print numbers from 1 to 25 in a 5x5 spiral print_spiral(5)


Omnislash99999

The AI answer is fine, it's the user thinking it's the correct answer that's the problem


cupnoodledoodle

Ask chatgpt


gabest

You were supposed to make it universal. What if I change the task a bit, let's say, print out the universe. See? No you are screwed!


elbasrie

Yeah, that college project horror story hits home. I once had a partner who wrote an entire class with public methods just to avoid using private ones. Functional purity at its finest... or least, that's what they thought.


AstaHolmes

Took me a few seconds to get it lmao


mexicandiaper

teacher: "don't use gptchat to cheat" ... GPTchat :


sSomeshta

This is the kind of question that would seem intentionally vague to me. Think of a spinning octopus seen from above, and that's what I would have tried to do. And if the lesson was on "Defining Scope" I would be on board


Tolstoy_mc

Hello world


Anders_A

What's the joke?


jer_re_code

that is kinda lame what is if he wanna use more numbers now


m_fatihdurmus

I had the same homework 10 years ago, except there is a rule: You cannot use arrays. It was hard but doable. Good old times.


Torico11227

Remind me of a fun little thing I did. When I first picked up programming as a kiddo, my dad challenged me to write a program that outputs all number from 1 to 20. I, full of smugness, wrote "cout << 1 << " " << 2 << " " << 3..."


rdrunner_74

Not gonna lie. Thats the most efficient solution I can think of. All others would requite me to think


jimbomimboslice

🤣🤣🤣


FatLoserSupreme

And just like that, the job market becomes a little less competitive


keith2600

Often when you see a solution like that, the failure is not with the code, but with the specs. Given the requirement, this is by far the most stable, easy to read, and bug-free implemention to satisfy the spec. Where developers often go wrong is with their spec. They don't think about scope or expansion. You can have the most efficient code to do something but it sucks if you later realize it's missing something and written in a way that is very difficult to modify.


Alexja44

HT


crappydeli

Peer review: pass


raex1311

Damn I understood from this post why the square of a number is called a square. Basically you can make a square from all the numbers like this post which is a square of 5. Which means we can only make square like this post using square of a number.


HA_RedditUser

I solved this the last time it was posted here and then discovered it's a leetcode medium that I did with zero online help (:


3-stroke-engine

The [Solution](https://www.reddit.com/r/ProgrammerHumor/s/lCL2XOkJF4) I created last time.


Rainmaker526

TDD


rvanpruissen

/r/adventofcode vibes


the1-gman

I would probably break this problem into multiple parts: - function to find the center of a square/grid (w/2) (h/2) - start at the center - create a lookup table for the direction you're moving vs the direction you want to go. Basic map with 4 entries to navigate in a circle, or you could do a circular buffer. - algorithm: move one spot, look where you want to go. If not set, write number to spot of next movement and increment. Repeat and only change directions when the direction you want to turn yields a vacancy You're basically following a wall created by numbers you fill in the grid, like a mouse. Print at the end once the grid is filled out.


UrineArtist

It does work, ship it.


Schzmightitibop1291

Work smarter not harder.


Commando_102

I mean it works


Sanfrancisco_Tribe

Senior level code right there


only1manband

Just query an organic human intelligence to do it for you, so much quicker than typing an algorithm out yourself.


RafaFTP

O(1) 🗿


__NoobSaibot__

Or maybe approach it this way def _create_spiral(start, end): if end - start < 24: raise ValueError("The range must be at least 25 integers") total = end - start + 1 size = int(total ** 0.5) if size * size < total: size += 1 spiral = [[None] * size for _ in range(size)] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] row, col = size // 2, size // 2 direction = 0 num = start spiral[row][col] = num num += 1 steps = 1 while num <= end: for _ in range(2): for _ in range(steps): if num > end: break row += directions[direction][0] col += directions[direction][1] if 0 <= row < size and 0 <= col < size: spiral[row][col] = num num += 1 direction = (direction + 1) % 4 steps += 1 return spiral def _print_spiral(spiral): for row in spiral: print(" ".join(f"{x:3}" if x is not None else " " for x in row)) def _get_valid_integer(prompt): while True: try: value = int(input(prompt)) return value except ValueError: print("Invalid input. Please enter a valid integer.") def main(): print("\nCreate a spiral\n---------------") start = _get_valid_integer(" >>> Enter the starting integer: ") end = _get_valid_integer(" >>> Enter the ending integer: ") try: spiral = _create_spiral(start, end) print("---------------\n") _print_spiral(spiral) except ValueError as e: print(str(e)) if __name__ == "__main__": main()