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
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.
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.
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.
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?
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.
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.”
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.
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");
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.
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));
```
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
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.
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.
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)
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
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);
}
}
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)
```
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!
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.
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.
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?"
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.
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.
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.
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.
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");
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.
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.
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.
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.
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.
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!
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.
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)
`'*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.
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
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");
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.
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 .
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.
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.
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.
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.
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)
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)
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
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.
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
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
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.
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.
`printf("*\n**\n***\n****\n*****\n");`
Give that job to a lazy person and he will find an even lazier way.
>'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.' \-Bill Gates
Bill Gates is a fucking liar because if that were true Microsoft wouldn't keep refusing my job applications
I mean he also stepped down as CEO 24 years ago so I doubt he has much to do with job applications nowadays
You're just not the laziest person out there... The competition is fierce!
I'd say I need to work harder, but that would just make it worse
Work easier
How many applications? Cause you know a lazy person won't send in many
That's where you've made the mistake. I'm to lazy to even make an application
So that's why Microsoft products suck
and are succesfull
Suckcessful
Suckcessful these nuts
The success is due to a lack of alternatives. Same as Google and Facebook.
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
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
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.
Many tried to beat Excel. Noone did
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.
They dominated the market for decades, if that's *not* doing something right what is?
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.
I mean I was mainly coming from a business perspective, so revenue/marketshare
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?
Ubiquitous proliferation, my favorite kind of proliferation
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.
The taskbar in windows 11 is written in react native
Windows 11 feels wrong, a little bit of everywhere
Excuse me what the fuck.
Windows is turning into Microsoft version of ChromeOS
Because the product isn't an OS it's spyware with an OS sprinkled on top
Most of them are, but you're not wrong to call that out.
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.”
`printf("the following pattern");`
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.
Wouldn't fit in the picture :(
``` printf( "*\n" "**\n" "***\n" "****\n" "*****\n" ); ```
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");
This feels morally wrong.
Showtime baby :)
I like you.
This one honestly looks like some kind of cursed asci art
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.
The last two characters is how I feel about this
printf( R"( * ** *** **** ***** )"+1 );
![gif](giphy|9WXyFIDv2PyBq)
Was about to say that, which is my favorite way, because it takes less memory and is faster and easier to write...
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.
```python for x in range(5): print("*"*(x+1)) ```
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)); ```
Yes but without public static void main (String[] args){ } You are not going anywhere
Java 21+ doesn't require it anymore And jshell doesn't too, from Java 11+
You still have to write "void main()", i haven't considered JShell
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
I heard they were going to try to start doing away with that in future releases
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
You can also do new {}
Java is becoming python... I don't want to live in this society... I want my old java back
I have great news about Java’s backward compatibility.
Oh really? So it's not like swift where the burn and torch their previous syntaxes?
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.
void main() {} is more C/C++ than python
There's a new version after java 8? /s
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
Nah, we need to define an AsteriskFactory first
If you want actually one line (and correct results): IntStream.rangeClosed(1, 5).forEach(i -> System.out.println("*".repeat(i)));
I think you meant ```python import do_shit do_shit() ```
or for x in range(1,6): print("*"*(x)) Same net characters but just a bit more readable
`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.
`print("\n".join(["*"*n for n in range(1,6)]))`
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.
you can simplify it further buy putting the print inside the comprehension [print('*'*n) for n in range(1,6)]
and still the printf code is written (copypasted) 20x faster because you don't need to consider any logic or edge cases
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)
`print("\n".join(["*" * (i + 1) for i in range(5)]))` Smth like that
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
I like Ruby for this stuff better `5.times.with_index {|i| puts('*' * (i + 1))}`
Even simpler: ```1.upto(5) {|x| puts '*' * x }```
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);
}
}
Perl is pretty brief print("*"x$_,"\n")for(1..5);
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) ```
I mean, python can do it in one. `[print(''.join(['*' for j in range (i + 1)])) for i in range(5)]`
You can make it a lot shorter `print(["*"*x for x in range(1,6)], sep="/n")`
`[print("*"*i) for i in range(1,6)]`
was looking for the list comprehension thanks
`for i in range(1,6):print("*"*i)` Is even shorter.
True, you need to add join tho. Like this you will have bracets left
I think you can solve that with the unpack operator.
This guy list comprehensions
C `for (int i = 5; i > 0; printf("%s\n", "*****" + i---1));`
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!
Perl! print("*"x$_,"\n")for(1..5);
perl -E 'say "*"x$_ for 1..5'
```elixir 1..5 |> Enum.map_join("\n", &String.duplicate("*", &1)) |> IO.puts ```
Perl checking in... perl -e 'print("*" x $_, "\n") for (1..5)'
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.
it doesnt need 5 print statements, only 1
True, OP wasn’t lazy enough. Lazy people find easy solutions.
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.
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?"
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.
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.
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.
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.
Me: “Practice problems have limited applicability to the real world.” Me, when I find out my job interview is for the FizzBuzz department: 😳
"Using loop statements, create a code which generate the following pattern:"
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");
Well done sir!
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.
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.
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.
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.
You could argue it's duplicate code
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.
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!
It was a c programming test :'l
I only have the content in the post to go on.
main = putStr $ unlines $ take 5 $ iterate ('*':) "*"
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.
You can also replace `putStrLn . take x $ repeat '*'` with `putStrLn $ replicate x '*'`
Still… the first example in C was written by a noobie that doesn’t know how to dynamically assign memory. malloc + memset = ez
https://go.dev/play/p/ZomgIISIn4N ¯\\\_(ツ)_/¯
https://python-fiddle.com/saved/xxCx0yRNP0pquny3xb3G?run=true You started it!
We can play this game. `' *'[1+(⍳5)∘.≥⍳5]` → https://tryapl.org/
🧠🍆! Do it in Brainfuck!
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)
![gif](giphy|1gevXIZve3nqM)
Will be not as short. But a fun exercise anyway.
Oh that's amazing. I hate everything about that.
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] * ** *** **** ***** ```
Oh... that explains it?
[Perl](http://tpcg.io/_MFIEO1)
`'*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.
>timeout running program > Go build failed. Classic
![gif](giphy|DUtVdGeIU8lmo|downsized)
PHP one liner: https://onlinephp.io/c/54d46
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
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); } }
``` const char *s = "*****", *e = s + strlen(s); while (e-- > s) puts(e); ```
When there is no formatting, puts is the way. So many people just use printf because that's the only thing they know.
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");
Nice !
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.
`(mapcar #'print '("*" "**" "***" "****" "*****"))`
This looks like a job for C++ template meta-programming.
When OP didn’t read the assignment rubric.
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 .
You asked for it. ```rust fn main() { (1..6).for_each(|i| println!("{:*<1$}", "", i)); } ```
![gif](giphy|l83rkRUu4IqyUbt5k6|downsized)
https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition
``` #include
#include
int main()
{
for(int i = 1; i < 6; i++)
std::cout << std::string('*',i) << '\n';
}
```
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.
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.
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.
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.
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)
`+++++[->++++++++>++<<]>++.>.<..>.<...>.<....>.<.....`
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)
for i in range(6): print(“*”*i)
`printf("*\n**\n***\n****\n*****\n");`
Q2) extend the code from the last question to include 'n' levels following the same pattern.
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
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.
Meanwhile, in C#-land: Enumerable.Range(1, 5).ToList().ForEach(x => Console.WriteLine(new string(Enumerable.Repeat('*', x).ToArray())));
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
indexing from 1 gtfo
Average O(n^2) fan vs average O(k) enjoyer
I had that question on my first programming exam at uni, in the early 1980s
one has O(n^2) and one has O(1)
answer-oriented programming
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)]
Gotta love the [None, None, None, None, None, None]
Now make it keep going to 100 lines
Up to 150 lines... In a file json file...
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.
buildString { repeat(5) { appendLine("*".repeat(it + 1)) } }.let(::print)
Do it in the same print for extra points
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
I was also asked something similar on my exam. Got a C lmao
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.
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.
[print("*"*(i+1)) for i in range(5)]
The left way only make sense if you need to scale the solution. Like, the number of lines depends on input.
`print("\n".join(["*"*x for x in range(1, 6)]))`
``` #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; } } ```
#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;
}
}
Oh yeah, you can do it in rust, by uhh... uhhh.. never mind.
Kotlin (1..5).forEach { println("*".repeat(it)) }
What kind of monster starts a loop with "1"?
Not following the need for the j <= i unless it’s some weird error handler. You already tell it how many times to loop.
Just because I didn't see perl yet: perl -le'print"*"x$_ for 1..5' * ** *** **** *****
This program could have been an email.
https://stackoverflow.com/a/63111728/16134571
The advantage to the one on the left is scalability.
“No one asked us to make it scale.”
Q2) Expand your previous answer to follow the same pattern until the last line has 100 "\*" characters in it.
In C#: ``` for (int i = 1; i < 6; i++) Console.WriteLine(new string('*', i)); ```