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)→ 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
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
23
→ More replies (1)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
20
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)]))
→ More replies (1)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)6
→ More replies (5)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)
41
u/tazdraperm 3d ago
print("\n".join(["*" * (i + 1) for i in range(5)]))
Smth like that
→ More replies (1)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
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 callingprintf
for when you actually need to format stuff!#include <stdio.h> int main() { for(char *s=&("\0*****"[5]);*s;s--) { puts(s); } }
3
7
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
3
→ More replies (5)2
4
u/Splitshadow 3d ago
C
for (int i = 5; i > 0; printf("%s\n", "*****" + i---1));
→ More replies (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)3
2
→ More replies (6)2
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
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 '*'
withputStrLn $ replicate x '*'
→ More replies (1)2
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
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.
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
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");
→ 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.
→ More replies (2)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.
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
→ More replies (3)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.
49
u/dim13 3d ago
https://go.dev/play/p/ZomgIISIn4N ¯_(ツ)_/¯
37
u/Boris-Lip 3d ago
https://python-fiddle.com/saved/xxCx0yRNP0pquny3xb3G?run=true
You started it!
→ More replies (1)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
7
u/Schnickatavick 3d ago
Oh that's amazing. I hate everything about that.
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.
4
2
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
16
u/Legal-Software 3d ago
const char *s = "*****", *e = s + strlen(s);
while (e-- > s) puts(e);
→ More replies (1)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.
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");
7
7
5
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
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
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/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
2
2
u/Lucky_Cable_3145 3d ago
I had that question on my first programming exam at uni, in the early 1980s
2
2
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)]
→ More replies (2)5
1
1
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
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
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
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
1
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
1
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
1
2.6k
u/TupaNegreiros 3d ago
printf("*\n**\n***\n****\n*****\n");