What do you think? Should I hire him?

Grayson Stewart
Grayson Stewart

What do you think? Should I hire him?

Attached: signal-2018-03-28-101758.png (20 KB, 618x480)

All urls found in this thread:

github.com/id-Software/DOOM/blob/77735c3ff0772609e9c8d29e3ce2ab42ff54d20b/linuxdoom-1.10/r_draw.c
lmgtfy.com/?q=gotofail

Bentley Lopez
Bentley Lopez

this looks like something you could find on stackoverflow

Charles Jenkins
Charles Jenkins

Given the task, that's expected.

Ian Williams
Ian Williams

No, this is absolutely awful.

Jaxon Rogers
Jaxon Rogers

Yeah, sure. At least he knows how to use statics. This is probably about as good as you're going to get for a java programmer.

Ethan Reed
Ethan Reed

i mean i don't want to be a dick but this is just basic java. there's seriously nothing innovative about this. if you're looking for someone that just knows java, yea go ahead i guess. You're asking Sup Forums for business decisions so don't expect too much

Eli Foster
Eli Foster

that terrible tabbing and not putting curly braces on their own line

I wouldn't

Julian Gonzalez
Julian Gonzalez

how would you write it better?

Hunter Gomez
Hunter Gomez

method is called reverseString
doesnt reverse the string
wow

Thomas Cooper
Thomas Cooper

yes i would, this code is fine

Angel Morales
Angel Morales

there are two ways of putting curly braces, it makes no difference while the program executes, unless you're autistic and you need another space for a curly bracket or to increase the number size of your code to look as if you put in more work go for it i guess

Xavier Davis
Xavier Davis

+statics
+correct regex
-improper array declaration
-looping over the wrong value

It doesn't count against him, but I would have liked to see a test and a StringBuilder. There's pressure to hire him just to secure that part of the budget, but I'm not happy about it.

Ryder Thompson
Ryder Thompson

Isn't that output variable an array instead of string as requested? (I dont code java)

Cooper Torres
Cooper Torres

The declaration for output is wrong and this will not compile.

Lincoln Ward
Lincoln Ward

-looping over the wrong value
please explain

Camden Smith
Camden Smith

I would not hire him and by him I mean OP. This is clearly some shit homework.

all this aside, the code is garbage, he splits into an array are you kidding me? this is some entry level shit at best.

How to do it correctly:

set the output string length to be same as input string.
initialize a char pointer to the last char of the input string,
if last char is space then dec pointer until you hit a none-space char, otherwise dec until you hit space.
great, here's your first char word or spaces only word, memcopy that to the start of the output string.

etc...

next time do your own homework kiddo.

Asher Roberts
Asher Roberts

the fuck is a char pointer in java

Justin Morgan
Justin Morgan

he wants to reverse the string, but hes taking the 0th value of the split array, that being the first word of original string

Daniel Russell
Daniel Russell

  
s ="this is a test".split(" ")
print(" ".join([s[x] for x in range(len(s)-1 ,-1 ,-1 )]))

Nathaniel Harris
Nathaniel Harris

i dont know op. I didnt see the way he planned out the code, the way he wrote it, how much time he took, etc. An interview test isnt about the final product, its about how they get that final product. or at least it should be.

Justin Hall
Justin Hall

java
delete your entire company

Austin Robinson
Austin Robinson

Integer underflow once i hits 0

Attached: C0ADF382-857D-4C84-81DA-3266DC965D8F.jpg (84 KB, 750x895)

Brandon Campbell
Brandon Campbell

noob

print("test"[::-1])

Dylan Collins
Dylan Collins

Op here. This is what I would expect from an entry level dev. I put the test in the same file for ease of screenshotting. This took me about ten minutes, in-between bites of my lunch.

int i = input.length() - 1
1. Length is a field, not a method
2. You want it to be splitArray.length anyway

You'd be surprised what we have to start with to weed out candidates.

Also, your proposed solution is really more complex than we need. Remember, developer time is more expensive than CPU time.

When can you start?

Attached: IMG-20180328-125110-879.jpg (91 KB, 828x762)

Alexander Foster
Alexander Foster

Should I hire him?
Depend on experience.
Bachelor degree? Why not for some babysitted position where you can teach him real java.
Master degree? No.
Experience java dev? Fuck no.

The code is something a first-year would do, he clearly doesn't know java.
Also this Give us more code and the time he spent to do it.

Ethan Wood
Ethan Wood

oh wow java, you are fucked with that shit.

in any normal language a char pointer is a typed pointer that points to a character.

I guess the java thing would be to have a char variable instead of a pointer and hope that the compiler handles that like a pointer, LOL. Fucking pleb language.

Aiden Phillips
Aiden Phillips

def reverse_string(s):
return ' '.join(reversed(s.split()))

Colton Williams
Colton Williams

Multi-billion dollar companies use Java
some NEET on Sup Forums "dElEtE yOuR eNtIrE CoMpAnY"

Isaac Nelson
Isaac Nelson

wouldnt the words be backwards eith that method.

for instance, the first word in the output would be txet instead of text?

Nathaniel Hughes
Nathaniel Hughes

Wrong.

According to your solution the output is

'tset a si siht'  

Tyler Moore
Tyler Moore

nice spongebob meme!

Justin Wilson
Justin Wilson

reverse_string = lambda s: ' '.join(reversed(s.split()))

Elijah Murphy
Elijah Murphy

I too watch Rick and Morty

Sebastian Myers
Sebastian Myers

it's not complex. It's only complex to you because you write in java and all you know is higher level abstract functions you call from your standard libraries.

Bentley Bailey
Bentley Bailey

This doesn't solve the problem.

We always get one candidate that tries to show off. They take 40+ minutes, don't write any tests, and never get it correct.

According to the recruiter he's a Full stack developer with 4+ years experience with the same consulting company. Experience with cloud computing, microservices, spring boot, angular 1.5, and creating apis.

This is all the Java we asked him to write. It took about 15 minutes.

Jace Hill
Jace Hill

no, you are recording the start char and end char position of a word using pointer arithmetic and once you have a full word you do a single memory copy operation. there is no character reverse going on.

Noah Torres
Noah Torres

The code is perfectly fine.

What are you sperging about?

He should have used epic one liners instead

Nolan Johnson
Nolan Johnson

A language to test OOP proficiency: Java
A language to test ability to fuck around with string manipulation: anything but Java

Yes, yes. StringBuilder autism and knowing that String is immutable in Java. But if this is for a Java developer position you'll want to make sure they can actually grok the SOLID principles, because you're using fucking Java.

In any case
instantiating a string array then immediately discarding it
bad indent
leaves trailing whitespace

9/10, you've found your average senior java dev

Bentley Lewis
Bentley Lewis

" ".join ((raw_input()).split (" ")[-1::-1]

Muh python

Asher Evans
Asher Evans

Just hire me remote for like 90k. More if you're going to make me suffer through some spring bullshit.

Aaron Smith
Aaron Smith

Whoops forgot a parenthesis. You know where to add it.

Angel Richardson
Angel Richardson

Look, his solution works, so it's fine.
You can bet your ass it won't make a change in Java.
It would be a whole lot different if you were hiring a C++ developer.

Xavier Morris
Xavier Morris

doesn't work

Jonathan Sanchez
Jonathan Sanchez

It's not supposed to be complex. It's supposed to be clean and correct. If you have access to high-level constructs, use them.

Which code is perfectly fine?

That string array never even gets instantiated, because it doesn't even compile.

Ian Sanchez
Ian Sanchez

Which code is perfectly fine?
The OP picture.

William Myers
William Myers

Nope. It is not. Try to compile it.

Levi Morris
Levi Morris

Looks like legacy code to me.

Attached: reverse.png (6 KB, 531x60)

Elijah Morgan
Elijah Morgan

Also depends what's important to you.
Do you want a readable code, or best performance?

Andrew Robinson
Andrew Robinson

One too many left parathesis

Oliver Long
Oliver Long

Are most interview questions this simple?

Luis Fisher
Luis Fisher

It probably wouldn't if you tried to compile python code in java.

" ".join ((raw_input()).split (" ")[-1::-1])

Werks on my machine.

Henry Garcia
Henry Garcia

){

eww

Landon Sullivan
Landon Sullivan

Are you trolling? You have to tell me if you are. It's the law.

Assuming you fix the type issues, what is the output for a single word? What should it be?

Readable code > performance in 99% of cases.

Isaac Green
Isaac Green

Delete your entire company

Noah Bell
Noah Bell

his curly braces are mismatched and he has his return value tabbed wrong

David Myers
David Myers

I'll bite.
First, if I were being interviewed I'd ask what the default behavior for white spaces should be.
Second, if we're speaking of being effective and implementing an actual solution to the problem - use of string builder - instead of only showing the correct way to solve it (which imho should always be the case on entry level interviews), I would expect someone to present a faster and more memory effective way of doing things than just splitting string to array on space character. No idea how split is implemented in java, maybe it's on equal with processing string one character at time, maybe it's not. Probably it's not. Additionally, adding " " at the very end of sentence and then trimming it is most definitely more cpu and memory intensive than writing a ternary operator.
Third, whereas unit tests are generally a good thing as they eliminate most of the stupid errors, those are the last thing I'd write on an interview. Unless, obviously, I'd be explicitly told to write them.

Simple, write it in any other language. Java is shit.

Anyways, OP - if that was an interview for entry level job (I assume it was), hire him. He doesn't seem brained, he just seems to barely know good coding practices and java standard library. Give him several months and a good supervisor and he'll be better than average pajeet.

David Walker
David Walker

muh muh code readability is what matter
meanwhile in another thread
that's it I'm done, <insert_software_name> is shiet Sup Forums what should I use?
I hope you're not that kind of person...
Eearly optimization IS the problem, caring about performance should be a given for any competent developer on this planet.
Lowering the entrance barrier is a problem, we end up with shitty devs with 4 years of experience and can't use fucking StringBuilder.
This "it's fine as long as it compils" mentality must dies.

Jaxson Davis
Jaxson Davis

pleb cumming thru

public static String reverseString(String input) {
String output = "";
ArrayList <String> arr = new ArrayList<String>();

for (String lel : input.split("\\s+"))
arr.add(lel);

for (int i = arr.size()-1; i>=0 ; i--)
output += arr.get(i) + " ";

return output;
}

rate

Jeremiah Ward
Jeremiah Ward

i spit on python 2 users

Gavin Jones
Gavin Jones

Checked.
no nullpointerexception
no stringbuilder
no trimming of the last space
first-year_CS/20

Lincoln Gutierrez
Lincoln Gutierrez

You are right in almost every way. Interviewers love unit tests, and we lose our shit when we see them. They are also a good way to document your assumptions about how whitespace should work. It shows that you can be given an underspecified problem and still make progress on it.

The follow up questions are

1. Runtime complexity
2. Space complexity.
3. We're deploying your new Enterprise String Word Reverser, and we expect strings to be no more than a gigabyte in size? How much RAM should you request on the server order form?

So, pretty much any solution is fine as long as it uses less than 4x the input memory. The candidates know this at the start.

Have you ever worked with legacy code? Have you ever found a nasty hack that took you an hour to understand, but saves like a second of computation time over a long-running batch process? It happens all the time. You could print this word order reversal thing onto an asic chip for ~*maximum performance*~, but you're fucked as soon as your client decides they don't actually want the order of words reversed, they just want a palindrome generator or something.

Jordan Bell
Jordan Bell

It is dying, cloud computing is putting fixed costs on computation and helping companies to find the right balance between "CPU time" and "developer time"

Its not happening here clearly. After you all are finished with java, I guess python is next

Logan Morales
Logan Morales

print ' '.join(s.spit()[::-1])

Attached: DZT4BLSWsAEpsM8.jpg:large.jpg (107 KB, 600x772)

Isaac Stewart
Isaac Stewart

Put some braces on those for loops and call hr.

William Reyes
William Reyes

Can anyone tell me is this better or not
Create pointer variables for every letter after \n and create an array of pointers.
reverse the pointer array.
concat everything .

Isaac Davis
Isaac Davis

function reverseString(str) {
return str.length <= 1
? str
: reverseString(str.substr(1)) + str.charAt(0);
}

The absolute state of OOP cucks

Jordan Baker
Jordan Baker

> reverseString("this is a test")                                                                                                                             'tset a si siht' 

fuck off cuckold

Adrian Collins
Adrian Collins

If "early optimization" means "well-considered scalable design", I agree.

If it means "let's start with pointer arithmetic because I need this fizzbuzz to be fast", I disagree.

Michael Cook
Michael Cook

Have you ever worked with legacy code?
Mostly c-ansi
Have you ever found a nasty hack that took you an hour to understand, but saves like a second of computation time over a long-running batch process?
I care more about cache-misses and misused memory which are real problem for alot more companies than faster computing.
maximum performance
We have powerful tool, use them. It's not like StringBuilder is complex or something...
Like using ArrayList for FIFO, it works but it's plain retarded.

It is dying, cloud computing is putting fixed costs on computation and helping companies to find the right balance between "CPU time" and "developer time"
yeah, because cloud computing is magic and you don't need actual developers to, you know, develop these systems...

Brandon Walker
Brandon Walker

I meant whitespace not \n

Christian Robinson
Christian Robinson

Write it. You have ten minutes.

Ayden Morris
Ayden Morris

Don't flame me or my language of choice

# 9.000000000000002e-06
proc reverseRegex(s: string): string = s.splitWhitespace.foldl(b & " " & a, "").strip

# 3.999999999999989e-06
proc reverseOnWord(s: string): string =
result = newString s.len
var
start = s.high
n = 0
for i in countdown(s.high, 0):
if s[i] in Whitespace:
for c in i + 1..start:
result[n] = s[c]
inc n
start = i - 1
result[n] = s[i]
inc n
elif i == 0:
for c in i..start:
result[n] = s[c]
inc n

Dominic Harris
Dominic Harris

don't do it user, he'll put too many curly braces in all your projects and ruin them every time, his code otherwise looks fine but if he's going to make the simplest mistakes that can ruin large projects instantly, its not worth the extra time it will take to fix them, no matter how trivial it is to find and fix, that's still time unnecessarily spent, and it'll add up

Nicholas Young
Nicholas Young

are you retarded? or did you just memorize how to type up a for loop and forget how they work? i.e. for loops don't have to start at i=0 and in fact this one doesn't

Aaron Jenkins
Aaron Jenkins

Cache misses aren't a real problem here. We mostly deal with stuff like, some new data provider decides to use 4 character country codes when everyone else uses the ISO standard, so we have to change to seamlessly support both. In cases like this, it's much more important to be able to say what kind of code you're looking at, and not so much how it fits in your L2 cache or whatever.

This is what I mean when I say readability is more important. Does that make sense?

Kevin King
Kevin King

pascal?

Owen Foster
Owen Foster

nim

Andrew Gonzalez
Andrew Gonzalez

first time trying java

import java.util.Collections;
import java.util.Arrays;
import java.util.List;

class Main {
public static void main(String[] args) {
System.out.println(reverse("this is a test"));
}
public static String reverse(String s) {
List<String> l = Arrays.asList(s.split(" "));
Collections.reverse(l);
return String.join(" ", l);
}
}

Sebastian Taylor
Sebastian Taylor

first of all, checked
second of all, don't listen to this guy fuck those gay braces, back up your for loop body onto the same line as the for statement, then call hr

Brody Gutierrez
Brody Gutierrez

you're writing Java so thats probably the best you're going to get

Java engineer skill distribution has basically 0 std deviation

Jackson Turner
Jackson Turner

Let me know when you graduate, you parrot.

Josiah Roberts
Josiah Roberts

say brother, is that based nim?

Jackson Thompson
Jackson Thompson

hell yes, brother

Xavier Hughes
Xavier Hughes

reverse(null)

Levi Evans
Levi Evans

I often say that a lot of job employers test for the wrong shit. To be quite honest, as a coder myself, I know I'm 99% better than any person you will pick off the street cause I'm interested in obscure shit than whatever pejeet or some out of college coder can pull off. You'll be 10 times better with someone who has code sense and can probably give you a better product, too.

Hunter King
Hunter King

I dropped out of high school and manage hordes of programmers like you.

Isaac Moore
Isaac Moore

Does that make sense?
of course that's not gonna make sense to someone like that. Developers like him are the reason the Linux kernel is a bloated unportable clusterfuck that can't even compile without legacy gnu bloat. Ignore him.

Adrian Rivera
Adrian Rivera

you'll get something like this

char[] charArray = strings.toCharArray();
char[] outputString = charArray.clone(); // so the have the same size
for (int i = charArray.length - 1, j = 0; i >= 0; --i, ++j) {
outputString[j] = charArray[i];
}

reverse the pointer array.
concat everything .
It's not enough to preserve the letter order within a word.
You have to consider words as entities within the sentence else you won't be able to get the good result.

the goal is to actually write the reverse method.

Nolan Parker
Nolan Parker

Linux kernel is a bloated unportable clusterfuck t

Doesn't Linux give support to hundreds of architectures ?

Jordan Morris
Jordan Morris

2018
Java Array can't reverse itself
Kek

Jack Rivera
Jack Rivera

not switching to Scala
It's like you want to live in the past grandpa

Jayden Gutierrez
Jayden Gutierrez

missing the point this hard

kys

Oliver Hall
Oliver Hall

Should it return null if given null? Then null propagation?
Should it throw NullPointerException? It already does

Jaxon Young
Jaxon Young

this is better if he was doing it in c#

public static string reverseWord(string s) {
string ret = "";
Regex reg = new Regex(@"\b\w+\b", RegexOptions.None);
MatchCollection mc = reg.Matches(s, 0);
for(int i = 0; i<mc.Count; i++) {
ret += mc[(mc.Count - 1) - i] + " ";
}
return ret;
}

Grayson Rivera
Grayson Rivera

Simple, write it in any other language. Java is shit.
That's not how the real world works

Jack Johnson
Jack Johnson

Returning null would be preferred. Returning an empty string is also okay.

You can use more than 3 characters to name a variable.

Joseph Miller
Joseph Miller

regex
why

William Gutierrez
William Gutierrez

using 3
Yikes

Isaac Torres
Isaac Torres

Does this work?

reverseString :: String -> String
reverseString = unwords . reverse . words

Dominic Cooper
Dominic Cooper

This looks horrible

Easton Mitchell
Easton Mitchell

I wish I could use Haskell here. Good job.

Christian Lopez
Christian Lopez

problems I see:
misleading function name
only concats words with spaces, not with original separators
iterates over length of input, not over words; idiot
bad appending to array
bad return type
adds trailing whitespace to last word
iterator would be better than indexing but whatever
didn't check it properly and has additional bracket at the end
fucking no, this is barely ~0.5y or programming experience

Benjamin Rogers
Benjamin Rogers

And this is why you will never make it

Liam Brown
Liam Brown

Very good. Why not try writing it yourself? I bet you can get it.

*Masturbation gesture*

Ayden Perry
Ayden Perry

Exactly, it does the job, it's not elegant, but does the job
So it all depends on the agreement(or not) of salary

Alexander Campbell
Alexander Campbell

I love how Phil ends up on all these kinds of images

Kevin Brooks
Kevin Brooks

Was this supposed to be a test on domain specific knowledge?

Jeremiah Phillips
Jeremiah Phillips

python is a cancer to the coding community.

Connor Bennett
Connor Bennett

Attached: 1519461615025.gif (1.78 MB, 350x255)

Kayden Wright
Kayden Wright

meanwhile in C++
memory leaks
memory leaks
disgusting syntax
::
****************

Asher Lewis
Asher Lewis

Why would doing it this way reduce salary? The guy knows about regexes; that's as good as you'll see among Java developers. Now if you're talking about optimization, I can't think of any solution requiring to iterate at least twice through the string.

Landon Robinson
Landon Robinson

That for loop shouldn't even have curly braces.

Nicholas Evans
Nicholas Evans

int i = input.length() - 1; i >= 0; i--

Don't hire people that count backwards. Never. There is literally never a reason to count backwards in loops on a CPU. Every backwards count can easily transform into a forward count. If your applicant can't do this don't hire him.

Also avoid hiring Java people if you can. I mean avoid Java only guys; avoid it if they only speak Java. I am fluent in Java, Python, Haskell and C, (spend 90% of my time writing C).

Easton Sanchez
Easton Sanchez

t. brainlet

Nathaniel White
Nathaniel White

void revstr(const char *s) {
size_t n = strlen(s);
for (size_t i = 0; i < n / 2; ++i) {
char t = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = t;
}
}

This is how easily it should be done and a proof that easy languages corrupt programmers

Kayden Reyes
Kayden Reyes

added const out of habit
drop that

Eli Moore
Eli Moore

did you read what the function supposed to do?

Landon Russell
Landon Russell

I've seen a LOT worse.

Landon Long
Landon Long

no
i saw keywords reverse and string

Aiden Cruz
Aiden Cruz

Of course it does. How many times does Haskell have to prove its superior elegance? The way I see it, let them for in their imperative suffering, while we live in the future.

Kayden Watson
Kayden Watson

pajeet

Noah Carter
Noah Carter

these
OP, just go ahead and after hiring him literally tell him "Use StringBuilders and proper method names, faggot".

Blake Cruz
Blake Cruz

Always use brackets, even when they're optional. Otherwise you end up breaking SSL on every iOS device.

Plus, it looks better when it's uniform.

Brandon Sullivan
Brandon Sullivan

fn reverse_words(input: &str) -> String {
let mut output = String::with_capacity(input.len());
let mut words_rev = input.split_whitespace().rev();

if let Some(w) = words_rev.next() {
output.push_str(w);
}

for w in words_rev {
output.push(' ');
output.push_str(w);
}
output
}

Luke Mitchell
Luke Mitchell

let reverseWords = s => s.split(' ').reverse().join(' ')

Kevin Roberts
Kevin Roberts

strings are immutable, and pure functions > state mutating functions

Mason Parker
Mason Parker

No, the problem is that it doesn't reverse a string, it reverses the order of the words in the string. It's a misleading name.

Blake Cook
Blake Cook

the goal is to actually write the reverse method.
you want a programmer to waste his time reinventing the concept of reversing a collection of things, and other stuff that's already been done, instead of using existing code and concepts to trivially solve a dumb problem? you're a shitty interviewer looking for shitty programmers then. Arrays.aslist(string..split(regex)).reverse().join(" ") (pseudocode) is the best solution there is: no custom fucking around with stuff, no reinvention of the wheel, no excess verbosity, etc

Grayson Gray
Grayson Gray

reverse the string word by word
What a terribly ambigous way of saying "reverse the order of words in a string". If I were an applicant, I'd consider such inability to precisely formulate thoughts a huge red flag.

Dominic Hernandez
Dominic Hernandez

that is a very trivial issue that's instantly fixed, and it's only wrong because you're thinking in the context of a total solution while he was only thinking in a more limited context of "just write the method body"

Returning null would be preferred. Returning an empty string is also okay.
that is not universal. It depends on the project, context, and local conventions. What isnt specified, shouldn't be implemented. Best of all is to throw an exception when undefined conditions are encountered because then you immediately know an unexpected situation happened. Implementing behavior that wasn't asked for is a great way to hide implementations errors elsewhere by delaying the onset of resulting issues.

Jayden Sullivan
Jayden Sullivan

in C

#define IS_LETTER(ch)   (((ch) >= 'A' && (ch) <= 'Z') || ((ch) >= 'a' && (ch) <= 'z'))

void
reverse(char *arr, size_t len)
{
size_t i;
for (i = 0; i < len/2; i++) {
char tmp = arr[i];
arr[i] = arr[len-1-i];
arr[len-i-1] = tmp;
}
}

void
reverse_words(char *arr, size_t len)
{
size_t i, prev = 0;
int is_word = 0;
reverse(arr, len);
for (i = 0; i <= len; i++) {
if (i == len || (IS_LETTER(arr[i]) == is_word)) {
reverse(&arr[prev], i-prev);
prev = i;
is_word = !is_word;
}
}
}

Liam Cooper
Liam Cooper

I'd consider such inability to precisely formulate thoughts a huge red flag.
it is a huge red flag, but unfortunately there isn't a company in the world that doesn't formulate its assignments vaguely.

William Rodriguez
William Rodriguez

Never
carmack used backwards counting here
github.com/id-Software/DOOM/blob/77735c3ff0772609e9c8d29e3ce2ab42ff54d20b/linuxdoom-1.10/r_draw.c
how do you feel about that

Angel Wright
Angel Wright

you're a shitty interviewer looking for shitty programmers then.
i'm not OP, my man.
I agree with you that it's retarded but this is the question asked in op picture.
No reason to play the smartass during an interview.

Jeremiah Hernandez
Jeremiah Hernandez

jesus christ, what a bunch of dinosaurs posting here. You're all writing tons of code for a trival problem, doing everything manually instead of composing existing generic code that handles the problems you're solving manually, and in the end, none of it is readable. If you had to read the decompiled code or something, you'd have no fucking idea what any of it does anymore. Reviewers would have a difficult time determining implementation correctness.

public static String reverseWords(String input) {
String[] words = input.split("\\s+");
ArrayUtils.reverse(words);
return StringUtils.join(words, " ");
}

There. It's even pretty goddamn performant because it avoids using collections and inserts. Only uses apache commons-lang, which is a lbrary people put on literally every java project ever because its entire point is to implement really basic shit that for some miraculous reason is not in the jdk (like Arrays.reverse(arr)). If you don't have that library, use another. If you can't use any library, at least have the decency to implement a single generic array swap method and such elsewhere and -reuse it so your actual logic can stay high-level like this.

Asher Perez
Asher Perez

 function reverseString(str) {
var reversed = str.split(' ').reverse().join(' ');
return reversed;
};

Colton Morgan
Colton Morgan

Because the question is to write the reverse method, not to use it...

 public static void reverse(final Object[] array, final int startIndexInclusive, final int endIndexExclusive) {
if (array == null) {
return;
}
int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
int j = Math.min(array.length, endIndexExclusive) - 1;
Object tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}

This is the source code of the reverse method for Object[] in ArrayUtils, it looks pretty much like what was posted here.
If you can't use any library, at least have the decency to implement a single generic array swap method and such elsewhere and -reuse it so your actual logic can stay high-level like this.
hence the interview question, to check if you can write libraries and things like that...

Sebastian Roberts
Sebastian Roberts

You should use recursion instead of iteration, you stupid fuck.

Brandon Phillips
Brandon Phillips

what a bunch of dinosaurs posting here

Oh the irony. The latest Java already has a String.join() method built in.

Who's the dinosaur now.

Christopher Allen
Christopher Allen

biggest retard itt. this is what happens when you google how to do everything and think you're "learning"

Camden Russell
Camden Russell

weak b8, nobody is this retarded

Easton Lopez
Easton Lopez

POSIX.1-2008 compliant

#!/bin/sh
s="this is a test"; these=""; for i in $s; do these="$i $these"; done; echo $these

Sebastian Howard
Sebastian Howard

Equivalent while staying statically typed and on the JVM:

def reverseWords(s: String) = s.split(' ').reverse.mkString(" ")

Juan Brooks
Juan Brooks

Writing this on my phone. Sorry for any mistakes. Essentially this does two things different: Regex is a slow way to split the string and completely unnecessary - use toCharArray instead. Uses StringBuilder instead of concatenation as Java default concatenation produces a new immutable string. StringBuilder concatenates all at once with toString.

public static reverseString(String input) {
StringBuilder outputBuilder = new StringBuilder();
char[] splitString = input.toCharArray();
for(int I = 0; I < splitString.length; I++) {
outputBuilder.append(splitString[I]);
}
return outputBuilder.toString();
}

Jace Wright
Jace Wright

statically typed
good
on the JVM
bad

Wyatt Campbell
Wyatt Campbell

JVM
bad
Trust me, there's plenty of downsides. But you've got to admit it's the best choice for a lot of projects.
Your proposed alternative?

Logan Myers
Logan Myers

proc readstr_space
pop
swap
1 +
""
end

proc readstr
swap getch
dup "." = @end if
dup " " = @readstr_space @concat ifelse
swap
readstr
end

proc printstr
dup 0 = @end if
swap " " concat print
1 -
printstr
end

"" 1 readstr pop swap

printstr

rate

Hunter Thomas
Hunter Thomas

this is the type of people that fanboi over C, everyone.

Ian Richardson
Ian Richardson

s = "this is a test"
these = ""
for i in s.split(' '):
these = i + " " + these
print these

Carson Miller
Carson Miller

That reverses the string but the op's program reverses word by word.

Adrian Long
Adrian Long

why are the braces all fucked up

Lucas Richardson
Lucas Richardson

Your proposed alternative?
Pretty much anything else? You're more likely to find a user that doesn't have a JVM than you are likely to find a user not using x86 or ARM these days, so just compile for those platforms (or just x86 if you aren't targeting mobile) and ship like that.
If you really want to just ship non-native code and have it run anywhere, you'd be better off with JS since every user has a web browser capable of running it, and there are lightweight standalone runtimes for it for other purposes.

What reason is there to target the JVM nowadays?

Jordan Torres
Jordan Torres

Idk lol

Isaiah Bailey
Isaiah Bailey

Tokenize on spaces. I would not hire someone who uses regexp for this.

Also use a better language, as others mentioned.

Ian Hall
Ian Hall

Ah, I see you're thinking of
- sufficiently small projects
- projects that don't benefit from existing libraries
or
- people that put up with Electron-tier software quality
Sure, for those, non-JVM is probably a better choice.
What reason is there to target the JVM nowadays?
Ecosystem, pre-existing deployments, memory safety, large business support network, higher development speed, and so on.

Adam Barnes
Adam Barnes

String x = new String[]
what language is this

Benjamin Peterson
Benjamin Peterson

Tokenize on spaces
literally the best method in java.
We just want the reversed sentence, not reversed letters within words.

Glorious java.

Cooper Ortiz
Cooper Ortiz

"this is a test".reverse.split(" ").map(l => l.reverse).reduce(_ ++ " " ++ _)

Jason Adams
Jason Adams

My bad. I'm on my phone and op's method said reverseString. But I would still parse it character by character and then prepend it on spaces, (then ignore any subsequent spaces?). Still faster than regex. StringBuilder is still the best way because of how Java strings are immutable.

It's possible the pic in OP was instructed to use Java. It's still used by lots of corporations. But regardless, I feel like language is irrelevant. As long as you can understand basic software engineering concepts, any language should be sufficient. Java is still very popular and is still the first programming language taught by many universities. Implementation is what I would look for. Did they do it efficiently for the language and did they follow language standards.

It's true that in C and C++, heap-allocated strings are mutable but since they chose Java, StringBuilder is the best choice for that language. That said, I would give less weight to answers submitted in JavaScript or anybody who attempts to do a single-liner just because they can. I'm looking at

Colton Scott
Colton Scott

That was not the goal. Obviously.

You get it.

Read the problem again.

Part of the problem was to name that method. He chose that name.

You'll never get a fully-specified problem in real life. You write tests to document those assumptions, and so other engineers know when they've violated them.

In our code base, null pointer exceptions are not to be relied on.

I know, right?

High-level thinking is difficult for me\0

Op here. I know about how String Builder is used in the background in modern Java. I just want to hear the candidate mention it.

I didn't name that method, btw.

Leo Hernandez
Leo Hernandez

I know the process behind all these methods, which is why I just use the implementations that have already been written and are readily available instead of rolling my own every time again, wasting time and effort and creating the possibility of bugs. work smart and efficiently, not hard and unnecessarily.

do you chop trees, render the wood to pulp, and press your own toilet paper, or do you just buy rolls of paper from the store? do you store all your files as manually managed strings of bytes laid out on your harddrives in some just-you way, or do you pick a filesystem and let it do the work of storing your files?

doing tedious shit manually and reinventing every wheel when there's no need to is what dinosaurs do.

If the reviewer wanted to test my knowledge of array swapping and the like, the low-level stuff, he should ask that instead of asking a high-abstraction question to which the most applicable answer is a high-abstraction one. If you answered the "reverse the words in the sentence" question with a bunch of manual array fuckery, you're just trying to prove how hardcore your e-peen is, not actually doing real work

Logan Sullivan
Logan Sullivan

if you can't understand "reverse, then reverse the words and put them back together", your stupoid.

Isaac Adams
Isaac Adams

depends on the context. User input tends to have oddities like double spaces, tabs, or weird unicode fuckery. Tokenizing on pure spaces is good if you know the string will be "clean", but using the regexp in questionable cases is a great forethought.

William Hughes
William Hughes

Out of curiosity, how's this for a perl solution, where regex is a first-class citizen? Running without it being cached on my system according to time:

real 0m0.012s
user 0m0.008s
sys 0m0.004s

#!/usr/bin/env perl

use strict;
use warnings;

sub reverse_string {
my $str = shift;
my @words = split /\W+/xms, $str;
return join q( ), ( reverse @words ), "\n";
}

print reverse_string('this is a test');

Would this acceptable?

Brayden Young
Brayden Young

Out of curiosity, how's this for a perl solution, where regex is a first-class citizen?
that doesn't mean what you think it means

John Davis
John Davis

I mean I was mainly just being retarded about the language.
The main point is that you obviously should be using tokenization here and I would not hire someone who "solves" this with regexp.
Regexp is slow and potentially unsafe.

There are tokenizers which will convert from regexp to tokenization as well.

James White
James White

a

Andrew Morales
Andrew Morales

I know about how String Builder is used in the background in modern Java.
Granted my Java knowledge is outdated, but I was under the assumption that this was not applicable to for loops. But I'll take your word for it - I'd imagine it should make that optimization.
You're right, but I didn't read, I skimmed.

Austin Rodriguez
Austin Rodriguez

Should I hire him?
Does he poo in the loo?

Colton Russell
Colton Russell

Part of the problem was to name that method. He chose that name.
The problem with interview questions is they're never representative. Of course he'd pick a better name in a real situation where he knows the method will be called. He didn't here because nobody would call this interview question method and the essence of your question is or seems to be the implementation. In non-real situations you need to specify a lot of stuff you wouldn't in a real situation, because assumptions become very different in real vs non-real situations. I wouldn't spontaneously write a unit test for this reverseWords method in an interview either because I expect no reviewer to actually want me to do so unless told to. If you assume the opposite, you'll just think less of me for making a logical assumption, while really you just failed to specify information that should have been given.

In our code base, null pointer exceptions are not to be relied on.
good programmers will always validate mthod arguments, and ideally thrown an exception when any of them are unexpected. Nobody relies purely on NPEs.

Lucas Murphy
Lucas Murphy

What I mean is that I am under the understanding that the perl interpreter optimizes for regular expressions quite well, as well as being able to use them throughout the language in a myriad of places and fashions quite intuitively. While there are certain circumstances wherein perl regular expressions will be faster or slower than competitor $x, overall it is generally regarded as being favorable, and therefore I suspect the speed penalty will be less than Java's, making it a suitable perl-centric solution. Is that wrong?

Thomas Barnes
Thomas Barnes

You get it.
Read the problem again.
Then what's this?
You did the exact same thing.
High-level thinking is difficult for me\0
Sounds about right

You just confirm the java meme spreading around here, you're plain incompetent and in the process of hiring an even more incompetent dude.

Kayden Allen
Kayden Allen

The problem with interview questions is [...]
what are you on about m8, literally the first few words give you an idea of how to properly name the method
"reverse the string word by word"
nigga chose "reverseString", which is obviously retarded for several reasons
if he wasn't spazzing out that badly and gave it 5 more seconds of collected thought, he'd name it "reverseWords"

Leo Morgan
Leo Morgan

obviously
debatable. Environmental conditions not specified, string could be "clean" and contain only regular spaces, or could be input directly from a user with irregularities like leading/trailing spaces, double spaces, tabs, or unicode fuckery out the ass

Juan Ortiz
Juan Ortiz

yup, a better approach is to talk the interviewer through the first version
"Alright, I'm just sketching up some code to do the simplest possible interpretation of the problem - safe, single regular spaces only, etc.
Now that it's done, shall I list the issues we might need to handle - double spaces, unicode fuckery, non-space whitespaces, punctuation and so on?"

Hudson Gutierrez
Hudson Gutierrez

#!/usr/bin/pytard 

import StackOverFlowSolver as brainlet

def StringReverser(input):

brainlet.Ask("function that ask user for an string and returns reversed word by workd").apply(input)

Juan Richardson
Juan Richardson

omg it works.

Evan Morales
Evan Morales

slow and potentially unsafe
Just like an employee who imports Antlr in a screening interview.

Yes, exactly.

Give me the job, I swear I'd wash my hands if this was a real kitchen.

I accidentally quoted you when I didn't mean to. I was trying to talk to the guy who just reversed the whole string.

"You get it" refers to using using libraries. I didn't use any there so we could compare and contrast the candidates implementation with a neater one. Obviously your way is better. You get it.

Good thing I'm a good programmer :^)

We're hiring for a remote position, and we were warned to use video chat so that somebody else in the room couldn't do the typing.

Xavier Cox
Xavier Cox

video chat
crap, that means I'd need to put on pants, dun it?

Chase Scott
Chase Scott

Attached: 2018-03-28-191839-385x22-scrot.png (4 KB, 385x22)

Jason Powell
Jason Powell

Otherwise you end up breaking SSL on every iOS device
What is this? So leaving curly braces out messes up iOS devices? How?

Jordan Peterson
Jordan Peterson

Output:

Closed: Marked as a duplicate of "What does C#'s Array.Reverse() do?"

Jacob Hill
Jacob Hill

what is gotofail

Oliver Bailey
Oliver Bailey

Still lost. Why wouldn't this work on iOS?

Thomas Morgan
Thomas Morgan

A little Bit Different

Attached: 2.png (8 KB, 625x164)

Cameron White
Cameron White

Not really, we can only see shoulders and up

This is what the dream candidate does.

Why wouldn't you just write the test? It takes two minutes and shows that you thought about corner cases?

Samuel King
Samuel King

Disregard this retard

string ReverseWords(string text) => string.Join(" ", text.Split().Reverse());

Thomas Jones
Thomas Jones

What's with your brackets?

Dylan Anderson
Dylan Anderson

Why is the Java solution so long?
Also, there are errors in your solution. "line" can be null. What if words are separated by more than one space?

Mason Bell
Mason Bell

fucking really?
kids these days
lmgtfy.com/?q=gotofail

Hunter Sullivan
Hunter Sullivan

Best solution ITT, hands down.
Also the best language.

Evan Howard
Evan Howard

This is what the dream candidate does.
Coincidentally, this is what I do.
Crap, how do I disqualify myself as quickly as possible?
Would pretending to have /dpt/-tier autism do the trick, or are you that desperate?

Samuel Gutierrez
Samuel Gutierrez

best language
join method on String instead of on collection
yeah nah cunt
also
lolvendorlockin

Thomas Collins
Thomas Collins

You're Absolutely right , I'm a Fresh Developer , What should I do in that case ?

Nolan Anderson
Nolan Anderson

Best solution
doesn't accommodate multiple sentences

Matthew Jones
Matthew Jones

tl;dr. So basically I shouldn't care if I'm not writing java for iOS devices, right?

Juan Thomas
Juan Thomas

closed not-a-bug
out of scope

Eli Murphy
Eli Murphy

Don't speak about a language that you don't know.
In .NET, the type "string" implements IEnumerable<char>
So you can enumerate it as well as use collection's extension methods.

Andrew Howard
Andrew Howard

string ReverseWords(string text) => text.Split().Reverse().Aggregate((l, r) => $"{l} {r}");

Justin King
Justin King

java
what do you have instead of brains in that thick skull of yours
The problem soon came to light, in a file called sslKeyExchange.c [...]

Levi Gomez
Levi Gomez

I didn't even read it, dude

Grayson Williams
Grayson Williams

this is why your post was retarded

Easton Thompson
Easton Thompson

    public static String reverseByWords(String phrase) {
String[] words = phrase.split(" ");
String output = new String();

for (int i = words.length - 1; i >= 0; i--) {
output = output.concat(words[i]).concat(" ");
}

return output.trim();
}


r8/h8

Jack Powell
Jack Powell

muh extension methods
then why didn't you use the more readable approach, faggot?
needing a full lambda instead of having an overload with a simple char/string
best language
shiggy

Jose Sullivan
Jose Sullivan

Anyways, that for loop shouldn't have any curly braces.

Christopher Baker
Christopher Baker

You're an idiot.

Colton Wood
Colton Wood

devastating rebuttal

Aiden Barnes
Aiden Barnes

I think you missed the part that said that, in C#, the type string is a collection of char.
So everything you say after:
join method on String instead of on collection
makes you look like an idiot.
Stop giving excuses on matters you don't understand.

Robert Richardson
Robert Richardson

-looping over the wrong value
implying you should loop at all

Angel Hill
Angel Hill

Depends on the type of people working on it, and the impact of gotofail-type fuckups.
Which is why that other dude mentioned it.

Logan Lopez
Logan Lopez

That's not PEP-8 compliant (which is stupid, but still).

Blake Kelly
Blake Kelly

It's a small block of code that reverses a string by its words. I don't think there will be gotofail-type fuckups here.

For such a small program, the braces are poor form.

Angel King
Angel King

This is the easiest and best-paying job I've ever had. It's not the most interesting.

Just use the braces. It's not hard.

Fair enough

Nathaniel Baker
Nathaniel Baker

I think you missed the part
Nope
in C#, the type string is a collection of char.
"implements IEnumerable<char>", more precisely
makes you look like
nope, that's your failure to read my post.
Jeez, is this the level of competence one would expect of C# devs? Now I see where the stereotypes come from.

Jacob Hughes
Jacob Hughes

don't tell me what to do.

Samuel Hernandez
Samuel Hernandez

Good argument.
The best approach IMHO is to point it out while writing or talking about the code - and to ask what the company's code style says with regards to that.

Alexander Ward
Alexander Ward

It's small, but it's supposed to show your mastery of the form. You don't want your employer to know you can solve fizzbuzz, you want them to know they can trust you with larger projects.

Same reason you'd write a test.

Brayden Fisher
Brayden Fisher

If you can't reverse a string without stack overflow, then you are fucked mate

Adam Gutierrez
Adam Gutierrez

easiest and best-paying job I've ever had
not the most interesting
Now this sounds interesting.
How easiest and best-paying are we talking?

Christian Jackson
Christian Jackson

Same reason you'd write a test.
I would never.

Grayson Watson
Grayson Watson

The true standards-compliant pro's gotta check with SO before incrementing a variable, m80.

Zachary Lewis
Zachary Lewis

you sure you replied to the right post?

Daniel Jenkins
Daniel Jenkins

Poor requirements.
What should we do with punctuation? What about non-english scripts with other word separators or none at all? What about contractions of words? Empty strings? Leading or tailing whitespace? Define "word"!

Hire a better PM first, don't want your job.

Michael Morris
Michael Morris

What happened to the Carrer/Recruiting generals? I don't know why you Sup Forumsentlemen where so opposed to them.

Jaxon Jones
Jaxon Jones

no. i hope OP never hires someone like me, I make a lot of mistakes like that lol

Isaac James
Isaac James

It reminded them of their NEET status. Too painful

Christian Green
Christian Green

practice makes perfect m8

Robert Reed
Robert Reed

Sounded too sketchy for me. Why would professional adults with rewarding careers be posting here? I always assumed those threads were full of pajeet scammers who wanted you to program some Android app for them and then not pay you

Joshua Reyes
Joshua Reyes

feel free to ask requirement clarifications
i.e. "if you don't, that shows you're a clueless code monkey that isn't fit for a team that doesn't have the resources to hand hold him constantly"

Luis Myers
Luis Myers

That's a pretty insightful perspective. Hired.
Shitposting is for all ages.

Joshua Ross
Joshua Ross

I'll never understand why people struggle with sorts of questions. Just add it to a stack then remove it. It couldn't be simpler.

Logan Murphy
Logan Murphy

adding unnecessary complexity compared to the alternatives
"clever" solution that raises a red flag desu famalam

Jace Sanders
Jace Sanders

someone took data structures

Wyatt Fisher
Wyatt Fisher

How is a stack unnecessary complicated? A stack is extremely simple.

Bentley Russell
Bentley Russell

a stack would work better here if you don't know about StringBuilder

Eli Ortiz
Eli Ortiz

Why, when you could just create an ActiveRecord for each word and index, then commit it to SQL Server and execute a SELECT * from words SORT DESC.

Carson Brooks
Carson Brooks

I feel like you just answered your own question.

Adrian Kelly
Adrian Kelly

Can you write it in code, then? Not talking about reimplementing a stack, just using it.
Then let's compare to the single for loop in the OP.
How?

Nathan Stewart
Nathan Stewart

that user's retarded
maybe he's complaining about the Linux kernel using GCC extensions, which makes it somewhat unportable to other compilers, being non-standard C

Thomas Ward
Thomas Ward

These are exactly the questions I want a candidate to ask

I'm making $121k with some stock and I got a 10k bonus this month. They also pay me to travel.

It's a lot of Enterprise Big Data ™ bullshit. Consume that API, store it over there, add it to that batch job, serve it through another API.

Adam Campbell
Adam Campbell

how
First in, last out. Simple, you don't even have to think about the logic.

Blake Lopez
Blake Lopez

Ask him to whip out fizzbuzz without so, google, or a lifeline text message. Have him put his phone away and watch him fizz his buzz.

Samuel Sullivan
Samuel Sullivan

Oh, I thought we were doing overly complicated solutions to simple problems.

Joshua Jones
Joshua Jones

Yeah, I know how a FILO works.
My question is how would it "work better here"?

Jose Cox
Jose Cox

adding the contents of a string to a stack and then removing them is complex

Adrian Reed
Adrian Reed

They obviously are. Let's see how long it takes them to figure it out though.

Ayden Young
Ayden Young

unnecessary complexity compared to the alternatives
As in "stuff that's even simpler and *more appropriate* than using a stack".
This isn't your DS&A freshman "clever tricks" section, the goal is to write readable code.
Although it's nice to mention "btw you could do it with a stack, but IMO this is more appropriate" while sketching up the code.

Lincoln Gray
Lincoln Gray

push chars in between white spaces from string
pop chars in between white spaces to string

there's literally no logic involved here, stacks inherently reverse things

Brody Morris
Brody Morris

$121k with some stock and I got a 10k bonus this month
neat
travel
hm

So, is this the type of position you guys are currently interviewing for, and what kind of skills are you looking for?

Zachary Reyes
Zachary Reyes

No clue, but I know it would work. Does the OP code work?

David Hill
David Hill

I know how it works.
I'm asking you to write the code, because you don't seem to comprehend that it'd look messier (for no good reason) compared to the more direct approaches.

James Butler
James Butler

I know it would work
Sure, but we were talking about it being a worse solution than the more direct ones.
Does the OP code work
Obviously not, IIRC.

Gabriel Turner
Gabriel Turner

or just split, reverse, join

Liam Thompson
Liam Thompson

lost cause m8, they're stuck on the stack to the exclusion of things like good judgement

Nathaniel Anderson
Nathaniel Anderson

It doesn't even compile afaik, String array=new String[] is not Java legal.

Owen Brooks
Owen Brooks

It took about 15 minutes.
For that shit?. LOL.

Samuel Thompson
Samuel Thompson

What kind of skills/years experience would someone need to get a job like that? I'm only at my first real job making 65k so I'm just looking to keep getting more experience and getting better at all this shit so I can make that kind of money one day

Noah Perez
Noah Perez

Recursion, pajeet detected.

Brandon Wright
Brandon Wright

Not that guy, but if you move to Seattle or SF, that could be your first job. I question weather it's worth it, tho.

Xavier Morgan
Xavier Morgan

type this code up exactly
it doesn't compile for half a dozen reasons
I would say no.

Adrian King
Adrian King

reverse(s):
for i = 0, j = len(s) - 1; i < j; ++i, --j
temp = s[i]
s[i] = s[j]
s[j] = temp

psuedocode but still this is a basic algorithm wtf is this input.split, regexp shit?

Asher Ward
Asher Ward

he should have asked for more requirements before building on assumptions.

Jacob Baker
Jacob Baker

what are you doing, son?

Charles White
Charles White

oh i'm retarded and didn't read the description guess i failed the interview baka

Kevin Campbell
Kevin Campbell

Turns out, Sup Forums's fucking huge, and is basically the largest english speaking anonymous board, period.
As such, you get all kinds, and people who should probably act their age take anonymity as a chance to pretend they're only 14 years old again.
Elon fucking Musk could be posting on Sup Forums, and you wouldn't have any way to know.

Nicholas Ward
Nicholas Ward

yup, you need to be more suspicious
if multiple other tards do something that doesn't make sense: check yoself before yo wreck yoself out

Joseph Gomez
Joseph Gomez

people who should probably act their age take anonymity as a chance to pretend they're only 14 years old again.

technology that allows you to feel young again, if only for a little while
no real life worries, no health problems, no stress
just nostalgic teenager silliness
can you really blame them
*sniff*

Jordan Brown
Jordan Brown

Seeing someone use a stack is a lot more intuitive/readable imo than invoking some library functions I'm not familiar with.

Bentley Allen
Bentley Allen

public static String reverseWordOrder(String s) {
if(s == null){
return null;
}
StringBuilder complete = new StringBuilder("");
StringBuilder word = new StringBuilder("");
char c;
for(int i = s.length()-1; i>=0;i--){
c = s.charAt(i);
if(c == ' '){
complete.append(c);
if(word.length()>0){
complete.append(word.reverse().toString());
word.setLength(0);
}
} else if(i == 0 && word.length()>0){
complete.append(word.reverse().toString());
word.setLength(0);
} else {
word.append(c);
}
}
return complete.toString();

}


This takes care of edge cases, like double spaces, spaces at start and end of string.

Charles Mitchell
Charles Mitchell

stack
loop for pushing
loop for popping
still doing concatenation all over the place instead of a string builder

better than split-reverse-join
library functions I'm not familiar with
thank you for your time

Christian Wood
Christian Wood

reverseWordOrder

not
newWordOrder
(measured) bantz during the interview are an asset you should utilize, to compensate for that overly complicated and possibly wrong solution.

Jack Gutierrez
Jack Gutierrez

Just being honest, I don't know Java faggotry! And I'd be interested to see which is actually more efficient, what are these library functions doing that makes them better?

Kayden Adams
Kayden Adams

I'd be interested to see which is actually more efficient, what are these library functions doing that makes them better?
It depends on whether we're optimizing for efficiency or maintainabiliy.
It's usually a sign of bad prioritization (I did that too back in the day) to optimize code for efficiency before having it measured and hot spots being marked.
We're excluding stuff like throwing quadratic+ algos at your main biggest-N data, obviously.

In any case, efficiency is also a nice thing to bring up while doing this. You can go like "I'm optimizing this first draft for readability. It should be linear, but IIRC probably does several more passes over the data than absolutely necessary - is this meant to be a hot path which we want to further optimize in a next draft?"

Lincoln Hill
Lincoln Hill

Good point, and I did find an error indeed, specifically Strings of length 1, but this fixes it. Without paying atention edge cases I'd ofc just split the string and iterate over that.

public static String newWordOrder(String s) {
if(s == null){
return null;
}
StringBuilder complete = new StringBuilder("");
StringBuilder word = new StringBuilder("");
char c='c';
for(int i = s.length()-1; i>=0;i--){
c = s.charAt(i);
if(c == ' '){
complete.append(c);
if(word.length()>0){
complete.append(word.reverse().toString());
word.setLength(0);
}
} else {
word.append(c);

}
}
if(word.length()>0){
complete.append(word.reverse().toString());
}
return complete.toString();

}

Jacob Bailey
Jacob Bailey

So when do I start?
So when do I start?

import java.util.Scanner;

public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Hello, world!");
if(1==2)
System.out.println("false"); //should not happen.....
Scanner myScanner = new Scanner(System.in);
//This does not compile?
//List<Object> myList = Arrays.as list(myArray);
//Collections.reverse(myList);
//System.out.println(myList.toArray().toString());

//A T T E M P T # 2
Scanner scanner = new Scanner(System.in);
System.out.println("Type in word 1!");
String word = scanner.next();
System.out.println("Type in word 1!");
String word1 = scanner.next(); System.out.println("Type in word 2!");
String word2 = scanner.next();
System.out.println("Type in word 3!");
String word3 = scanner.next();
System.out.println("Type in word 4!");
String word4 = scanner.next();
System.out.println("Type in word 5!");
String word5 = scanner.next();
System.out.println("Type in word 6!");
String word6 = scanner.next();

System.out.println("Type in word 7!");

String word7 = scanner.next();

System.out.println("Type in word 8!");

String word8 = scanner.next();

System.out.println("Type in word 9!");

String word9 = scanner.next();

System.out.println("Type in word 10!");

String word10 = scanner.next();

//Prints out the string reversed
System.out.println(word10+word9+word8+word7+word6+word5+word4+word3+word2+word1);
}

Jaxson Rogers
Jaxson Rogers

word.reverse()

Ian Bell
Ian Bell

Definitely not. Faggot made all that rainbow text. Pick a fucking color, snowflake.

Blake Gomez
Blake Gomez

Why not just use Haskell? The code would literally be "reverse string"

Camden Lewis
Camden Lewis

Actually, the order of operations should be this:

public static String reverseWordOrder(String s) {
if(s == null){
return null;
}
StringBuilder complete = new StringBuilder("");
StringBuilder word = new StringBuilder("");
char c='c';
for(int i = s.length()-1; i>=0;i--){
c = s.charAt(i);
if(c == ' '){
if(word.length()>0){
complete.append(word.reverse().toString());
word.setLength(0);
}
complete.append(c);

} else {
word.append(c);
}
}
if(word.length()>0){
complete.append(word.reverse().toString());
}
return complete.toString();

}

Justin Baker
Justin Baker

another quality candidate with excellent attention to detail

Robert Foster
Robert Foster

not using s.split(' ')

William Green
William Green

Who are you quoting?

Ayden Price
Ayden Price

The point of that wall of code is to not get rid of double spaces and spaces at the end/beginning of the sentence.

Nicholas Morris
Nicholas Morris

the voices inside my head when I read the silliness you wrote.

Grayson Morgan
Grayson Morgan

Ah, crap, I just noticed that you can't reconstitute >1 separators from the split() output. Right-o.
Doesn't Java have a more sane split-like function in the stdlib?

Juan Torres
Juan Torres

Could begin by having something that even compiles.

Justin Hughes
Justin Hughes

Actually you were right, and I was retarded. .split(' ') works just fine, the only edge case that needs to be paid attention to is a ' ' at the end of the sentence. .
This does the same thing as my previous crap

Thomas Parker
Thomas Parker

 
public static String newWordOrder(String s) {
if(s == null){
return null;
}
String[] a = s.split(" ");
StringBuilder complete = new StringBuilder("");
if(s.charAt(s.length()-1) == ' '){
complete.append(' ');
}
for(int i = a.length-1; i>= 0;i--){
complete.append(a[i]);
if(i != 0){
complete.append(' ');
}
}
return complete.toString();

}

Parker Russell
Parker Russell

Eh, I gotta admit split's interface is shit - no trivial way to keep delimiters. Lookarounds etc should not be required for such a (I feel) common use case.

Landon James
Landon James

s.charAt(s.length()-1) == ' '

- what about strings that end on 2+ spaces?
- holy fuck how inconsistent can split get? It keeps empty tokens on spaces in the start of the string, but not in the end. Such retarded semantics design certainly contributes to the unnecessary verbosity of Java code, IMO.

Carson Perez
Carson Perez

well, damn you are right. A proper fix that comes to mind is to iterate the string from the back and just count the empty tokens until first real char. But yeah, you are right, this makes for ugly code.

Isaac Thomas
Isaac Thomas

in a real interview, go for the simplest solution (e.g. ignores multi-space delims), then bring the interviewer's attention to the shortcomings and discuss if they want to see you write the ugly code to handle the corner cases.
Most often this is just a on-fail-stop-interview smoke test (think fizzbuzz 1.3), so going all deep-dive on them might be counter-productive.

Benjamin Phillips
Benjamin Phillips

as it turns out the curly brace is not part of the if statement, but part of the block construct.

Putting it next to the if makes it seem like it belongs to the if, and it is also easier to miss when people have a bare if-statement where the next line is not a block, so only the atomic statement on the next line gets included in the if

putting them on a new line you can instantly match curly braces by their indentation level and also know which statement they belong to

Liam Perry
Liam Perry

Yeah, in a real interview I'd have never started with the edge cases right away.
But it just goes to show you that stuff like that can still trip you up, even if you already got a job building complex distributed systems.

Xavier Moore
Xavier Moore

His comment game is on point... having a comment block as large as the actual function...

Jose Richardson
Jose Richardson

That comment block is from the interviewer you dummy

Nolan Ortiz
Nolan Ortiz

Oh yeah, definitely.
Often it's the majority of your time wasted on such silliness, instead of more productive shit.
But interfacing with shit code is often the more realistic approach than doing shit "the proper way".
Worse is better and all that :\

Robert Hernandez
Robert Hernandez

What's with all the premature optimization? The task isn't to design a class. It's literally one function that will be written once and never looked at again. If your application is running within whatever time/memory you've identified as necessary then who cares?

Alexander Morgan
Alexander Morgan

i put effort into this shitpost someone acknowledge

Jaxon Ross
Jaxon Ross

fn reverse_string(input: &str) -> String {
input.split_whitespace().rev().collect::<Vec<_>>().join(" ")
}

and people say Rust is shit

Aiden Taylor
Aiden Taylor

Curly braces don't need to be on their own line if shit is indented properly.
The problem with the code in the OP is that the indentation is fucked.

Sebastian James
Sebastian James

even if stuff is indented properly, it is easier to miss a curly brace next to e.g an else-statement than it is to miss one on its own line

Cameron Ramirez
Cameron Ramirez

if shit is indented properly.
not to mention that curly-brace languages do not actually rely on indentation, so you are setting yourself up for disaster if you rely on indentation rather than the actual curly braces, even if indentation helps

Alexander Martin
Alexander Martin

Fastest and most dangerous solution coming through

void revwords(char *src, char *dest, size_t len) { 
size_t srcptr = len;
size_t destptr = 0;
size_t wordlen = 0;
while (srcptr--) {
if (src[srcptr] == ' ') {
memcpy(dest+destptr, src+srcptr+1, wordlen);
destptr += wordlen;
dest[destptr++] = ' ';
wordlen = -1;
}
wordlen++;
}
memcpy(dest+destptr, src, wordlen);
dest[len] = '\0';
}

int main() {
char *src = "foo bar baz qux";
char dest[strlen(src)+1];
revwords(src, dest, strlen(src));
printf("%s\n", dest); // qux baz bar foo
}

Jordan Lewis
Jordan Lewis

def reverse_words(s):
return " ".join(reversed(s.split()))

Get with the times you geezers! No one uses compiled languages anymore.

Caleb Bell
Caleb Bell

my solution is better because if you only split by spaces then you don't account for punctuation marks

Andrew Rodriguez
Andrew Rodriguez

Just use split(" "), it will be faster than tokenizer in modern java.

Alexander Perez
Alexander Perez

fuck, i need to git gud at C
well here's my implementation

void reverse_words_len(char *output, char *input, int length)
{
int word_size = 0;
int i = 0;
for (; i <= length; i++)
{
if (input[i] == ' ' || !input[i])
{
int word_index = 0;
output[length - i - 1] = input[i];
for (; word_index < word_size; word_index++)
{
output[length - i + word_index] = input[i - word_size + word_index];
}
word_size = 0;
}
else
{
word_size++;
}
}
output[length] = '\0';
}

void reverse_words(char *output, char *input)
{
int string_size = 0;
/*One iteration to get the string length*/
while (input[string_size])
{
string_size++;
}
reverse_words_len(output, input, string_size);
}

Ryan Murphy
Ryan Murphy

return implode(' ', array_reverse(explode(' ', $text)));

Angel Carter
Angel Carter

Reading this thread made me sad.

"this is a test".split(' ').reverse()

Connor Watson
Connor Watson

Well for Java I would have liked to see the StringSingletonFactoryBeanReverser interface implemented and maybe an StringAbstractObserverReversalProxyFlyweight to make sure we don't have any contention issues when doing double-checked locking. Did you check with your Kanban Scrum leader at your daily standup to see if this implementation works
?

Kayden Bell
Kayden Bell

js makes me sad too. too many """""devs"""" think they know software engineering because they can use js functions

Ethan Jones
Ethan Jones

all the pleb langs itt

   revwords =: |.&.;:

Christian Sanders
Christian Sanders

part of software engineering is about not reinventing the wheel. Not using a tested library function and rolling your own actually makes you a worse programmer.

Bentley Bailey
Bentley Bailey

spotted the junior dev

Logan Phillips
Logan Phillips

<?php

class homo
{
public static function revWords($sentence)
{
return implode(" ", array_reverse(explode(" ", $test)));
}
}


what do I win

David Thomas
David Thomas

php is the worst language i've ever seen

Chase Allen
Chase Allen

but why

Lucas Gomez
Lucas Gomez

well if about 100 people thought about a problem and there is a clean, neat, fast solution that everyone agrees on, MAYBE, just MAYBE it's better than what your 9000 iq can come up with.

We know, you are better than the entire SO, everyone could learn from you, etc. Glad you are so smart, buddy!

Dominic Barnes
Dominic Barnes

Dream candidate would be a cute girl(male) and offer to rim me to orgasm.

Attached: original.png (635 KB, 1280x1280)

Disable AdBlock to view this page

Disable AdBlock to view this page

Confirm your age

This website may contain content of an adult nature. If you are under the age of 18, if such content offends you or if it is illegal to view such content in your community, please EXIT.

Enter Exit

About Privacy

We use cookies to personalize content and ads, to provide social media features and to analyze our traffic. We also share information about your use of our site with our advertising and analytics partners.

Accept Exit