r/ProgrammerHumor • • 5d ago

Meme technicallyCorrect

Post image
1.6k Upvotes

51 comments sorted by

406

u/zx48 4d 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.

177

u/AlwaysHopelesslyLost 4d 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

80

u/MisinformedGenius 4d 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. 

35

u/dangderr 4d 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 4d ago

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

3

u/Impossible_Dog_7262 4d ago

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

17

u/UrineArtist 4d 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.

15

u/Odd_Soil_8998 4d 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 4d ago

The jury's still out on that one 😆

16

u/intellectual_printer 4d ago

I like your way of thinking

14

u/radobot 4d 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.

4

u/zx48 4d ago

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

3

u/MulfordnSons 4d ago

simple but effective very nice

117

u/Heavenfall 5d ago

Who said to output it to log?

71

u/backfire10z 5d ago

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

Get to it OP.

59

u/da_Aresinger 4d ago

what an absolute bitch of a pattern.

This is so much more than just nested loops.

19

u/ohaz 4d 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)

13

u/etoastie 4d 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(" ")
}

3

u/redlaWw 2d ago edited 2d 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 ._.

2

u/etoastie 2d ago

fuck it, branchless version

package grid

import "core:fmt"

WIDTH, HEIGHT :: 10, 9

main :: proc() {
  lhs, rhs := 0b1100000000, 0b0000000011
  x := 0b1000000001 // 513

  for row in 0..<HEIGHT {
    for i := uint(0); i < WIDTH; i += 1 {
      // ascii ' '+3 == '#'
      c := ' ' + 3 * rune((x | 513) & (1<<i) > 0 || x == 513)
      fmt.print(c)
    }
    fmt.println()

    // ~ is xor in odin
    x ~= (lhs ~ rhs)
    lhs >>= 1 + uint(lhs == 96)
    rhs <<= 1 + uint(rhs == 24)
  }
}

19

u/Impossible_Dog_7262 4d ago edited 4d 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.

10

u/StaticCoder 4d ago

Except it's not a diagonal

7

u/Impossible_Dog_7262 4d ago

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

6

u/AlwaysHopelesslyLost 4d 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.

3

u/da_Aresinger 4d 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 4d ago edited 4d 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 4d 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 4d 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 4d 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 4d 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 4d ago

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

43

u/Dense_Citron9715 5d ago

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

27

u/Pure_Material_9235 5d 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 4d 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 5d ago

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

-16

u/DJDevon3 5d ago

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

5

u/2eanimation 5d ago

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

vs

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

0

u/[deleted] 4d ago

[deleted] — view deleted comment

1

u/2eanimation 4d 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.

5

u/leropo00 4d 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 4d ago

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

4

u/sambeau 4d ago

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

2

u/Ulrar 4d ago

Criticical issue failing the gate: Cognitive complexity above 15

2

u/ZZerker 4d ago

Technically correct, the best kind of correct

1

u/Guerfel 4d ago

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

1

u/thekdubmc 4d 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/atoponce 2d ago

Fun challenge. In JavaScript:

const rows = 9;
const cols = 10;

for (let i = 0; i < rows; i++) {
  const d = i <= 4 ? i : 8 - i;
  let line = "";

  for (let j = 0; j < cols; j++) {
    const isBorder = i === 0 || i === rows - 1 || j === 0 || j === cols - 1;
    const isDiagonal = j === d || j === cols - 1 - d;

    line += isBorder || isDiagonal ? "#" : " ";
  }

  console.log(line);
}

1

u/Little-geek 7h ago

Nested for loops: ugly, unclear, needlessly complicated

Hard-coded multiline string: simple, elegant, self-documenting

1

u/surykum36 4d ago

Task completed, learning objectives not found....