[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
>Alright, for this next part, i want you to go up to the whiteboard
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 135
Thread images: 3
File: Interviewer.jpg (17 KB, 350x244) Image search: [Google]
Interviewer.jpg
17 KB, 350x244
>Alright, for this next part, i want you to go up to the whiteboard and write a function that reverses a string in place
>You can write it in any language you like, but you can't use any built-in string members or standard library functions like string.reverse().
>Also, you only have 10 minutes.

What do?
>>
>>51447396
/g/ isn't the place to ask for help on your homework. Try StackOverflow.
>>
Can't strings are immutable.
>>
>>51447411
>any language
>homework
>>
String[::-1]
>>
>>51447396
Concatenate letters in reverse order
Chop off original

Tons of ways to do this OP
>>
>>51447396
>Now invert a binary tree.
>>
>>51447423
Fuck off java
>>
> can't use any built-in string members or standard library functions
> operator[] and string's constructors are both members of std::string

Congratulations you indirectly banned C++.
>>
>no standard library functions
ok
void strrev(char *str, int len)
{
int j = len - 1;
int k = 0;
char c;
while (j > k)
{
c = *(str+j);
*(str+j) = *(str+k);
*(str+k) = c;
j--;
k++;
}
}
>>
>>51447450
Good
>>
>>51447396
print x[::-1]
>>
>>51447427
>>51447506
Uses a built-in string member

>>51447450
Use character arrays.

>>51447481
Good. Now let's see one with no ints chars declared. Just the pointer in the function declaration, and one other pointer. String is zero terminated and has no specified length...
void strrev(char *str) {
char *p = str;
while(*(++p));
for(--p; p>str; --p, ++str) {
*p ^= *str;
*str ^= *p;
*p ^= *str;
}
}
>>
>>51447396
no standard library functions at all or no standard library functions specifically designed for strings?

and if there's no built-in string members, are we to assume that the string in question is of a custom member?

now i'm thinking about customizing my member and I think i need to go to bed.
>>
Walk out because I'm not a good programmer....
:(
>>
>>51447450
Needing a std::string to reverse an array. Anon...
>>
>>51448198
This is bordering on autism.
I'd kick you out for that shit because you'd no doubtedly pepper our codebase with autistic autistic bitwise xor functions that actually manage to run slower on modern architectures.
>>
>>51448560
People who do stuff like that usually only do it for least-lines or other artificial challenges. Stuff like Perl golf or IOCCC. For real production code, they'd use a standard library function for string reversing and tend toward readability and maintainability rather than clever or obfuscated shit.
>>
def reverse_string(string):
string = list(string)
k = len(string) - 1
i = 0
while k > i:
string[i], string[k] = string[k], string[i]
i += 1
k -= 1

print ''.join(string)


def reverse_string(string):
characters = [""]*len(string)
for i in xrange(len(string)):
characters[i] = string[i]
characters = reverse_array(characters)
string = ""
for character in characters:
string += character
print string

def reverse_array(arr):
i = 0
k = len(arr) - 1
while k > i:
arr[i], arr[k] = arr[k], arr[i]
k -= 1
i += 1
return arr


def reverse_string(string):
orig_length = len(string)
for i in xrange(len(string) - 1, -1, -1):
string += string[i]
print string[orig_length:len(string)]


sorry if none of this satisfies your autism OP, in the real world string[::-1] works just fine
>>
File: cry.png (1 MB, 1280x720) Image search: [Google]
cry.png
1 MB, 1280x720
>>51448681
>for i in xrange(len(string) - 1, -1, -1):

>mfw this designated street shitter has a job and I don't
>>
>>51448198
hello, I like how you made this whole thread just so you could smugly post your dumb string reverser ehehehehehehhhhhhhhhhhhhhhh
>>
>inb4 js

(function reverse(str) {
for(var i = 0, out = "", len = str.length; i < len; i++) {
out += str.substring(len - i - 1, len - i);
}

return out;
})("simple");
>>
>>51448942
You're right, how un-Pythonic of me.

def reverse_string(string):
orig_length = len(string)
for char in reversed(string):
string += char
print string[orig_length:len(string)]

reverse_string(")^: beew ,erom yrc")
>>
>>51447396
>Why would I write code on a whiteboard?
>Why would I not use the efficient built-in library functions?
>>
>>51447396
why?
>>
>>51449804
>>51449765
I think I have seen enough, we will call you.
>>
"TOGGAF A SI PO".split("").reverse().join("")
>>
Ask if I can design a turing machine that would do it.
>>
int len =strlen(array);
for(int i = 0; i < len/2; i++)
{
int tmp = array[i];
array[i] = array[(len-1)-i];
array[(len-1)-i] = tmp;
}


Was this meant to be difficult?
>>
Javascript is the obvious choice here
>>
fn reverse(string)
l, r := 1, len(string)
while l < r do
string[l], string[r] := string[r], string[l]
l +:= 1
r -:= 1
od
end
>>
package main

func main() {
s := []byte("TOGGAF A SI PO")
l := len(s)
t := make([]byte, l)
for i, c := range s {
t[l-i-1] = c
}
println(string(t))
}
>>
>>51448198
Honestly just show that you have autism line count.
>>
I'm still learning programming but couldn't you just used an inverse for loop and loop through each character using something like charAt?
>>
>>51450046
>charAt
does your language even let you access array elements directly?
>>
return(gnirts)
>>
>>51447396
Let's see if I can still do this.
int i = 0;
while (true)
{
switch (i%8)
{
case 0:
cout << 'f';
break;
case 1:
cout << 'u';
break;
case 2:
cout << 'c';
break;
case 3:
cout << 'k';
break;
case 4:
cout << ' ';
break;
case 5:
cout << 'y';
break;
case 6:
cout << 'o';
break;
case 7:
cout << 'u';
break;
}
i++;
}


Is this the proper way to do it ?
>>
>can't use library functions
>no #import <string>
Then the given string is a C string. They can be used without libraries (not practical but neither is this assignment). Reversing a C string is trivial and I'd hope anyone here knows how.
>>
def revs(s):
return "".join([s[i-1] for i in range(len(s), 0, -1)])

I probably used something I'm not allowed, right? I don't even understand what "string member" means in Python context. Yeah, that probably makes me a dumb shit, but OP should've worded the specs more carefully.
>>
Could this be done in complexity < O(n) ?
>>
>>51450123
I'm pretty sure mine is O(n/2)
>>
>>51450123
I'm about 98% sure you need to at least access every element of the string once in order to do it. If you disagree I'd love to hear why because I don't believe it's possible.
>>
>>51448198
it's perfect
>>
>>51450123
I'd think you'd have to check with every element of a string if you want to reverse it without basic strings functions, so I say no, but some genius anon feel free to correct me.
>>
>>51450128
>What is O(.)
>>
>>51450128
O(n/2) = O(n) btw.
>>
>>51450181
what

why?
>>
>>51447396
test = "boobs"
result = ""
for i in range(1, len(test) + 1):
result += test[-i]

On my phone so I probably fucked it up.
>>
>>51450184
It's a measure of asymptotic growth of runtime as a function of input size.
>>
>>51450184
to put it naively, asymptotic notations ignore constant factors
>>
fuck this took me 12 minutes
#include <stdio.h>

void rev(char *in) {

char *end = in;

while(*end)
end++;

for(end--; end >= in; end--, in++)
{
char tmp = *in;
*in = *end;
*end = tmp;
}
}

int main ()
{
char str[] = "can I haz job now?";
rev(str);
puts(str);
return 0;
}
>>
>>51450184
Complexity ignores constants because it's meant to express the growth rate, not the precise time that it will take. I advise reading introduction to algorithms.
>>
Something like this

for i = 0; i < length/2; ++i
str[i] = str[i] | str[length-i]
str[length-i] = str[i] | str[length-i]
str[i] = str[i] | str[length-i]
>>
>>51450259
>
str[i] = str[i] | str[length-i]
str[length-i] = str[i] | str[length-i]
str[i] = str[i] | str[length-i]

why do you people do this? you trying to be smart is just making it harder for the compiler to optimize your code for you.
>>
>>51450259
Pretend the "|"s are "^"s.
>>
>>51447440
That's not in place
>>
>>51450280
He said in place. Using a temporary variable is not in place.
>>
>>51450298
what the fuck, yes it is.
>>
>>51450298
in place means writing over the original string
who gives a fuck if you used a temp variable.
>>
>>51447396

> me trying to be really clever

> go to whiteboard
> get a laptop and put it on the table infront of the whiteboard
> write a function that prints the string
> the string is reversed in the laptops reflection on the whiteboard


lateralThinking.jpeg
>>
>>51450298
You are wrong.
>>
>>51450303
Nuh uh.

>>51450306
Okay, I'll use as many temporary variables as places are in the array, then write back on top of the old array. Oh wait, that's not in place.
>>
>>51450298
>>51450329

Fuck your bullshit, "in place" just means it uses O(1) additional space. And guess what, on almost all computers you'll ever be compiling code for
tmp := a
a := b
b := tmp
will be optimized to just two loads and two stores while
a |:= b
b |:= a
a |:= b
involves doing actual math alongside the loads and stores and is slower.
>>
>>51450329
I can't even imagine why you would need more than 3 variables.
>>
>>51449862
This is just these bullshit interviews that's the problem. You want lateral thinking and problem solving. Not a "write real code on a whiteboard"

If it was work out an algorithm for it, then fine, but actual code, fuck off.
>>
>>51449971
You failed. You called a built in function to calculate the length of the string. >>51449971
>>
>>51450390
They're not asking for code that fucking compiles. They'd be happy seeing pseudocode that shows you thinking through an algorithm
>>
>>51450405
>you can use any language

Implies they want code.
>>
>>51450416
They're not gonna run the code off the whiteboard.
They just want you to write an algorithm in a language you're comfortable in.
>>
>>51450397
then substitute it with a for loop counting until null
>>
>>51447396
>>51447445
That's fucking trivial. Anyone who fails at this isn't even capable of bringing the real devs coffee.
>>
>>51450341
It's also less clear what your intent is which kills maintainability.
>>
(define (reverse str)
(define (reverse-list lst)
(if (null? lst)
'()
(append (reverse-list (cdr lst)) (list (car lst)))))
(set! str (list->string (reverse-list (string->list str)))
str)

because fuck you OP
>>
>>51447396
prepare for the worst: PHP done in under 20secs
<?php
$string ="Hello World";
echo $string."\n";
for ($i=strlen($string)-1;$i>=0;$i--){echo $string[$i]."\n";}
?>
>>
>>51450315
kek
>>
does psuedocode count?

for(length of string)
{
temp = string[length - i]
string[length-i]=string[i]
string[i]=temp
}
>>
>>51450921
Now do it without a temporary variable.
>>
>>51450943
>arbitrary limitations of no real-world consequence
>>
>>51450921
That string didn't change at all anon.
>>
>>51448198
I like how that would fail on an empty string and keep increasing p and accessing memory that doesn't belong to you.

10/10
>>
And now, in motherfucking PIKE.

string reverse_string(string str)
{
string *arr_str = explode(str);
string new_str = "";

int i = sizeof(str);
while(i--) new_str += arr_str[i];

return new_str;
}
>>
>>51449146
>>51449239
>>51449971
>>51450000
>>51450010

 private string reverse(string str)
{
string a = "";
for (int i = 0; i < str.Length; i++)
{
a = str[i] + a;
}
return a;
}


>uh
>>
for(var i = 0, reverse = ""; i < string.length; i++) {
reverse = string[i] + reverse;
}
>>
Now write a lazy string reverser.
>>
>>51451428

for(length of string)
{
Print(" fuck off, I'm too lazy")
}
>>
>>51447396

public static function(String s1){
String s2 = "";
for(int i = s1.length -1; i>= 0; i--){
System.out.print("TO TEACHER: this nigger is not doing his homework properly, but going online asking others to do it");
s2 += s1.charAt(i);
}
>>
>>51451156
>in place
>>
>>51447396
rev (x:xs) = rev xs ++ [x] 
rev x = x

beat that
>>
>being autistic enough to want to reverse a string in place
rev = lambda s: reduce(lambda a, b: b + a, s, '')
>>
>>51453925
Nothing is in-place in Haskell, everything is immutable. Try again
>>
>>51454452
>>51454437
>>
>>51447396
A better question adds the caveat "without knowing the length of the string".
>>
>>51447396
I tell him its kind of a shitty thing to not use string.reverse(), then I go write the function on the whiteboard
>>
let rec rev xs acc = match xs with
| [] -> acc
| x :: xs -> rev xs (x :: acc)
>>
>>51450461
90% of /g/ would fail on the spot.
>>
>>51453925
That's pretty inefficient. Better would be:

rev               :: [a] -> [a]
rev xs = rev' xs []

rev' :: [a] -> [a] -> [a]
rev' x ys = x:ys
rev' (x:xs) ys = rev' xs (x:ys)
>>
I love this troll thread
>"do x trivial example, but without any temp variables or civilized features".
>>
str = "Faggot" # OP
rev = "" # Reversed string
for i in range(len(str) - 1, 0, -1):
rev += str[i]
print(rev)

Python
>>
>>51454578
>Demonstrate a simple algorithm without being autistic about it
>>
most people would get shown out the door, desu
>>
>>51447481
undefined behaviour.

>>51448198
undefined behaviour.
Plus you do not check if the characters are equal, nice bug.
>>
>>51456688
>undefined behavior?
I'm not running off the array, and if they let me use strlen (built-in, or otherwise), running off the array is impossible.
>>
>>51456738
defining functions that start with str is undefined behaviour.
>>
>>51454656
>>51452170
>>51451183
>>51451156
>>51451052
>>51450921
>>51450202
>>51449971
ITT: niggers don't know what "in place" means
>>
>>51447396
Is this in place or not?

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


I tested it with:

#include <stdio.h>
int main(void){
char mystring[] = "hello";
reverse(mystring, 5);
printf("%s", mystring);
}
>>
>>51448198
What the fuck is going on here. Someone please explain to me like I'm a retard
>>
>>51457659
Someone writing shitty and unreadable code.
>>
>>51457659
bitwise operators
it's unmaintainable garbage, do NOT use them in actual code you intend to look at more than once
>>
>>51457659
theres a special brand of _ in neckbeards that causes them to get off to bitwise operations and manually accessing registers when reimplementing the standard library, instead of writing clear and maintainable code like >>51453925 or:
(defun rev (str)
(let (revstr)
(loop for char across str do
(push char revstr))
(coerce revstr 'string)))
>>
Memory chunk size optimization.
#include <stdio.h>
#include <limits.h>
void strrev (char* s)
{
char* t = s;
char tmp;
// find the final memory chunk
s -= 1;
while (*(s+=8));
// go back to the beginning of the memory chunk
s -= 7;
while (*(s++));
// go back to the final character
s -= 2;
// reverse the string
do
{
tmp = *t;
*t = *s;
*s = tmp;
} while ((++t) < (--s));
}
int main (int argc, const char** argv)
{
int i;
char s[] = "The quick brown fox jumped over the lazy dog.";
for (i = 0; i < 10000000; i++)
{
strrev (s);
}
printf ("%s\n", s);
}

1.28 seconds according to gprof.
#include <stdio.h>
#include <limits.h>
void strrev (char* s)
{
char* t = s;
char tmp;
while (*(++s));
s -= 1;
do
{
tmp = *t;
*t = *s;
*s = tmp;
} while ((++t) < (--s));
}
int main (int argc, const char** argv)
{
int i;
char s[] = "The quick brown fox jumped over the lazy dog.";
for (i = 0; i < 10000000; i++)
{
strrev (s);
}
printf ("%s\n", s);
}

2.10 seconds according to gprof.

I have no idea why there's a NULL byte at the end of every memory chunk, but it works on my system. The only situation it doesn't work is if someone manually puts a NULL byte somewhere in a string and puts a non-NULL byte at the end of the memory chunk.
>>
Come at me.

#include <stdio.h>

int strlength(char s[]) {
int l = 0;
do {
l++;
} while (s[l] != '\0');

return l;
}


int main() {
char s[] = "the quick brown fox jumps over the lazy dog";
char tmp;

for (int i=0; i<strlength(s)/2; i++) {
tmp = s[i];
s[i] = s[strlength(s)-i-1];
s[strlength(s)-i-1] = tmp;
}

printf("%s\n",s);
return 0;
}
>>
May I ?

char* reverseRecursive(char* from, char* to, int depth, int* length)
{
if (from[depth] == '\0')
{
*length = depth;
to = malloc(sizeof(char) * (*length));
to[depth] = '\0';
return to;
}
else
{
to = reverseRecursive(from, to, depth + 1, length);
to[*length - depth - 1] = from[depth];
return to;
}
}

char* reverse(char* from)
{
int* length = malloc(sizeof(int));
char* to = reverseRecursive(from, NULL, 0, length);
return to;
}
>>
>>51457659
He's using a trick called an XOR swap to swap the two things. It's not a great thing go do nowadays since compilers will optimize away a temporary variable but won't optimize the series of mathematical operations that can't really take advantage of the pipeline.
>>
Just convert the string to a char array and read each element backwards with a simple for loop.
>>
>>51447396
string reversestr(string rev){
string revPlace = "";

for(int i = 1; i <= rev.size(); i++)
{
revPlace += rev[rev.size() - i];
}

return revPlace;
}

What did i do wrong ?
>>
>>51447396
size_t len = strlen(s);
for(size_t i = 0; i < len/2; ++i) {
char tmp = s[i];
s[i] = s[len-i-1];
s[len-i-1] = tmp;
}
>>
>>51459301
Is this a good way to do it ?
>>
>>51459399
technical recruiter here,

this is the exact way that i expect.
>>
reverseMe = "this is the string"
newString = ""
newString += reverseMe[17]
newString += reverseMe[16]
newString += reverseMe[15]
newString += reverseMe[14]
newString += reverseMe[13]
newString += reverseMe[12]
newString += reverseMe[11]
newString += reverseMe[10]
newString += reverseMe[9]
newString += reverseMe[8]
newString += reverseMe[7]
newString += reverseMe[6]
newString += reverseMe[5]
newString += reverseMe[4]
newString += reverseMe[3]
newString += reverseMe[2]
newString += reverseMe[1]
newString += reverseMe[0]
reverseMe = newString
print reverseMe
>>
>>51459492
10 / 10
>>
>>51459399
>>51459419
>can't use any built-in string members
you're both fired.
>>
for(i = 0; i<=string.size; i++)
{
string[i] ^= string[size-i];
string[size-i] ^= string[i];
string[i] ^= string[size-i];
}
>>
static char * inplace_reverse(char *s) {
size_t len = 0;
for(char *tmp = s; *tmp != '\0'; ++tmp) {
++len;
}
for(size_t i = 0; i < len/2; ++i) {
char tmp = s[i];
s[i] = s[len-i-1];
s[len-i-1] = tmp;
}
return s;
}
>>
Reversing a string is not a well defined concept in the unicode world. Doing it by hand without calling ready-made functions would be asinine.
>>
>>51460684
Interview problems like this are not a display of practical knowledge, they are a display of problem solving capability.
>>
>>51460699
Ask about reversing an array then. The world doesn't fit into ASCII and devs need to know it.
>>
Double points for a recursive function.
>>
>>51460730
The question ensures that programmers know the implementation of a string is a null-terminated array.
>>
>>51460758
Nowhere in the OP is the language mentioned. Some of them have sane array (and string) implementations.
>>
>>51447396
def rev(string):
string = [string[-i] for i in range(1, len(string) + 1)]
return ''.join(string)
>>
>>51459520
This will return the original string
>>
>>51460804
Then it lets them display their knowledge of those string implementations. I could spend all day spelling things out for you, or you could think for yourself.
>>
>>51459520
https://en.wikipedia.org/wiki/XOR_swap_algorithm
>>
>>51447396
static String reverse(String s)
{
String reverse = """;
int n = s.length() - 1;

for (int i = n; i >= 0; i--)
{
reverse = reverse + s.charAt(i);
}

return reverse;
}
>>
reverse = foldr (flip (:)) []
Thread replies: 135
Thread images: 3

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.