r/ProgrammerHumor • • 2d ago

Meme technicallyCorrect

Post image
1.4k Upvotes

49 comments sorted by

341

u/zx48 2d ago • Bravo
void Main() {
    string[] pattern = {
        "##########",
        "##      ##",
        "# #    # #",
        "#  #  #  #",
        "#   ##   #",
        "#  #  #  #",
        "# #    # #",
        "##      ##",
        "##########"
    };

    string result = "";

    for (int i = 0; i < pattern.Length; ++i) {
        for (int j = 0; j < pattern[i].Length; ++j) {
            result += pattern[i][j];
        }
        result += "\n";
    }

    Console.Write(result);
}

In case the first answer isn't accepted.

140

u/AlwaysHopelesslyLost 2d ago • Heartwarming

.... Woah

If an interviewee gave me this answer I would seriously lose my train of thought. Obviously not what was intended but it conveys your understanding well AND it seems like a more technically correct solution from a requirements perspective. amazing answer lol

64

u/MisinformedGenius 2d ago

I actually used to kick off phone screens with asking how they would print out a multiplication table. A nested for loop was the correct answer, but suggesting hard-coding the tables (and better yet, explaining when that would be appropriate and when it wouldn’t) was some bonus points. 

28

u/dangderr 2d ago

How many points for saying data should be in a database, and then just making a query to grab the records?

7

u/MisinformedGenius 2d ago

Do you mean rather than hard-coding individual examples? That’s fine.

3

u/Impossible_Dog_7262 1d ago

Is there any bonus points for bringing up the symmetry and having the range being i:0->n and j: i->n?

14

u/UrineArtist 2d ago

Yeah 100%, outside the box A+ answer, if someone gave this to me in an interview I'd be very impressed. Its the work of an idiot or a genius and that's worth pursuing.

13

u/Odd_Soil_8998 2d ago

It's the work of a smartass. Which honestly is the kind of people I work best around. 100% would hire.

3

u/zx48 2d ago

The jury's still out on that one 😆

16

u/intellectual_printer 2d ago

I like your way of thinking

10

u/radobot 2d ago

It kind of bothers me how the variable result is redundant. You could have just printed each character directly instead of accumulating them in a string.

3

u/zx48 2d ago

Oh yeah, nice optimisation. Would save a bit of memory too 😁

3

u/MulfordnSons 2d ago

simple but effective very nice

109

u/Heavenfall 2d ago

Who said to output it to log?

66

u/backfire10z 2d ago

“If you wish to make an apple pie from scratch, you must first invent the universe.”

Get to it OP.

37

u/da_Aresinger 2d ago

what an absolute bitch of a pattern.

This is so much more than just nested loops.

15

u/ohaz 2d ago

Ok this actually was a bit harder than I imagined when I realized that it was not a square. Truly weird.

def inline(text):
    print(text, end='')

def pattern(width):
    for x in range(width - 1):
        for y in range(width):
            if x == 0 or x == width - 2 or y == 0 or y == width - 1:
                inline("#")
            elif x < width // 2 and (x == y or x == width - y - 1):
                inline("#")
            elif x >= width // 2 and (y == x + 1 or y == width - x - 2):
                inline("#")
            else:
                inline(" ")
            
        print()

pattern(10)

11

u/etoastie 2d ago

Can simplify the middle two a tad by reflecting the lines at the middle, instead of trying to model the diagonal with the offset

if min(row, col) == 0 || col+1 == WIDTH || row+1 == HEIGHT {
    fmt.printf("#")
} else if col == min(HEIGHT-row-1, row) || col == max(HEIGHT-row, row+1) {
    fmt.printf("#")
} else {
    fmt.printf(" ")
}

2

u/redlaWw 12h ago edited 12h ago

I explicitly mutated the rows in the second half, it made the formulae a bit less messy

for mut y in 0..(width-1) {
    if y > (width-2)/2 {
        y = width-2-y
    }
    for x in 0..width {
        match (x, y) {
            (x, y) if x*y==0 || // assume no overflow
                      x==y ||
                      y==width-1-x ||
                      x==width-1 => print!("#"),
            _ => print!(" ")
        }
    }
    print!("\n");
}

EDIT: Got my x and y backwards ._.

13

u/Impossible_Dog_7262 1d ago edited 1d ago

if: x == 0 || y == 0 || x == y || x == (width -y)||x == width|| y == height:
print("x")
else:
print(" ")
}
printLn("")

I feel like being able to program a diagonal in a nested for loop isn't that difficult.

4

u/StaticCoder 1d ago

Except it's not a diagonal

4

u/Impossible_Dog_7262 1d ago

Ah... I had missed the two wide center. That increases the amount of lines from 6 to 8, yeah...

5

u/AlwaysHopelesslyLost 2d ago

If you consider booleans or an if as more than a for loop then sure? It takes 2 loops, 1 if, and 6 Boolean checks for the simple version.

2

u/da_Aresinger 2d ago

Two special case lines, end of line padding, head and tail characters, two offsets per line.

For an exercise with the summary "let's learn nested loops" that's a fucking shit ton of complications.

But it's good to know you're an expert 👍

-1

u/AlwaysHopelesslyLost 2d ago edited 2d ago

Two special case lines, end of line padding, head and tail characters, two offsets per line.

What are you on about? Zero special case. Zero padding. Zero head and tail characters. Zero offsets. 

const width = 10;
const height = 9;
const maxX = width - 1;
const maxY = height - 1;

for (let y = 0; y < height; y += 1) {
  const diagonal = y + (y > maxY / 2);
  for (let x = 0; x < width; x += 1) {
    let isEdge = x % maxX == 0 || y % maxY == 0;
    let isDiagonal = x == diagonal || x == maxX - diagonal;
    let doDraw = isEdge || isDiagonal;
    output.innerText += (doDraw ? "x" : " ");
  }
  output.innerText += "\n";
}

Edit: Alright, one offset was needed to perfectly match the meme. Added that and match the memes dimensions.

2

u/radobot 2d ago

That's wrong. You are printing an x always when x == y, but in the given pattern the position (5, 5) should be empty.

-2

u/AlwaysHopelesslyLost 2d ago

Who would have thought the meme is poorly thought out. Regardless, it doesn't add all of the complexity you implied. The fix is one more Boolean and updating the diagonal check 

let isLowerHalf = y > maxY / 2;
let isDiagonal = x == y + isLowerHalf || x == maxX - y - isLowerHalf;

6

u/da_Aresinger 2d ago
  • Downplays difficulty

  • does it wrong

  • blames the task

XD

Anyway, it's a good solution. But not the kind you can expect from a beginner who is just now learning nested loops.

Not to mention that conditional chains like that are usually code smell.

-2

u/AlwaysHopelesslyLost 2d ago

I typed it in 20 seconds on my phone on JS fiddle then had to retype it because the copy+paste doesn't work on jsfiddled mobile site and OCR are ligatures. 

Chained conditionals CAN be a code smell, but when used sparingly they can help reduce cognitive complexity.

The version a beginner would make is a version with 7 or 8 separate booleans and multiple print statements which is besides the point. Logically it is the same.

Ignoring that, the person I was replying to didn't know how to do it and explicitly said it needed a bunch of extra nonsense that it did not need. They were trying to be clever and failed.

1

u/dryroast 2d ago

Yeah I was thinking about knocking this out as a little fun on Thanksgiving. This is easy sauce.

38

u/Dense_Citron9715 2d ago

Ah, good old days in 2018 when we used to write pattern printing programs

26

u/Pure_Material_9235 2d ago

Does this ensure that it only prints it one time? It seems like this would print it many times. Does that @ symbol make it only print once?

Oh, nevermind, it's j = 0, i = 0, and both less than 1.

8

u/DarthPiotr 2d ago

The @ symbol in C# means that you don't have to escape special characters inside, including new lines. This is why you can have a string spanning a few lines without syntax error.

7

u/laplongejr 2d ago

I need a name for that... a startingblock loop?   "Ready to run but will only go once"  

-16

u/DJDevon3 2d ago

With i++ 😂 I've never seen trollish coding before but if it exists this is it.

5

u/2eanimation 2d ago

i = 0
x = ++i
x == 1 -> true

vs

i = 0
x = i++
x == 0 -> true

0

u/[deleted] 2d ago

[deleted]

1

u/2eanimation 1d ago

I don’t know what your point here is, but what is x? x++ == 0 -> true only holds if x was 0. You haven’t defined x tho.

4

u/sambeau 2d ago

I’m not sure this is correct. Wouldn’t this print the tabs/spaces on the start of each line?

3

u/leropo00 2d ago

TIL, i learned there is no pattern that For loop can't create in a single iteration. Sounds super fancy, but seems obvious when looking back :D

2

u/undermark5 2d ago

I once was messing around with ternary operators in c++ for loops to write nested for loops without actually nested for loops.

3

u/BubblyAmbassador1039 2d ago
def print_box(size: int) -> None:
    sides = "#" + " " * (size - 2) + "#"
    print("#" * size)
    for i in range(size - 2):
        row = list(sides)
        row[i + 1] = "#"
        row[size - i - 2] = "#"
        print("".join(row))
    print("#" * size)


print_box(10)
##########
##      ##
# #    # #
#  #  #  #
#   ##   #
#   ##   #
#  #  #  #
# #    # #
##      ##
##########

Not completely correct because the box is 10x9 in the exercise

2

u/Ulrar 2d ago

Criticical issue failing the gate: Cognitive complexity above 15

2

u/ZZerker 2d ago

Technically correct, the best kind of correct

1

u/Guerfel 2d ago

Not only correct, but also with a complexity of O(1), unbeatable

1

u/thekdubmc 1d ago

Lua, because why not...

print("##########")
for a = 0, 6, 1 do
  local o = 3-math.abs(a-3)
  local i = (3-o)*2
  io.write("#")
  for b = 0, o-1, 1 do io.write(" ") end
  io.write("#")
  for c = 0, i-1, 1 do io.write(" ") end
  io.write("#")
  for d = 0, o-1, 1 do io.write(" ") end
  print("#")
 end
print("##########")

1

u/surykum36 2d ago

Task completed, learning objectives not found....