#include <math.h> int sumMultiples (int N, int k){ int countMultiples = floor(N/k); int sumMultiples = 0.5*k*countMultiples*(countMultiples+1); return sumMultiples; } int solution (int N, int a, int b){ return sumMultiples(N, a)+sumMultiples(N, b)-sumMultiples(N, a*b); }
using System;- #include <math.h>
namespace Kumite{public class Problem{public static long Sum(int N){// Add your code here.return 0;}}- int sumMultiples (int N, int k){
- int countMultiples = floor(N/k);
- int sumMultiples = 0.5*k*countMultiples*(countMultiples+1);
- return sumMultiples;
- }
- int solution (int N, int a, int b){
- return sumMultiples(N, a)+sumMultiples(N, b)-sumMultiples(N, a*b);
- }
#include <criterion/criterion.h> int sumMultiples(int,int); int solution(int,int,int); Test(the_multiply_function, should_pass_all_the_tests_provided) { cr_assert_eq(solution(30, 3, 7), 214); }
namespace Solution {using NUnit.Framework;using System;- #include <criterion/criterion.h>
[TestFixture]public class SolutionTest{[Test]public void TestForProblemDescription(){Assert.AreEqual(214, Kumite.Problem.Sum(30));}[Test]public void TestForNEquals1(){Assert.AreEqual(0, Kumite.Problem.Sum(1));}[Test]public void TestForNEquals2(){Assert.AreEqual(0, Kumite.Problem.Sum(2));}[Test]public void TestForNEquals3(){Assert.AreEqual(3, Kumite.Problem.Sum(3));}- int sumMultiples(int,int);
- int solution(int,int,int);
[Test]public void TestForExtremeN(){Assert.IsTrue(498404749818 == Kumite.Problem.Sum(1525087));}[Test]public void TestForNEquals8(){Assert.AreEqual(16, Kumite.Problem.Sum(8));}[Test]public void TestForNEqualsGreaterThan300(){Assert.AreEqual(36346, Kumite.Problem.Sum(412));}}- Test(the_multiply_function, should_pass_all_the_tests_provided) {
- cr_assert_eq(solution(30, 3, 7), 214);
- }
const countMultiplesOfKUpToN = (N, k) => Math.floor(N/k), sumLMultiplesOfN = (l, n) => 0.5*n*l*(l+1), sumMultiplesOfAOrBUpToN = (a, b, N) => { const lA = countMultiplesOfKUpToN(N, a), lB = countMultiplesOfKUpToN(N, b), lAB = countMultiplesOfKUpToN(N, a*b), sA = sumLMultiplesOfN(lA, a), sB = sumLMultiplesOfN(lB, b), sAB = sumLMultiplesOfN(lAB, a*b) return sA+sB-sAB } console.log(sumMultiplesOfAOrBUpToN(3,7,30)) console.log(sumMultiplesOfAOrBUpToN(3,7,500000000))
using System;- const countMultiplesOfKUpToN = (N, k) => Math.floor(N/k),
- sumLMultiplesOfN = (l, n) => 0.5*n*l*(l+1),
- sumMultiplesOfAOrBUpToN = (a, b, N) => {
- const lA = countMultiplesOfKUpToN(N, a),
- lB = countMultiplesOfKUpToN(N, b),
- lAB = countMultiplesOfKUpToN(N, a*b),
- sA = sumLMultiplesOfN(lA, a),
- sB = sumLMultiplesOfN(lB, b),
- sAB = sumLMultiplesOfN(lAB, a*b)
- return sA+sB-sAB
- }
namespace Kumite{public class Problem{public static long Sum(int N){// Add your code here.return 0;}}}- console.log(sumMultiplesOfAOrBUpToN(3,7,30))
- console.log(sumMultiplesOfAOrBUpToN(3,7,500000000))
const AbbreviateTwoWords = s => { const [first, middle, ...rest] = s.split(' ') return `${first.slice(0,1)}.${middle.slice(0,1)}. ${rest}` }
public class AbbreviateTwoWords {public static String abbrevName(String name) {String[] names = name.split(" ");return (names[0].charAt(0) + "." + names[1].charAt(0)).toUpperCase();}- const AbbreviateTwoWords = s => {
- const [first, middle, ...rest] = s.split(' ')
- return `${first.slice(0,1)}.${middle.slice(0,1)}. ${rest}`
- }
Test.assertEquals(AbbreviateTwoWords('Jeffrey Jacob Abrams'), 'J.J. Abrams')
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testFixed() { assertEquals("S.H", AbbreviateTwoWords.abbrevName("Sam Harris")); assertEquals("P.F", AbbreviateTwoWords.abbrevName("Patrick Feenan")); assertEquals("E.C", AbbreviateTwoWords.abbrevName("Evan Cole")); assertEquals("P.F", AbbreviateTwoWords.abbrevName("P Favuzzi")); assertEquals("D.M", AbbreviateTwoWords.abbrevName("David Mendieta")); } }- Test.assertEquals(AbbreviateTwoWords('Jeffrey Jacob Abrams'), 'J.J. Abrams')
const rot13 = s => s.replace(/[a-z]/g, m => String.fromCharCode(97+(m.charCodeAt(0)-97+13)%26))
def rot13(s):return rot.encode(s,"rot_13")- const rot13 = s => s.replace(/[a-z]/g, m => String.fromCharCode(97+(m.charCodeAt(0)-97+13)%26))
Test.assertEquals(rot13('abcdefghijklmnopqrstuvwxyz'), 'nopqrstuvwxyzabcdefghijklm')
# TODO: Replace examples and use TDD development by writing your own tests# These are some of the methods available:# test.expect(boolean, [optional] message)# test.assert_equals(actual, expected, [optional] message)# test.assert_not_equals(actual, expected, [optional] message)# You can use Test.describe and Test.it to write BDD style test groupingstest.assert_equals(rot13('abcdefghijklmnopqrstuvwxyz'), 'nopqrstuvwxyzabcdefghijklm')- Test.assertEquals(rot13('abcdefghijklmnopqrstuvwxyz'), 'nopqrstuvwxyzabcdefghijklm')
const decrypt = (s,d,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ') => s.replace(/[A-Z]/g, m => a[(a.indexOf(m)+26-d)%26])
def decrypt(code,amount):#place code herelet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"word = ""x=0for c in range(0,len(code)):for i in range (0,len(let)):if code[c] == " ":word+=" "breakelif code[c] == let[i]:x=ix-=amountif x < 0:x+=26word+=let[x]breakreturn word- const decrypt = (s,d,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ') => s.replace(/[A-Z]/g, m => a[(a.indexOf(m)+26-d)%26])
Test.assertEquals(decrypt("MJQQT YMJWJ",5),"HELLO THERE") Test.assertEquals(decrypt("FVB NVA TL",7),"YOU GOT ME")
Test.assert_equals(decrypt("MJQQT YMJWJ",5),"HELLO THERE")Test.assert_equals(decrypt("FVB NVA TL",7),"YOU GOT ME")- Test.assertEquals(decrypt("MJQQT YMJWJ",5),"HELLO THERE")
- Test.assertEquals(decrypt("FVB NVA TL",7),"YOU GOT ME")
const rotateLeft = arr => arr.map((row,i,s) => row.map((_,j) => s[j][s.length-i-1])) const rotateRight = arr => arr.map((row,i,s) => row.map((_,j) => s[s.length-j-1][i]))
const rotateLeft = (arr) => {let retArr = [[],[],[]]for (let i = 0; i < arr.length; i++){for (let j = 0; j < arr[i].length; j++){retArr[i][j] = arr[j][arr.length - (i + 1)]}}return retArr}const rotateRight = (arr) => {let retArr = [[],[],[]]for (let i = 0; i < arr.length; i++){for (let j = 0; j < arr[i].length; j++){retArr[i][j] = arr[arr.length - (j + 1)][i]}}return retArr}- const rotateLeft = arr => arr.map((row,i,s) => row.map((_,j) => s[j][s.length-i-1]))
- const rotateRight = arr => arr.map((row,i,s) => row.map((_,j) => s[s.length-j-1][i]))
with(Math)highAndLow=s=>max(...s=s.match(/-?\d+/g))+` `+min(...s)
highAndLow=a=>Math.max(...a=a.split` `)+` `+Math.min(...a)- with(Math)highAndLow=s=>max(...s=s.match(/-?\d+/g))+` `+min(...s)
describe('tests', () => { Test.assertEquals(highAndLow("So, even list of 1, 3, -5, 7 and 14 is handled properly"), "14 -5") Test.assertEquals(highAndLow("1 4 2 6 1 6 1 5 2 8 9"), "9 1") Test.assertEquals(highAndLow("1 4 2 6 -10 6 1 5 2 8 9"), "9 -10") Test.assertEquals(highAndLow("5"), "5 5") Test.assertEquals(highAndLow("-13"), "-13 -13") Test.assertEquals(highAndLow("-42 -15 -16 -23 -8 -4"), "-4 -42") Test.assertEquals(highAndLow("7 2369"), "2369 7") Test.assertEquals(highAndLow("138 2945 78 0 18752 924"), "18752 0") Test.assertEquals(highAndLow("-289 0 289"), "289 -289") })
- describe('tests', () => {
- Test.assertEquals(highAndLow("So, even list of 1, 3, -5, 7 and 14 is handled properly"), "14 -5")
- Test.assertEquals(highAndLow("1 4 2 6 1 6 1 5 2 8 9"), "9 1")
- Test.assertEquals(highAndLow("1 4 2 6 -10 6 1 5 2 8 9"), "9 -10")
- Test.assertEquals(highAndLow("5"), "5 5")
- Test.assertEquals(highAndLow("-13"), "-13 -13")
- Test.assertEquals(highAndLow("-42 -15 -16 -23 -8 -4"), "-4 -42")
- Test.assertEquals(highAndLow("7 2369"), "2369 7")
- Test.assertEquals(highAndLow("138 2945 78 0 18752 924"), "18752 0")
- Test.assertEquals(highAndLow("-289 0 289"), "289 -289")
- })
const getIDS = n => [...`${n}`].reduce((r,n) => r+Number(n),0)
function getIDS($number) {return array_sum(str_split($number));}- const getIDS = n => [...`${n}`].reduce((r,n) => r+Number(n),0)
Test.assertEquals(getIDS('1345'), 13); Test.assertEquals(getIDS('12'), 3); Test.assertEquals(getIDS('110'), 2); Test.assertEquals(getIDS('011'), 2);
class MyTestCases extends TestCase{public function testOutput() {$this->assertEquals(getIDS('1345'), 13);$this->assertEquals(getIDS('12'), 3);$this->assertEquals(getIDS('110'), 2);$this->assertEquals(getIDS('011'), 2);}}- Test.assertEquals(getIDS('1345'), 13);
- Test.assertEquals(getIDS('12'), 3);
- Test.assertEquals(getIDS('110'), 2);
- Test.assertEquals(getIDS('011'), 2);
When asked about closest to N
integer divisible by n
, you might think of a neat and simple n*Math.round(N/n)
.
But, is there anything even more concise and fast?
closestMultiple=(N,n)=>n*(N/n+0.5>>0)
describe("Solution", function() {
it('must be rocket fast', function() {
Array.from({length:50000}, (_,i) => i).forEach(n => Test.expect((res=closestMultiple(n,7),!(res%7)&&Math.abs(n-res)<7), `There's a closer to ${n} multiple of 7 than ${res}`))
});
it('has to be short', function(){
Test.expect(solution.length<50)
})
});
const average = grades => !grades.length ? undefined : grades.reduce((avg,score,_,self) => avg+score/self.length, 0)
function average(grades) {if (grades && grades.length) {return grades.reduce((total, grade) => total + grade, 0) / grades.length}}- const average = grades => !grades.length ? undefined : grades.reduce((avg,score,_,self) => avg+score/self.length, 0)
In JavaScript the most popular way of inverting strings would be something, similar to [...str].reverse().join('')
.
And what would be your unusual way?
const invert = str => str.replace(/./g, (_,o,s) => s.charAt(s.length-1-o));
const seed = Array.from({length:10}, (rnd,char) => (rnd=Math.random(), char=String.fromCharCode(Math.round(rnd*25)+97), rnd > 0.8 ? char.toUpperCase() : char)),
str = seed.join(''),
strInv = seed.reverse().join('');
Test.assertEquals(invert(str),strInv);
const multiples = (a,b,max) => Array.from({length:~~(max/(a*b))}, (_,i) => (i+1)*a*b)
#!/bin/bashfor i in $(eval echo {1..$3});doif [ `expr $i % $1` -eq 0 -a `expr $i % $2` -eq 0 ]thenecho $ifidone- const multiples = (a,b,max) => Array.from({length:~~(max/(a*b))}, (_,i) => (i+1)*a*b)
Test.assertDeepEquals(multiples(3,4,120), [12,24,36,48,60,72,84,96,108,120]); Test.assertDeepEquals(multiples(2,7,85), [14,28,42,56,70,84]); Test.assertDeepEquals(multiples(14,15,185), []); Test.assertDeepEquals(multiples(14,17,480), [238,476]); Test.assertDeepEquals(multiples(2,5,90), [10,20,30,40,50,60,70,80,90]); Test.assertDeepEquals(multiples(4,7,97), [28,56,84]);
output = run_shell args: [3,4,120]describe "Solution" doit "should return proper results for 3,4,120" doexpect(output).to include("12\r\n24\r\n36\r\n48\r\n60\r\n72\r\n84\r\n96\r\n108\r\n120")endendoutput2 = run_shell args: [2,7,85]describe "Solution" doit "should return proper results for 2,7,85" doexpect(output2).to include("14\r\n28\r\n42\r\n56\r\n70\r\n84")endendoutput3 = run_shell args: [14,15,185]describe "Solution" doit "should return proper results for 14,15,185" doexpect(output3).to include("")endendoutput4 = run_shell args: [14,17,480]describe "Solution" doit "should return proper results for 14,17,480" doexpect(output4).to include("238\r\n476")endendoutput5 = run_shell args: [2,5,90]describe "Solution" doit "should return proper results for 2,5,90" doexpect(output5).to include("10\r\n20\r\n30\r\n40\r\n50\r\n60\r\n70\r\n80\r\n90")endendoutput6 = run_shell args: [4,7,97]describe "Solution" doit "should return proper results for 4,7,97" doexpect(output6).to include("28\r\n56\r\n84")endend- Test.assertDeepEquals(multiples(3,4,120), [12,24,36,48,60,72,84,96,108,120]);
- Test.assertDeepEquals(multiples(2,7,85), [14,28,42,56,70,84]);
- Test.assertDeepEquals(multiples(14,15,185), []);
- Test.assertDeepEquals(multiples(14,17,480), [238,476]);
- Test.assertDeepEquals(multiples(2,5,90), [10,20,30,40,50,60,70,80,90]);
- Test.assertDeepEquals(multiples(4,7,97), [28,56,84]);
const det = m => m.length == 1 ? m[0][0] : m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0] : m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*det(m.slice(1).map(c => c.filter((_,j) => i != j))),0);
double Matrix::GetValueOfDeterminant(){if((2 == MaxRow)&&(2 == MaxCol)){return GetElement(1,1)* GetElement(2,2) - GetElement(1,2) * GetElement(2,1);}else{double ResultValue = 0;for(int c = 1; c <= MaxCol; c++){int PowOfNegativeOne = std::pow(-1, c);ResultValue += GetCofactorMatrix(1,c).GetValueOfDeterminant() * GetElement(1,c) * PowOfNegativeOne;}return ResultValue;}}- const det = m =>
- m.length == 1 ?
- m[0][0] :
- m.length == 2 ?
- m[0][0]*m[1][1]-m[0][1]*m[1][0] :
- m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*det(m.slice(1).map(c => c.filter((_,j) => i != j))),0);
const test1 = [[3]]; // 3 const test2 = [[3,-2],[7,4]]; // 26 const test3 = [[1,3,7],[2,-1,4],[5,0,2]]; // 81 const test10 = [[3,-3,0,-4,2,0,-3,-3,1,2], [2,-1,2,-3,2,1,0,-3,0,2], [-2,1,4,2,2,-1,-3,4,2,3], [-5,-4,-1,3,0,-5,2,-3,-5,3], [-1,2,-4,4,-1,-4,-1,2,0,-5], [4,-5,-1,2,3,-4,4,-2,-5,-5], [3,4,1,4,-3,-2,-3,-4,3,-3], [-3,0,0,0,5,-5,2,-2,2,0], [-5,-1,0,4,2,3,-3,4,5,2], [3,2,-4,1,-2,-2,0,1,1,-2]]; //−38864151 Test.assertEquals(det(test1), 3); Test.assertEquals(det(test2), 26); Test.assertEquals(det(test3), 81); Test.assertEquals(det(test10), -38864151);
// TODO: Replace examples and use TDD development by writing your own testsDescribe(calculate_determinant){It(calculating){Assert::That(Test3_3Matrix.GetValueOfDeterminant(), Equals(Test3_3Matrix.Test()));Assert::That(Test4_4Matrix.GetValueOfDeterminant(), Equals(Test4_4Matrix.Test()));Assert::That(Test5_5Matrix.GetValueOfDeterminant(), Equals(Test5_5Matrix.Test()));}};- const test1 = [[3]]; // 3
- const test2 = [[3,-2],[7,4]]; // 26
- const test3 = [[1,3,7],[2,-1,4],[5,0,2]]; // 81
- const test10 = [[3,-3,0,-4,2,0,-3,-3,1,2],
- [2,-1,2,-3,2,1,0,-3,0,2],
- [-2,1,4,2,2,-1,-3,4,2,3],
- [-5,-4,-1,3,0,-5,2,-3,-5,3],
- [-1,2,-4,4,-1,-4,-1,2,0,-5],
- [4,-5,-1,2,3,-4,4,-2,-5,-5],
- [3,4,1,4,-3,-2,-3,-4,3,-3],
- [-3,0,0,0,5,-5,2,-2,2,0],
- [-5,-1,0,4,2,3,-3,4,5,2],
- [3,2,-4,1,-2,-2,0,1,1,-2]]; //−38864151
- Test.assertEquals(det(test1), 3);
- Test.assertEquals(det(test2), 26);
- Test.assertEquals(det(test3), 81);
- Test.assertEquals(det(test10), -38864151);
const pairs = (arr,twin) => (twin = arr.find(element => arr.includes((-1)*element)), [twin, (-1)*twin].sort())
function pairs(arr){let sorted = arr.sort();let length = arr.length;for (let i = 0; i < length; i++) {if (sorted.includes(arr[i] * -1)) {return [sorted[i], sorted[i] * -1];}}}- const pairs = (arr,twin) =>
- (twin = arr.find(element => arr.includes((-1)*element)), [twin, (-1)*twin].sort())
describe("Solution", function() { it("should return right pair", function() { Test.assertSimilar(pairs([1, 3, 6, -2, 4, -6]), [-6,6]) Test.assertSimilar(pairs([3, 6, 8, -2, 4, 5, -1, -8]), [-8, 8]) Test.assertSimilar(pairs([3, 6, 8, -14, 4, 5, -1, -7, 14]), [-14, 14]) }); });
- describe("Solution", function() {
- it("should return right pair", function() {
- Test.assertSimilar(pairs([1, 3, 6, -2, 4, -6]), [-6,6])
- Test.assertSimilar(pairs([3, 6, 8, -2, 4, 5, -1, -8]), [-8, 8])
- Test.assertSimilar(pairs([3, 6, 8, -14, 4, 5, -1, -7, 14]), [-14, 14])
- });
- });
const maxProductOf3 = arr => (arr = arr.sort((a,b) => a-b), Math.max(arr[0]*arr[1]*arr[arr.length-1],arr.slice(-3).reduce((p,e) => p*e,1)))
def maximum_product_of_three(lst):max_pr = 0num_num = 0for num in lst:for i in range(0,len(lst)):if i != lst[num_num] and num_num+2 < len(lst):try:if (num*lst[i+1]*lst[i+2])>max_pr:max_num = num*lst[i+1]*lst[i+2]except:passnum_num =+ 1return max_num- const maxProductOf3 = arr =>
- (arr = arr.sort((a,b) => a-b),
- Math.max(arr[0]*arr[1]*arr[arr.length-1],arr.slice(-3).reduce((p,e) => p*e,1)))
Test.assertEquals(maxProductOf3([-3,-2,-1,0,1,2]), 12); Test.assertEquals(maxProductOf3([-3,0,1,2,3]), 6); Test.assertEquals(maxProductOf3([-3,-2,0,1]), 6);
# TODO: Replace examples and use TDD development by writing your own tests# These are some of the methods available:# test.expect(boolean, [optional] message)test.assert_equals(maximum_product_of_three([-4,-4,2,8]), 128)# test.assert_not_equals(actual, expected, [optional] message)# You can use Test.describe and Test.it to write BDD style test groupings- Test.assertEquals(maxProductOf3([-3,-2,-1,0,1,2]), 12);
- Test.assertEquals(maxProductOf3([-3,0,1,2,3]), 6);
- Test.assertEquals(maxProductOf3([-3,-2,0,1]), 6);