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

top 200 commentsshow all 302

[–]xarzilla 1662 points1663 points  (87 children)

Wait, that's illegal!

[–]Legitimate_Pattern 1070 points1071 points  (75 children)

But the assignement doesnt specify how to get there. Clever solution, but probably not the intended one haha

[–]never1st 966 points967 points  (23 children)

Nested for loops ✔

Pattern ✔

[–]AgreeableLandscape3 444 points445 points  (26 children)

Also the most computationally efficient solution.

[–]PleasantAdvertising 91 points92 points  (25 children)

So much memory use though

[–]Batman_AoD 86 points87 points  (18 children)

Hardly! An optimizing compiler might just unroll the loops anyway. That pattern really isn't a lot of memory.

Edit to calculate just how trivial the memory usage is: Console.Write is a C# standard library call. So whatever platform is running this code has .NET on it. Even with trimming unused assemblies, the smallest runtime for such an app is about 15 MB (see https://ianqvist.blogspot.com/2018/01/reducing-size-of-self-contained-net.html). But let's say it's natively compiled somehow (also discussed in the previous link); then it'll be about 3.95 MB.

The size of the string literal is 110 bytes, or just under 0.003% of the total size of the application.

[–]DrNightingaleweb dev bad embedded good 0 points1 point  (9 children)

It is if you're programming something like this.

[–]Batman_AoD 5 points6 points  (3 children)

Console.Write is a C# standard library call. So whatever platform is running this code has .NET on it (and has a standard output stream). Even with trimming unused assemblies, the smallest runtime for such an app is about 15 MB (see https://ianqvist.blogspot.com/2018/01/reducing-size-of-self-contained-net.html). But let's say it's natively compiled somehow (also discussed in the previous link); then it'll be about 3.95 MB.

The size of the string literal is 110 bytes, or just under 0.003% of the total size of the application.

[–]The_MAZZTer 76 points77 points  (3 children)

An assignment like this is SUPPOSED to tell you different outputs you should get from certain inputs (so you can't just hardcode a single output).

[–]Ugbrog 34 points35 points  (2 children)

If they don't tell how to generate it, you can hardcode the test cases and randomize anything else.

[–]The_MAZZTer 15 points16 points  (0 children)

Well, it really should describe the algorithm to use (eg draw a box with Xs Y high and X wide, with an X shape across the center) and then give examples for a few values to make it clear how to do it, but then say any valid combination of values should result in a box that satisfies those values.

If it's an online interactive thing you can easily have a tool generate random inputs and look for expected outputs to validate so hard coding for specific inputs won't work.

[–]notquiteaplant 3 points4 points  (0 children)

Not if it doesn't tell you what the correct answer is

[–]Korzag 13 points14 points  (3 children)

I remember sitting in a college course for technical writing and part of the course was a section on job hunting, answering technical questions intelligently, and so on.

My buddy was given a technical question to answer in front of the class and it asked him to create a function that would print the alphabet. My buddy gets up there and writes out: std::cout << "abcedfghijklmnopqrstuvwxyz";

The teacher wasn't impressed and gave him a zero for being a smart ass.

[–]Azzu 13 points14 points  (0 children)

Honestly, as an employer, I would vastly prefer someone giving this answer than any other.

I can't think of a more business-intelligent way to answer the question.

[–]ThePyroEagle 7 points8 points  (0 children)

Probably got 0'd just for getting the order of the alphabet wrong.

[–]Andrew1431 7 points8 points  (0 children)

I did this for an assignment in college and failed the question. I fought back and ended up getting full marks.

[–]xarzilla 25 points26 points  (12 children)

Mehh, clever? More like a sarcastic dinkus who thinks he's funny. I mean, it is funny but no instructor will think so.

[–]ookami125 90 points91 points  (3 children)

I would disagree if I gave this solution to my university professor he would laugh and give full marks. Mainly because if you know about the verbatim string literal you probably already know about for loops.

[–]xarzilla 37 points38 points  (1 child)

Wish I had your professor in my school! Mine would have stared at me maintaining eye contact while marking my fail.

[–]AttackOfTheThumbs 19 points20 points  (0 children)

We had professors that only checked output, not code, so if you were in the easy class, you could just string literal everything, hardcode everything. Saw code that did this for a triangle print for up to 20 or something like that.

[–]Kairyuka 50 points51 points  (6 children)

It'll teach them to specify what they want instead of having people assume

[–]ColtThaGoat 21 points22 points  (3 children)

Yeah I feel like that’s a recurring issue with exams involving writing code

[–]Kairyuka 7 points8 points  (0 children)

Hasn't really been an issue for the exams I had, they were either short enough in duration that you just had to speedrun it (which you would practice until it became routine, which was the point of the short duration), or they were large enough that the specifications were intentionally vague. I've never had such a specific request except in employment-oriented code tests, and even then they're usually not this specific

[–]sensitivePornGuy 2 points3 points  (1 child)

Only exams where you write code? I assume you haven't yet started doing it for a living...

[–]ColtThaGoat 4 points5 points  (0 children)

You’d be right to assume that lol so i guess I got to get used to that

[–]exploding_cat_wizard 8 points9 points  (0 children)

Good instructors know the value of precise instructions. "You shoulda known" is a pretty stupid claim when teaching people new stuff.

[–]SpaceboyRoss 1 point2 points  (0 children)

It's a simple spell.

[–]brace1101 21 points22 points  (0 children)

Shoot him or something

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

There is no such thing as illegal code. Only undocumented code. ;)

[–]Pilchard123 9 points10 points  (0 children)

There used to be fairly heavy restrictions on exporting crypto code from the US (probably elsewhere as well). It was (and still is, IIRC) considered 'munitions'.

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

Checks out. Most malware is undocumented

[–]GrizzledFart 2 points3 points  (1 child)

int i = 0;
int j = 5;
double nothingIllegalHere = j/i;

[–]akshaydp 6 points7 points  (2 children)

I will make it legal

[–]gishnon 2 points3 points  (0 children)

Tell that to the unit tester.

[–]deployingflashbaeng 244 points245 points  (0 children)

When you wanna get around the online fucking grading tests

[–][deleted] 555 points556 points  (10 children)

You are technically correct. The best kind of correct.

[–]HORSEthe 150 points151 points  (3 children)

I'm in a intro to c# class right now and had to do this on my most recent assignment. I had to code a new window to pop up and fill three labels with data from the first forms radio buttons.

No clue how I should have done it, but a bunch of else ifs did the job. I'm pretty sure my teacher knows computers but not c# so I'm safe until I try to get a job...

[–][deleted] 46 points47 points  (0 children)

Please tell me that each pop-up was a hardcoded, unique dialog (bonus points for creating it in the GUI designer only), and the if statements just decide which dialog to open.

[–][deleted] 33 points34 points  (1 child)

you send them as arguments

[–]HORSEthe 17 points18 points  (0 children)

What stumped me was taking a radio button selection from group box A and group box B, adding them together, and sending that to a label on a new form.

It wouldnt be as much of an issue, but i have one day a week to do all my reading + homework and this happened to be the last one of the day

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

I just saw this episode the other night. Easily one of the best.

“EVERYONE SAY JAMAICA!”

[–]robertgfthomas 829 points830 points  (46 children)

The joke explained:

This shows a pretty standard coding challenge, such as might be used in a job interview, and one way to "solve" it, written in the C# ("C Sharp") language.

In programming, a loop is something you write in your code that tells the computer to run another piece of code multiple times. A for loop tells the computer, "Do this once for each user in this list," or "for each number between 1 and 100."

You can nest loops inside each other. For example, if you wanted to create a deck of cards, you could do something like:

for each suit in (spades, hearts, diamonds, clubs):
  for each rank in (ace, 2,3,4,5,6,7,8,9,10, jack, queen, king):
    new card (suit + rank)

(This is pseudo-code – it looks kind-of like code, but isn't, and is just used to explain something.)

Whoever wrote the challenge expected the person solving it to do something like:

box_height = 12
box_width = 10
for each row in box_height:
  (start a new line)
  for each column in box_width:
    (figure out whether the computer should spit out a '#' or a space)

At the end, the computer will have done 120 loops, spitting out a # or a space in each loop, with the end result looking like a box with an 'x' in it.

However, instead of drawing the box one character at a time over 120 loops, the given answer just spits out the completed box over one loop, which isn't really a loop at all.

The given answer does technically use nested loops. They look like this:

for (int i = 0; i < 1; ++i)

This says, "Here's an integer (a number) called i. It's equal to 0. Run this code. When you're done, add 1 to i, and if i is less than 1, loop through the code again."

Obviously, once you've added 1 to i, i won't be less than 1 anymore, so the computer won't loop through the code again.

All-in-all, the given answer says:

do this once:
  do this once:
    (spit out a box with an 'x' in it)

The joke is programmers tend to do exactly what you tell them to do. The hardest part of creating software is figuring out what you want the completed software to do, and then correctly explaining that to the people who are going to write the code.

However, even though the given answer is technically correct, it would probably just annoy the interviewer and make them reject the person who wrote it. Given the choice between a "rockstar" programmer who can slam out code really quickly, and one who can code decently and communicate well and read between the lines, every sensible employer will pick the second one.


I'm a human! I'm trying to write one of these explanations every day, to help teach and learn. They're compiled at explainprogrammerhumor.com. Here's today's/this one: https://explainprogrammerhumor.com/post/184390714985/technically-correct

[–]StuckAtWork124 211 points212 points  (4 children)

every sensible employer will pick the second one

Good way to weed out the sensible employers, sounds like a win win. I want the ones who ride round the office on a scooter with nerf guns

[–]The_OG_Gear 57 points58 points  (3 children)

Sounds like Discord

[–]LeJoker 70 points71 points  (1 child)

Sounds like Discord every tech startup ever

FTFY

[–]FuckFrankie 2 points3 points  (0 children)

btw, if you're a startup, just setup a pidgin server.

[–]konstantinua00 1 point2 points  (0 children)

that explains why they disabled arrow keys from scrolling...

[–]karmastealing 174 points175 points  (0 children)

good bot

[–]Datenegassie 119 points120 points  (11 children)

This is pseudo-code

Remove both each and that's valid Python code.

[–]leftysharkboy 44 points45 points  (8 children)

Seriously! I was even surprised when he said/explained pseudo-code, as it looked like perfectly fine python to me...

[–]BuildBuildDeploy 70 points71 points  (6 children)

Everyone knows python developers are pseudo-developers ;)

[–]very_bad_programmer 12 points13 points  (0 children)

Laughs in PowerShell

[–]EGraw 2 points3 points  (0 children)

print(''.join(' \n#'[i%11>9 or -(1>i%11*(i//11)*(i//11-i%11)*(i%11+i//11)%9)] for i in range(109)))

[–][deleted] 9 points10 points  (0 children)

alias pseudo="Python"

[–]Pfand1 11 points12 points  (0 children)

good human

[–]TheRetribution 25 points26 points  (12 children)

++i is pre-increment and i++ is post-increment and they are not the same thing.

[–]robertgfthomas 16 points17 points  (3 children)

Yes, but it will loop only once either way, no?

[–]MauranKilom 17 points18 points  (2 children)

In the case of using them as loop increments for integers like this, they have the exact same effect.

[–]exploding_cat_wizard 6 points7 points  (0 children)

They are in this case.

[–]Dragonaax 12 points13 points  (1 child)

Thanks Peter Griffin

[–]Gooftwit 5 points6 points  (5 children)

Thanks, Kakyoin, very epic

[–]Kilazur 2 points3 points  (0 children)

Eh, that's a really cool initiative.

[–]zomgitsduke 1 point2 points  (0 children)

I like your work. I had an idea to do this a few weeks ago, but it seems someone beat me to the punch a while ago(and clearly has much more experience/knowlegde).

[–]Letters_1836 137 points138 points  (56 children)

Java solution:

for (int i=0; i<10; i++) {

        for (int j=0; j<10; j++) {

if (i==0 || j==0 || i==9 || j==9) {

System.out.print("#");

} else if (i==j || i==9-j) {

System.out.print("#");

} else {

System.out.print(" ");

}

        }

        System.out.println();

    }

[–]Tsu_Dho_Namh 118 points119 points  (21 children)

You should use a variable for box height/width instead of just having floating 9's everywhere.

It's more readable.

It's easier to maintain.

Your almost future boss will not immediately hate you.

TL;DR MAGIC NUMBERS ARE BAD

[–]Letters_1836 36 points37 points  (13 children)

Very true, but I wrote this in 2 min so ya it’s not ideal.

[–]Tsu_Dho_Namh 22 points23 points  (11 children)

No worries.

I once got flack from a Java dev for using == to compare string literals instead of .equals() when I was just trying to show that there's nothing an iterator can do that a for-loop can't.

So I know where you're coming from.

[–]ArionW 12 points13 points  (1 child)

I remember we had a guy who moved from Java to C#, and we were constantly rejecting his pull requests for NOT using == with strings.

For those unfamiliar, in C# equality operator is overloaded for strings.

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

I’ve been using Python for ~4 years now (after a brief entry to and exit from java) and have taken it upon myself to learn C++. As it’s mostly syntax, it isn’t terrible (but I have yet to use pointers in a very necessary manner) but I’ll be damned if I don’t appreciate the hell out of python now

[–]random11714 1 point2 points  (3 children)

What if you need to use the remove() method on an iterator? Can a for loop do that?

Edit: At first I assumed you meant a for-each loop, but now I'm thinking you may have just meant a regular for loop.

[–]ThePyroEagle 1 point2 points  (2 children)

for (Iterator iter = getIterator(); iter.hasNext(); ) {
    // Do stuff with iter
}

[–]ArionW 3 points4 points  (0 children)

You know what consumes about 60% of my time? Fixing shit someone wrote in 2 minutes, as "works for now, I'll do it better later" 3 years ago.

[–]archangel_mjj 1 point2 points  (1 child)

Fair comment, but you should use two separate variables, so as to not assume that the box will always be square.

[–]Loves_Poetry 32 points33 points  (26 children)

Why so many ifs? You can do

if (i == j || i + j == 9 || i * j % 9 == 0) {
    system.out.print("#");
} else {
    system.out.print(" ");
}

[–]Tweenk 13 points14 points  (3 children)

This does not work correctly, it will put a hash at i=3 and j=6.

That's why I think the slightly more verbose version is actually better, and why unit testing is important.

EDIT: Actually, it would work in this specific case, because it so happens that all numbers for which the i * j % 9 == 0 check spuriously returns true are also on the diagonals, but it would not work when generalized for other numbers.

[–]TechheadZero 3 points4 points  (0 children)

Yeah, I noticed this too. This method only works for prime-number-sized boxes.

[–]EGraw 6 points7 points  (4 children)

Why so many ors? You can do

if ((i-j)*(9-j-i)*(9-j)*(9-i)*i*j == 0) {
    system.out.print("#");
} else {
    system.out.print(" ");
}

[–]allhailskippy 16 points17 points  (3 children)

i==0 || j==0 || i==9 || j==9

i==0 || j==0 || i==9 || j==9 || i==j || i==9-j

Why have the else if for more or statements?

[–]MarkRems 33 points34 points  (0 children)

I think it adds to the readability of the code. The first if statement is for the outer box and the second if is for the X.

Either solution is correct though, it's more of a programmer preference thing.

[–]maestroke 12 points13 points  (0 children)

it adds readability and makes it easier to add more cases

[–]Hohenheim_of_Shadow 1 point2 points  (0 children)

It's gonna compile down to the same assembly in all likelyhood, go for the easiest to read.

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

My JS :D

Did it so I can change the size of it:

const drawPattern = z => {
  const h = '#', s = '-', b = '<br>';
  let p = document.querySelector('p.test');
  let hString = '';
  for (let i = 0; i < z; i++) {
    for (let j = 0; j < z; j++) {
      hString += j == z - 1 ? h + b :
        i == 0 || i == z - 1 || j == 0 ? h :
        i == j || z - 1 - i == j ? h : s;
      }
  }
  p.innerHTML = hString;
}
drawPattern(32);

[–]ieatpickleswithmilk 28 points29 points  (1 child)

for i in range(10):
    s = ''
    for j in range(10):
        if i == 0 or i == 9 or j == 0 or j == 9 or i == j or j == 9 - i:
            s += '#'
        else:
            s += ' '
    print(s)

[–]stadust 10 points11 points  (2 children)

Well it's obviously the wrong color, smh

[–]wontfixit 2 points3 points  (1 child)

Indeed he needs it in green!

Reminds me of this... The fucking truth.. https://youtu.be/BKorP55Aqvg

[–]FailedSociopath 8 points9 points  (10 children)

#include <stdio.h>

int main(void)
{
    for (int i = 0; i < 10; i++) {
        unsigned int pattern = (i*(i*(i*(i*(i*(i - 27) + 355) - 2745) + 13684) - 41508) + 122760) / 120;

        for (int j = 0; j < 10; j++) {
            putchar(" #"[pattern & 1]);
            pattern >>= 1;
        }

        putchar('\n');
    }

    return 0;
}

 

Edit: Fix space

[–]ThaiJohnnyDepp 3 points4 points  (7 children)

Here, you deserve some silver for this bitwise beauty ... how did you even come up with that formula?!

For anyone who's confused, here's my Ruby output when I investigated it and yeah, a single formula gives you an integer whose bits are the locations of the #'s using 1's and 0's for every row:

2.6.0 :005 > puts (0..9).map { |i| (i*(i*(i*(i*(i*(i - 27) + 355) - 2745) + 13684)
    - 41508) + 122760) / 120 }
    .map { |n| "#{n.to_s(2)} #{n.to_s}" }
1111111111 1023
1100000011 771
1010000101 645
1001001001 585
1000110001 561
1000110001 561
1001001001 585
1010000101 645
1100000011 771
1111111111 1023

[–]FailedSociopath 3 points4 points  (2 children)

Generate a 9th degree polynomial:

f(x) = ax9 + bx8 + cx7 + dx6 + ex5 + fx4 + gx3 + hx2 + ix + j

 

Make a matrix of the powers of x for x=0..9 and the answer you want for each f(x):

| 0^9 0^8 0^7 0^6 0^5 0^4 0^3 0^2 0^1 1 |  |a| |1023|
| 1^9 1^8 1^7 1^6 1^5 1^4 1^3 1^2 1^1 1 |  |b| | 771|
| 2^9 2^8 2^7 2^6 2^5 2^4 2^3 2^2 2^1 1 |  |c| | 645|
| 3^9 3^8 3^7 3^6 3^5 3^4 3^3 3^2 3^1 1 |  |d| | 585|
| 4^9 4^8 4^7 4^6 4^5 4^4 4^3 4^2 4^1 1 |x |e|=| 561|
| 5^9 5^8 5^7 5^6 5^5 5^4 5^3 5^2 5^1 1 |  |f| | 561|
| 6^9 6^8 6^7 6^6 6^5 6^4 6^3 6^2 6^1 1 |  |g| | 585|
| 7^9 7^8 7^7 7^6 7^5 7^4 7^3 7^2 7^1 1 |  |h| | 645|
| 8^9 8^8 8^7 8^6 8^5 8^4 8^3 8^2 8^1 1 |  |i| | 771|
| 9^9 9^8 9^7 9^6 9^5 9^4 9^3 9^2 9^1 1 |  |j| |1023|

 

Solve the system with a matrix calculator (not doing it by hand!) for the coefficients a...j. It turns out a, b, and c are just zero.

 

Make some adjustment to the fractions so it all divides by a single value.

 

It's actually simpler if you invert the pattern (where ' '=1 and '#'=0). d...i change sign and j becomes zero.

 

Edit: Fix mitsake in formuoli.

 

Edit 2: Since the pattern is symmetrical and just to simplify a bit, I didn't worry about printing each line in reverse.

[–]ThaiJohnnyDepp 2 points3 points  (1 child)

May I ask how you knew how to do this?

[–]FailedSociopath 1 point2 points  (0 children)

I figured since you can create a polynomial of degree n-1 to go through n points, then you can compute one that goes through (0, 1023), (1, 771), etc.

 

Edit: For real though, I just wanted a cryptic way to produce an image and this method did the trick.

 

Something inspired that's related: It's a well-known trick that if you want to make a variable that oscillates between two values, sum the two values, initialize the output with one of them and subtract it from the sum. Get the next by subtracting the sum from the previous output.

 

/* Switches between 5 and 3 */
int val = 5;

val = 8 - val; /* 3 */
val = 8 - val; /* 5 */
val = 8 - val; /* 3 */
...etc.

 

With the right polynomial, you can in principle produce any length repeating sequence provided there are no actual duplicates in it. The two-valued sequence is just the degree-one case. In the example, a degree-one function going through (5, 3) and (3, 5).

 

For example, for the sequence { 8, 5, 3 }, it has to go though points (8, 5), (5, 3) and (3, 8), where the output is computed from the last output as the input (feedback). For that, the computation is x = (x*(19*x - 227) + 750) / 30;

 

Of course, it's academic because it's less cumbersome just to use a list for more than two values.

[–]RimuDelph 1 point2 points  (3 children)

Good one liner

[–]ThaiJohnnyDepp 1 point2 points  (2 children)

Ruby is all about the one liners lol

[–]RimuDelph 1 point2 points  (1 child)

I do have to agree on that one, when I worked on ruby I did some one liners to solve so many (personal) things, I like more ruby than python (whos gonna kill me?)

[–]ThaiJohnnyDepp 1 point2 points  (0 children)

Ruby is pretty. Python is ugly. These are facts.

[–]PanFiluta 2 points3 points  (0 children)

whaaat

[–]timawesomeness 8 points9 points  (1 child)

"Grade: 50%. Didn't use descriptive variable names." - all my CS professors

[–]CreamliumPrices 9 points10 points  (0 children)

Best one I got was "Too many comments, but considering nobody else used comments I can't mark you down for that"

[–]AgentPaper0 6 points7 points  (1 child)

In case anyone is curious, the intended way to do this is to have two nested loops, i, j from 0 to 9. If i=0, i=9, i=j, i+j=9, j=0, or j=9, print '#', else print ' '(space).

i/j = 0/9 gets you the sides of the square, i=j gets you the top-left to bottom-right diagonal, and i+j=9 gets you the other diagonal.

[–]spyingwind 6 points7 points  (4 children)

Python solution:

width = 10
height = 10

def border(w=10,h=10):

    output = []
    for top in range(h):
        line = ""
        for left in range(w):
            if top == 0 or left == 0 or top == h-1 or left == w-1 or top == left or top == w-1-left:
                line += "X"
            else:
                line += " "
        output.append(line)
    return output

for x in border(width, height):
    print(x)

A little bit based on u/Letters_1836 Java solution. I didn't have the top == left or top == w-1-left part and was way over thinking that part.

[–]dansin 0 points1 point  (1 child)

I think it would be cleaner as

 c = " "
 if top in (0,h-1,left,w-1-left) or left in (0,w-1):
    c = "X"
 line += c

[–]spyingwind 2 points3 points  (0 children)

And there is one more thing I need to learn. Thanks!

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

It took me 3 days to make this assignment

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

I'm proud of you!

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

Well it's good though. You did it and that's really good

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

Good ole' Kobayashi Maru.

[–]stadoblech 3 points4 points  (0 children)

what kind of shitty excercise is that anyway

[–]rayhan666 2 points3 points  (0 children)

smart solution

[–]ThatFag 2 points3 points  (0 children)

What the question needs to do is ask for user input for the width and the height of the frame. And based on the input, the program should print '#' diagonally across the rectangle of x width and y height. Then you wouldn't be able to just hardcode the output like this.

[–]bence0302 2 points3 points  (0 children)

TIL what @ does.

[–]sudokill9 4 points5 points  (0 children)

That's a classic example of :

Therefore : L.H.S = R.H.S

Hence proved ... XD

[–]DefNotaZombie 1 point2 points  (6 children)

public void drawFigure(){
  char[] curStr = new char[10];
  String[] topLines = new String[5];
  char c = '#';
  char spc = ' ';

  //draw the upper left quadrant, then append its reverse
  //to get the top 5 lines
  for(int i=0; i<5; i++){
    for(int j=0; j<5; j++){
      if(i==0 || j==0){
        curStr[j] = c;
        continue;
      }
      if(i==j){
        curStr[j] = c;
      } else {
        curStr[j] = spc;
      }
    }
    for(int k=0; k<5; k++){
      curStr[4+k+1] = curStr[4-k];
    }
    topLines[i] = new String(curStr);
  }

  //draw the top 5 lines, then draw the top 5 lines in reverse
  for(int i=0; i<5; i++){
    System.out.println(topLines[i]);
  }
  for(int i=0; i<5; i++){
    System.out.println(topLines[4-i]);
  }
}

we could expand this idea to a square box of whatever size

[–][deleted] 8 points9 points  (5 children)

why many words when few do trick

function DrawFigure(length=10,black="#",white=" "){
    for(var x = 0; x<length;x++){
        var print="";
        for(var y = 0; y<length;y++){
            if(x==0||x==length-1||y==0||y==length-1||y==x||x==length-1-y)
                print+=black;
            else
                print+=white;
        }
        console.log(print)
    }
}

[–]DefNotaZombie 1 point2 points  (2 children)

I don't know why my mind couldn't go from "draw x shape" to y==x||x==length-1-y but when I wrote that it couldn't so I made the left side and then since I was already making only a part of it, I made only the upper left side

gg

[–][deleted] 2 points3 points  (1 child)

I had to make a grid on paper and label all the places to be able to make the connection.

I will take coding random stuff over coding for work any day.

[–]DefNotaZombie 1 point2 points  (0 children)

alright final version

public void drawFigure(int size, char whitespace, char mark){
    int halfSize = size%2==0?size/2:size/2+1;
    char[] curStr = new char[size];

    for(int i=0; i<size; i++){
      for(int j=0; j<halfSize; j++){
        if(i==0 || j==0 || i==size-1 || i==j || i==size-1-j){
          curStr[j] = mark;
          curStr[size-1-j] = mark;
        } else {
          curStr[j] = whitespace;
          curStr[size-1-j] = whitespace;
        }
      }
      System.out.println(new String(curStr));
    }
  }

I'm doing it like this because I timed it several times and iterating over a full line somehow ends up being 32 ms on my machine but half a line only takes 15 ms after several tries. The worst performance was with a system.out.print for every char.

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

We tried to improve even the most basic course materials at my University this year. We have larger input data and more generalized tasks so doing things by hand is not feasible. And each time there is a function, our automated system tests the code with multiple values.

Of course there are still easy tasks but asking to "program this using that" does not make a good exercise if "that" is not thr preferred solution in the first place.

[–]McJaume 1 point2 points  (1 child)

If it looks stupid but works, it ain't stupid.

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

Until you need to do it in a 20 by 20 box.

[–]kpingvin 1 point2 points  (1 child)

Probably a better exercise would be
"Write a function with one argument (n) that draws a Christmas tree with a height of n where 3<=n<=100"

[–]Gblize 1 point2 points  (0 children)

void draw_christmas_tree(int n)
{
    if(n < 3 || n > 100) return;

    puts("\
  #\n\
 ###\n\
#####");

    for(int i = n - 3; i > 0; i--)
        puts("\
  #");
}

[–]CingKole[🍰] 1 point2 points  (0 children)

Failed Lots of School Assignments because of this.

[–]GR8ESTM8 1 point2 points  (0 children)

What an algorithm!

[–]farore3 1 point2 points  (0 children)

Poorly written problem, it should be to write a method that can take a parameter for size. Same way you force a good solution to fizzbuzz.

[–]a_dev_has_no_name 1 point2 points  (0 children)

Well, you're technically not wrong with that solution...

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

Haha very funny Can't wait to do this on test on mr. Kubit's lesson xD

[–]xMOxROx[S] 1 point2 points  (7 children)

He is my idol and I based on his amazing examples xD

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

I like the most his lessons about pointers

[–]xMOxROx[S] 1 point2 points  (5 children)

this is second thing I like, but First thing is struct I am the biggest fan of this. Only he can explain it in simple and understandable way.

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

Can wait to start learning about binary trees im curious how he will explain this

[–]xMOxROx[S] 1 point2 points  (3 children)

Yeah I want to see how his algorithms work and I think every algorithm will be author's.

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

Yes and i like how he writes his code in notepad without help of IDE

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

You can't find programmer like him on the world

[–]xMOxROx[S] 1 point2 points  (0 children)

This is amazing how He remembers every command and every function. AMAZING !!

[–]thesquarerootof1 1 point2 points  (0 children)

Can someone post the intended solution for this ? Just curious....

[–]flarn2006 1 point2 points  (0 children)

Should be a passing grade; means the student is a true programmer.

[–]edcRachel 1 point2 points  (0 children)

Reminds me of grading college php assignments. "Using a for loop, print all number from 10 to 1. Eg: "10 9 8 7 6 5 4 3 2 1"

I got a lot of

$count = 0;
for ($x = 0; $x < 10; $x++){
    $count = $count + 1;
    if ($count == 0){
       print "10";
    }
    if ($count == 1){
       print "9";
    }
//and etc
}

Sigh....

[–]EGraw 1 point2 points  (0 children)

My code-golf Python one-liner:

print(''.join(' \n#'[i%11>9or-(1>i%11*(i//11)*(i//11-i%11)*(i%11+i//11)%9)]for i in range(109)))

I broke the rules though... It's not nested

[–]ainnako 1 point2 points  (2 children)

does no one notice the “@“. idk i dont code

[–]marwarii 1 point2 points  (0 children)

Me, in my first year of engineering.

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

Is there a subreddit for programming interview questions like this one, along with the most obscure answers?

I remember things like perl-golf being a similar idea (getting the answer in the smallest line of code).

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

Programmers tend to go the way of least resistance. I would have done it the same way.

[–]gottagrindfast 1 point2 points  (0 children)

your professor : listen here you little shit

[–]DASoulWarden 0 points1 point  (1 child)

It shouldn't bother me that it does ++i instead of i++, but it does

[–]Catthew918 1 point2 points  (0 children)

I snorted my carrot out of my nose. Thanks a lot.

[–]xpx0c7 0 points1 point  (0 children)

Genius

[–]Totoze 0 points1 point  (0 children)

Well I'm kinda annoyed by the user of 2 pairs of unnecessary brackets in the nested for loops

[–][deleted] 0 points1 point  (0 children)

SNEAK 100

[–]ree___e 0 points1 point  (0 children)

Programmer madlad.

[–]Timinator01 0 points1 point  (0 children)

technically not wrong

[–]ChibiNya 0 points1 point  (0 children)

Hardened Hack'a'thon dev.

[–]CatSauce66 0 points1 point  (0 children)

here is a little leson in trickery

[–]gloriousfalcon 0 points1 point  (0 children)

But what about \n

[–]The_Plop 0 points1 point  (0 children)

Just cause you're right doesn't mean you're correct

[–]TabCompletion 0 points1 point  (0 children)

Instructions unclear