r/badcode • • Jul 17 '20

js Found this "answer" on Stackoverflow. Pretty sure it's not working.

Post image
978 Upvotes

90 comments sorted by

342

u/alexsteb Jul 17 '20 edited Jul 17 '20

min = array[i + 1] ........... I assume that worked with the special set of numbers they tried it with..

67

u/LoyalSol Jul 17 '20

It has to be some sort of strangely sorted list or something. Only way I could see that being a thing.

0

u/[deleted] Jul 17 '20

[deleted]

34

u/jamestadleygreen Jul 17 '20

You could just take array[-1] then?

0

u/[deleted] Jul 17 '20

[deleted]

25

u/FizixMan Jul 17 '20

Lovely index out of range failure when the last item in the array is the smallest value.

I'm kidding of course. There are no failures in Javascript.

3

u/Andersmith Jul 17 '20

it'd just be null, yeah.

10

u/FizixMan Jul 17 '20

Well, undefined I think. Same difference, right?

1

u/[deleted] Jul 18 '20

Well, is undefined equal to difference?

4

u/FizixMan Jul 18 '20

Let's find out!

var difference;

if (undefined == difference)
    alert("I guess so!") ;

Yup!

1

u/Raknarg Jul 17 '20

Only if the list has an even amount of items

6

u/Raknarg Jul 17 '20 edited Jul 17 '20

It would work as long as the minimum and the second minimum items are the last thing in the array, and the third minimum item is not right before the second, unless the fourth item is directly before it, but not if the fifth item is directly before it, unless the sixth item is before it, but not if the seventh items is before it, etc.. to the beginning of the list.

In other words as long as there is an even-length chain of minimum descending numbers at the end of the list it should work

1

u/emilsteen Jul 19 '20

He did give an example where the lowest number was first. I guess his test cases are as bad as his code.

17

u/[deleted] Jul 17 '20

i am ashamed to say i have done similar in c, not knowing of any better way

73

u/emilsteen Jul 17 '20

Just add a few extra "min = min" and you are safe.

2

u/[deleted] Jul 18 '20

I need the stack overflow link, it's comedy gold

1

u/emilsteen Jul 18 '20

You are not supposed to shame people here, but I will send a pm link if I find it again.

1

u/[deleted] Jul 18 '20

I just want to share it with my friends

14

u/[deleted] Jul 17 '20

ye those help a lot

37

u/Spire Jul 17 '20

Extra assignments for extra credit. A+.

114

u/MistAway Jul 17 '20

Gosh. This stuff is just plain psychedelic

And if your really need that solution:
const arrayMin = arr => Math.min(...arr);

33

u/popadi Jul 17 '20

In JS the spread operator fails if the length of the array is bigger than 65536. Also, it's at least two times slower than an equivalent for loop.

17

u/galaktos Jul 17 '20

In JS the spread operator fails if the length of the array is bigger than 65536.

In what engine? This works in both Firefox and Node:

Math.max(...Array(100000).fill().map((_, i) => i))

In Firefox, it stops working at Array(500001) (“too many function arguments”); in Node, at Array(123059) (“maximum call stack size exceeded”, might not be directly related to the number of arguments).

9

u/droomph Jul 17 '20 edited Jul 17 '20

https://stackoverflow.com/questions/22747068/is-there-a-max-number-of-arguments-javascript-functions-can-accept

But given it’s Chrome 33, it’s most likely just out of date.

Edit: nup it’s still 62866 on Chrome for some reason, probably stack size

Edit 2: maybe it’s because v8 compiles eagerly while spidermonkey does lazy compilation, but I don’t quite remember if that still holds nowadays

Edit 3: pertaining to the question at hand, it actually has come up with String.fromCharCode, and the solution was obviously just to chunk it over a certain string length.

7

u/Schlipak Jul 18 '20

Here's a faster version using reduce :

const arrayMin = arr => arr.reduce((min, v) => Math.min(min, v));
Setup JavaScriptconst arr = Array(10000).fill().map(() => ~~(Math.random() * 10000));
Array spread3136.76 ops/s ± 0.89%30.47 % (slower)
Reduce4511.52 ops/s ± 0.75% (Fastest)

3

u/[deleted] Jul 18 '20 edited Jul 18 '20

[removed] — view removed comment

2

u/DelishMango Jul 18 '20

Youre skipping the first element in the array. Did you maybe mean to say minimum = arr[0]

1

u/xjcl Jul 19 '20

In JS the spread operator fails if the length of the array is bigger than 65536

Oh my God. I started a JS job on July 1st and I just keep hearing these nasty surprises and I already regret it.

-37

u/AutoModerator Jul 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

MistAway, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

83

u/the_poope Jul 17 '20

How come that the bots are smart enough to detect the code block formatting, but reddits formatting engine can't just format both styles correctly. Does reddit even have a single capable webdev employed or is it all marketing/advertising people nowadays like in all other corporations?

25

u/scirc Jul 17 '20

Technically, triple-backtick code blocks aren't part of the original Markdown design. But then again, Markdown has no formal specification... the closest thing is CommonMark.

Besides that: new reddit does support triple-backtick, just old reddit doesn't. Why they're even using different renderers? Who knows.

9

u/the_poope Jul 17 '20

Indenting every code line, including blank lines, with four spaces is just ridiculous. So whoever came up with the original markdown specification fucked up and deserves to manually fix all the badly formatted code on this site by hand from now to eternity...

6

u/scirc Jul 17 '20

I believe Markdown was based off of text-based email formatting, where such practices were common. Of course, fenced code blocks are much easier to type, but they look a bit worse when displayed without formatting.

I'm not saying it's a good thing, of course. I like fenced code blocks, but I can understand why the original design didn't include them.

2

u/moekakiryu Jul 17 '20

as someone who loves plain text formatting in general, I'm a bit more partial towards the indented format, but do appreciate the need for triple backticks, especially on mobile

0

u/[deleted] Jul 17 '20

[deleted]

1

u/the_poope Jul 17 '20

But on mobile it sucks having to format just three lines of code.

6

u/Lightfire228 Jul 17 '20 edited Jul 17 '20

They (sort of) explain it here

tl;dr, the old markdown engine is a mess and can't be easily updated, the new one has a different rule set, and for whatever reason, they can't [yet] use the new engine with old reddit

(if your reddit client doesn't jump to the right section, look for the "Rationale for transitioning to CommonMark" section, near the bottom)

6

u/Poddster Jul 17 '20

The bot is written by reddit moderators, who are competent.

Reddit is written by the reddit staff, who aren't.

-3

u/hamza1311 Jul 17 '20

This bot is also configured in yaml whereas Reddit is written in actual programming language

1

u/zacharypamela Jul 17 '20

Since this post relates to SO: I do like their pre-submission preview. Also, they fully support code fences. Although not tables yet…

15

u/seniorpreacher Jul 17 '20

Works great on arrays with 1 element

5

u/seniorpreacher Jul 17 '20

Also on already sorted arrays of any length

8

u/Smithmonkey98 Jul 17 '20

I was like "well yeah the unnecessary assignments are very odd but it'll work!" Then I saw 'i + 1' and just got frustrated and angry

5

u/jnguyen7410 Jul 17 '20

I spy with my little eye a potential IndexOutOfBoundsException...

4

u/fvasi Jul 17 '20

You should just trust the comment.

10

u/Simply2Pro Jul 17 '20

Just a quick


const smallestElementOfArray = (arr: number[]) => {
    let min = arr[0];

    for (let el of arr) {
        if (el < min) min = el;
    }

    return min;
} 

Would do the job

1

u/AutoModerator Jul 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

Simply2Pro, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/megaman97897 Jul 17 '20

Where to begin...There should only be one if statement there as the other cases are redundant (only the case where min is greater is necessary), and the use of a for loop instead of just doing an array.reduce is stupid, and the obvious they indexed to the wrong value for changing the value of min.

2

u/TheLucatus27 Jul 17 '20

W-What is happening there?

2

u/n_ullman176 Jul 18 '20 edited Jul 18 '20
// do handling for edge cases    
var min = array[0];
for(i=1;i<array.length;i++){ if(min>array[i]) { min=array[i]; } }

3

u/developerzero Jul 18 '20

This is the correct answer, but I would make just one small thing to make it cleaner and more logical: change the if to

if(array[i]<min)

When reading the code it's a slightly cleaner way to show you've found a smaller number than the previous smallest number.

2

u/ddnfdve Aug 11 '20

As my professor likes to say: Use Google.

1

u/[deleted] Jul 17 '20

That stresses me out.

Makes me very thankful we don't live in a world without built-in methods.

1

u/algoritm420 Jul 17 '20

How dare you make me look at this with my own two eyes!

1

u/Not_Sugden Jul 18 '20

arr.reduce((num, next) => next < num ? next : num, 0);

1

u/[deleted] Jul 18 '20

This scares me

1

u/[deleted] Jul 18 '20

Min IS min

1

u/MorphTheMoth Jul 18 '20

you were very desperate to search for this tho

1

u/[deleted] Jul 18 '20

It would have been easier and prettier to just go with:

function min(arr) {
    return arr.reduce(
        (acc, val) => (acc > val ? val : acc),
        0
    );
}

-3

u/Yangishrobin Jul 17 '20

This kids, is why we use Python. Where can do lisst.sort(), then list[:1]

106

u/[deleted] Jul 17 '20 edited Jul 17 '20

[removed] — view removed comment

116

u/Gooftwit Jul 17 '20

And the min = min is also bot necessary

110

u/frankferri Jul 17 '20

I really enjoyed that part actually, I kind of wonder what was going through their head at that point

44

u/vigbiorn Jul 17 '20

OCD of programming? Constantly have to check the memory every cycle or the program will crash.

8

u/frankferri Jul 17 '20

is there a language in which this makes sense?

6

u/vigbiorn Jul 17 '20

I have no clue. If there is, it's not a production language. I know at least the basics of the more common production languages. Or maybe a scripting language meant for small, fast processing. It would be a kind of efficient. No need for garbage collection if the space is guaranteed freed in a few cycles.

4

u/leonardishere Jul 17 '20

Possibly a hypothetical language with some kind of loop scoping. I hope such a language doesn't exist

1

u/frankferri Jul 18 '20

Poopity loopity scoop

0

u/[deleted] Jul 17 '20

[deleted]

8

u/[deleted] Jul 18 '20

Liked the idea. Almost finished it. I'll go to sleep since it's 6:30 AM where I live, but I will publish it soon. I'll reply to this message.

7

u/[deleted] Jul 18 '20

Done. I added a little bit of spice to it.

2

u/SuperSupermario24 while True: print("owo") Jul 18 '20

That... actually sounds kinda cool.

7

u/timleg002 Jul 17 '20

I think its to show beginners, absolute beginners to show the value stays the same.. not sure why it wasn't a comment.. and they should understand that logic if they want to learn programming lol

2

u/Mr2-1782Man Jul 17 '20

There wasn't anything going through their head at that point. I see students make this mistake all the time. The blindly code without understanding what the code is suppose to be doing so they just throw ever condition in there because that's all they know.

1

u/[deleted] Jul 17 '20

this looks like a result of a student writing something that almost works, but without understanding how or why, and then changing things at random until the code works for the one input they have prepared. I wrote quicksort for class this way

2

u/[deleted] Jul 17 '20

Well it’s not necessary but it’d work

26

u/DeliciousConfections Jul 17 '20

I cannot figure out what their thinking was behind that +1.

5

u/therealpussyslayer shameless Jul 17 '20

Isn't it common knowledge, that the first value of an array is insignificant?

5

u/gaj7 Jul 17 '20

Ya I mean the basic strategy of folding over the array and accumulating a min value is on point. The identity assignments are what makes it bad style, the off-by-one error makes it wrong.

0

u/[deleted] Jul 17 '20

[deleted]

13

u/FizixMan Jul 17 '20

Takes too long. You're checking each value one at a time. Instead you should spin off a thread with a sleep timeout equal to the value. The first one that competes gets its value returned. That way you're checking each value simultaneously and you avoid the overhead of having to do an if check on each one or even having to check each value. Once the smallest value completes, you can just ignore all the other ones. It's basically an O(1) operation at that point rather than O(n).

8

u/mgrier123 Jul 17 '20

Ahh, good ole Sleep Sort

4

u/stratoscope Jul 18 '20

The best thing about this approach is that if the array contains any negative numbers, you will get the result back before you start the search!

2

u/erinyesita shameless Jul 17 '20

Now this is badcode!

2

u/Nythe08 Jul 18 '20

But that's O(n) because you have to iterate through the list to spin off all the threads!

1

u/Andersmith Jul 17 '20

wouldn't a zero-length array also return null in op's code? Since any array index not set is by default null?

0

u/[deleted] Jul 17 '20

[deleted]

1

u/Andersmith Jul 17 '20

Yeah you guys are right. Hard to remember sometimes