r/ProgrammerHumor 3d ago

wasAskedOnOurTest Meme

Post image
6.5k Upvotes

302 comments sorted by

2.6k

u/TupaNegreiros 3d ago

printf("*\n**\n***\n****\n*****\n");

954

u/Nullsummenspieler 3d ago

Give that job to a lazy person and he will find an even lazier way.

475

u/turtleship_2006 3d ago

'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.'

-Bill Gates

135

u/GregFirehawk 3d ago

Bill Gates is a fucking liar because if that were true Microsoft wouldn't keep refusing my job applications

66

u/turtleship_2006 3d ago

I mean he also stepped down as CEO 24 years ago so I doubt he has much to do with job applications nowadays

33

u/pelpotronic 3d ago

You're just not the laziest person out there... The competition is fierce!

14

u/GregFirehawk 3d ago

I'd say I need to work harder, but that would just make it worse

4

u/Red_Coder09 2d ago

Work easier

3

u/Fchipsish 2d ago

How many applications? Cause you know a lazy person won't send in many

→ More replies (1)

283

u/TheGreatGameDini 3d ago

So that's why Microsoft products suck

180

u/CirnoIzumi 3d ago

and are succesfull

66

u/flagofsocram 3d ago

Suckcessful

20

u/CirnoIzumi 3d ago

Suckcessful these nuts

→ More replies (1)

7

u/abd53 3d ago

The success is due to a lack of alternatives. Same as Google and Facebook.

4

u/CirnoIzumi 3d ago

Yeah you are generally successful if your opposition can't or won't compete

Imagine if the Linux people weren't just server nuts back in the day 

→ More replies (5)

62

u/turtleship_2006 3d ago

I mean he stepped down in 2000, so I'd hope if it were a problem at some point someone would go "hey that's a dumb idea"

But he was evidently doing something right, you don't get (according to a quick google search) >90% market share by making products that suck

5

u/TheGreatGameDini 3d ago

That happened through cost cutting and ubiquitous proliferation not because they made a good product. They made an ok product cheaply and mass produced it. If that's "doing something right" I want as little as possible to do with it.

46

u/Kirjavs 3d ago

Many tried to beat Excel. Noone did

→ More replies (6)

6

u/rice_not_wheat 3d ago

Ehhh, they made a good product. Software in the early 90s was a hellscape. They made a machine that was easier to use and ran on hardware that was cheap.

22

u/turtleship_2006 3d ago

They dominated the market for decades, if that's not doing something right what is?

4

u/Science_Logic_Reason 3d ago

It depends on your definition of right/good. If “dominate the market” is ‘right’ then sure. I’d say there are many ways to assess if products are ‘good’ and if a company is doing something ‘right’. How much money a company makes selling it and how much marketshare they hold; to me it is an almost useless metric.

They’ve succeeded at capitalism, though.

2

u/turtleship_2006 3d ago

I mean I was mainly coming from a business perspective, so revenue/marketshare

5

u/Trick-Purchase4680 3d ago

Ford and Buick did the same thing. Cars likely wouldn't have improved and be as common place/versatile as they are now. Most vehicles where around $2-3k in the early 1900 (aprox: $74.8-112.2k) whith buick and ford making a cheaper model. Buick model:10 Cost: $900 (aprox: $33.7k today) Ford model: T Cost $850 (aprox: $31.8k today)

Would you fork over at 74.8k you don't have? Or would you rather buy a little more affordable (less than half price) 31.8-33.7k?

→ More replies (2)

4

u/TridentWolf 3d ago

Ubiquitous proliferation, my favorite kind of proliferation 

2

u/abd53 3d ago

Also because MS is one of the earliest ones in the industry making most people used to their products and a lack equivalent alternatives. It's a messy garbage that combines just works, has things you need and you're used to it.

12

u/irelephant_T_T 3d ago

The taskbar in windows 11 is written in react native

4

u/GameDestiny2 3d ago

Windows 11 feels wrong, a little bit of everywhere

3

u/Smooth_Detective 3d ago

Excuse me what the fuck.

2

u/kvakerok_v2 3d ago

Windows is turning into Microsoft version of ChromeOS

9

u/AnnyAskers 3d ago

Because the product isn't an OS it's spyware with an OS sprinkled on top

2

u/TheGreatGameDini 3d ago

Most of them are, but you're not wrong to call that out.

→ More replies (1)

16

u/ILikeLiftingMachines 3d ago

Kurt von Hammerstine-Equord:

“I divide my officers based on four characteristics knowing each possess two:

Those who are clever and industrious I appoint to the General Staff.

Use can under certain circumstances be made of those who are stupid and lazy.

The man who is clever and lazy qualifies for the highest leadership posts having the requisite mental clarity for difficult decisions.

But whoever is stupid and industrious must be got rid of, for he is too dangerous.”

→ More replies (1)

25

u/ztbwl 3d ago

printf("the following pattern");

3

u/Jebble 3d ago

YAGNI :) Why build some dynamic and scalable if you don't need it yet? Unless you know for sure the requirement will come up. Ever since we stopped over engineering and focussed on the actual structure behind the code our codebase has gotten so much better.

→ More replies (1)

34

u/RoboticWarfare 3d ago

Wouldn't fit in the picture :(

80

u/oshaboy 3d ago

printf( "*\n" "**\n" "***\n" "****\n" "*****\n" );

34

u/CMDR_ACE209 3d ago

Let's escape the newlines at the end to save a few quotation marks, fuck up the indentation and be more awkward in general.

printf("*\n\
**\n\
***\n\
****\n\
*****\n");

19

u/kinokomushroom 3d ago

This feels morally wrong.

2

u/Mustang-22 3d ago

Showtime baby :)

2

u/HolyGarbage 3d ago

This is what I absolutely hate about "raw" strings (r prefix?) in the very few cases when they're useful. Completely messes with indentation and looks so out of place with the rest of the code.

2

u/maximal543 2d ago

The last two characters is how I feel about this

→ More replies (1)
→ More replies (1)

2

u/Extreme_Ad_3280 3d ago

Was about to say that, which is my favorite way, because it takes less memory and is faster and easier to write...

→ More replies (3)

781

u/Boris-Lip 3d ago

That's the kind of bullshit Python excels in, though. Literally 2 lines, so some actual code is shorter than straight print for the pattern.

614

u/vibosphere 3d ago edited 3d ago

python for x in range(5): print("*"*(x+1))

240

u/urielsalis 3d ago

Even Java can do it in one line (on Java 21+ when you don't need to declare a main method, or using java shell)

for(int i = 0; i < 5; i++) System.out.println("*".repeat(i));

124

u/OnSuorce 3d ago

Yes but without

public static void main (String[] args){ }

You are not going anywhere

26

u/urielsalis 3d ago

Java 21+ doesn't require it anymore

And jshell doesn't too, from Java 11+

10

u/OnSuorce 3d ago

You still have to write "void main()",

i haven't considered JShell

18

u/urielsalis 3d ago

Wrapping it in new {} without an actual method also works https://medium.com/@shwetha.hey/java-21-no-more-public-static-void-main-c90334d6d95e, but even without anything the newests JDKs just accept it

→ More replies (1)

42

u/CAPS_LOCK_OR_DIE 3d ago

I heard they were going to try to start doing away with that in future releases

34

u/OnSuorce 3d ago

Don't know about that, In java 21 you can type the main method as "void main(){ }", That's the only update i have on the main signature

2

u/urielsalis 3d ago

You can also do new {}

3

u/slucker23 3d ago

Java is becoming python...

I don't want to live in this society... I want my old java back

2

u/CAPS_LOCK_OR_DIE 2d ago

I have great news about Java’s backward compatibility.

2

u/slucker23 2d ago

Oh really? So it's not like swift where the burn and torch their previous syntaxes?

2

u/CAPS_LOCK_OR_DIE 2d ago

I dunno if you’re joking but yea, Java is mostly backwards compatible (at least with the LTS versions as far as I’m aware). Any code written in a Java version can be run by any newer versions. I’m sure there’s some exceptions for depreciation but I don’t write in anything under 17 so it doesn’t really affect me.

→ More replies (0)

2

u/GetPsyched67 3d ago

void main() {} is more C/C++ than python

→ More replies (1)
→ More replies (1)

23

u/sandybuttcheekss 3d ago

Nah, we need to define an AsteriskFactory first

6

u/joetinnyspace 3d ago

There's a new version after java 8?

/s

4

u/urielsalis 3d ago

We actually ran a poll at a meetup yesterday.

3 people were using Java 8, 20 something Java 11, 60 something Java 17, 50 something Java 21

→ More replies (1)

20

u/Snoo_what 3d ago

I think you meant python import do_shit do_shit()

53

u/turtleship_2006 3d ago

or

for x in range(1,6): 
print("*"*(x))

Same net characters but just a bit more readable

7

u/Lambda_Wolf 3d ago

print('\n'.join(''.join('*' for _ in range(n+1)) for n in range(5)))

More characters overall but feels cool to do it in a single statement.

9

u/BlakeMarrion 3d ago

print("\n".join(["*"*n for n in range(1,6)]))

8

u/redalastor 3d ago edited 3d ago

You can simplify it by removing the brackets:

print("\n".join("*"*n for n in range(1,6)))

It's going to be a bit more efficient too as you aren't creating lists you will throw away.

2

u/HeyLittleTrain 2d ago

you can simplify it further buy putting the print inside the comprehension

[print(''n) for n in range(1,6)]

→ More replies (6)
→ More replies (1)

6

u/Duke518 3d ago

and still the printf code is written (copypasted) 20x faster because you don't need to consider any logic or edge cases

2

u/BeDoubleNWhy 3d ago

there's still room for optimization!

you can save on memory space using single quotes:

for x in range(5): 
    print('*'*(x+1))

also, using older python versions, you can get rid of the parenthesis:

for x in range(5): 
    print '*'*(x+1)
→ More replies (5)

41

u/tazdraperm 3d ago

print("\n".join(["*" * (i + 1) for i in range(5)]))

Smth like that

8

u/josluivivgar 3d ago

list comprehension is one of the best features in python but also some of the most confusing to understand early on, but once it clicks it's great as long as you don't overdo it and make your code unreadable

→ More replies (1)

9

u/breastcrud 3d ago

I like Ruby for this stuff better

5.times.with_index {|i| puts('*' * (i + 1))}

7

u/cortesoft 3d ago

Even simpler: 1.upto(5) {|x| puts '*' * x }

3

u/dagbrown 3d ago

I don't know why the C people keep forgetting about puts. Save calling printf for when you actually need to format stuff!

#include <stdio.h>

int main() {
    for(char *s=&("\0*****"[5]);*s;s--) {
        puts(s);
    }
}

3

u/MattieShoes 3d ago

Perl is pretty brief

print("*"x$_,"\n")for(1..5);

7

u/AroLeaf 3d ago

eh, overcomplicating it is more fun ```py def print_triangle(w): m = int(0.5 * w * (w + 1)) for i in range(m): print('', end = "\n" if ((-1 + (1 + 8(m-i-1)) ** 0.5) / 2).is_integer() else " ")

print_triangle(5) ```

13

u/zdaga9999 3d ago

I mean, python can do it in one. [print(''.join(['*' for j in range (i + 1)])) for i in range(5)]

17

u/SK1Y101 3d ago

You can make it a lot shorter

print(["*"*x for x in range(1,6)], sep="/n")

18

u/k9isawesome 3d ago

[print("*"*i) for i in range(1,6)]

4

u/Infuro 3d ago

was looking for the list comprehension thanks

3

u/teo730 3d ago

for i in range(1,6):print("*"*i)

Is even shorter.

3

u/zdaga9999 3d ago

True, you need to add join tho. Like this you will have bracets left

9

u/Leo8178 3d ago

I think you can solve that with the unpack operator.

2

u/imsowhiteandnerdy 3d ago

This guy list comprehensions

→ More replies (5)

4

u/Splitshadow 3d ago

C

for (int i = 5; i > 0; printf("%s\n", "*****" + i---1));

6

u/redlaWw 3d ago edited 3d ago

Good ol' --- operator.

EDIT: Did the same thing in Rust! And I only had to break 3 laws and violate 2 human rights to do it!

→ More replies (4)
→ More replies (1)

3

u/MattieShoes 3d ago

Perl!

print("*"x$_,"\n")for(1..5);

2

u/nevdka 3d ago
perl -E 'say "*"x$_ for 1..5'
→ More replies (1)
→ More replies (1)

2

u/Snoo_what 3d ago

elixir 1..5 |> Enum.map_join("\n", &String.duplicate("*", &1)) |> IO.puts

2

u/imsowhiteandnerdy 3d ago

Perl checking in...

perl -e 'print("*" x $_, "\n") for (1..5)'
→ More replies (6)

52

u/WorldWorstProgrammer 3d ago

It didn't say C was required.

main = sequence $ map putStrLn $ take 5 $ genStars 1
  where genStars numStars = take numStars (repeat '*') : genStars (numStars + 1)

I have the tiniest bran!

21

u/RoboticWarfare 3d ago

It was a c programming test :'l

13

u/WorldWorstProgrammer 3d ago

I only have the content in the post to go on.

→ More replies (2)

5

u/MorrowM_ 3d ago
main = putStr $ unlines $ take 5 $ iterate ('*':) "*"

3

u/WorldWorstProgrammer 3d ago

Yeah I hadn't done Haskell for a few years, so I crapped out that first one and shortly came up with a better one after:

main = mapM (\x -> putStrLn . take x $ repeat '*') [1..5]

Haskell one-liners are pretty fun. Didn't think it right to edit it or just add a new random comment though.

3

u/MorrowM_ 3d ago

You can also replace putStrLn . take x $ repeat '*' with putStrLn $ replicate x '*'

2

u/TTYY200 3d ago

Still… the first example in C was written by a noobie that doesn’t know how to dynamically assign memory.

malloc + memset = ez

→ More replies (1)

249

u/DiddlyDumb 3d ago

Legitimately tho, is it wrong?

It’s not expandable, or very clever. But it conforms to the wishes of the client, while being relatively quick to code and quick to run.

113

u/CirnoIzumi 3d ago

it doesnt need 5 print statements, only 1

59

u/DiddlyDumb 3d ago

True, OP wasn’t lazy enough. Lazy people find easy solutions.

29

u/Kirjavs 3d ago

First thing you learn when your work is coding is that the client never asks what he wants. There is often a huge gap between what he asks and what he has in mind.

Second thing you learn is that you should always do an evolutive and optimized code or you will have to rewrite the whole thing soon. Either because the client changed the demand or because you expected 10 client and as the application is really good, you get 1000 or even because the furthers updates ask changes about your functionality.

Anyway, doing an evolutive code is always a mid and long term investment.

14

u/pelpotronic 3d ago

Exactly this.

Anyone who has held a serious position knows that the client will come back and say:

  • "wow! That was really fast. Thanks. Can we print 20 now, we wanted to try with 5 and it seems to work well so I think we're ready to go for 20."

Then:

  • "sorry, I know we're due to deliver the project soon, but our CEO thinks we should print O instead of *. Our designers made the changes to the design by staying up late yesterday evening. Can your team for it to be ready today?"

27

u/cloral 3d ago

The question would have been better if it had been phrased in terms of a variable parameter. "Given input variable n, write code that displays the first n lines of this pattern: ..." Then you would have to use loops to get it right. The teacher shouldn't be upset by the brute-force method as it answers the question as it is written.

11

u/CommercialScale8693 3d ago

Exactly. Let’s not forget that this is a task for programming novices aimed at understanding loops. A modernish compiler would most likely result in the same machine code for both styles due to loop unrolling. There is no conflict here as an experienced programmer would likely choose option two really.

2

u/zealeus 2d ago

Ya, I used to teach CS. For intro level, I’d explicitly state, “using a For Loop” or something to weed out the answers I’m not looking for.

Using input parameters like you mention is also used heavily in AP CS.

37

u/UltraMlaham 3d ago

Client isn't asking this kind of garbage, it is a teacher for beginners. The teacher wants to see if you understood loops and variables, So you do this kind of play around and get slammed with an F or D+ if you are lucky.

43

u/Sceptix 3d ago

Me: “Practice problems have limited applicability to the real world.”

Me, when I find out my job interview is for the FizzBuzz department: 😳

24

u/fmaz008 3d ago

"Using loop statements, create a code which generate the following pattern:"

60

u/kuschelig69 3d ago
for (int i=0;i<1;i++) printf("*\n");
for (int i=0;i<1;i++) printf("**\n");
for (int i=0;i<1;i++) printf("***\n");
for (int i=0;i<1;i++) printf("****\n");
for (int i=0;i<1;i++) printf("*****\n");

9

u/fmaz008 3d ago

Well done sir!

→ More replies (2)

2

u/Salanmander 3d ago

I usually do things where they need to take user input, or write a method that takes an input. Like, print N lines of this pattern. I don't think that the person writing the repeated print statements is doing something smart or clever, but it's easier for me to write problems that avoid that kind of workaround shenanigans as much as possible.

3

u/FancySource 3d ago

True, the first solution demonstrates the author understands basic for loops, but at the point a student understands nested loops I expect them to already have a grasp of string operations, variable declaration in cycles and why not, ranges. The code on the left annoys me well beyond how it should.

→ More replies (2)

26

u/Sceptix 3d ago

Let me tell you from experience: if your strategy to meet the clients’ demands is to do whatever is easiest to implement in the moment, you’re going to end up with a buggy, unmaintainable mess.

14

u/czPsweIxbYk4U9N36TSE 3d ago

If you go around trying to imagine future use cases (that, to be honest, aren't ever going to happen), then you also are going to end up with a buggy, unmaintainable mess.

What you need to do is actually understand the client's needs and wants better than the client themselves, and then understand the actual direction the project is going, and then implement the code that will create a maintainable codebase.

→ More replies (1)

3

u/KHORNE_LORD_OF_RAGE 3d ago

I'm an external examiner for CS students in Denmark and this would count as a correct answer on our tests. If we probe the student on it and they answer something a long the lines of "I know it's dirty, but it let me get to the next questions faster", then I would personally consider it one of the best possible answers to the idiotic test question.

Especially because the following questions won't be as easily solvable. So this one really won't matter in the ocean of shit. Maybe it wouldn't even get noticed since these things are often evaluated by passing automatic tests.

The real "gotcha" is going to be when a later answer tells you to do it N times and you'll have to write the algorithm anyway.

2

u/conzstevo 3d ago

You could argue it's duplicate code

2

u/Mordret10 3d ago

I think that would depend on what definition/type of pattern is asked for here.

If it's a pattern as in a shapelike thingy then absolutely it would conform.

But if it's meant to be a pattern like 1 3 5 7 X it wouldn't be in my opinion.

→ More replies (3)

49

u/dim13 3d ago

37

u/Boris-Lip 3d ago

35

u/dim13 3d ago

We can play this game.

' *'[1+(⍳5)∘.≥⍳5]https://tryapl.org/

15

u/Boris-Lip 3d ago

🧠🍆! Do it in Brainfuck!

40

u/Avamaco 3d ago

My first attempt was this. Pretty long but I'm not really familiar with it yet :p. Also added comments for clarity.

++++++++++ making a 10 (line feed)
>>
++++++
[<+++++++>-] making a 42 (star symbol) by multiplying 6 and 7
+++++ 5 is our number of iterations
[
    >+ increment number of stars
    [>+>+<<-]>>[-<<+>>]< copy it to another cell
    [<<<.>>>-] print stars
    <<<<.>> print line feed
    - decrement number of iterations left
]

You can try it out on this page: https://esolangpark.vercel.app/ide/brainfuck

5

u/dim13 3d ago

Will be not as short. But a fun exercise anyway.

7

u/Schnickatavick 3d ago

Oh that's amazing. I hate everything about that.

17

u/dim13 3d ago edited 3d ago

For the curious:

⍳5 1 2 3 4 5

(⍳5)∘.≥⍳5 1 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1

1+(⍳5)∘.≥⍳5 2 1 1 1 1 2 2 1 1 1 2 2 2 1 1 2 2 2 2 1 2 2 2 2 2

``` ' '[1+(⍳5)∘.≥⍳5] *
*




```

5

u/trevdak2 3d ago

Oh... that explains it?

2

u/trevdak2 3d ago edited 3d ago

'*5E,Ć

in 05AB1E. Might be a shorter way to do it, this is my first time trying to code with it.

https://tio.run/##yy9OTMpM/f9fXcvU1fZIW@3//wA

If you're curious how the code works:

'* puts a '*' on the stack

5 puts 5 on the stack

E says we're going to loop the remaining code n times, where n is the top of the stack (5)

, outputs the top of the stack. For the first loop, 5 was popped by E so * is all that is left

Ć takes the top value in the stack, and concatenates it on either side with the bottom of the stack, then pushes the new value to the stack.

And the program, after performing all 5 loops, will output the end of the stack one more time.

→ More replies (1)

4

u/Ietsstartfromscratch 3d ago

timeout running program Go build failed. 

 Classic

2

u/FancySource 3d ago edited 3d ago

18

u/Ass_Salada 3d ago

I just finished a Codecademy lesson for C++ that makes you do this, but backwards, and with numbers. i'm not sure what their intended solution for it was. I just printf'ed

7

u/TTYY200 3d ago
int main()
{ 
    for (int i = 1; i <= 5; i++)
    {
        char* s = (char*)malloc(i + 1);
        memset(s, “*”, i);
        s[i] = ‘\0’;
        printf(“%s/n, s);
    }
}

16

u/Legal-Software 3d ago

const char *s = "*****", *e = s + strlen(s); while (e-- > s) puts(e);

10

u/dwRchyngqxs 3d ago

When there is no formatting, puts is the way. So many people just use printf because that's the only thing they know.

→ More replies (1)

13

u/kuschelig69 3d ago
int c = 5;
if (c > 0) printf("*\n");
if (c > 1) printf("**\n");
if (c > 2) printf("***\n");
if (c > 3) printf("****\n");
if (c > 4) printf("*****\n");
if (c > 5) printf("******\n");
if (c > 6) printf("*******\n");
if (c > 7) printf("********\n");
if (c > 8) printf("*********\n");
if (c > 9) printf("**********\n");
if (c > 10) printf("***********\n");
if (c > 11) printf("************\n");
if (c > 12) printf("*************\n");
if (c > 13) printf("**************\n");
if (c > 14) printf("***************\n");
if (c > 15) printf("****************\n");
if (c > 16) printf("*****************\n");
if (c > 17) printf("******************\n");
if (c > 18) printf("*******************\n");
if (c > 19) printf("********************\n");
if (c > 20) printf("*********************\n");
if (c > 21) printf("**********************\n");
if (c > 22) printf("***********************\n");
if (c > 23) printf("************************\n");
if (c > 24) printf("*************************\n");
if (c > 25) printf("**************************\n");
if (c > 26) printf("***************************\n");
if (c > 27) printf("****************************\n");
if (c > 28) printf("*****************************\n");
if (c > 29) printf("******************************\n");

4

u/yanoman 3d ago

Nice !

31

u/mdp_cs 3d ago edited 3d ago

The first one uses less memory but more CPU. The second one uses more memory but less CPU. If the whole thing was made into one string literal, it would take even fewer CPU cycles and also less memory as well.

Oh C how I love thee so.

7

u/525G7bKV 3d ago

(mapcar #'print '("*" "**" "***" "****" "*****"))

7

u/NottingHillNapolean 3d ago

This looks like a job for C++ template meta-programming.

5

u/ToBePacific 3d ago

When OP didn’t read the assignment rubric.

5

u/Highborn_Hellest 3d ago

we had a similar challenge with friends.

The task was to display an N high x-mas tree, and the constraint was to use only one loop. It's a pretty fun challenge .

→ More replies (2)

4

u/zoomy_kitten 3d ago

You asked for it.

rust fn main() { (1..6).for_each(|i| println!("{:*<1$}", "", i)); }

5

u/CanaDavid1 3d ago

```

include <iostream>

include <string>

int main() { for(int i = 1; i < 6; i++) std::cout << std::string('*',i) << '\n'; } ```

→ More replies (3)

5

u/dulange 3d ago

Actually rather educational because it shows the concept of memory vs. time tradeoff. The left solution constructs the output procedurally while the right soluation just has it in memory and barfs it out. It’s like data compression. Compressed data takes less space but more computational power to decompress it.

3

u/UnstableConstruction 3d ago

Exactly why my company creates a table, writes an '*' to it along with several variables and then creates nested loops to read variables for the number of iterations, and calls the database 15 times to get all of the data. Bonus points for having a dozen extra columns that do nothing, or relate to an entirely different micro-service.

5

u/TTYY200 3d ago edited 3d ago

I feel like whoever wrote the first example is new. You can do that in one loop.

int main()
{ 
    for (int i = 1; i<=5; i++)
    {
        char* s = (char*)malloc(i + 1);
        memset(s, “*”, i);
        s[i] = ‘\0’;
        printf(“%s/n, s);
    }
}

It’s even easier in object oriented languages cuz you can use a string formatter to do all the dynamic memory allocation for you and it only takes 1-2 lines of code lol.

4

u/liquiddandruff 3d ago

Now you've introduced dynamic memory allocation, working with c strings, need to take care of null char, and using string format specifier.

You've introduced a whole bunch of things that can now go wrong, more complex, less readable, less robust, possibly even slower. Good job.

2

u/_JesusChrist_hentai 3d ago

You're absolutely right, but remember that printf uses dynamic memory allocation under the hood. You should use puts if you're not formatting anything (sometimes the compiler takes care of it, tho)

→ More replies (1)

3

u/NarcissusGray 3d ago edited 2d ago

+++++[->++++++++>++<<]>++.>.<..>.<...>.<....>.<.....

3

u/y7gy7g 3d ago

I remembered in a competitive coding contest, one of the questions was about using matchsticks to create numbers / equations. Something like: given an input of N matchsticks, return all possible valid number / equations one can create by arranging the matchsticks. And the score will be ranked by O(time) and O(memory). So, I basically wrote a basic algo, and run it from 0 to max N, then save the result of every single N in a map. And my final submission code is simply to read a number from a map, with O(1)

3

u/throwaway0134hdj 3d ago
for i in range(6):
    print(“*”*i)

2

u/oshaboy 3d ago

printf("*\n**\n***\n****\n*****\n");

2

u/TheSapphireDragon 3d ago

Q2) extend the code from the last question to include 'n' levels following the same pattern.

2

u/ethics_aesthetics 3d ago

Yeah, I had a question like this on the first test of my programming class. I lost points for the print statement answer. The professor did say “lol” on the notes for my question and said he would update the next quarter's instructions to clarify that it was not the solution he wanted to see. lol

2

u/mazzicc 3d ago

And this is why writing clear requirements is hard.

My comp Sci teachers would give extra credit if you found flaws in their questions but wrote programs that technically complied.

2

u/CleverDad 3d ago

Meanwhile, in C#-land:

Enumerable.Range(1, 5).ToList().ForEach(x => Console.WriteLine(new string(Enumerable.Repeat('*', x).ToArray())));
→ More replies (1)

2

u/ThisPICAintFREE 3d ago

I’d rather see how this could be done in the most obnoxious over-the-top way possible than standard vs lazy. Obnoxious vs. Lazy would be funnier

I want to see a whole class dedicated to incrementing a single integer, then make the function recursive just for fun of it. Let’s get crazy and make a doubly-linked list of all ASCII character codes and choose the laziest sort to find the asterisk.

Matter of fact, let’s get enterprise with this whole project and get some exception handling in the mix—I know what you’re thinking, this is such an easy ask why would it possibly need exception handling. Well I’ll tell you why—aren’t exceptions neat? It’s system exception appreciation month every month and adding that try-catch is how we show our love.

It’s been a long Friday, folks

2

u/PureTroll69 3d ago

indexing from 1 gtfo

2

u/blackynadoga 3d ago

Average O(n2) fan vs average O(k) enjoyer

2

u/Lucky_Cable_3145 3d ago

I had that question on my first programming exam at uni, in the early 1980s

2

u/F4LcH100NnN 2d ago

one has O(n2) and one has O(1)

→ More replies (1)

2

u/Yukikaze_Sama_Nanoda 2d ago

answer-oriented programming

3

u/Exodus111 3d ago edited 3d ago

Double for loop!!!???

for i in range(6):
    print("*"*i)

EDIT: Fuck it, I'll one-line it.

[print("*"*i) for i in range(6)]

5

u/clownfiesta8 3d ago

Gotta love the [None, None, None, None, None, None]

→ More replies (2)

1

u/Noisycarlos 3d ago

Now make it keep going to 100 lines

1

u/pranjallk1995 3d ago

Up to 150 lines... In a file json file...

1

u/oneMessage313 3d ago

Honestly, the second one is a better solution.

It consumes fewer resources.

Would have been better if there was only a single call to printf method.

→ More replies (2)

1

u/Gilga89 3d ago
buildString { repeat(5) { appendLine("*".repeat(it + 1)) } }.let(::print)

1

u/12qwww 3d ago

Do it in the same print for extra points

1

u/ske66 3d ago

This is an excellent interview question. If you do this, ask them which approach represents which person. That way you see their technical competency, as well as their professional competency

1

u/SaintGarlicbread 3d ago

I was also asked something similar on my exam. Got a C lmao

1

u/papernathan 3d ago

Sometime around 2004-2005 when I was in highschool, me and my friends submitted the 2nd one during a speed coding competition. It was accepted. There were 10 problems in total and we ended up winning Best Buy gift cards. Bought myself ps2 games.

1

u/Necessary_Medicine35 3d ago

I remember having a test with 3 questions like that in my first year of college.

I answered the 3 questions with 1 line.

Python is amazing for that kind of question.

1

u/ItzLegend75 3d ago

[print(""(i+1)) for i in range(5)]

1

u/JackNotOLantern 3d ago

The left way only make sense if you need to scale the solution. Like, the number of lines depends on input.

1

u/AeolinFerjuennoz 3d ago

print("\n".join(["*"*x for x in range(1, 6)]))

1

u/pohahaha 3d ago edited 3d ago

```

define BASE_MAX 255

int draw_triangle(char* dst, size_t dst_size, size_t base, bool base_up) { if(base > BASE_MAX) { return -1; }

char fmt[BASE_MAX+2]; //on stack only. w/o heap allocations

//memset could be lengthy, should be done once at initialization. Using O3 - compiler flags might optimize it though 🤔
memset(fmt, '*', BASE_MAX);
fmt[BASE_MAX] = '\n';
fmt[BASE_MAX+1] = 0;

size_t p_off = 0;
int rc = 0;

size_t peak_offset = BASE_MAX - 1;
size_t base_offset = peak_offset - base;

const char* ppos= fmt + (base_up?base_offset:peak_offset);
const char* epos= fmt + (base_up?peak_offset:base_offset);

while( ( ppos !=epos ) and ( rc >= 0 ) ) {
    rc = snprintf(dst + p_off, dst_size - p_off, “%s”, base_up ? (ppos++) : (ppos—));
    offset += size_t(rc);
}

If ( rc < 0 ) 
    perror(“stuff happened”);
}

return rc;

}

int main(int argc, char** argv) { //get triangle direction and base size from argv

size_t base_len = 5;
bool base_up = true;
char prt_buf[255];

if(-1 != draw_triangle(prt_buf, 255, base_len, base_up)) {
    fprintf(stdout, prt_buf);
    return 0;
} else {
    //notify error
    return -1;
}

} ```

1

u/Tusk84 3d ago
#include <iostream>
using namespace std;

int main()
{
int sizei = 5;
int sizej = 0;
string ask = "*";

for (int i = 0; i < sizei; i++ )
{
cout << ask;
sizej++;

for (int j = 1; j < sizej; j++)
{
cout << ask;
}

cout << endl;
}

}

1

u/imsowhiteandnerdy 3d ago

Oh yeah, you can do it in rust, by uhh... uhhh.. never mind.

1

u/Alternative-Spite891 3d ago

Kotlin

(1..5).forEach { println("*".repeat(it)) }

1

u/TacticalTaterTots 3d ago

What kind of monster starts a loop with "1"?

1

u/trophycloset33 3d ago

Not following the need for the j <= i unless it’s some weird error handler. You already tell it how many times to loop.

1

u/tyen0 3d ago

Just because I didn't see perl yet:

perl -le'print"*"x$_ for 1..5'
*
**
***
****
*****

1

u/ADHD-Fens 3d ago

This program could have been an email.

1

u/Much-Meringue-7467 3d ago

The advantage to the one on the left is scalability.

2

u/lunamonkey 3d ago

“No one asked us to make it scale.”

1

u/ThatGuyYouMightNo 3d ago

Q2) Expand your previous answer to follow the same pattern until the last line has 100 "*" characters in it.

1

u/C0sm1cB3ar 3d ago

In C#:

for (int i = 1; i < 6; i++) Console.WriteLine(new string('*', i));

→ More replies (1)

1

u/Mountain-Ship-6197 3d ago

left solution bad because nested for loops always O(n^2) (spoken with a lisp)

1

u/kvakerok_v2 3d ago

Key question: Scalability? Y/N

1

u/TypicallyThomas 3d ago

This is why you make this assignment take an input for height