Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Show HN: My vs. chat-GPT's improvement with whitehouse.gov code challenge (pastie.org)
1 point by cranberryturkey on March 28, 2024 | hide | past | favorite
// after about 30 seconds of thinking time I came up with this in 30 minutes (w/o being able to execute the code)

function compress(str) { const arr =str.split(''); let output = ''; let prev = ''; let count = 1; let next = '';

    for (const [i, c] of arr.entries()) {
        if (typeof arr[i+1] !== 'undefined') {
            next = arr[i+1];
        }

        if (prev && prev === c) {
            count++;
        }
        
        if (prev) {
            if (count > 1 && c !== next) {
                output += count;
                output += c; // f
            }

            if (c !== next) {
                count = 1;
            }
        } else {
            output += c
        }

        prev = c;
    }

    return output;
}

const res = compress('feeeedddmmee'); console.log(res);

// I was rejected from the position candidacy, but I decided to ask chat-gpt to improve it:

function compress(str) { // Initialize output string and the count of current character let output = ''; let count = 1;

    for (let i = 0; i < str.length; i++) {
        // Check if the current character is the same as the next character
        if (str[i] === str[i + 1]) {
            // If so, increment the count
            count++;
        } else {
            // If the current character is different from the next or it's the last character,
            // append the count (if greater than 1) and the character to the output string
            if (count > 1) {
                output += count;
            }
            output += str[i];
            // Reset the count for the next character
            count = 1;
        }
    }

    return output;
}

const res = compress('feeeedddmmee'); console.log(res);

/*

As you can see chat gpt's versions is much more succinct and readable but I had to write this without being able to execute/debug the code as I worked on it.

*/

© 2020 Josh Goebel Powered by Node.js, Express, Highlight.js, and Love.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: