DEV Community

Ali Spittel
Ali Spittel

Posted on

Daily Coding Puzzles

I think a lot of people know this at this point, but I love writing code. To wake myself up in the morning and get my brain running, I normally solve a code puzzle first thing when I get to work.

I normally find these on Project Euler, CodeWars, or HackerRank -- though I'm totally open to suggestions if anybody has a really good alternate resource! I really love the problem-solving nature of these code challenges, and how I can sometimes can come up with really cool out of the box solutions to them. I do feel like they help me become a stronger programmer, and an added bonus is that if I am interviewing at the time a lot of interview questions are similar to these (for better or for worse).

Since I'm already doing these every day, I thought it would be really cool to share my results on social media to keep me accountable and to see how other people solve the same problem. I normally solve these challenges in Python or JavaScript, but other people have been posting in Ruby, Rust, Ramda, and Clojure so far (which is so cool to see!). Some of them I have solved before at some point, so I post multiple answers in different languages or my refactors!

If you would like to follow along and post your own solutions (or just see other people's), follow me on Twitter or I've been using the hashtag #CodingPuzzle on them, so you could follow there instead! I normally post in between 8 and 9 AM EST since that is normally when I get to work! It's also led to some interesting discussions on efficiency and the strengths of different programming languages for solving these types of problems! These problems are also a variety of difficulties, so if one day's problem is too hard, still follow the next day for a new one!

To get started, today's problem was Project Euler Problem 2: Even Fibonacci Numbers: Each new term in the Fibonacci sequence is generated by adding the previous two terms. Find the sum of the even-valued terms. Please post your answer here!

If you want to catch up on the previous ones, they were:

Hope to see your answers!

Top comments (12)

Collapse
 
sam_ferree profile image
Sam Ferree

Okay, just pipe the number of even terms you want into STDIN (an input of 4 will display the sum of the first 4 even terms of fibonacci) and you're good to go.

Befunge 93:

188p199p&1                     v
88g99g+88p88g99g+:99p+\1-:!#v_\>
                            >\.@

Kind of disappointed as this solution uses get and put and therefore is less... "fungical"? but trying to do this all on a single stack got away from me.

A Funge++ solution might look more elegant...

Collapse
 
sam_ferree profile image
Sam Ferree • Edited

Here we go, MUCH happier with this Funge++ solution:

&}1}1      v
{{1-:!#v_}}>:[+:]+
       >}.@
Collapse
 
zenmumbler profile image
zenmumbler • Edited

Just to show, Day 3 in C, Time: O(n), Space: O(1), the result is processed in place. Of course, this one only works with ASCII…

Quick subquiz for anyone actually reading this: under what circumstances will this program crash or exhibit undefined behaviour?

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void esrever(char *s, int from, int to) {
    while (from < to) {
        char temp = s[from];
        s[from] = s[to];
        s[to] = temp;
        from++;
        to--;
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        return 1;
    }

    char *s = argv[1];
    int begin = 0, end = 0, len = strlen(s);

    do {    
        while (end < len && ! isspace(s[end])) {
            end++;
        }
        if (end - begin > 4) {
            esrever(s, begin, end - 1);
        }
        begin = end + 1;
        end = begin;
    } while (end < len);

    printf("%s\n", s);
}
Collapse
 
rpalo profile image
Ryan Palo

Awesome, thanks for sharing. 😁 If you have any interest in learning about bioinformatics (genetics, DNA, inheritance, and the data analysis surrounding it) rosalind.info is a really good site with quite a few puzzles!

Collapse
 
aspittel profile image
Ali Spittel

These are awesome! Definitely adding them to the rotation

Collapse
 
zenmumbler profile image
zenmumbler • Edited

Day 1

const piggy = (str) =>
    str.split(" ")
    .map(word =>
        word[0].match(/\w/) ?
            word.slice(1) + word[0] + 'ay' :
            word
    )
    .join(" ");

console.info(piggy("Pig latin is cool"));
console.info(piggy("Hello world !"));

Time: O(n), Space: O(n)

Day 2

const opposites = {
    "}": "{",
    ")": "(",
    "]": "["
};

function isBalanced(str) {
    if (str.length & 1) {
        return false;
    }
    const openers = [];
    for (const c of str) {
        if (c === "{" || c === "(" || c === "[") {
            openers.push(c);
        }
        else {
            const opener = openers.pop();
            if (opener !== opposites[c]) {
                return false;
            }
        }
    }
    return true;
}

function balance(input) {
    const lines = input.split("\n");
    const testCount = parseInt(lines[0]);
    let index = 1;
    while (index <= testCount) {
        const result = isBalanced(lines[index]);
        console.info(result ? "YES" : "NO");
        index++;
    }
}

balance(`7
{[()]}
{[(])}
{{[[(())]]}}
[]{}()
[({})]{}()
({(){}[]})[]
({(){}[]})[](
`);

Time: O(n), Space: O(n)

Day 3

const esrever = (word) =>
    word.split("").reverse().join("");

const spinWords = (str) =>
    str.split(" ")
    .map(word =>
        word.length > 4 ?
            esrever(word) :
            word
    )
    .join(" ");

console.info(spinWords("Hey fellow warriors"));
console.info(spinWords("This is a test"));
console.info(spinWords("This is another test"));

Time: O(n), Space: O(n)

Day 4

let a = 1, b = 2;
let sum = 0;

while (a <= 4000000) {
    if ((a & 1) === 0) {
        sum += a;
    }

    let nb = a + b;
    a = b;
    b = nb;
}
console.info(sum);

Time: O(n), Space: O(1)

Nice exercise, this also shows how clumsy JS is when dealing with string data. Everything has to be converted to and from arrays. And these exercises do not work with non-BMP Unicode characters, but that was not in the requirement ;)

Collapse
 
pbouillon profile image
Pierre Bouillon

Awesome !
Unfortunately I don't have twitter.. but here are my answers:

Day 1

def day_1(sentence: str) -> str:
    result = []

    for word in sentence.split():
        if word.isalpha():
            word = word[1:] + word[0] + 'ay'
        result.append(word)

    return ' '.join(result)

Day 2
Pretty sure it can be waaaay better

def day_2(sequences: List[str]) -> List[str]:
    opening_seq = ('(', '[', '{')
    closing_seq = (')', ']', '}')

    matchs = {
        closing_seq[i]: opening_seq[i]
        for i in range(len(opening_seq))
    }

    def check(sequence: str) -> bool:
        if len(sequence) % 2:
            return False

        if not all([
            sequence.count(i) == sequence.count(matchs[i])
            for i in matchs
        ]):
            return False

        stack = []
        for c in sequence:
            if c in opening_seq:
                stack.append(c)

            elif c in closing_seq:
                if not stack:
                    return False

                elif stack.pop() != matchs[c]:
                    return False

        return not stack

    return ['YES' if check(s) else 'NO' for s in sequences]

Day 3

def day_3(sentence: str) -> str:
    return ' '.join([
        word if len(word) < 5 else word[::-1]
        for word in sentence.split()
    ])

Day 4

def day_4(limit: int) -> int:
    seq = [0, 1]
    while seq[-1] < limit:
        seq.append(sum(seq[-2:]))
    return sum([i for i in seq if i % 2 == 0])
Collapse
 
maxart2501 profile image
Massimo Artizzu

Day 4 (Project Euler #2) has been already proposed by @peter : dev.to/peter/project-euler-2---eve...

I gave my answer there 🙂

Others here have proposed pretty good solutions for the other three, but my answer to the fourth problem is distinctively different IMO.

Collapse
 
rrampage profile image
Raunak Ramakrishnan

Thanks for this, Ali. Another source of good programming puzzles is the Daily Programmer subreddit . The tasks are categorized as easy, intermediate and hard and there is a good discussion on how the solutions can be improved.

Collapse
 
gmartigny profile image
Guillaume Martigny

It's only JS and really hacky, but I've come to like alf.nu.

Collapse
 
aspittel profile image
Ali Spittel

Oh awesome! Definitely adding those to the rotation -- I like the RegEx series because I don't like writing them so I should get more practice in!

Collapse
 
ronaldoperes profile image
Ronaldo Peres

You can try this one:

codingame.com/servlet/urlinvite?u=...

Add me as a friend!!