## DEV Community is a community of 603,019 amazing developers

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

loading... # Coding Puzzles: Week of 4/8

Ali Spittel on April 08, 2019

I'm bringing back the coding puzzles after a few month hiatus! Every day, I post coding puzzles. These are quick coding challenges that increase i...  Laurie • Edited

Haha, bitwise xor. Since it's immutable and commutative it'll reduce down to the stray!

I should add that this only works because it’s an odd number of elements in the array. An even number of matching elements cancel each other out to result in the “stray”.

Thread russ

Oh my, it even works in python!

``````def stray(arr):
count = {}
for index, i in enumerate(arr):
count[i] = count.setdefault(i, 0) + 1
if index >= 2 and len(count.keys()) > 1:
break
return next(k for k, v in count.items() if v == 1)

from functools import reduce

def intstray(arr: [int]):
return reduce(lambda x,y: x ^ y, arr)

assert(intstray([1, 1, 2]) == 2)
#nope..!
#assert(intstray([1, 1, 2, 1]) == 2)
assert(intstray([17, 17, 3, 17, 17, 17, 17]) == 3)
assert(intstray([1, 2, 2]) == 1)
assert(stray(["bob", "bob", "bob", "steve", "bob"]) == "steve")
``````
Thread Ahmed Musallam • Edited

here my cheap solution:

``````function stray(array) {
var sorted = array.sort((a,b) => a - b)
if (sorted === sorted) return sorted.pop();
else return sorted.shift()
}
``````

or shorter and more unreadable:

``````function stray(array) {
var sorted = array.sort((a,b) => a - b)
return sorted === sorted ? sorted.pop() : sorted.shift();
}

`````` Jelle Bekker

in c# using linq:

``````public static int Stray(int[] numbers)
{
return numbers.Aggregate((x, y) => x ^ y);
}
``````

or:

``````public static int Stray(int[] numbers)
{
return numbers.GroupBy(x => x).Single(num => num.Count() == 1).Key;
}
`````` Joshua Gilless

Thanks for this! I don't really know C++, but I figured I'd give it a shot:

``````int stray(std::vector<int> numbers) {
int n1, n2, n3;
for (int i = 2; i < numbers.size(); i++) {
n1 = numbers[i];
n2 = numbers[i - 1];
n3 = numbers[i - 2];
if (n1 == n2 && n1 != n3) {
return n3;
} else if (n1 == n3 && n1 != n2) {
return n2;
} else if (n1 != n2 && n2 == n3) {
return n1;
}
}
};
`````` Joshua Gilless • Edited

@laurieontech did something really cool in JS with a bitwise XOR (her answer is above), so I figured I'd update this C++ answer with a bitwise XOR since I love it!

``````int stray(std::vector<int> numbers) {
int r = numbers;
for (int i = 1; i < numbers.size(); i++)
{
r ^= numbers[i];
}
return r;
};
`````` russ

Looks a bit messy, but I was going for something that might not be too inefficient with a large input array

``````def stray(arr):
count = {}
for index, i in enumerate(arr):
count[i] = count.setdefault(i, 0) + 1
if index >= 2 and len(count.keys()) > 1:
break
return next(k for k, v in count.items() if v == 1)
`````` Courtney • Edited

This is the first I'm finding this, excited to play along! Here is yesterday's (edited to make the colors show up):

``````function stray(numbers) {
let num1 = numbers, num2;
let dupOf1 = false;
for(let i=1; i<numbers.length; i++) {
if(numbers[i] === num1) {
if(num2) return num2;
else dupOf1 = true;
}
else if(numbers[i] === num2) return num1;
else num2 = numbers[i];
}
return dupOf1 ? num2 : num1;
}
`````` russ • Edited
``````import re

def highlight(cmd):
colour_map = [
(r'F+', 'pink'),
(r'L+', 'red'),
(r'R+', 'green'),
(r'\d+', 'orange'),
(r'()+', None),
]
highlighted = []
while(len(cmd)):
for regex, colour in colour_map:
match = re.match(regex, cmd)
if match:
idx_start, idx_end = match.span()
highlighted.append((cmd[idx_start:idx_end], colour))
cmd = cmd[idx_end:]
break
else:
highlighted.append((cmd, None))
cmd = cmd[1:]
return ''.join(['<span style="color: {}">{}</span>'.format(colour, string) if colour else string for string, colour in highlighted])
`````` russ

And now with added re.sub with a callable, which I had no idea was a thing! These coding things are pretty nifty for leaning new tricks I must say!

``````import re

def highlight(cmd):
colour_map = [
(r'F+', 'pink'),
(r'L+', 'red'),
(r'R+', 'green'),
(r'\d+', 'orange'),
(r'()+', None),
]

def replacer(match : re.Match):
substr = match.group()
colour = next((colour for regex, colour in colour_map if re.match(regex, substr)), None)
return '<span style="color: {}">{}</span>'.format(colour, substr) if colour else substr

return re.sub(r'(\D)\1*|(\d+)', replacer, cmd)
`````` Laurie • Edited

Booo regex

``````function highlight(code) {
return code.replace(/(\D)\1+|(\d+|\D)/g, (substr) => {
var color;
let testChar = substr.charAt(0);

if (testChar === 'F') {
color = 'pink';
} else if (testChar === 'L') {
color = 'red';
} else if (testChar === 'R') {
color = 'green';
} else if (!isNaN(testChar)) {
color = 'orange';
} else {
return substr;
}
return '<span style="color: ' + color + '">' + substr + '</span>';
})
}
`````` Laurie • Edited

Quick edit with a dictionary.

``````function highlight(code) {
const colorDict = {'F': 'pink', 'L': 'red', 'R':'green'};

return code.replace(/(\D)\1*|\d+/g, (substr) => {
let testChar = substr.charAt(0);

if (testChar in colorDict) {
return '<span style="color: ' + colorDict[testChar] + '">' + substr + '</span>';
} else if (!isNaN(testChar)) {
return '<span style="color: orange">' + substr + '</span>';
} else {
return substr;
}
})
}
`````` Laurie

Ooh, you're right. I had it that way to start and then ran into problems with a test case that had 663. It was splitting that grouping because it hit the matching case first. But when I removed the capture group generic and made it non-digit that solved that. So can revert back. Thanks :) Courtney

The answers to this kata on codewars are blowing my mind.

``````function highlight(code) {
let codeString = '';
let leftPointer, currentItem;
let colorObj = {'F': '<span style=\"color: pink\">', 'L': '<span style=\"color: red\">', 'R': '<span style=\"color: green\">'};
for(let i=0; i<code.length; i++){
currentItem = code[i];
if(!isNaN(code[i])) {
codeString += '<span style=\"color: orange\">'
leftPointer = i;
while(i+1 < code.length && !isNaN(code[i+1])) {
i++;
}
codeString += code.slice(leftPointer, i+1) + '</span>';
}
else if(colorObj[currentItem]) {
codeString += colorObj[currentItem];
while(i+1 < code.length && currentItem === code[i+1]) {
i++;
codeString += currentItem;
}
codeString += currentItem  + '</span>';
}
if(currentItem === '(' || currentItem === ')') codeString += currentItem;
}
return codeString;
}
`````` Jelle Bekker

Not a one liner like you guys but C#:

``````using System;
public class Kata
{
public static long StairsIn20(int[][] stairs)
{
long sum = 0;
foreach (var weekday in stairs)
foreach (var steps in weekday)
sum += steps;

return sum * 20;
}
}
`````` Jelle Bekker

Okay, I couldn't help myself:

``````using System;
using System.Linq;

public class Kata
{
public static long StairsIn20(int[][] stairs)
{
return stairs.SelectMany(x => x).Sum() * 20;
}
}
`````` Courtney

Practicing TypeScript for my upcoming internship. And I figured out how to add code highlighting!

``````function stairsIn20(stairs : number[][]) : number {
let totalStairs : number = 0;
for(let day of stairs) {
totalStairs += day.reduce((total, num) => total + num);
}
return totalStairs * 20;
}
`````` Ali Spittel
``````n_cases = int(input())
for i in range(1, n_cases + 1):
check_amount = int(input())
unfound = True
fours = [int(i) for i in str(check_amount)]
others = ["1" if n == 4 else "0" for n in fours]
n = int(''.join(others))
print("Case #{}: {} {}".format(i, n, check_amount - n))
`````` Courtney

brute force for me so far.

``````const readline = require('readline');

function foregone() {
let argumentsArray = [], answerArray = [];
let linecounter = 0, tests;

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (line) => {
linecounter++;
if(linecounter === 1) tests = line;
else {
argumentsArray.push(line);
if(linecounter > tests) rl.close();
}
}).on('close', () => {
for(let i=0; i< argumentsArray.length; i++) {
answerArray.push(noFours(argumentsArray[i]));
}
for(let i=0; i<answerArray.length; i++) {
console.log(`Case #\${i+1}: \${answerArray[i]} \${answerArray[i]}`)
}
process.exit(0);
});

function noFours(num) {
let a = num - 1, b = num - a;
while(a.toString().indexOf('4') !== -1 || b.toString().indexOf('4') !== -1 && a >= b) {
a--, b++;
}
if(a.toString().indexOf('4') === -1 && b.toString().indexOf('4') === -1) return [a, b];
else return undefined
}
}
`````` E. Choroba
``````#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use Math::BigInt;

chomp( my \$cases = <> );
for my \$case (1 .. \$cases) {
chomp( my \$n = <> );
(my \$i = \$n) =~ tr/4/3/;
my \$j = 'Math::BigInt'->new(\$n) - 'Math::BigInt'->new(\$i);
say "Case #\$case: \$i \$j";
}
`````` E. Choroba
``````#!/usr/bin/perl
use warnings;
use strict;

sub perimeters {
my (\$n) = @_;
my @f = (1, 1);
my \$s = 0;
for (0 .. \$n) {
\$s += \$f;
@f = (\$f, \$f + \$f);
}
return 4 * \$s
}

# In a good TDD tradition, I started with these lines:
use Test::More tests => 2;
is perimeters(5), 80;
is perimeters(7), 216;
`````` Courtney

TypeScript. Great practice!

``````export class G964 {
public static perimeter = (n) => {
let fibArray : number[] = [0, 1, 1];
for(let i=3; i<=n+1; i++) {
fibArray[i] = fibArray[i-1] + fibArray[i-2];
}
return fibArray.reduce((a, b) => a + b) * 4;
}
}
``````