## DEV Community is a community of 604,851 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# 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!

Liquid error: internal

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

Liquid error: internal

Liquid error: internal

Liquid error: internal

Hope to see your answers!

## Discussion (13)  Michael Kohl • Edited

Day 4

``````sumEvenFib :: Integer -> Integer
sumEvenFib x = sum . takeWhile (<x) . filter even \$ fibs
where fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

main :: IO ()
main = print \$ sumEvenFib 4000000
`````` 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;
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);
}
`````` 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... zenmumbler • Edited

### Day 1

``````const piggy = (str) =>
str.split(" ")
.map(word =>
word.match(/\w/) ?
word.slice(1) + word + '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);
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 ;) 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 + '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])
``````