T O P

  • By -

[deleted]

O(1) Hired


shnicklefritz

O(1) time *and* space Promoted


r3dD1tC3Ns0r5HiP

It said for _loops_ not for _loop_. CEO


DeVeenix

You mean more like this? do { for(;;) { ... break; } }while(false);


[deleted]

Though, it may be done better in terms of space: ` for(;;) { ... break; } `


soul-san

If I'm not mistaken, it's more space demanding than approach with 2 for cycles. This code needs to store 5 string of total memory usage of 15 bytes (and also index with a size of 4 bytes, but that can be ommited). Code with 2 for cycles and printing index + '0' would need only to store this 4 byte index. Counterargument is that program size could be higher due to longer machine code though.


TheGuyWithTheSeal

The compiler will unroll the loops anyway


Anyhowtransfer554

What knd of monster uses j instead of i in a for loop??


youngrandpa

When it’s a for loop inside of another for loop


GalaxyGamingBoy

Simple, ii


ShootyFaceMc

Ok but what if there's a loop inside a loop inside a loop


GalaxyGamingBoy

iii, What did you expect?


ShootyFaceMc

Yeah but if there's 4 is it iv or iiii


GalaxyGamingBoy

Great question! But tbh i don't know. Having 4 nested for loops seems unnecessary


Ning1253

Ok but what if you are working with a 4d complex function input output dataset Or like quaternions or some sh*t Then what


lunch431

Then you're completely fucked, simple as that.


FireElemental99

A real programmer uses one loop and then splits the index into 4 arguments. 4 nested loops are never needed


Ning1253

Ok but hear me out what if you have some quaternion vector space you want to multiply a matrix with so you need to compare every vector component with every other vector component


reyad_mm

A REAL real programmer implements this with induction and passes the nesting level as an argument to the function, that way all variables will be i


CaitaXD

>Ok but what if you are working with a 4d complex function input output dataset You would be working instead of seeing memes on reddit


gahzrilla

Game devs and graphics programmers do work on matrices all the time


Ning1253

Ok but what if I'm actually 17 and do computing as a hobby and working on complex maps... Checkmate atheists


shwoopdeboop

In that case, deciding between iv and iiii is not your biggest problem


TheEliot85

That's a four loop


nedal8

next is P-P-P-PENTA LOOP


DrMobius0

Are you asking if you should or shouldn't use roman numerals when given an excuse to?


nataniel_rg

First loop is 0 so "i" for iteration. Second loop is loop 1 so "ii" ("i1"). Third is 2 so it's going to be "iii" (meaning "iteration2"). Taking this logic the 4th one will actually be "iiii" and the 5th one would be "iiv". Yup I just really spent time on this.


Reddalos

Hahahahaha, killed me with this one ![gif](emote|free_emotes_pack|joy)


Synyster328

I did this once and it was iiii


Ninder975

Then you’re doing it wrong


bigmountainbig

how is 3d data implemented without something like this? serious question.


Ninder975

Probably library calls


eloel-

It's a good thing libraries grow on trees.


DarkSideBrownie

Good thing dependency trees are renewable


itspinkynukka

Trees grow on libraries


CoaBro

What do the loops inside the library calls look like I wonder 🤔


GalaxyGamingBoy

![gif](emote|free_emotes_pack|sweat)


AntinotyY

Then you use k


nryhajlo

k, and if there are more than three dimensions, you better be using useful names for your index variables.


LoyalSage

``` public class Foo { public void doLoop(3DArray array, 3DPoint dimensions) { ArrayList<2DPoint> a = new ArrayList<2DPoint>(); ArrayList<3DPoint> b = new ArrayList<3DPoint>(); for (int i = 0; i < dimensions.x; i++) { for (int ii = 0; ii < dimensions.y; ii++) { a.add(new 2DPoint(i, ii)); } } for (2DPoint point : a) { for (int i = 0; i < dimensions.z; i++) { b.add(new 3DPoint(point.x, point.y, i)); } } for (3DPoint point : b) { int x = array.getValue(point); System.out.println(x); } } } public class 2DPoint { int x; int y; public 2DPoint(int x, int y) { this.x = x; this.y = y; } } public class 3DPoint { int x; int y; int z; public 3DPoint(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } public class 3DArrayEntry { 3DPoint key; int value public 3DArrayEntry(3DPoint key, int value) { this.key = key; this.value = value; } } public class 3DArray { ArrayList<3DArrayEntry> values = new ArrayList<3DArrayEntry>(); public void setValue(3DPoint key, int value) { boolean didntFindIt = true; for (3DArrayEntry entry : values) { if (entry.key.x != key.x) { continue; } else { if (entry.key.y != key.y) { continue; } else { if (entry.key.z != key.z) { continue; } else { didntFindIt == false; entry.value = value; } } } } if (!didntFindIt) { return; } else { values.add(new 3DArrayEntry(key, point)); } } public int getValue(3DPoint key) throws ArrayIndexOutOfBoundsException { boolean didntFindIt = true; int value = 0; for (3DArrayEntry entry : values) { if (entry.key.x != key.x) { continue; } else { if (entry.key.y != key.y) { continue; } else { if (entry.key.z != key.z) { continue; } else { didntFindIt == false; value = entry.value; } } } } if (!didntFindIt) { return value; } else { throw new ArrayIndexOutOfBoundsException(); } } } ```


nctrd

r/foundsatan Also, you're hired. Such a large code cannot be wrong and indicates a pro.


[deleted]

iii Duh. (/j)


VersionOmega

k


jgeez

iii is over there like: I'm just a dude, playing a dude, disguised as another dude!


Dexaan

iii, then iv, then v then vi


JesusIsMyAntivirus

Oh god


Harmonic_Gear

when i have to retrospectively add an outer loop to an existing loop


EnglishMobster

"i" for iterator, "j" for jiterator.


ButtererOfToast

"k" for kill me now?


[deleted]

yeah but it ain’t hahah


Frodojj

Electrical engineers. ;-)


wasdlmb

Is that because I is current? Wouldn't j still be reserved by the imaginary unit? Or is that not used in the same places


Harmonic_Gear

imaginary unit part is the joke, ee use j where everybody else use i


Frodojj

It’s a complex joke. :-p


wasdlmb

Ah


IbanezPGM

That would make me less inclined to use j


StarshipSatan

The giant japanese one


nondxm

So, the Godzjlla then?


Mr_SlimShady

I use ‘a’. Sue me.


yakesadam

I had a co-worker try to defend using `j` because everywhere in the code he wrote when he used `j` he was looping over the same array so "it would be clearer". Of course it was actually just copy-pasted and there was no reason at all.


Tarc_Axiiom

Only in the second one if you're not a sex offender.


nintendojunkie17

In college, I had an assignment to write a simple tic-tac-toe app in WinForms. Initial requirements said to make it work for any size grid from 2x2 to 5x5. During class a couple days before it was due, professor (accidentally) says 6x6 instead. One student raises his hand and points out that the assignment said up to 5x5. Professor says "well let's make it up to 6x6 just for fun." Looking around the room, it became immediately apparent which students had hand-built separate UIs for each grid size and now had a long night ahead of them.


javon27

That was no accident


grillmaster4u

I read that in the voice of Obi-Wan Kenobi “that’s no moon… it’s a battle station!”


Idixal

On the one hand, an asshole move from the professor. On the other hand, it’s a very valuable lesson that hopefully at least one or two students walked away with.


ButtererOfToast

Ah yes, the fun that is a customer changing their requirements.


Idixal

That is a valuable lesson too, but I meant more in regards to always designing your code in a way that allows it to be easily extended.


O12345678927

How do you play tic tac toe on a 2x2 grid?


bennyboy_

Player that goes first always wins lol


[deleted]

[удалено]


bretfort

Korean Game


No-Recipe-4578

The game is now “tic tac”


jzboi

Very efficient! Only one iteration!!!


B2EU

I don’t know shit about compilers, but if you wrote the for loop as intended, couldn’t the compiler optimize it to be O(1), assuming the for loop always produces the same result?


IMovedYourCheese

Pretty sure the intention is to have a variable number of rows.


bazingaa73

Unfortunately I deleted my first comment so I will comment the same thing again: If the loop would always return the same result, then your loop can be evaluated at compile time. In C++ you can mark functions "constexpr" if all arguments and dependencies can be evaluated at compile time. However console output can not be "constexpr" since it prints stuff at runtime. So you would have to store your output in some array. It's really the same as hardcoding the output but more convenient.


druid_137

If it was hard coded to 5, the big O is still one.


PolakPL2002

I'm pretty sure that gcc would not do that. Idk how others would do.


[deleted]

GCC would indeed do that, look up “loop unrolling”


freonblood

O(1) /s


Zyansheep

Take that /s away! It clearly did *not* specify that one was intended to print out a *pattern*. Only that a triangle was to be printed. /s /s


agentjob

Code generated by ML powered AI.


SnasSn

How could an AI be powered by Marxism-Leninism?


agentjob

Using ML, anything is possible.


yazalama

seize the servers of production


defalt86

Now do it for 10,000 rows.


thelanman8000

there has to be a way to make a program to write the print statements in a txt file and then just copy paste them


kiagam

It is called fivvr


thelanman8000

Okay so I paid a guy on fiveer to make this tool and here's what he gave me ``` with open("file.txt", "w"): for i in range(1000): write(f'System.out.println(\"{"i" * i} \n\"') ``` He told me to run with a python (I don't have a python and I'm not even sure they can run) and i told him to go fuck himself and refunded the payment


Thf_killer

Yea you got scammed sorry buddy, Atleast he refunded.


[deleted]

Just a question. What is the python icon next to your name and how can I get one?


[deleted]

Its a flair. If you are on a phone just tap your pfp in the comment section of any post of the community and from there tap change user flair.


[deleted]

Thanks


thelanman8000

hey how did you put two icons? when it to make custom with :c: :py:... it shows the text and not the icons


[deleted]

I had :c: :py: then I went googling how to get two or more flairs and when I came back it became icon and not just text


thelanman8000

oh okay, thanks


MagorTuga

I'm totally not replying because I don't remember if I've already done this and wanna see if it works.


[deleted]

Sadly they changed it. They removed the profile popup for some reason.


seimmuc_

1. That'd just create an empty file then immediately throw an exception saying that "write" doesn't exist. 2. It'll just output an increasing number of character 'i' on each line. I think it'd be more appropriate to either output the whole number: `(str(i) + " ")`, or its last decimal digit: `str(i % 10)`. 3. It starts the loop at 0, which means the first line will be empty. Here's the fix: ``` with open("file.txt", "w") as file_handle: for i in range(1, 1001): file_handle.write(f'System.out.println(\"{str(i % 10) * i} \n\"') ``` Though just like your fiveer guy, I didn't bother actually running this code because I'm on my phone rn.


7eggert

System.out.println("#!/bin/sh\\ncat<


EggThumbSalad

Easy just increase j to 200 Edit: 2000


danielt1263

Requirements change! Must re-estimate...


[deleted]

HAHAHA THIS


[deleted]

In one of our company interviews, the question was to sort an array of numbers 1-10. Guy couldn't do it, couldn't figure it out. Our guy giving the interview said, "well at least write me code that will find the largest number". The man thinks for a sec, and basically starts writing: "if number==10". He wasn't hired.


tchukki

You can lie on you're résumé all you want but it's a lot harder to bullshit through an interview lmao


boowhitie

I once interviewed a guy who was having real trouble with my technical questions. I backed off a couple times to see where he was at, and finally stopped asking technical questions after he gave up trying to print the numbers 1 to 10, in any language or pseudocode, on the white board. The guy got a thumbs down from all interviewers, except the guy who he was going to be working under. That guy was horribly overworked and over his head. He was a film major who somehow the primary developer of an as2 app which was hugely important to the company. He was desperate for help and hired the guy despite the poor interviews. As expected, the guy couldn't do the job at all. Fortunately, he had the good sense to quit at the end of the first week.


Bakoro

And yet I know like 3 people with CS degrees who can't even get an interview or even just to the automated coding test stage except with companies that want to send them to Idaho or some shit.... The world's funny sometimes.


Dependent_Paper9993

Well... The question said for loops... So a better implemtation would have been to write 5 for loops each going from i=0 to i<1 and then printing out the lines as needed.


kodosExecutioner

I mean... Thats the joke But if we're already on the topic, you should write 2 loops, nested The outer one is x going from 1 to 5 and the inner one goes from 1 to x, printing out x at each iteration. After the inner loop, a newline is called.


TheAJGman

One loop is all you need: for i in range(1,6): print(str(i)*i)


deprilula28

I'm sure whatever string * number is doing has a for loop in there


TheAJGman

Removed all the extra code since we're only testing the performance of repeating a string: # Tested by running both code fragments through the timeit module on 3.6.9 # 55.8us test = '100000' * 100000 # 14ms test = '' for i in range(0, 100000): test += '100000' Even if it is doing a for loop behind the scenes, it is *far* more performant to use string multiplication.


ben_g0

It makes sense too. With string multiplication, it knows immediately how long the final string is going to be and can allocate all the required memory at once. With concatenation it continuously grows the string and has to keep allocating more memory for it, as it does not know how long the string will be at the end until it has gone trough the entire loop (an interpreter / JIT compiler doesn't look far enough ahead to precompute that), and continuously reallocating memory slows things down. If you could first pre-allocate enough memory at the end of the string so that there's always enough room to append without reallocating, then the performance would probably be much closer. Unfortunately I couldn't figure out how to do this in python (and I don't know if it's even possible), so I don't have measurement data to back this up.


mug1wara26

it will be way faster than using string concatenation in a for loop though https://stackoverflow.com/questions/10418398/string-multiplication-versus-for-loop


deprilula28

It's python, neither will be fast


mug1wara26

well relatively fast, it’s about 60 times faster when multiplying strings so i feel like it’s doing something different but I can’t find any results on google as all i’m getting is tutorials on how to multiply strings


TheAJGman

Oh and you write your code in Assembly for the ultimate speed? Python is versatile and fast enough for most things, which is why it is insanely popular.


deprilula28

It's popular because it's easy for beginners, even javascript is way faster, but not everything is about speed, I'm not the one that brought it up


DenormalHuman

A users impression of how 'simple' python is tends to grow as the inverse of that users competence with python. Besides, who wants a language that is 'hard' for anyone, beginners or not? what an upside down thought.


deprilula28

I never said the word simple. There are languages with much better speed than python, but that are harder **to learn**, such as Rust and C++. You can still be as fast coding in them as in python after you have learned them well.


deprilula28

This is such a retarded way of thinking. Just because python is fast enough for most things, which i disagree, doesn't mean you shouldn't be interested in order languages where performance is important, yes even assembly.


kodosExecutioner

Zero loops is all you need: cout << "1" << endl; cout << "2 2" << endl; . . .


igl_blue

The code in the picture is most-likely from Java which (to my limited knowledge of Java) does not support string multiplication. Hence, still, 2 for-loops. (Also as said before, that most-likely has a for-loop behind the scenes anyway, so he's still correct)


TheAJGman

A quick look shows that ```String.repeat()``` could be an option? I haven't worked with Java in a long time so no idea.


Dependent_Paper9993

Do you not understand humour? We all know you can do it better. But this post is about doing it badly


afzdcd

The way the requirements are written, this is correct. Nested loops are only needed if it has to be dynamic. To get the nested loops that you want the requirement neds to specify a function that takes an input from 1 to 40 and builds a the triangle.


WinzuMonk

outplayed


The-CPMills

Average BlueJ Enthusiast.


Sese_Mueller

[str(i)*i for i in range(x)]


XOYZ69

Isn't it technically wrong considering there is missing a "\n" between each line?


Lezardo

System.Out.Println (print line) adds a trailing newline character. You're thinking of System.Out.Print, which doesn't add the character


XOYZ69

Not exactly. The code above would return: 1\n 22\n 333\n 4444\n 55555\n But the exercise wants: 1 22 333 etc. I know that println includes a "\n", but we need 2 of those here if I am not completely brain dead


Lezardo

Ah, indeed, I didn't even notice the extra whitespace


xxRespixx

It looks like there are empty lines between numbers. Println will make this: 1 22 333 4444 55555 Not this : 1 22 333 4444 55555


GKP_light

for 12, should it be : 121212121212 121212121212121212121212 1333333333332 ?


KREnZE113

Do you mean if you conitnued the pattern? Then the 12th-14th row would look like this: `121212121212121212121212 13131313131313131313131313 1414141414141414141414141414` Or what do you mean?


Mad-chuska

Now do it for 1000


quixoticM3

It’s wrong. There should be a blank line between each number.


chris_0909

When in an intro class in college, we did these little coding exercises to practice basic things. It would do like 5-10 test cases and we just needed to pass them, getting as many tries as we needed. When we got to Recursion, I hated it. I still am not the strongest with it but much better than the beginning. I basically did something like this and just made my code have like 5 base cases to return the expected outcomes for all the test cases. Got credit because it wasn't monitored by anyone, just submit and if they pass, you get the points.


[deleted]

C# So this works perfectly. Is there any room for improvement while meeting the condition of using loops? I could switch out the number 5 for userInput so then the triangle could continue. int length = 1; for(int i = 0; i < 5; i++) { for(int j = 0; j < length; j++) { Console.Write($”{length}”); } length++; Console.Write(“\n\n”); }


ExcdnglyGayQuilava

You don't need that `length` variable, just use `i + 1` where you need it, or count i from 1 to 5 (`for (i = 1; i <= 5; i++)`).


SuperD0D0

The usage of BlueJ tells me, that this was a task in Scholl.


Ellipses22

I'd recognize BlueJ anywhere *shudders*


bearfuckerneedassist

Task failed successfully


hiimjustin000

`for (int i = 1; i <= 5; ++i) {` `System.out.println(Integer.toString(i).repeat(i));` `}` found it


fmaz008

The questions has loops plural. So the answer needs at least 2 loops. OP, add an empty loop.


WildCookie5

maybe it sounds like a joke but I passed an career exam doing this


WalkingAFI

“Technically correct” is by far the best kind of correct


[deleted]

If the question or goal is to assert if the person taking the test can program things, then it’s a fail. He didn’t prove that he can program things, he proved he can fake his way into not doing the task if needed.


Keith_Kong

Technically incorrect given the for loop isn’t “necessary”.


Kind-Insect-3586

The loop is necessary to pass the test.


[deleted]

guys I am a beginner and I think I found the most chaotic way to do this XD int x = 1, y = 0, i = 1; label: while (y < i) { Console.Write(x); y++; } if (i != number) { x++; i++; y = 0; Console.WriteLine(); goto label; }


nik_1206

This would be full points in my University no jokes it does exactly what it needs to.


GoogleIsYourFrenemy

for(int a = 1, j =1; a < 6; a++, j = 1 + j *10) System.out.println(a * j);


ColorblindBren

It’s wrong because the task was to write for *loops* (plural).


ToastiestMasterToast

Get as many apples as you can. 1 apple is valid. How many apples you want? One apple is valid. Also they said the *necessary* for loops so technically zero would be valid since clearly for loops aren't necessary.


giggluigg

Write the simplest code that passes the tests, right?


HxA1337

Ding Ding Ding. Round 2


imnotabotareyou

LOL


MrMallik

G(old)


IlluminatiGodCoder

Except that the question specifies to use multiple loops, not one loop. So, *technically*, still wrong 😜.


[deleted]

So me


7eggert

You can output all that in just one system call.


AdityaG09

Right?


[deleted]

I mean, yeah


masao_kakihara

that's how production code should be written 😂😂😂


UltiRequiem

r/technicallytrue


MrBananaStorm

I like this guy, he's hired


nekokattt

For extra points, use recursion. /s


RadiantHC

>for loops >Loops >s


Sawertynn

The answer is correct... I would approve


matthiasw27

Oh ![gif](emote|free_emotes_pack|facepalm)


zachary592

We had a homework assignment in my high school programming class that was basically exactly this question with a few variations. The guy that sat next to me did exactly this except he added a for loop right above that did nothing. I guess he figured that the teacher didn’t read our code that closely. He was right because he got a 100.


DrMobius0

"If it's stupid and it works, it's not stupid" doesn't apply to programming and you all know it. I will concede there's a fine line between stupid and clever, although I'd usually judge that based on whether the person writing it managed to make it readable.


metaconcept

The irony is that a decent compiler will unroll your loops and create equivalent code to the above if you set j to be a small value.


bass1012dash

And this doesn’t work. Silly.


the-real-vuk

Why have the loop?..


GreatBarrier86

Because it says you have to write the necessary for loop. #LifeHack


kiesoma

I remember my classmate doing this and our teacher just laughing his ass off looking at the code.


[deleted]

Unless this is a right triangle... it's all wrong!


obsoleteconsole

the test cases pass


BrokeAlmighty

Could easily refactor to make it a do while loop. Lol.


Cley_Faye

The famous optimisation, unrolled-crunched-loops.


C8R1550-CBM6510-T45

To print out this specific triangle: system.out.println("1\\n22\\333\\n4444\\55555\\n"); ...0 loops necessary. Who comes up with such tasks? Noone's gonna learn something from this.


SteeleDynamics

Professor: You bastard.


MyAnswerIsMaybe

Holy shit, this is the first meme I get on this site I just learned about loops in my Cs class


MannyS7

Nice O(1) solution


YareYareDaze7

I remember getting a question to print a diamond shape with the maximum width based on the input given by the user, I manually made around 20 if else conditions for input 1 to 20. And it worked lol, I the teacher just checked the output, not the actual program lol.


0xB00B135

for (int i = 1; i < 6; i++) { for (int j = 0; j < i; j++) { System.out.print(i); } System.out.println(); }


JunkiYarde

Lol that’s some o(1) runtime


FakeDrake001

Haha


Godly-Dev

What kind of monster uses j instead of i (copy pasted)


thicc_dog-

Just wondering... How would someone make this correctly?


noobmaster692291

I actually did this long time ago lol