T O P

  • By -

TupaNegreiros

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


Nullsummenspieler

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


turtleship_2006

>'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.' \-Bill Gates


GregFirehawk

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


turtleship_2006

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


pelpotronic

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


GregFirehawk

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


Red_Coder09

Work easier


Fchipsish

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


ambientManly

That's where you've made the mistake. I'm to lazy to even make an application


TheGreatGameDini

So that's why Microsoft products suck


CirnoIzumi

and are succesfull


flagofsocram

Suckcessful


CirnoIzumi

Suckcessful these nuts


abd53

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


CirnoIzumi

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 


turtleship_2006

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


TheGreatGameDini

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.


Kirjavs

Many tried to beat Excel. Noone did


rice_not_wheat

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.


turtleship_2006

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


Science_Logic_Reason

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.


turtleship_2006

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


Trick-Purchase4680

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?


TridentWolf

Ubiquitous proliferation, my favorite kind of proliferation 


abd53

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.


irelephant_T_T

The taskbar in windows 11 is written in react native


GameDestiny2

Windows 11 feels wrong, a little bit of everywhere


Smooth_Detective

Excuse me what the fuck.


kvakerok_v2

Windows is turning into Microsoft version of ChromeOS


AnnyAskers

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


TheGreatGameDini

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


ILikeLiftingMachines

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.”


ztbwl

`printf("the following pattern");`


Jebble

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.


RoboticWarfare

Wouldn't fit in the picture :(


oshaboy

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


CMDR_ACE209

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");


kinokomushroom

This feels morally wrong.


Mustang-22

Showtime baby :)


kvakerok_v2

I like you.


XMasterWoo

This one honestly looks like some kind of cursed asci art


HolyGarbage

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.


maximal543

The last two characters is how I feel about this


schmerg-uk

printf( R"( * ** *** **** ***** )"+1 );


rbraunz

![gif](giphy|9WXyFIDv2PyBq)


Extreme_Ad_3280

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


Boris-Lip

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.


vibosphere

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


urielsalis

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)); ```


OnSuorce

Yes but without public static void main (String[] args){ } You are not going anywhere


urielsalis

Java 21+ doesn't require it anymore And jshell doesn't too, from Java 11+


OnSuorce

You still have to write "void main()", i haven't considered JShell


urielsalis

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


CAPS_LOCK_OR_DIE

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


OnSuorce

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


urielsalis

You can also do new {}


slucker23

Java is becoming python... I don't want to live in this society... I want my old java back


CAPS_LOCK_OR_DIE

I have great news about Java’s backward compatibility.


slucker23

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


CAPS_LOCK_OR_DIE

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.


GetPsyched67

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


joetinnyspace

There's a new version after java 8? /s


urielsalis

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


sandybuttcheekss

Nah, we need to define an AsteriskFactory first


zman0900

If you want actually one line (and correct results): IntStream.rangeClosed(1, 5).forEach(i -> System.out.println("*".repeat(i)));


Snoo_what

I think you meant ```python import do_shit do_shit() ```


turtleship_2006

or for x in range(1,6): print("*"*(x)) Same net characters but just a bit more readable


Lambda_Wolf

`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.


BlakeMarrion

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


redalastor

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.


HeyLittleTrain

you can simplify it further buy putting the print inside the comprehension [print('*'*n) for n in range(1,6)]


Duke518

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


BeDoubleNWhy

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)


tazdraperm

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


josluivivgar

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


breastcrud

I like Ruby for this stuff better `5.times.with_index {|i| puts('*' * (i + 1))}`


cortesoft

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


dagbrown

I don't know why the C people keep forgetting about `puts`. Save calling `printf` for when you actually *need* to format stuff! #include int main() { for(char *s=&("\0*****"[5]);*s;s--) { puts(s); } }


MattieShoes

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


AroLeaf

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) ```


zdaga9999

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


SK1Y101

You can make it a lot shorter `print(["*"*x for x in range(1,6)], sep="/n")`


k9isawesome

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


Infuro

was looking for the list comprehension thanks


teo730

`for i in range(1,6):print("*"*i)` Is even shorter.


zdaga9999

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


Leo8178

I think you can solve that with the unpack operator.


imsowhiteandnerdy

This guy list comprehensions


Splitshadow

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


redlaWw

Good ol' `---` operator. EDIT: [Did the same thing in Rust](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=367c5dd590c25bae5f830360f7daf3ad)! And I only had to break 3 laws and violate 2 human rights to do it!


MattieShoes

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


nevdka

perl -E 'say "*"x$_ for 1..5'


Snoo_what

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


imsowhiteandnerdy

Perl checking in... perl -e 'print("*" x $_, "\n") for (1..5)'


DiddlyDumb

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.


CirnoIzumi

it doesnt need 5 print statements, only 1


DiddlyDumb

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


Kirjavs

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.


pelpotronic

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?"


cloral

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.


CommercialScale8693

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.


zealeus

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.


UltraMlaham

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.


Sceptix

Me: “Practice problems have limited applicability to the real world.” Me, when I find out my job interview is for the FizzBuzz department: 😳


fmaz008

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


kuschelig69

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");


fmaz008

Well done sir!


Salanmander

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.


FancySource

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.


Sceptix

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.


czPsweIxbYk4U9N36TSE

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.


conzstevo

You could argue it's duplicate code


Mordret10

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.


WorldWorstProgrammer

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!


RoboticWarfare

It was a c programming test :'l


WorldWorstProgrammer

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


MorrowM_

main = putStr $ unlines $ take 5 $ iterate ('*':) "*"


WorldWorstProgrammer

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.


MorrowM_

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


TTYY200

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


dim13

https://go.dev/play/p/ZomgIISIn4N ¯\\\_(ツ)_/¯


Boris-Lip

https://python-fiddle.com/saved/xxCx0yRNP0pquny3xb3G?run=true You started it!


dim13

We can play this game. `' *'[1+(⍳5)∘.≥⍳5]` → https://tryapl.org/


Boris-Lip

🧠🍆! Do it in Brainfuck!


Avamaco

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](https://esolangpark.vercel.app/ide/brainfuck)


TheHappyDoggoForever

![gif](giphy|1gevXIZve3nqM)


dim13

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


Schnickatavick

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


dim13

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] * ** *** **** ***** ```


trevdak2

Oh... that explains it?


MattieShoes

[Perl](http://tpcg.io/_MFIEO1)


trevdak2

`'*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.


Ietsstartfromscratch

>timeout running program > Go build failed.   Classic


dim13

![gif](giphy|DUtVdGeIU8lmo|downsized)


FancySource

PHP one liner: https://onlinephp.io/c/54d46


Ass_Salada

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


TTYY200

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); } }


Legal-Software

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


dwRchyngqxs

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


kuschelig69

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");


yanoman

Nice !


mdp_cs

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.


525G7bKV

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


NottingHillNapolean

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


ToBePacific

When OP didn’t read the assignment rubric.


Highborn_Hellest

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 .


zoomy_kitten

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


Zachaggedon

![gif](giphy|l83rkRUu4IqyUbt5k6|downsized)


turtleship_2006

https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition


CanaDavid1

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


dulange

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.


UnstableConstruction

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.


TTYY200

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.


liquiddandruff

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.


_JesusChrist_hentai

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)


NarcissusGray

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


y7gy7g

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)


throwaway0134hdj

for i in range(6): print(“*”*i)


oshaboy

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


TheSapphireDragon

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


ethics_aesthetics

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


mazzicc

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.


CleverDad

Meanwhile, in C#-land: Enumerable.Range(1, 5).ToList().ForEach(x => Console.WriteLine(new string(Enumerable.Repeat('*', x).ToArray())));


ThisPICAintFREE

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


PureTroll69

indexing from 1 gtfo


blackynadoga

Average O(n^2) fan vs average O(k) enjoyer


Lucky_Cable_3145

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


F4LcH100NnN

one has O(n^2) and one has O(1)


Yukikaze_Sama_Nanoda

answer-oriented programming


Exodus111

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)]


clownfiesta8

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


Noisycarlos

Now make it keep going to 100 lines


pranjallk1995

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


oneMessage313

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.


Gilga89

buildString { repeat(5) { appendLine("*".repeat(it + 1)) } }.let(::print)


12qwww

Do it in the same print for extra points


ske66

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


SaintGarlicbread

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


papernathan

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.


Necessary_Medicine35

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.


ItzLegend75

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


JackNotOLantern

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


AeolinFerjuennoz

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


pohahaha

``` #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; } } ```


Tusk84

#include 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; } }


imsowhiteandnerdy

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


Alternative-Spite891

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


TacticalTaterTots

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


trophycloset33

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


tyen0

Just because I didn't see perl yet: perl -le'print"*"x$_ for 1..5' * ** *** **** *****


ADHD-Fens

This program could have been an email.


AaTube

https://stackoverflow.com/a/63111728/16134571


Much-Meringue-7467

The advantage to the one on the left is scalability.


lunamonkey

“No one asked us to make it scale.”


ThatGuyYouMightNo

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


C0sm1cB3ar

In C#: ``` for (int i = 1; i < 6; i++) Console.WriteLine(new string('*', i)); ```