#include <iostream>#include <fstream>#include <sstream> // for string streams#include <string> // for stringint main() { ostringstream str1;std::ofstream file("index.cpp");
// Write the initial code to the filefile << "#include <iostream>\n\nint main() {\n ";// Generate the code to write the numbers 1 to 100for (int i = 1; i <= 100; i++) {str1 << i;file << "std::cout << " <<i.str()<< ";\n ";}
// Write the final code to the filefile << "return 0;\n}";// Close the filefile.close();
std::cout << "Code generated successfully and savedto index.cpp!\n";
It looks like C, it's possible it is also explaining the assembly behind it and expects OP to recreate the approach using a label and if(...) goto approach.
It was something we had to do in our college computing class to make sure we understood what was happening when we used higher level features(like function calls, C++ objects, etc).
They're all forms of loops though, just different high level ways of writing it
The only way I can think about getting around it is enforcing unrolling. I think you may be able to hack your way around this with some form of recursive include if you can't use pragmas, but I guess that's loops at a high level but not low... The given solution is the only way I can see to do it without either.
Recursion is a loop in the sense that the same code is running many times, but each iteration would have it's own stack frame. It also wouldn't use any of the loop constructs built into the language.
If I was the instructor, and one of my students used recursion as a solution, then I'd give them full marks as long as they understood what the compiler would produce, and what would happen at run time.
Now, if the directions were to print every even number from 2 to 1 trillion, and they used recursion as a solution, then I'd smack them on the back of the head and tell them to try again.
Eh, tail recursion is just a form of loop with a funny syntax. That's what I told my interviewer, anyway; we had a little discussion of how TR works and its limitations, no big deal.
Maybe throw in an error check to make sure print_me is valid.
Could also be an exercise in using a label with goto. Assuming this is a real assignment, you'd have to have the context given to students to know what is desired. Could even be about benchmarking a loop versus hardcoding the answer directly.
That is a good point, I guess rather than trying to define things explicitly I will just say that a goto with a conditional tends to compile out to something indistinguishable from a while loop and that something has a structure more similar to the goto structure and is something I think most of us look for when we're reading assembler. We do sometimes jump backward when not in a loop, jumping back to a buffer block for instance, but when we jump back to a conditional after a state change like an increment without making a new stack frame, to me that is what a loop is. I guess that is less explicit a definition than I used to believe it to be, I will agree just including a jump with no new stack does not cut the mustard.
If I was going to judge these kind of answers on some kind of continuing to award prizes; in other words, if I want make a loosely justifiable hierarchy, and not one that I have to defend in front of a tenure committee:
I’m more referring to the fact that I like to treat homework in programming classes as “logic puzzles” and as a result the shortest possible solution is the one I gravitated to.
The code I actually use is a lot more verbose but a hell of a lot more readable
The first time I used a loop back in vb6.0 I didn't like that sometimes I got an off-by-one error depending on what I was doing. It bugged me so much that I ended up implemented a goto by opening 2 forms that would open each other over and over again whilst decrementing a counter and running code and stopping on a condition
My teacher told me I had set programming back by 30 years
without a loop and without recursion (in python 3):
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
a = 250
b = 10 ** 3
c = b ** a
d = b * c
e = b - 1
f = a * (e * (c-1) + c - d) + d - b
g = (f*2) // (e**2)
formatted_output = locale.format_string("%d", g, grouping=True).zfill(e).replace(',', '\n')
print(formatted_output)
I couldn't find my original, but I threw this at it:
if (action.equals(ActionEnum.INIT_SELECT) && (me instanceof ValidationException)) {
initSelect(action);
} else if (action.equals(ActionEnum.GET_VAL) && (me instanceof ValidationException)) {
initNewVal(action);
} else if (action.equals(ActionEnum.ADD_VAL) && (me instanceof ValidationException)) {
initNewVal(action);
} else if (action.equals(ActionEnum.MOD_VAL) && (me instanceof ValidationException)) {
initNewVal(action);
} else if (action.equals(ActionEnum.SHOW_VAL) && (me instanceof ValidationException)) {
initNewVal(action);
} else if (action.equals(ActionEnum.DEL_VAL) && (me instanceof ValidationException)) {
initNewVal(action);
} else if (action.equals(ActionEnum.INIT_SELECT_MAN) && (me instanceof ValidationException)) {
initSelectMan(action);
} else if (action.equals(ActionEnum.INIT_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
} else if (action.equals(ActionEnum.GET_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
} else if (action.equals(ActionEnum.MOD_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
} else if (action.equals(ActionEnum.SHOW_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
} else if (action.equals(ActionEnum.DEL_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
} else if (action.equals(ActionEnum.SELECT_MAN) && (me instanceof ValidationException)) {
initNewMan(action);
}// And then there was this
else if (action.equals(ActionEnum.MOD_VAL) && me.getMessageCode().equals(MessageConstants.MSG_1004)) {
initNewVal(action);
} else if (action.equals(ActionEnum.DEL_VAL) && me.getMessageCode().equals(MessageConstants.MSG_1007)) {
initNewVal(action);
} else {
System.out.println("NOPE!");
}
And got this back:
if (me instanceof ValidationException) {
String newAction;
switch (action) {
case ActionEnum.INIT_SELECT:
newAction = action;
break;
case ActionEnum.GET_VAL:
case ActionEnum.ADD_VAL:
case ActionEnum.MOD_VAL:
case ActionEnum.SHOW_VAL:
case ActionEnum.DEL_VAL:
newAction = ActionEnum.MOD_VAL;
if (me.getMessageCode().equals(MessageConstants.MSG_1004) && action.equals(ActionEnum.DEL_VAL)) {
newAction = action;
}
break;
case ActionEnum.INIT_SELECT_MAN:
case ActionEnum.INIT_MAN:
case ActionEnum.GET_MAN:
case ActionEnum.MOD_MAN:
case ActionEnum.SHOW_MAN:
case ActionEnum.DEL_MAN:
case ActionEnum.SELECT_MAN:
newAction = ActionEnum.MOD_MAN;
break;
default:
System.out.println("NOPE!");
return;
}
if (newAction != null) {
if (newAction.equals(ActionEnum.INIT_SELECT)) {
initSelect(newAction);
} else if (newAction.equals(ActionEnum.MOD_VAL)) {
initNewVal(newAction);
} else if (newAction.equals(ActionEnum.MOD_MAN)) {
initNewMan(newAction);
}
}
}
Could be a good look lesson for embedded style systems to show that in real life sometimes it may be better to precalculate the results to give a faster response .
Also it's probably the only way to do it as gotos and even compares may induce a loop so just give the person the result and collect the payment and run like fk..
Could be a good look lesson for embedded style systems to show that in real life sometimes it may be better to precalculate the results to give a faster response .
At which point we enter the fun field of code generation, which has a lot of uses, when languages (or language tooling) hits their limits.
The first time I passed the 200k on a solo project I felt proud for a sec. Then they sent me a major change of specs last minute and almost jumped off a bridge.
def print_even(num):
if num > 500:
return
if num & 1 == 0:
print(num)
print_even(num >> 1 << 1 | 2)
# Call print_even for 0 (the first even number)
print_even(0)
Why would you try to replace num += 2 with three instructions? And it's not even correct... this is a major case of trying to make confusing code to be cool instead of trying to write clean code that also works and is faster.
import subprocess
with open("loopless.py", "w") as f:
for i in range(2, 501, 2):
f.write(f"print({i})\n")
subprocess.check_call(["python3", "loopless.py"])
It's a memory addressing error, when you try to access a protected memory.
String literals in C are pointers, and adding a number to pointer produces new pointer. So, this code will print "\n", then it will try to print a string located in memory after "\n", which is probably incorrect, and so on. There's a great chance of running into SEGFAULT this way.
For one, the assignment was to do this without a loop. Secondly, your solution starts at 0 when theirs starts at 2. Lastly, that isn't how printf works.
This is what code golf looks like with C++ metaprogramming. Write a template which generates code for printing even numbers from 0 to 500, fastest possible solution
May not be as fast as you think. Instructions are also cached, so sometimes, a loop is faster than puking out all the code.
This isn't how performance works. The only way to know is to test it. Caching can make code that seems more/less efficient be less/more efficient. Instruction count is a crude approximation that is full of error - it doesn't take into account caching, not all instructions execute in the same timeframe, and there are data dependencies between some instructions (which can hinder parallel execution of instructions) among other things. I only know the surface of performance computing, but it seems like you know even less than that and insist on commenting about the topic for some reason.
As a simple example of how a cache can impact performance, the fastest way to find if an integer is in a small set of integers is to store those integers in a contiguous chunk and do a brute force check. It will outperform a hash map for some sizes due to the insane speed caching can bring. Similarly, when sorting a small array, selection sort (O(n2 )) can be much faster than a more sophisticated algorithm that has a higher constant in its time complexity / that isn't a rapid reading of cached data.
232
u/This_Growth2898 May 03 '23
145
u/pikapichupi May 03 '23
the only other way i could see this being done is by using a recursive function lol
94
u/Borisica May 03 '23
printf("all even numbers from 1 to 500");
119
u/This_Growth2898 May 03 '23
No loops!
7
u/wischichr May 03 '23 edited May 04 '23
without a loop and without recursion (in python 3):
https://ideone.com/FUMlqF
22
u/[deleted] May 03 '23
I'd ask ChatGPT, then blindly copy/paste whatever code it spits out... I'm a really skilled developer.
10
u/[deleted] May 03 '23
Could be a good look lesson for embedded style systems to show that in real life sometimes it may be better to precalculate the results to give a faster response .
Also it's probably the only way to do it as gotos and even compares may induce a loop so just give the person the result and collect the payment and run like fk..
2
u/AdventurousSquash May 03 '23 edited May 03 '23
1am bash
2
u/[deleted] May 04 '23
No loops doen't mean you can't be lazy.
select last line, ctrl-c, ctrl-v 499 times. Or just
dd500pin vim.4
u/Borisica May 03 '23
response = get_completion("print all even numbers from 1 to 500")
print(response)
3
u/etocasper sadistic May 03 '23
And what is he wrong about...
2
u/ja_maz May 03 '23
The first time I passed the 200k on a solo project I felt proud for a sec. Then they sent me a major change of specs last minute and almost jumped off a bridge.
2
u/BenBastard May 03 '23
And here I am getting a for loop ready like a barbarian.
1
u/gpathak May 03 '23
Elon would be proud! So many lines of code!
1
u/moldor_the_flatulent May 04 '23
Here's a start;
# Python program to print all even numbers in range
for even_numbers in range(0,102,2):
print(even_numbers,end=' ')
1
u/am_edmonstone May 04 '23
def p_even(s,e):
if s>e:
return
print(s)
print(s+2,e)
//function ends here
//init the method
p_even(2,500)
1
u/amosreginald_ May 04 '23
Recursion?
1
u/bluebird_ai May 04 '23
1
u/yodacola May 04 '23 edited May 04 '23
Thinking too small here…
int main() { int i; while (i=fork()) printf(“%d\n”, i % 250 * 2 + 2); }Edit: Even numbers lol
1
u/horenso05 May 04 '23
I hope they did use a loop to create this code.
1
u/ivanskodje May 04 '23
I suspect they wanted recursive code (albeit beating around the bushes instead of directly asking for it).
I had to google the C syntax, but i think this would work:
1
u/Electrical-Mission27 May 04 '23
It's not even correct you missed 1.
1
u/NickSicilianu May 04 '23
What about if you make a program to write that program 😂😂 just saying
1
u/Valuable-Rush-1532 May 05 '23
This is just amazing.
1
u/Heinrich_v_Schimmer May 03 '23
void foo(int n)
{ if (n > 0) foo(n-2);
printf("%d\n", n);
}
int main()
{ foo(500);
}
1
u/freeve4 May 03 '23
i think i know where this person should work...
1
u/[deleted] May 03 '23 edited May 03 '23
for python
1
u/aNutSac May 03 '23 edited May 03 '23
0
u/kireina_kaiju May 03 '23
yy249pq1|f"lyejF"lvep<Ctrl>a<Ctrl>aq248@21
0
u/s2004Gamer May 03 '23
int n = 2; int main() { printf("%d", n); n += 2; if(n != 500) return main(); return 0;
0
u/RoadRunnerChris May 03 '23
looplessTM
-1
u/thekwoka May 03 '23
0
u/Alt_0126 May 03 '23
char numbers[2000]; //max of 500 numbers of 3digit + 1comma
printf("Write all even numbers from 1 to 500\n");
fgets(numbers, sizeof(numbers), stdin);
printf("%s\n", numbers);
-2
u/Friendputer May 03 '23
In Clojure: (run! println (range 2 500 2))
-1
u/Eggimix May 03 '23
Who are you bart simpson
-1
u/kewlness May 03 '23 edited May 03 '23
Edit: Formatting is hard...
-1
u/TransportationNo6850 May 03 '23
Use a for that increments +2?? Why not?
-1
u/Zdravstvuyte94 May 03 '23
Wait, is there actually a better way to do this?
-1
u/fiddz0r May 03 '23
I would like to use string.join but I can't think of a way to let it know whether to split every 1 numbers, 2 numbers or 3 numbers.
Of that was solved wed just have to find a formula that results in 2468101214161820.....500
And then we do the strong.join('\n', veryBigNumbe)
-1
u/Biden_Been_Thottin May 03 '23
Turing incomplete typa mf
-1
u/lumo19 May 03 '23
Hear me out:
No loops involved. Just a string and an eval statement.
-2
u/R3D3-1 May 03 '23 edited May 03 '23
Solving the problem both with and without a loop:
Or in Python:
-5
u/Ecstatic_Student8854 May 03 '23
For(int i=0;i<501;i+=2){ Printf(“\n”+i);}
0
u/[deleted] May 04 '23
[deleted] — view deleted comment
0
u/[deleted] May 03 '23
[deleted] — view deleted comment
0
u/[deleted] May 03 '23
[deleted] — view deleted comment