task_id
stringlengths
4
14
prompt
stringlengths
112
1.41k
canonical_solution
stringlengths
17
2.16k
test
stringlengths
148
2.54k
declaration
stringlengths
22
1.2k
example_test
stringlengths
0
679
buggy_solution
stringlengths
13
2.16k
bug_type
stringclasses
6 values
failure_symptoms
stringclasses
3 values
entry_point
stringlengths
1
30
signature
stringlengths
14
76
docstring
stringlengths
23
1.21k
instruction
stringlengths
103
1.32k
CPP/100
/* Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a vector, where element at index i represents the number of stones in the level (i+1). Examples: >>> make_a_pile(3) {3, 5, 7} */ #include<stdio.h> #include<vector> using namespace std; vector<int> make_a_pile(int n){
vector<int> out={n}; for (int i=1;i<n;i++) out.push_back(out[out.size()-1]+2); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(make_a_pile(3) , {3, 5, 7})); assert (issame(make_a_pile(4) , {4,6,8,10})); assert (issame(make_a_pile(5) , {5, 7, 9, 11, 13})); assert (issame(make_a_pile(6) , {6, 8, 10, 12, 14, 16})); assert (issame(make_a_pile(8) , {8, 10, 12, 14, 16, 18, 20, 22})); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> vector<int> make_a_pile(int n){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(make_a_pile(3) , {3, 5, 7})); }
vector<int> out={n}; for (int i=1;i<n;i++) out.push_back(out[out.size()-1]+2+i); return out; }
excess logic
incorrect output
make_a_pile
vector<int> make_a_pile(int n)
Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a vector, where element at index i represents the number of stones in the level (i+1). Examples: >>> make_a_pile(3) {3, 5, 7}
Write a C++ function `vector<int> make_a_pile(int n)` to solve the following problem: Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a vector, where element at index i represents the number of stones in the level (i+1). Examples: >>> make_a_pile(3) {3, 5, 7}
CPP/101
/* You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return a vector of the words. For example: words_string("Hi, my name is John") == {"Hi", "my", "name", "is", "John"} words_string("One, two, three, four, five, six") == {"One", 'two", 'three", "four", "five", 'six"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> words_string(string s){
string current=""; vector<string> out={}; s=s+' '; for (int i=0;i<s.length();i++) if (s[i]==' ' or s[i]==',') { if (current.length()>0) { out.push_back(current); current=""; } } else current=current+s[i]; return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(words_string("Hi, my name is John") , {"Hi", "my", "name", "is", "John"})); assert (issame(words_string("One, two, three, four, five, six") , {"One", "two", "three", "four", "five", "six"})); assert (issame(words_string("Hi, my name") , {"Hi", "my", "name"})); assert (issame(words_string("One,, two, three, four, five, six,") , {"One", "two", "three", "four", "five", "six"})); assert (issame(words_string("") , {})); assert (issame(words_string("ahmed , gamal") , {"ahmed", "gamal"})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> vector<string> words_string(string s){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(words_string("Hi, my name is John") , {"Hi", "my", "name", "is", "John"})); assert (issame(words_string("One, two, three, four, five, six") , {"One", "two", "three", "four", "five", "six"})); }
string current=","; vector<string> out={}; s=s+' '; for (int i=0;i<s.length();i++) if (s[i]==' ' or s[i]==',') { if (current.length()>0) { out.push_back(current); current=","; } } else current=current+s[i]; return out; }
value misuse
incorrect output
words_string
vector<string> words_string(string s)
You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return a vector of the words. For example: words_string("Hi, my name is John") == {"Hi", "my", "name", "is", "John"} words_string("One, two, three, four, five, six") == {"One", 'two", 'three", "four", "five", 'six"}
Write a C++ function `vector<string> words_string(string s)` to solve the following problem: You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return a vector of the words. For example: words_string("Hi, my name is John") == {"Hi", "my", "name", "is", "John"} words_string("One, two, three, four, five, six") == {"One", 'two", 'three", "four", "five", 'six"}
CPP/102
/* This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: choose_num(12, 15) = 14 choose_num(13, 12) = -1 */ #include<stdio.h> using namespace std; int choose_num(int x,int y){
if (y<x) return -1; if (y==x and y%2==1) return -1; if (y%2==1) return y-1; return y; }
#undef NDEBUG #include<assert.h> int main(){ assert (choose_num(12, 15) == 14); assert (choose_num(13, 12) == -1); assert (choose_num(33, 12354) == 12354); assert (choose_num(5234, 5233) == -1); assert (choose_num(6, 29) == 28); assert (choose_num(27, 10) == -1); assert (choose_num(7, 7) == -1); assert (choose_num(546, 546) == 546); }
#include<stdio.h> #include<math.h> using namespace std; #include<algorithm> #include<stdlib.h> int choose_num(int x,int y){
#undef NDEBUG #include<assert.h> int main(){ assert (choose_num(12, 15) == 14); assert (choose_num(13, 12) == -1); }
if (y<x) return -1; if (y==x and y%2==1) return -1; if (y%2==1) return x-1; return y; }
variable misuse
incorrect output
choose_num
int choose_num(int x,int y)
This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: choose_num(12, 15) = 14 choose_num(13, 12) = -1
Write a C++ function `int choose_num(int x,int y)` to solve the following problem: This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: choose_num(12, 15) = 14 choose_num(13, 12) = -1
CPP/103
/* You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer(smaller one) and convert that to binary. If n is greater than m, return "-1". Example: rounded_avg(1, 5) => "11" rounded_avg(7, 5) => "-1" rounded_avg(10, 20) => "1111" rounded_avg(20, 33) => "11010" */ #include<stdio.h> #include<math.h> #include<string> using namespace std; string rounded_avg(int n,int m){
if (n>m) return "-1"; int num=(m+n)/2; string out=""; while (num>0) { out=to_string(num%2)+out; num=num/2; } return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (rounded_avg(1, 5) == "11"); assert (rounded_avg(7, 13) == "1010"); assert (rounded_avg(964,977) == "1111001010"); assert (rounded_avg(996,997) == "1111100100"); assert (rounded_avg(560,851) == "1011000001"); assert (rounded_avg(185,546) == "101101101"); assert (rounded_avg(362,496) == "110101101"); assert (rounded_avg(350,902) == "1001110010"); assert (rounded_avg(197,233) == "11010111"); assert (rounded_avg(7, 5) == "-1"); assert (rounded_avg(5, 1) == "-1"); assert (rounded_avg(5, 5) == "101"); }
#include<stdio.h> #include<math.h> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> string rounded_avg(int n,int m){
#undef NDEBUG #include<assert.h> int main(){ assert (rounded_avg(1, 5) == "11"); assert (rounded_avg(7, 5) == "-1"); assert (rounded_avg(10,20) == "1111"); assert (rounded_avg(20,33) == "11010"); }
if (n>m) return "-1"; int num=(m+n+1)/2; string out=""; while (num>0) { out=to_string(num%2)+out; num=num/2; } return out; }
value misuse
incorrect output
rounded_avg
string rounded_avg(int n,int m)
You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer(smaller one) and convert that to binary. If n is greater than m, return "-1". Example: rounded_avg(1, 5) => "11" rounded_avg(7, 5) => "-1" rounded_avg(10, 20) => "1111" rounded_avg(20, 33) => "11010"
Write a C++ function `string rounded_avg(int n,int m)` to solve the following problem: You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer(smaller one) and convert that to binary. If n is greater than m, return "-1". Example: rounded_avg(1, 5) => "11" rounded_avg(7, 5) => "-1" rounded_avg(10, 20) => "1111" rounded_avg(20, 33) => "11010"
CPP/104
/* Given a vector of positive integers x. return a sorted vector of all elements that hasn't any even digit. Note: Returned vector should be sorted in increasing order. For example: >>> unique_digits({15, 33, 1422, 1}) {1, 15, 33} >>> unique_digits({152, 323, 1422, 10}) {} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> unique_digits(vector<int> x){
vector<int> out={}; for (int i=0;i<x.size();i++) { int num=x[i]; bool u=true; if (num==0) u=false; while (num>0 and u) { if (num%2==0) u=false; num=num/10; } if (u) out.push_back(x[i]); } sort(out.begin(),out.end()); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(unique_digits({15, 33, 1422, 1}) , {1, 15, 33})); assert (issame(unique_digits({152, 323, 1422, 10}) , {})); assert (issame(unique_digits({12345, 2033, 111, 151}) , {111, 151})); assert (issame(unique_digits({135, 103, 31}) , {31, 135})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> unique_digits(vector<int> x){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(unique_digits({15, 33, 1422, 1}) , {1, 15, 33})); assert (issame(unique_digits({152, 323, 1422, 10}) , {})); }
vector<int> out={}; for (int i=0;i<x.size();i++) { int num=x[i]; bool u=true; if (num==0) u=false; while (num>0 and u) { if (num%2==0) u=false; num=num/10; } if (u) out.push_back(x[i]); if (u) out.push_back(num); } sort(out.begin(),out.end()); return out; }
excess logic
incorrect output
unique_digits
vector<int> unique_digits(vector<int> x)
Given a vector of positive integers x. return a sorted vector of all elements that hasn't any even digit. Note: Returned vector should be sorted in increasing order. For example: >>> unique_digits({15, 33, 1422, 1}) {1, 15, 33} >>> unique_digits({152, 323, 1422, 10}) {}
Write a C++ function `vector<int> unique_digits(vector<int> x)` to solve the following problem: Given a vector of positive integers x. return a sorted vector of all elements that hasn't any even digit. Note: Returned vector should be sorted in increasing order. For example: >>> unique_digits({15, 33, 1422, 1}) {1, 15, 33} >>> unique_digits({152, 323, 1422, 10}) {}
CPP/105
/* Given a vector of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting vector, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". For example: arr = {2, 1, 1, 4, 5, 8, 2, 3} -> sort arr -> {1, 1, 2, 2, 3, 4, 5, 8} -> reverse arr -> {8, 5, 4, 3, 2, 2, 1, 1} return {"Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"} If the vector is empty, return an empty vector: arr = {} return {} If the vector has any strange number ignore it: arr = {1, -1 , 55} -> sort arr -> {-1, 1, 55} -> reverse arr -> {55, 1, -1} return = {"One"} */ #include<stdio.h> #include<vector> #include<string> #include<map> #include<algorithm> using namespace std; vector<string> by_length(vector<int> arr){
map<int,string> numto={{0,"Zero"},{1,"One"},{2,"Two"},{3,"Three"},{4,"Four"},{5,"Five"},{6,"Six"},{7,"Seven"},{8,"Eight"},{9,"Nine"}}; sort(arr.begin(),arr.end()); vector<string> out={}; for (int i=arr.size()-1;i>=0;i-=1) if (arr[i]>=1 and arr[i]<=9) out.push_back(numto[arr[i]]); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(by_length({2, 1, 1, 4, 5, 8, 2, 3}) , {"Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"})); assert (issame(by_length({}) , {})); assert (issame(by_length({1, -1 , 55}) , {"One"})); assert (issame(by_length({1, -1, 3, 2}) , {"Three", "Two", "One"})); assert (issame(by_length({9, 4, 8}) , {"Nine", "Eight", "Four"})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<map> #include<algorithm> using namespace std; #include<stdlib.h> vector<string> by_length(vector<int> arr){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(by_length({2, 1, 1, 4, 5, 8, 2, 3}) , {"Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"})); assert (issame(by_length({}) , {})); assert (issame(by_length({1, -1 , 55}) , {"One"})); }
map<int,string> numto={{0,"Zero"},{1,"One"},{2,"Two"},{3,"Three"},{4,"Four"},{5,"Five"},{6,"Six"},{7,"Seven"},{8,"Eight"},{9,"Nine"}}; vector<string> out={}; for (int i=arr.size()-1;i>=0;i-=1) if (arr[i]>=1 and arr[i]<=9) out.push_back(numto[arr[i]]); return out; }
missing logic
incorrect output
by_length
vector<string> by_length(vector<int> arr)
Given a vector of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting vector, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". For example: arr = {2, 1, 1, 4, 5, 8, 2, 3} -> sort arr -> {1, 1, 2, 2, 3, 4, 5, 8} -> reverse arr -> {8, 5, 4, 3, 2, 2, 1, 1} return {"Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"} If the vector is empty, return an empty vector: arr = {} return {} If the vector has any strange number ignore it: arr = {1, -1 , 55} -> sort arr -> {-1, 1, 55} -> reverse arr -> {55, 1, -1} return = {"One"}
Write a C++ function `vector<string> by_length(vector<int> arr)` to solve the following problem: Given a vector of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting vector, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". For example: arr = {2, 1, 1, 4, 5, 8, 2, 3} -> sort arr -> {1, 1, 2, 2, 3, 4, 5, 8} -> reverse arr -> {8, 5, 4, 3, 2, 2, 1, 1} return {"Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"} If the vector is empty, return an empty vector: arr = {} return {} If the vector has any strange number ignore it: arr = {1, -1 , 55} -> sort arr -> {-1, 1, 55} -> reverse arr -> {55, 1, -1} return = {"One"}
CPP/106
/* Implement the function f that takes n as a parameter, and returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: f(5) == {1, 2, 6, 24, 15} */ #include<stdio.h> #include<vector> using namespace std; vector<int> f(int n){
int sum=0,prod=1; vector<int> out={}; for (int i=1;i<=n;i++) { sum+=i; prod*=i; if (i%2==0) out.push_back(prod); else out.push_back(sum); } return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(f(5) , {1, 2, 6, 24, 15})); assert (issame(f(7) , {1, 2, 6, 24, 15, 720, 28})); assert (issame(f(1) , {1})); assert (issame(f(3) , {1, 2, 6})); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> vector<int> f(int n){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(f(5) , {1, 2, 6, 24, 15})); }
int sum=0,prod=1; vector<int> out={}; for (int i=1;i<=n;i++) { sum+=i; prod*=i; if (prod%2==0) out.push_back(prod); else out.push_back(sum); } return out; }
variable misuse
incorrect output
f
vector<int> f(int n)
Implement the function f that takes n as a parameter, and returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: f(5) == {1, 2, 6, 24, 15}
Write a C++ function `vector<int> f(int n)` to solve the following problem: Implement the function f that takes n as a parameter, and returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: f(5) == {1, 2, 6, 24, 15}
CPP/107
/* Given a positive integer n, return a vector that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned vector has the number of even and odd integer palindromes respectively. */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<int> even_odd_palindrome(int n){
int num1=0,num2=0; for (int i=1;i<=n;i++) { string w=to_string(i); string p(w.rbegin(),w.rend()); if (w==p and i%2==1) num1+=1; if (w==p and i%2==0) num2+=1; } return {num2,num1}; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(even_odd_palindrome(123) , {8, 13})); assert (issame(even_odd_palindrome(12) , {4, 6})); assert (issame(even_odd_palindrome(3) , {1, 2})); assert (issame(even_odd_palindrome(63) , {6, 8})); assert (issame(even_odd_palindrome(25) , {5, 6})); assert (issame(even_odd_palindrome(19) , {4, 6})); assert (issame(even_odd_palindrome(9) , {4, 5})); assert (issame(even_odd_palindrome(1) , {0, 1})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> vector<int> even_odd_palindrome(int n){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(even_odd_palindrome(12) , {4, 6})); assert (issame(even_odd_palindrome(3) , {1, 2})); }
int num1=0,num2=0; for (int i=1;i<=n;i++) { string w=to_string(i); string p(w.rbegin(),w.rend()); if (w==p and i%2==1) num1+=1; if (w==p and i%2==0) num2+=2; } return {num2,num1}; }
value misuse
incorrect output
even_odd_palindrome
vector<int> even_odd_palindrome(int n)
Given a positive integer n, return a vector that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned vector has the number of even and odd integer palindromes respectively.
Write a C++ function `vector<int> even_odd_palindrome(int n)` to solve the following problem: Given a positive integer n, return a vector that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned vector has the number of even and odd integer palindromes respectively.
CPP/108
/* Write a function count_nums which takes a vector of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums({}) == 0 >>> count_nums({-1, 11, -11}) == 1 >>> count_nums({1, 1, 2}) == 3 */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; int count_nums(vector<int> n){
int num=0; for (int i=0;i<n.size();i++) if (n[i]>0) num+=1; else { int sum=0; int w; w=abs(n[i]); while (w>=10) { sum+=w%10; w=w/10; } sum-=w; if (sum>0) num+=1; } return num; }
#undef NDEBUG #include<assert.h> int main(){ assert (count_nums({}) == 0); assert (count_nums({-1, -2, 0}) == 0); assert (count_nums({1, 1, 2, -2, 3, 4, 5}) == 6); assert (count_nums({1, 6, 9, -6, 0, 1, 5}) == 5); assert (count_nums({1, 100, 98, -7, 1, -1}) == 4); assert (count_nums({12, 23, 34, -45, -56, 0}) == 5); assert (count_nums({-0, 1}) == 1); assert (count_nums({1}) == 1); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> int count_nums(vector<int> n){
#undef NDEBUG #include<assert.h> int main(){ assert (count_nums({}) == 0); assert (count_nums({-1, 11, -11}) == 1); assert (count_nums({1, 1, 2}) == 3); }
int num=0; for (int i=0;i<n.size();i++) if (n[i]>0) num+=1; else { int sum=0; int w; w=abs(n[i]); while (w>=10) { sum+=w%10; w=w/10; } sum-=w*-1; if (sum>0) num+=1; } return num; }
excess logic
incorrect output
count_nums
int count_nums(vector<int> n)
Write a function count_nums which takes a vector of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums({}) == 0 >>> count_nums({-1, 11, -11}) == 1 >>> count_nums({1, 1, 2}) == 3
Write a C++ function `int count_nums(vector<int> n)` to solve the following problem: Write a function count_nums which takes a vector of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums({}) == 0 >>> count_nums({-1, 11, -11}) == 1 >>> count_nums({1, 1, 2}) == 3
CPP/109
/* We have a vector "arr" of N integers arr[1], arr[2], ..., arr[N].The numbers in the vector will be randomly ordered. Your task is to determine if it is possible to get a vector sorted in non-decreasing order by performing the following operation on the given vector: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the vector by one position in the right direction. The last element of the vector will be moved to the starting position in the vector i.e. 0th index. If it is possible to obtain the sorted vector by performing the above operation then return true else return false. If the given vector is empty then return true. Note: The given vector is guaranteed to have unique elements. For Example: move_one_ball({3, 4, 5, 1, 2})==>true Explanation: By performing 2 right shift operations, non-decreasing order can be achieved for the given vector. move_one_ball({3, 5, 4, 1, 2})==>false Explanation:It is not possible to get non-decreasing order for the given vector by performing any number of right shift operations. */ #include<stdio.h> #include<vector> using namespace std; bool move_one_ball(vector<int> arr){
int num=0; if (arr.size()==0) return true; for (int i=1;i<arr.size();i++) if (arr[i]<arr[i-1]) num+=1; if (arr[arr.size()-1]>arr[0]) num+=1; if (num<2) return true; return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (move_one_ball({3, 4, 5, 1, 2})==true); assert (move_one_ball({3, 5, 10, 1, 2})==true); assert (move_one_ball({4, 3, 1, 2})==false); assert (move_one_ball({3, 5, 4, 1, 2})==false); assert (move_one_ball({})==true); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> bool move_one_ball(vector<int> arr){
#undef NDEBUG #include<assert.h> int main(){ assert (move_one_ball({3, 4, 5, 1, 2})==true); assert (move_one_ball({3, 5, 4, 1, 2})==false); }
int num=0; if (arr.size()==0) return true; for (int i=1;i<arr.size();i++) if (arr[i]<arr[arr.size()-1]) num+=1; if (arr[arr.size()-1]>arr[0]) num+=1; if (num<2) return true; return false; }
variable misuse
incorrect output
move_one_ball
bool move_one_ball(vector<int> arr)
We have a vector "arr" of N integers arr[1], arr[2], ..., arr[N].The numbers in the vector will be randomly ordered. Your task is to determine if it is possible to get a vector sorted in non-decreasing order by performing the following operation on the given vector: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the vector by one position in the right direction. The last element of the vector will be moved to the starting position in the vector i.e. 0th index. If it is possible to obtain the sorted vector by performing the above operation then return true else return false. If the given vector is empty then return true. Note: The given vector is guaranteed to have unique elements. For Example: move_one_ball({3, 4, 5, 1, 2})==>true Explanation: By performing 2 right shift operations, non-decreasing order can be achieved for the given vector. move_one_ball({3, 5, 4, 1, 2})==>false Explanation:It is not possible to get non-decreasing order for the given vector by performing any number of right shift operations.
Write a C++ function `bool move_one_ball(vector<int> arr)` to solve the following problem: We have a vector "arr" of N integers arr[1], arr[2], ..., arr[N].The numbers in the vector will be randomly ordered. Your task is to determine if it is possible to get a vector sorted in non-decreasing order by performing the following operation on the given vector: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the vector by one position in the right direction. The last element of the vector will be moved to the starting position in the vector i.e. 0th index. If it is possible to obtain the sorted vector by performing the above operation then return true else return false. If the given vector is empty then return true. Note: The given vector is guaranteed to have unique elements. For Example: move_one_ball({3, 4, 5, 1, 2})==>true Explanation: By performing 2 right shift operations, non-decreasing order can be achieved for the given vector. move_one_ball({3, 5, 4, 1, 2})==>false Explanation:It is not possible to get non-decreasing order for the given vector by performing any number of right shift operations.
CPP/110
/* In this problem, you will implement a function that takes two vectors of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a vector of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". For example: exchange({1, 2, 3, 4}, {1, 2, 3, 4}) => "YES" exchange({1, 2, 3, 4}, {1, 5, 3, 4}) => "NO" It is assumed that the input vectors will be non-empty. */ #include<stdio.h> #include<vector> #include<string> using namespace std; string exchange(vector<int> lst1,vector<int> lst2){
int num=0; for (int i=0;i<lst1.size();i++) if (lst1[i]%2==0) num+=1; for (int i=0;i<lst2.size();i++) if (lst2[i]%2==0) num+=1; if (num>=lst1.size()) return "YES"; return "NO"; }
#undef NDEBUG #include<assert.h> int main(){ assert (exchange({1, 2, 3, 4}, {1, 2, 3, 4}) == "YES"); assert (exchange({1, 2, 3, 4}, {1, 5, 3, 4}) == "NO"); assert (exchange({1, 2, 3, 4}, {2, 1, 4, 3}) == "YES" ); assert (exchange({5, 7, 3}, {2, 6, 4}) == "YES"); assert (exchange({5, 7, 3}, {2, 6, 3}) == "NO" ); assert (exchange({3, 2, 6, 1, 8, 9}, {3, 5, 5, 1, 1, 1}) == "NO"); assert (exchange({100, 200}, {200, 200}) == "YES"); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> string exchange(vector<int> lst1,vector<int> lst2){
#undef NDEBUG #include<assert.h> int main(){ assert (exchange({1, 2, 3, 4}, {1, 2, 3, 4}) == "YES"); assert (exchange({1, 2, 3, 4}, {1, 5, 3, 4}) == "NO"); }
int num=0; for (int i=0;i<lst1.size();i++) if (lst1[i]%2==0) num+=1; for (int i=0;i<lst2.size();i++) if (lst2[i]%2==0) num+=1; if (num<lst1.size()) return "YES"; return "NO"; }
variable misuse
incorrect output
exchange
string exchange(vector<int> lst1,vector<int> lst2)
In this problem, you will implement a function that takes two vectors of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a vector of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". For example: exchange({1, 2, 3, 4}, {1, 2, 3, 4}) => "YES" exchange({1, 2, 3, 4}, {1, 5, 3, 4}) => "NO" It is assumed that the input vectors will be non-empty.
Write a C++ function `string exchange(vector<int> lst1,vector<int> lst2)` to solve the following problem: In this problem, you will implement a function that takes two vectors of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a vector of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". For example: exchange({1, 2, 3, 4}, {1, 2, 3, 4}) => "YES" exchange({1, 2, 3, 4}, {1, 5, 3, 4}) => "NO" It is assumed that the input vectors will be non-empty.
CPP/111
/* Given a string representing a space separated lowercase letters, return a map of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: histogram("a b c") == {{"a", 1}, {"b", 1}, {"c", 1}} histogram("a b b a") == {{"a", 2}, {"b", 2}} histogram("a b c a b") == {{"a", 2}, {"b", 2}} histogram("b b b b a") == {{"b", 4}} histogram("") == {} */ #include<stdio.h> #include<string> #include<map> using namespace std; map<char,int> histogram(string test){
map<char,int> count={},out={}; map <char,int>::iterator it; int max=0; for (int i=0;i<test.length();i++) if (test[i]!=' ') { count[test[i]]+=1; if (count[test[i]]>max) max=count[test[i]]; } for (it=count.begin();it!=count.end();it++) { char w1=it->first; int w2=it->second; if (w2==max) out[w1]=w2; } return out; }
#undef NDEBUG #include<assert.h> bool issame(map<char,int> a,map<char,int> b){ if (a.size()!=b.size()) return false; map <char,int>::iterator it; for (it=a.begin();it!=a.end();it++) { char w1=it->first; int w2=it->second; if (b.find(w1)==b.end()) return false; if (b[w1]!=w2) return false; } return true; } int main(){ assert (issame(histogram("a b b a") , {{'a',2},{'b', 2}})); assert (issame(histogram("a b c a b") , {{'a', 2},{'b', 2}})); assert (issame(histogram("a b c d g") , {{'a', 1}, {'b', 1}, {'c', 1}, {'d', 1}, {'g', 1}})); assert (issame(histogram("r t g") , {{'r', 1},{'t', 1},{'g', 1}})); assert (issame(histogram("b b b b a") , {{'b', 4}})); assert (issame(histogram("r t g") , {{'r', 1},{'t', 1},{'g', 1}})); assert (issame(histogram("") , {})); assert (issame(histogram("a") , {{'a', 1}})); }
#include<stdio.h> #include<math.h> #include<string> #include<map> using namespace std; #include<algorithm> #include<stdlib.h> map<char,int> histogram(string test){
#undef NDEBUG #include<assert.h> bool issame(map<char,int> a,map<char,int> b){ if (a.size()!=b.size()) return false; map <char,int>::iterator it; for (it=a.begin();it!=a.end();it++) { char w1=it->first; int w2=it->second; if (b.find(w1)==b.end()) return false; if (b[w1]!=w2) return false; } return true; } int main(){ assert (issame(histogram("a b b a") , {{'a',2},{'b', 2}})); assert (issame(histogram("a b c a b") , {{'a', 2},{'b', 2}})); assert (issame(histogram("a b c") , {{'a', 1},{'b', 1},{'c', 1}})); assert (issame(histogram("b b b b a") , {{'b', 4}})); assert (issame(histogram("") , {})); }
map<char,int> count={},out={}; map <char,int>::iterator it; int max=0; for (int i=1;i<test.length();i++) if (test[i]!=' ') { count[test[i]]+=1; if (count[test[i]]>max) max=count[test[i]]; } for (it=count.begin();it!=count.end();it++) { char w1=it->first; int w2=it->second; if (w2==max) out[w1]=w2; } return out; }
value misuse
incorrect output
histogram
map<char,int> histogram(string test)
Given a string representing a space separated lowercase letters, return a map of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: histogram("a b c") == {{"a", 1}, {"b", 1}, {"c", 1}} histogram("a b b a") == {{"a", 2}, {"b", 2}} histogram("a b c a b") == {{"a", 2}, {"b", 2}} histogram("b b b b a") == {{"b", 4}} histogram("") == {}
Write a C++ function `map<char,int> histogram(string test)` to solve the following problem: Given a string representing a space separated lowercase letters, return a map of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: histogram("a b c") == {{"a", 1}, {"b", 1}, {"c", 1}} histogram("a b b a") == {{"a", 2}, {"b", 2}} histogram("a b c a b") == {{"a", 2}, {"b", 2}} histogram("b b b b a") == {{"b", 4}} histogram("") == {}
CPP/112
/* Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a vector containing the result string and "True"/"False" for the check. Example For s = "abcde", c = "ae", the result should be ("bcd","False") For s = "abcdef", c = "b" the result should be ("acdef","False") For s = "abcdedcba", c = "ab", the result should be ("cdedc","True") */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; vector<string> reverse_delete(string s,string c){
string n=""; for (int i=0;i<s.length();i++) if (find(c.begin(),c.end(),s[i])==c.end()) n=n+s[i]; if (n.length()==0) return {n,"True"}; string w(n.rbegin(),n.rend()); if (w==n) return {n,"True"}; return {n,"False"}; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(reverse_delete("abcde","ae") , {"bcd","False"})); assert (issame(reverse_delete("abcdef", "b") , {"acdef","False"})); assert (issame(reverse_delete("abcdedcba","ab") , {"cdedc","True"})); assert (issame(reverse_delete("dwik","w") , {"dik","False"})); assert (issame(reverse_delete("a","a") , {"","True"})); assert (issame(reverse_delete("abcdedcba","") , {"abcdedcba","True"})); assert (issame(reverse_delete("abcdedcba","v") , {"abcdedcba","True"})); assert (issame(reverse_delete("vabba","v") , {"abba","True"})); assert (issame(reverse_delete("mamma", "mia") , {"", "True"})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> vector<string> reverse_delete(string s,string c){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(reverse_delete("abcde","ae") , {"bcd","False"})); assert (issame(reverse_delete("abcdef", "b") , {"acdef","False"})); assert (issame(reverse_delete("abcdedcba","ab") , {"cdedc","True"})); }
string n=""; for (int i=0;i<s.length();i++) if (find(c.begin(),c.end(),s[i])==c.end()) n=n+s[i]; if (n.length()==0) return {n,"True"}; string w(n.rbegin(),n.rend()); if (w==n) return {n,"False"}; return {n,"True"}; }
operator misuse
incorrect output
reverse_delete
vector<string> reverse_delete(string s,string c)
Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a vector containing the result string and "True"/"False" for the check. Example For s = "abcde", c = "ae", the result should be ("bcd","False") For s = "abcdef", c = "b" the result should be ("acdef","False") For s = "abcdedcba", c = "ab", the result should be ("cdedc","True")
Write a C++ function `vector<string> reverse_delete(string s,string c)` to solve the following problem: Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a vector containing the result string and "True"/"False" for the check. Example For s = "abcde", c = "ae", the result should be ("bcd","False") For s = "abcdef", c = "b" the result should be ("acdef","False") For s = "abcdedcba", c = "ab", the result should be ("cdedc","True")
CPP/113
/* Given a vector of strings, where each string consists of only digits, return a vector. Each element i of the output should be 'the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count({"1234567"}) {'the number of odd elements 4n the str4ng 4 of the 4nput."} >>> odd_count({"3","11111111"}) {'the number of odd elements 1n the str1ng 1 of the 1nput.", 'the number of odd elements 8n the str8ng 8 of the 8nput."} */ #include<stdio.h> #include<vector> #include<string> #include<map> using namespace std; vector<string> odd_count(vector<string> lst){
vector<string> out={}; for (int i=0;i<lst.size();i++) { int sum=0; for (int j=0;j<lst[i].length();j++) if (lst[i][j]>=48 and lst[i][j]<=57 and lst[i][j]%2==1) sum+=1; string s="the number of odd elements in the string i of the input."; string s2=""; for (int j=0;j<s.length();j++) if (s[j]=='i') s2=s2+to_string(sum); else s2=s2+s[j]; out.push_back(s2); } return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(odd_count({"1234567"}) , {"the number of odd elements 4n the str4ng 4 of the 4nput."})); assert (issame(odd_count({"3","11111111"}) , {"the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."})); assert (issame(odd_count({"271", "137", "314"}) , { "the number of odd elements 2n the str2ng 2 of the 2nput.", "the number of odd elements 3n the str3ng 3 of the 3nput.", "the number of odd elements 2n the str2ng 2 of the 2nput." })); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<map> using namespace std; #include<algorithm> #include<stdlib.h> vector<string> odd_count(vector<string> lst){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(odd_count({"1234567"}) , {"the number of odd elements 4n the str4ng 4 of the 4nput."})); assert (issame(odd_count({"3","11111111"}) , {"the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."})); }
vector<string> out={}; for (int i=0;i<lst.size();i++) { int sum=0; for (int j=0;j<lst[i].length();j++) if (lst[i][j]>=48 and lst[i][j]<=57 and lst[i][j]%2==1) sum+=1; string s="the number of odd elements in the string i of i the input."; string s2=""; for (int j=0;j<s.length();j++) if (s[j]=='i') s2=s2+to_string(sum); else s2=s2+s[j]; out.push_back(s2); } return out; }
excess logic
incorrect output
odd_count
vector<string> odd_count(vector<string> lst)
Given a vector of strings, where each string consists of only digits, return a vector. Each element i of the output should be 'the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count({"1234567"}) {'the number of odd elements 4n the str4ng 4 of the 4nput."} >>> odd_count({"3","11111111"}) {'the number of odd elements 1n the str1ng 1 of the 1nput.", 'the number of odd elements 8n the str8ng 8 of the 8nput."}
Write a C++ function `vector<string> odd_count(vector<string> lst)` to solve the following problem: Given a vector of strings, where each string consists of only digits, return a vector. Each element i of the output should be 'the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count({"1234567"}) {'the number of odd elements 4n the str4ng 4 of the 4nput."} >>> odd_count({"3","11111111"}) {'the number of odd elements 1n the str1ng 1 of the 1nput.", 'the number of odd elements 8n the str8ng 8 of the 8nput."}
CPP/114
/* Given a vector of integers nums, find the minimum sum of any non-empty sub-vector of nums. Example minSubArraySum({2, 3, 4, 1, 2, 4}) == 1 minSubArraySum({-1, -2, -3}) == -6 */ #include<stdio.h> #include<vector> using namespace std; long long minSubArraySum(vector<long long> nums){
long long current,min; current=nums[0]; min=nums[0]; for (int i=1;i<nums.size();i++) { if (current<0) current=current+nums[i]; else current=nums[i]; if (current<min) min=current; } return min; }
#undef NDEBUG #include<assert.h> int main(){ assert (minSubArraySum({2, 3, 4, 1, 2, 4}) == 1); assert (minSubArraySum({-1, -2, -3}) == -6); assert (minSubArraySum({-1, -2, -3, 2, -10}) == -14); assert (minSubArraySum({-9999999999999999}) == -9999999999999999); assert (minSubArraySum({0, 10, 20, 1000000}) == 0); assert (minSubArraySum({-1, -2, -3, 10, -5}) == -6); assert (minSubArraySum({100, -1, -2, -3, 10, -5}) == -6); assert (minSubArraySum({10, 11, 13, 8, 3, 4}) == 3); assert (minSubArraySum({100, -33, 32, -1, 0, -2}) == -33); assert (minSubArraySum({-10}) == -10); assert (minSubArraySum({7}) == 7); assert (minSubArraySum({1, -1}) == -1); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> long long minSubArraySum(vector<long long> nums){
#undef NDEBUG #include<assert.h> int main(){ assert (minSubArraySum({2, 3, 4, 1, 2, 4}) == 1); assert (minSubArraySum({-1, -2, -3}) == -6); }
long long current,min; current=nums[0]; min=nums[0]; for (int i=1;i<nums.size();i++) { if (current<0) current=current+nums.size(); else current=nums[i]; if (current<min) min=current; } return min; }
function misuse
incorrect output
minSubArraySum
long long minSubArraySum(vector<long long> nums)
Given a vector of integers nums, find the minimum sum of any non-empty sub-vector of nums. Example minSubArraySum({2, 3, 4, 1, 2, 4}) == 1 minSubArraySum({-1, -2, -3}) == -6
Write a C++ function `long long minSubArraySum(vector<long long> nums)` to solve the following problem: Given a vector of integers nums, find the minimum sum of any non-empty sub-vector of nums. Example minSubArraySum({2, 3, 4, 1, 2, 4}) == 1 minSubArraySum({-1, -2, -3}) == -6
CPP/115
/* You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: Input: grid : {{0,0,1,0}, {0,1,0,0}, {1,1,1,1}} bucket_capacity : 1 Output: 6 Example 2: Input: grid : {{0,0,1,1}, {0,0,0,0}, {1,1,1,1}, {0,1,1,1}} bucket_capacity : 2 Output: 5 Example 3: Input: grid : {{0,0,0}, {0,0,0}} bucket_capacity : 5 Output: 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid{:,1}.length <= 10^2 * grid{i}{j} -> 0 | 1 * 1 <= capacity <= 10 */ #include<stdio.h> #include<vector> using namespace std; int max_fill(vector<vector<int>> grid,int capacity){
int out=0; for (int i=0;i<grid.size();i++) { int sum=0; for (int j=0;j<grid[i].size();j++) sum+=grid[i][j]; if (sum>0) out+=(sum-1)/capacity+1; } return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (max_fill({{0,0,1,0}, {0,1,0,0}, {1,1,1,1}}, 1) == 6); assert (max_fill({{0,0,1,1}, {0,0,0,0}, {1,1,1,1}, {0,1,1,1}}, 2) == 5); assert (max_fill({{0,0,0}, {0,0,0}}, 5) == 0); assert (max_fill({{1,1,1,1}, {1,1,1,1}}, 2) == 4); assert (max_fill({{1,1,1,1}, {1,1,1,1}}, 9) == 2); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> int max_fill(vector<vector<int>> grid,int capacity){
#undef NDEBUG #include<assert.h> int main(){ assert (max_fill({{0,0,1,0}, {0,1,0,0}, {1,1,1,1}}, 1) == 6); assert (max_fill({{0,0,1,1}, {0,0,0,0}, {1,1,1,1}, {0,1,1,1}}, 2) == 5); assert (max_fill({{0,0,0}, {0,0,0}}, 5) == 0); }
int out=0; for (int i=0;i<grid.size();i++) { int sum=0; for (int j=0;j<grid[i].size();j++) sum+=grid[i][j]; if (sum>0) out+=sum/capacity+1; } return out; }
function misuse
incorrect output
max_fill
int max_fill(vector<vector<int>> grid,int capacity)
You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: Input: grid : {{0,0,1,0}, {0,1,0,0}, {1,1,1,1}} bucket_capacity : 1 Output: 6 Example 2: Input: grid : {{0,0,1,1}, {0,0,0,0}, {1,1,1,1}, {0,1,1,1}} bucket_capacity : 2 Output: 5 Example 3: Input: grid : {{0,0,0}, {0,0,0}} bucket_capacity : 5 Output: 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid{:,1}.length <= 10^2 * grid{i}{j} -> 0 | 1 * 1 <= capacity <= 10
Write a C++ function `int max_fill(vector<vector<int>> grid,int capacity)` to solve the following problem: You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: Input: grid : {{0,0,1,0}, {0,1,0,0}, {1,1,1,1}} bucket_capacity : 1 Output: 6 Example 2: Input: grid : {{0,0,1,1}, {0,0,0,0}, {1,1,1,1}, {0,1,1,1}} bucket_capacity : 2 Output: 5 Example 3: Input: grid : {{0,0,0}, {0,0,0}} bucket_capacity : 5 Output: 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid{:,1}.length <= 10^2 * grid{i}{j} -> 0 | 1 * 1 <= capacity <= 10
CPP/116
/* In this Kata, you have to sort a vector of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. It must be implemented like this: >>> sort_vector({1, 5, 2, 3, 4}) == {1, 2, 3, 4, 5} >>> sort_vector({-2, -3, -4, -5, -6}) == {-6, -5, -4, -3, -2} >>> sort_vector({1, 0, 2, 3, 4}) == {0, 1, 2, 3, 4} */ #include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; vector<int> sort_array(vector<int> arr){
vector<int> bin={}; int m; for (int i=0;i<arr.size();i++) { int b=0,n=abs(arr[i]); while (n>0) { b+=n%2;n=n/2; } bin.push_back(b); } for (int i=0;i<arr.size();i++) for (int j=1;j<arr.size();j++) if (bin[j]<bin[j-1] or (bin[j]==bin[j-1] and arr[j]<arr[j-1])) { m=arr[j];arr[j]=arr[j-1];arr[j-1]=m; m=bin[j];bin[j]=bin[j-1];bin[j-1]=m; } return arr; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(sort_array({1,5,2,3,4}) , {1, 2, 4, 3, 5})); assert (issame(sort_array({-2,-3,-4,-5,-6}) , {-4, -2, -6, -5, -3})); assert (issame(sort_array({1,0,2,3,4}) , {0, 1, 2, 4, 3})); assert (issame(sort_array({}) , {})); assert (issame(sort_array({2,5,77,4,5,3,5,7,2,3,4}) , {2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77})); assert (issame(sort_array({3,6,44,12,32,5}) , {32, 3, 5, 6, 12, 44})); assert (issame(sort_array({2,4,8,16,32}) , {2, 4, 8, 16, 32})); assert (issame(sort_array({2,4,8,16,32}) , {2, 4, 8, 16, 32})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> sort_array(vector<int> arr){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(sort_array({1,5,2,3,4}) , {1, 2, 4, 3, 5})); assert (issame(sort_array({-2,-3,-4,-5,-6}) , {-4, -2, -6, -5, -3})); assert (issame(sort_array({1,0,2,3,4}) , {0, 1, 2, 4, 3})); }
vector<int> bin={}; int m; for (int i=0;i<arr.size();i++) { int b=0,n=abs(arr[i]); while (n>0) { b+=n%2;n=n/2; } bin.push_back(b); } for (int i=0;i<arr.size();i++) for (int j=1;j<arr.size();j++) if (bin[j]<bin[j-1] or (bin[j]==bin[j-1] and arr[j]<arr[j-1])) { m=arr[j];arr[j]=arr[j-1];arr[j-1]=m; m=bin[j];bin[j]=bin[j-1];bin[j-1]=m; } return bin; }
variable misuse
incorrect output
sort_array
vector<int> sort_array(vector<int> arr)
In this Kata, you have to sort a vector of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. It must be implemented like this: >>> sort_vector({1, 5, 2, 3, 4}) == {1, 2, 3, 4, 5} >>> sort_vector({-2, -3, -4, -5, -6}) == {-6, -5, -4, -3, -2} >>> sort_vector({1, 0, 2, 3, 4}) == {0, 1, 2, 3, 4}
Write a C++ function `vector<int> sort_array(vector<int> arr)` to solve the following problem: In this Kata, you have to sort a vector of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. It must be implemented like this: >>> sort_vector({1, 5, 2, 3, 4}) == {1, 2, 3, 4, 5} >>> sort_vector({-2, -3, -4, -5, -6}) == {-6, -5, -4, -3, -2} >>> sort_vector({1, 0, 2, 3, 4}) == {0, 1, 2, 3, 4}
CPP/117
/* Given a string s and a natural number n, you have been tasked to implement a function that returns a vector of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty vector. Note: you may assume the input string contains only letters and spaces. Examples: select_words("Mary had a little lamb", 4) ==> {"little"} select_words("Mary had a little lamb", 3) ==> {"Mary", "lamb"} select_words('simple white space", 2) ==> {} select_words("Hello world", 4) ==> {"world"} select_words("Uncle sam", 3) ==> {"Uncle"} */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; vector<string> select_words(string s,int n){
string vowels="aeiouAEIOU"; string current=""; vector<string> out={}; int numc=0; s=s+' '; for (int i=0;i<s.length();i++) if (s[i]==' ') { if (numc==n) out.push_back(current); current=""; numc=0; } else { current=current+s[i]; if ((s[i]>=65 and s[i]<=90) or (s[i]>=97 and s[i]<=122)) if (find(vowels.begin(),vowels.end(),s[i])==vowels.end()) numc+=1; } return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(select_words("Mary had a little lamb", 4) , {"little"} )); assert (issame(select_words("Mary had a little lamb", 3) , {"Mary", "lamb"} )); assert (issame(select_words("simple white space", 2) , {} )); assert (issame(select_words("Hello world", 4) , {"world"} )); assert (issame(select_words("Uncle sam", 3) , {"Uncle"})); assert (issame(select_words("", 4) , {})); assert (issame(select_words("a b c d e f", 1) , {"b", "c", "d", "f"})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> vector<string> select_words(string s,int n){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(select_words("Mary had a little lamb", 4) , {"little"} )); assert (issame(select_words("Mary had a little lamb", 3) , {"Mary", "lamb"} )); assert (issame(select_words("simple white space", 2) , {} )); assert (issame(select_words("Hello world", 4) , {"world"} )); assert (issame(select_words("Uncle sam", 3) , {"Uncle"})); }
string vowels="aeiouAEIOU"; string current=""; vector<string> out={}; int numc=0; s=s+' '; for (int i=0;i<s.length();i++) if (s[i]==' ') { if (numc==n) out.push_back(current); current=""; numc=0; } else { current=current+s[i]; if ((s[i]>=65 and s[i]<=90) or (s[i]>=97 and s[i]<=122)) if (find(vowels.begin(),vowels.end(),s[i])!=vowels.end()) numc+=1; } return out; }
operator misuse
incorrect output
select_words
vector<string> select_words(string s,int n)
Given a string s and a natural number n, you have been tasked to implement a function that returns a vector of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty vector. Note: you may assume the input string contains only letters and spaces. Examples: select_words("Mary had a little lamb", 4) ==> {"little"} select_words("Mary had a little lamb", 3) ==> {"Mary", "lamb"} select_words('simple white space", 2) ==> {} select_words("Hello world", 4) ==> {"world"} select_words("Uncle sam", 3) ==> {"Uncle"}
Write a C++ function `vector<string> select_words(string s,int n)` to solve the following problem: Given a string s and a natural number n, you have been tasked to implement a function that returns a vector of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty vector. Note: you may assume the input string contains only letters and spaces. Examples: select_words("Mary had a little lamb", 4) ==> {"little"} select_words("Mary had a little lamb", 3) ==> {"Mary", "lamb"} select_words('simple white space", 2) ==> {} select_words("Hello world", 4) ==> {"world"} select_words("Uncle sam", 3) ==> {"Uncle"}
CPP/118
/* You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: get_closest_vowel("yogurt") ==> "u" get_closest_vowel("FULL") ==> "U" get_closest_vowel("quick") ==> "" get_closest_vowel("ab") ==> "" */ #include<stdio.h> #include<string> #include<algorithm> using namespace std; string get_closest_vowel(string word){
string out=""; string vowels="AEIOUaeiou"; for (int i=word.length()-2;i>=1;i-=1) if (find(vowels.begin(),vowels.end(),word[i])!=vowels.end()) if (find(vowels.begin(),vowels.end(),word[i+1])==vowels.end()) if (find(vowels.begin(),vowels.end(),word[i-1])==vowels.end()) return out+word[i]; return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (get_closest_vowel("yogurt") == "u"); assert (get_closest_vowel("full") == "u"); assert (get_closest_vowel("easy") == ""); assert (get_closest_vowel("eAsy") == ""); assert (get_closest_vowel("ali") == ""); assert (get_closest_vowel("bad") == "a"); assert (get_closest_vowel("most") =="o"); assert (get_closest_vowel("ab") == ""); assert (get_closest_vowel("ba") == ""); assert (get_closest_vowel("quick") == ""); assert (get_closest_vowel("anime") == "i"); assert (get_closest_vowel("Asia") == ""); assert (get_closest_vowel("Above") == "o"); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> string get_closest_vowel(string word){
#undef NDEBUG #include<assert.h> int main(){ assert (get_closest_vowel("yogurt") == "u"); assert (get_closest_vowel("FULL") == "U"); assert (get_closest_vowel("ab") == ""); assert (get_closest_vowel("quick") == ""); }
string out=" "; string vowels="AEIOUaeiou"; for (int i=word.length()-2;i>=1;i-=1) if (find(vowels.begin(),vowels.end(),word[i])!=vowels.end()) if (find(vowels.begin(),vowels.end(),word[i+1])==vowels.end()) if (find(vowels.begin(),vowels.end(),word[i-1])==vowels.end()) return out+word[i]; return out; }
excess logic
incorrect output
get_closest_vowel
string get_closest_vowel(string word)
You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: get_closest_vowel("yogurt") ==> "u" get_closest_vowel("FULL") ==> "U" get_closest_vowel("quick") ==> "" get_closest_vowel("ab") ==> ""
Write a C++ function `string get_closest_vowel(string word)` to solve the following problem: You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: get_closest_vowel("yogurt") ==> "u" get_closest_vowel("FULL") ==> "U" get_closest_vowel("quick") ==> "" get_closest_vowel("ab") ==> ""
CPP/119
/* You are given a vector of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string "(())()" is good, while the string "())" is not. Return "Yes" if there's a way to make a good string, and return "No" otherwise. Examples: match_parens({"()(", ")"}) == "Yes" match_parens({")", ")"}) == "No" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string match_parens(vector<string> lst){
string l1=lst[0]+lst[1]; int i,count=0; bool can=true; for (i=0;i<l1.length();i++) { if (l1[i]=='(') count+=1; if (l1[i]==')') count-=1; if (count<0) can=false; } if (count!=0) return "No"; if (can==true) return "Yes"; l1=lst[1]+lst[0]; can=true; for (i=0;i<l1.length();i++) { if (l1[i]=='(') count+=1; if (l1[i]==')') count-=1; if (count<0) can=false; } if (can==true) return "Yes"; return "No"; }
#undef NDEBUG #include<assert.h> int main(){ assert (match_parens({"()(", ")"}) == "Yes"); assert (match_parens({")", ")"}) == "No"); assert (match_parens({"(()(())", "())())"}) == "No"); assert (match_parens({")())", "(()()("}) == "Yes"); assert (match_parens({"(())))", "(()())(("}) == "Yes"); assert (match_parens({"()", "())"}) == "No"); assert (match_parens({"(()(", "()))()"}) == "Yes"); assert (match_parens({"((((", "((())"}) == "No"); assert (match_parens({")(()", "(()("}) == "No"); assert (match_parens({")(", ")("}) == "No"); assert (match_parens({"(", ")"}) == "Yes"); assert (match_parens({")", "("}) == "Yes" ); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> string match_parens(vector<string> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (match_parens({"()(", ")"}) == "Yes"); assert (match_parens({")", ")"}) == "No"); }
string l1=lst[0]+lst[1]; int i,count=0; bool can=true; for (i=0;i<l1.length();i++) { if (l1[i]=='(') count+=1; if (l1[i]==')') count-=1; if (count<0) can=false; } if (count!=0) return "No"; if (can==true) return "Yes"; l1=lst[1]+lst[0]; can=true; for (i=0;i<l1.length();i++) { if (l1[i]=='(') count+=1; if (l1[i]==')') count-=1; if (count<0) can=false; } if (can==true) return "yes"; return "no"; }
value misuse
incorrect output
match_parens
string match_parens(vector<string> lst)
You are given a vector of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string "(())()" is good, while the string "())" is not. Return "Yes" if there's a way to make a good string, and return "No" otherwise. Examples: match_parens({"()(", ")"}) == "Yes" match_parens({")", ")"}) == "No"
Write a C++ function `string match_parens(vector<string> lst)` to solve the following problem: You are given a vector of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string "(())()" is good, while the string "())" is not. Return "Yes" if there's a way to make a good string, and return "No" otherwise. Examples: match_parens({"()(", ")"}) == "Yes" match_parens({")", ")"}) == "No"
CPP/120
/* Given a vector arr of integers and a positive integer k, return a sorted vector of length k with the maximum k numbers in arr. Example 1: Input: arr = {-3, -4, 5}, k = 3 Output: {-4, -3, 5} Example 2: Input: arr = {4, -4, 4}, k = 2 Output: {4, 4} Example 3: Input: arr = {-3, 2, 1, 2, -1, -2, 1}, k = 1 Output: {2} Note: 1. The length of the vector will be in the range of {1, 1000}. 2. The elements in the vector will be in the range of {-1000, 1000}. 3. 0 <= k <= len(arr) */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> maximum(vector<int> arr,int k){
sort(arr.begin(),arr.end()); vector<int> out(arr.end()-k,arr.end()); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(maximum({-3, -4, 5}, 3) , {-4, -3, 5})); assert (issame(maximum({4, -4, 4}, 2) , {4, 4})); assert (issame(maximum({-3, 2, 1, 2, -1, -2, 1}, 1) , {2})); assert (issame(maximum({123, -123, 20, 0 , 1, 2, -3}, 3) , {2, 20, 123})); assert (issame(maximum({-123, 20, 0 , 1, 2, -3}, 4) , {0, 1, 2, 20})); assert (issame(maximum({5, 15, 0, 3, -13, -8, 0}, 7) , {-13, -8, 0, 0, 3, 5, 15})); assert (issame(maximum({-1, 0, 2, 5, 3, -10}, 2) , {3, 5})); assert (issame(maximum({1, 0, 5, -7}, 1) , {5})); assert (issame(maximum({4, -4}, 2) , {-4, 4})); assert (issame(maximum({-10, 10}, 2) , {-10, 10})); assert (issame(maximum({1, 2, 3, -23, 243, -400, 0}, 0) , {})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> maximum(vector<int> arr,int k){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(maximum({-3, -4, 5}, 3) , {-4, -3, 5})); assert (issame(maximum({4, -4, 4}, 2) , {4, 4})); assert (issame(maximum({-3, 2, 1, 2, -1, -2, 1}, 1) , {2})); }
sort(arr.begin(),arr.end()); vector<int> out(arr.end()-k,arr.end()); sort(out.end(),out.begin()); return out; }
excess logic
incorrect output
maximum
vector<int> maximum(vector<int> arr,int k)
Given a vector arr of integers and a positive integer k, return a sorted vector of length k with the maximum k numbers in arr. Example 1: Input: arr = {-3, -4, 5}, k = 3 Output: {-4, -3, 5} Example 2: Input: arr = {4, -4, 4}, k = 2 Output: {4, 4} Example 3: Input: arr = {-3, 2, 1, 2, -1, -2, 1}, k = 1 Output: {2} Note: 1. The length of the vector will be in the range of {1, 1000}. 2. The elements in the vector will be in the range of {-1000, 1000}. 3. 0 <= k <= len(arr)
Write a C++ function `vector<int> maximum(vector<int> arr,int k)` to solve the following problem: Given a vector arr of integers and a positive integer k, return a sorted vector of length k with the maximum k numbers in arr. Example 1: Input: arr = {-3, -4, 5}, k = 3 Output: {-4, -3, 5} Example 2: Input: arr = {4, -4, 4}, k = 2 Output: {4, 4} Example 3: Input: arr = {-3, 2, 1, 2, -1, -2, 1}, k = 1 Output: {2} Note: 1. The length of the vector will be in the range of {1, 1000}. 2. The elements in the vector will be in the range of {-1000, 1000}. 3. 0 <= k <= len(arr)
CPP/121
/* Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions. Examples solution({5, 8, 7, 1}) ==> 12 solution({3, 3, 3, 3, 3}) ==> 9 solution({30, 13, 24, 321}) ==>0 */ #include<stdio.h> #include<vector> using namespace std; int solutions(vector<int> lst){
int sum=0; for (int i=0;i*2<lst.size();i++) if (lst[i*2]%2==1) sum+=lst[i*2]; return sum; }
#undef NDEBUG #include<assert.h> int main(){ assert (solutions({5, 8, 7, 1}) == 12); assert (solutions({3, 3, 3, 3, 3}) == 9); assert (solutions({30, 13, 24, 321}) == 0); assert (solutions({5, 9}) == 5); assert (solutions({2, 4, 8}) == 0); assert (solutions({30, 13, 23, 32}) == 23); assert (solutions({3, 13, 2, 9}) == 3); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> int solutions(vector<int> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (solutions({5, 8, 7, 1}) == 12); assert (solutions({3, 3, 3, 3, 3}) == 9); assert (solutions({30, 13, 24, 321}) == 0); }
int sum=1; for (int i=0;i*2<lst.size();i++) if (lst[i*2]%2==1) sum+=lst[i*2]; return sum; }
value misuse
incorrect output
solution
int solutions(vector<int> lst)
Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions. Examples solution({5, 8, 7, 1}) ==> 12 solution({3, 3, 3, 3, 3}) ==> 9 solution({30, 13, 24, 321}) ==>0
Write a C++ function `int solutions(vector<int> lst)` to solve the following problem: Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions. Examples solution({5, 8, 7, 1}) ==> 12 solution({3, 3, 3, 3, 3}) ==> 9 solution({30, 13, 24, 321}) ==>0
CPP/122
/* Given a non-empty vector of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. Example: Input: arr = {111,21,3,4000,5,6,7,8,9}, k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) */ #include<stdio.h> #include<vector> using namespace std; int add_elements(vector<int> arr,int k){
int sum=0; for (int i=0;i<k;i++) if( arr[i]>=-99 and arr[i]<=99) sum+=arr[i]; return sum; }
#undef NDEBUG #include<assert.h> int main(){ assert (add_elements({1,-2,-3,41,57,76,87,88,99}, 3) == -4); assert (add_elements({111,121,3,4000,5,6}, 2) == 0); assert (add_elements({11,21,3,90,5,6,7,8,9}, 4) == 125); assert (add_elements({111,21,3,4000,5,6,7,8,9}, 4) == 24); assert (add_elements({1}, 1) == 1); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> int add_elements(vector<int> arr,int k){
#undef NDEBUG #include<assert.h> int main(){ assert (add_elements({111,21,3,4000,5,6,7,8,9}, 4) == 24); }
int sum=0; for (int i=0;i<arr.size();i++) if( arr[i]>=-99 and arr[i]<=99) sum+=arr[i]; return sum; }
missing logic
incorrect output
add_elements
int add_elements(vector<int> arr,int k)
Given a non-empty vector of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. Example: Input: arr = {111,21,3,4000,5,6,7,8,9}, k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr)
Write a C++ function `int add_elements(vector<int> arr,int k)` to solve the following problem: Given a non-empty vector of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. Example: Input: arr = {111,21,3,4000,5,6,7,8,9}, k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr)
CPP/123
/* Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. Note: 1. Collatz(1) is {1}. 2. returned vector sorted in increasing order. For example: get_odd_collatz(5) returns {1, 5} // The collatz sequence for 5 is {5, 16, 8, 4, 2, 1}, so the odd numbers are only 1, and 5. */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> get_odd_collatz(int n){
vector<int> out={1}; while (n!=1) { if (n%2==1) {out.push_back(n); n=n*3+1;} else n=n/2; } sort(out.begin(),out.end()); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(get_odd_collatz(14) , {1, 5, 7, 11, 13, 17})); assert (issame(get_odd_collatz(5) , {1, 5})); assert (issame(get_odd_collatz(12) , {1, 3, 5})); assert (issame(get_odd_collatz(1) , {1})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> get_odd_collatz(int n){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(get_odd_collatz(5) , {1, 5})); }
vector<int> out={1}; while (n!=1) { if (n%2==1) {out.push_back(n); n=n*2+1;} else n=n/2; } sort(out.begin(),out.end()); return out; }
value misuse
incorrect output
get_odd_collatz
vector<int> get_odd_collatz(int n)
Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. Note: 1. Collatz(1) is {1}. 2. returned vector sorted in increasing order. For example: get_odd_collatz(5) returns {1, 5} // The collatz sequence for 5 is {5, 16, 8, 4, 2, 1}, so the odd numbers are only 1, and 5.
Write a C++ function `vector<int> get_odd_collatz(int n)` to solve the following problem: Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. Note: 1. Collatz(1) is {1}. 2. returned vector sorted in increasing order. For example: get_odd_collatz(5) returns {1, 5} // The collatz sequence for 5 is {5, 16, 8, 4, 2, 1}, so the odd numbers are only 1, and 5.
CPP/124
/* You have to write a function which validates a given date string and returns true if the date is valid otherwise false. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy for example: valid_date("03-11-2000") => true valid_date("15-01-2012") => false valid_date("04-0-2040") => false valid_date("06-04-2020") => true valid_date("06/04/2020") => false */ #include<stdio.h> #include<string> using namespace std; bool valid_date(string date){
int mm,dd,yy,i; if (date.length()!=10) return false; for (int i=0;i<10;i++) if (i==2 or i==5) { if (date[i]!='-') return false; } else if (date[i]<48 or date[i]>57) return false; mm=atoi(date.substr(0,2).c_str()); dd=atoi(date.substr(3,2).c_str()); yy=atoi(date.substr(6,4).c_str()); if (mm<1 or mm>12) return false; if (dd<1 or dd>31) return false; if (dd==31 and (mm==4 or mm==6 or mm==9 or mm==11 or mm==2)) return false; if (dd==30 and mm==2) return false; return true; }
#undef NDEBUG #include<assert.h> int main(){ assert (valid_date("03-11-2000") == true); assert (valid_date("15-01-2012") == false); assert (valid_date("04-0-2040") == false); assert (valid_date("06-04-2020") == true); assert (valid_date("01-01-2007") == true); assert (valid_date("03-32-2011") == false); assert (valid_date("") == false); assert (valid_date("04-31-3000") == false); assert (valid_date("06-06-2005") == true); assert (valid_date("21-31-2000") == false); assert (valid_date("04-12-2003") == true); assert (valid_date("04122003") == false); assert (valid_date("20030412") == false); assert (valid_date("2003-04") == false); assert (valid_date("2003-04-12") == false); assert (valid_date("04-2003") == false); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> bool valid_date(string date){
#undef NDEBUG #include<assert.h> int main(){ assert (valid_date("03-11-2000") == true); assert (valid_date("15-01-2012") == false); assert (valid_date("04-0-2040") == false); assert (valid_date("06-04-2020") == true); assert (valid_date("06/04/2020") == false); }
int dd,mm,yy,i; if (date.length()!=10) return false; for (int i=0;i<10;i++) if (i==2 or i==5) { if (date[i]!='-') return false; } else if (date[i]<48 or date[i]>57) return false; dd=atoi(date.substr(0,2).c_str()); mm=atoi(date.substr(3,2).c_str()); yy=atoi(date.substr(6,4).c_str()); if (mm<1 or mm>12) return false; if (dd<1 or dd>31) return false; if (dd==31 and (mm==4 or mm==6 or mm==9 or mm==11 or mm==2)) return false; if (dd==30 and mm==2) return false; return true; }
variable misuse
incorrect output
valid_date
bool valid_date(string date)
You have to write a function which validates a given date string and returns true if the date is valid otherwise false. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy for example: valid_date("03-11-2000") => true valid_date("15-01-2012") => false valid_date("04-0-2040") => false valid_date("06-04-2020") => true valid_date("06/04/2020") => false
Write a C++ function `bool valid_date(string date)` to solve the following problem: You have to write a function which validates a given date string and returns true if the date is valid otherwise false. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy for example: valid_date("03-11-2000") => true valid_date("15-01-2012") => false valid_date("04-0-2040") => false valid_date("06-04-2020") => true valid_date("06/04/2020") => false
CPP/125
/* Given a string of words, return a vector of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return a vector with one element, the number of lower-case letters with odd order in the alphabet, ord("a") = 0, ord("b") = 1, ... ord("z") = 25 Examples split_words("Hello world!") ➞ {"Hello", "world!"} split_words("Hello,world!") ➞ {"Hello", "world!"} split_words("abcdef") == {"3"} */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; vector<string> split_words(string txt){
int i; string current=""; vector<string> out={}; if (find(txt.begin(),txt.end(),' ')!=txt.end()) { txt=txt+' '; for (i=0;i<txt.length();i++) if (txt[i]==' ') { if (current.length()>0)out.push_back(current); current=""; } else current=current+txt[i]; return out; } if (find(txt.begin(),txt.end(),',')!=txt.end()) { txt=txt+','; for (i=0;i<txt.length();i++) if (txt[i]==',') { if (current.length()>0)out.push_back(current); current=""; } else current=current+txt[i]; return out; } int num=0; for (i=0;i<txt.length();i++) if (txt[i]>=97 and txt[i]<=122 and txt[i]%2==0) num+=1; return {to_string(num)}; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(split_words("Hello world!") , {"Hello","world!"})); assert (issame(split_words("Hello,world!") , {"Hello","world!"})); assert (issame(split_words("Hello world,!") , {"Hello","world,!"})); assert (issame(split_words("Hello,Hello,world !") , {"Hello,Hello,world","!"})); assert (issame(split_words("abcdef") , {"3"})); assert (issame(split_words("aaabb") , {"2"})); assert (issame(split_words("aaaBb") , {"1"})); assert (issame(split_words("") ,{"0"})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> vector<string> split_words(string txt){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(split_words("Hello world!") , {"Hello","world!"})); assert (issame(split_words("Hello,world!") , {"Hello","world!"})); assert (issame(split_words("abcdef") , {"3"})); }
int i; string current=""; vector<string> out={}; if (find(txt.begin(),txt.end(),' ')!=txt.end()) { txt=txt+','; for (i=0;i<txt.length();i++) if (txt[i]==' ') { if (current.length()>0)out.push_back(current); current=""; } else current=current+txt[i]; return out; } if (find(txt.begin(),txt.end(),',')!=txt.end()) { txt=txt+','; for (i=0;i<txt.length();i++) if (txt[i]==',') { if (current.length()>0)out.push_back(current); current=""; } else current=current+txt[i]; return out; } int num=0; for (i=0;i<txt.length();i++) if (txt[i]>=97 and txt[i]<=122 and txt[i]%2==0) num+=1; return {to_string(num)}; }
value misuse
incorrect output
split_words
vector<string> split_words(string txt)
Given a string of words, return a vector of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return a vector with one element, the number of lower-case letters with odd order in the alphabet, ord("a") = 0, ord("b") = 1, ... ord("z") = 25 Examples split_words("Hello world!") ➞ {"Hello", "world!"} split_words("Hello,world!") ➞ {"Hello", "world!"} split_words("abcdef") == {"3"}
Write a C++ function `vector<string> split_words(string txt)` to solve the following problem: Given a string of words, return a vector of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return a vector with one element, the number of lower-case letters with odd order in the alphabet, ord("a") = 0, ord("b") = 1, ... ord("z") = 25 Examples split_words("Hello world!") ➞ {"Hello", "world!"} split_words("Hello,world!") ➞ {"Hello", "world!"} split_words("abcdef") == {"3"}
CPP/126
/* Given a vector of numbers, return whether or not they are sorted in ascending order. If vector has more than 1 duplicate of the same number, return false. Assume no negative numbers and only integers. Examples is_sorted({5}) ➞ true is_sorted({1, 2, 3, 4, 5}) ➞ true is_sorted({1, 3, 2, 4, 5}) ➞ false is_sorted({1, 2, 3, 4, 5, 6}) ➞ true is_sorted({1, 2, 3, 4, 5, 6, 7}) ➞ true is_sorted({1, 3, 2, 4, 5, 6, 7}) ➞ false is_sorted({1, 2, 2, 3, 3, 4}) ➞ true is_sorted({1, 2, 2, 2, 3, 4}) ➞ false */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; bool is_sorted(vector<int> lst){
for (int i=1;i<lst.size();i++) { if (lst[i]<lst[i-1]) return false; if (i>=2 and lst[i]==lst[i-1] and lst[i]==lst[i-2]) return false; } return true; }
#undef NDEBUG #include<assert.h> int main(){ assert (is_sorted({5}) == true); assert (is_sorted({1, 2, 3, 4, 5}) == true); assert (is_sorted({1, 3, 2, 4, 5}) == false); assert (is_sorted({1, 2, 3, 4, 5, 6}) == true); assert (is_sorted({1, 2, 3, 4, 5, 6, 7}) == true); assert (is_sorted({1, 3, 2, 4, 5, 6, 7}) == false); assert (is_sorted({}) == true); assert (is_sorted({1}) == true); assert (is_sorted({3, 2, 1}) == false); assert (is_sorted({1, 2, 2, 2, 3, 4}) == false); assert (is_sorted({1, 2, 3, 3, 3, 4}) == false); assert (is_sorted({1, 2, 2, 3, 3, 4}) == true); assert (is_sorted({1, 2, 3, 4}) == true); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> bool is_sorted(vector<int> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (is_sorted({5}) == true); assert (is_sorted({1, 2, 3, 4, 5}) == true); assert (is_sorted({1, 3, 2, 4, 5}) == false); assert (is_sorted({1, 2, 3, 4, 5, 6}) == true); assert (is_sorted({1, 2, 3, 4, 5, 6, 7}) == true); assert (is_sorted({1, 3, 2, 4, 5, 6, 7}) == false); assert (is_sorted({1, 2, 2, 2, 3, 4}) == false); assert (is_sorted({1, 2, 2, 3, 3, 4}) == true); }
for (int i=1;i<lst.size();i++) { if (lst[i]<lst[i-1]) return false; if (i>=2 and lst[i]==lst[i-1]) return false; } return true; }
missing logic
incorrect output
is_sorted
bool is_sorted(vector<int> lst)
Given a vector of numbers, return whether or not they are sorted in ascending order. If vector has more than 1 duplicate of the same number, return false. Assume no negative numbers and only integers. Examples is_sorted({5}) ➞ true is_sorted({1, 2, 3, 4, 5}) ➞ true is_sorted({1, 3, 2, 4, 5}) ➞ false is_sorted({1, 2, 3, 4, 5, 6}) ➞ true is_sorted({1, 2, 3, 4, 5, 6, 7}) ➞ true is_sorted({1, 3, 2, 4, 5, 6, 7}) ➞ false is_sorted({1, 2, 2, 3, 3, 4}) ➞ true is_sorted({1, 2, 2, 2, 3, 4}) ➞ false
Write a C++ function `bool is_sorted(vector<int> lst)` to solve the following problem: Given a vector of numbers, return whether or not they are sorted in ascending order. If vector has more than 1 duplicate of the same number, return false. Assume no negative numbers and only integers. Examples is_sorted({5}) ➞ true is_sorted({1, 2, 3, 4, 5}) ➞ true is_sorted({1, 3, 2, 4, 5}) ➞ false is_sorted({1, 2, 3, 4, 5, 6}) ➞ true is_sorted({1, 2, 3, 4, 5, 6, 7}) ➞ true is_sorted({1, 3, 2, 4, 5, 6, 7}) ➞ false is_sorted({1, 2, 2, 3, 3, 4}) ➞ true is_sorted({1, 2, 2, 2, 3, 4}) ➞ false
CPP/127
/* You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". {input/output} samples: intersection({1, 2}, {2, 3}) ==> "NO" intersection({-1, 1}, {0, 4}) ==> "NO" intersection({-3, -1}, {-5, 5}) ==> "YES" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string intersection( vector<int> interval1,vector<int> interval2){
int inter1,inter2,l,i; inter1=max(interval1[0],interval2[0]); inter2=min(interval1[1],interval2[1]); l=inter2-inter1; if (l<2) return "NO"; for (i=2;i*i<=l;i++) if (l%i==0) return "NO"; return "YES"; }
#undef NDEBUG #include<assert.h> int main(){ assert (intersection({1, 2}, {2, 3}) == "NO"); assert (intersection({-1, 1}, {0, 4}) == "NO"); assert (intersection({-3, -1}, {-5, 5}) == "YES"); assert (intersection({-2, 2}, {-4, 0}) == "YES"); assert (intersection({-11, 2}, {-1, -1}) == "NO"); assert (intersection({1, 2}, {3, 5}) == "NO"); assert (intersection({1, 2}, {1, 2}) == "NO"); assert (intersection({-2, -2}, {-3, -2}) == "NO"); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> string intersection( vector<int> interval1,vector<int> interval2){
#undef NDEBUG #include<assert.h> int main(){ assert (intersection({1, 2}, {2, 3}) == "NO"); assert (intersection({-1, 1}, {0, 4}) == "NO"); assert (intersection({-3, -1}, {-5, 5}) == "YES"); }
int inter1,inter2,l,i; inter1=max(interval1[0],interval2[0]); inter2=min(interval1[1],interval2[1]); l=inter2; if (l<2) return "NO"; return "YES"; }
missing logic
incorrect output
intersection
string intersection( vector<int> interval1,vector<int> interval2)
You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". {input/output} samples: intersection({1, 2}, {2, 3}) ==> "NO" intersection({-1, 1}, {0, 4}) ==> "NO" intersection({-3, -1}, {-5, 5}) ==> "YES"
Write a C++ function `string intersection( vector<int> interval1,vector<int> interval2)` to solve the following problem: You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". {input/output} samples: intersection({1, 2}, {2, 3}) ==> "NO" intersection({-1, 1}, {0, 4}) ==> "NO" intersection({-3, -1}, {-5, 5}) ==> "YES"
CPP/128
/* You are given a vector arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the vector, represented by 1, -1 or 0. Note: return -32768 for empty arr. Example: >>> prod_signs({1, 2, 2, -4}) == -9 >>> prod_signs({0, 1}) == 0 >>> prod_signs({}) == -32768 */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; int prod_signs(vector<int> arr){
if (arr.size()==0) return -32768; int i,sum=0,prods=1; for (i=0;i<arr.size();i++) { sum+=abs(arr[i]); if (arr[i]==0) prods=0; if (arr[i]<0) prods=-prods; } return sum*prods; }
#undef NDEBUG #include<assert.h> int main(){ assert (prod_signs({1, 2, 2, -4}) == -9); assert (prod_signs({0, 1}) == 0); assert (prod_signs({1, 1, 1, 2, 3, -1, 1}) == -10); assert (prod_signs({}) == -32768); assert (prod_signs({2, 4,1, 2, -1, -1, 9}) == 20); assert (prod_signs({-1, 1, -1, 1}) == 4); assert (prod_signs({-1, 1, 1, 1}) == -4); assert (prod_signs({-1, 1, 1, 0}) == 0); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> int prod_signs(vector<int> arr){
#undef NDEBUG #include<assert.h> int main(){ assert (prod_signs({1, 2, 2, -4}) == -9); assert (prod_signs({0, 1}) == 0); assert (prod_signs({}) == -32768); }
if (arr.size()==0) return -32768; int i,sum=0,prods=1; for (i=0;i<arr.size();i++) { sum+=abs(arr[i])*2; if (arr[i]==0) prods=0; if (arr[i]<0) prods=-prods; } return sum*prods; }
excess logic
incorrect output
prod_signs
int prod_signs(vector<int> arr)
You are given a vector arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the vector, represented by 1, -1 or 0. Note: return -32768 for empty arr. Example: >>> prod_signs({1, 2, 2, -4}) == -9 >>> prod_signs({0, 1}) == 0 >>> prod_signs({}) == -32768
Write a C++ function `int prod_signs(vector<int> arr)` to solve the following problem: You are given a vector arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the vector, represented by 1, -1 or 0. Note: return -32768 for empty arr. Example: >>> prod_signs({1, 2, 2, -4}) == -9 >>> prod_signs({0, 1}) == 0 >>> prod_signs({}) == -32768
CPP/129
/* Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range {1, N * N} inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered vectors of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered vector of the values on the cells that the minimum path go through. Examples: Input: grid = { {1,2,3}, {4,5,6}, {7,8,9}}, k = 3 Output: {1, 2, 1} Input: grid = { {5,9,3}, {4,1,6}, {7,8,2}}, k = 1 Output: {1} */ #include<stdio.h> #include<vector> using namespace std; vector<int> minPath(vector<vector<int>> grid, int k){
int i,j,x,y,min; for (i=0;i<grid.size();i++) for (j=0;j<grid[i].size();j++) if (grid[i][j]==1) { x=i;y=j; } min=grid.size()*grid.size(); if (x>0 and grid[x-1][y]<min) min=grid[x-1][y]; if (x<grid.size()-1 and grid[x+1][y]<min) min=grid[x+1][y]; if (y>0 and grid[x][y-1]<min) min=grid[x][y-1]; if (y<grid.size()-1 and grid[x][y+1]<min) min=grid[x][y+1]; vector<int> out={}; for (i=0;i<k;i++) if (i%2==0) out.push_back(1); else out.push_back(min); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(minPath({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 3) , {1, 2, 1})); assert (issame(minPath({{5, 9, 3}, {4, 1, 6}, {7, 8, 2}}, 1) , {1})); assert (issame(minPath({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}, 4) , {1, 2, 1, 2})); assert (issame(minPath({{6, 4, 13, 10}, {5, 7, 12, 1}, {3, 16, 11, 15}, {8, 14, 9, 2}}, 7) , {1, 10, 1, 10, 1, 10, 1})); assert (issame(minPath({{8, 14, 9, 2}, {6, 4, 13, 15}, {5, 7, 1, 12}, {3, 10, 11, 16}}, 5) , {1, 7, 1, 7, 1})); assert (issame(minPath({{11, 8, 7, 2}, {5, 16, 14, 4}, {9, 3, 15, 6}, {12, 13, 10, 1}}, 9) , {1, 6, 1, 6, 1, 6, 1, 6, 1})); assert (issame(minPath({{12, 13, 10, 1}, {9, 3, 15, 6}, {5, 16, 14, 4}, {11, 8, 7, 2}}, 12) , {1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6})); assert (issame(minPath({{2, 7, 4}, {3, 1, 5}, {6, 8, 9}}, 8) , {1, 3, 1, 3, 1, 3, 1, 3})); assert (issame(minPath({{6, 1, 5}, {3, 8, 9}, {2, 7, 4}}, 8) , {1, 5, 1, 5, 1, 5, 1, 5})); assert (issame(minPath({{1, 2}, {3, 4}}, 10) , {1, 2, 1, 2, 1, 2, 1, 2, 1, 2})); assert (issame(minPath({{1, 3}, {3, 2}}, 10) , {1, 3, 1, 3, 1, 3, 1, 3, 1, 3})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> minPath(vector<vector<int>> grid, int k){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(minPath({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 3) , {1, 2, 1})); assert (issame(minPath({{5, 9, 3}, {4, 1, 6}, {7, 8, 2}}, 1) , {1})); }
int i,j,x,y,min; for (i=0;i<grid.size();i++) for (j=0;j<grid[i].size();j++) if (grid[i][j]==1) { x=i;y=j; } min=grid.size()*grid.size(); if (x>0 and grid[x-1][y]<min) min=grid[x-1][y]; if (x<grid.size()-1 and grid[x+1][y]<min) min=grid[x][y]; if (y>0 and grid[x][y-1]<min) min=grid[x][y]; if (y<grid.size()-1 and grid[x][y+1]<min) min=grid[x][y]; vector<int> out={}; for (i=0;i<k;i++) if (i%2==0) out.push_back(1); else out.push_back(min); return out; }
value misuse
incorrect output
minPath
vector<int> minPath(vector<vector<int>> grid, int k)
Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range {1, N * N} inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered vectors of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered vector of the values on the cells that the minimum path go through. Examples: Input: grid = { {1,2,3}, {4,5,6}, {7,8,9}}, k = 3 Output: {1, 2, 1} Input: grid = { {5,9,3}, {4,1,6}, {7,8,2}}, k = 1 Output: {1}
Write a C++ function `vector<int> minPath(vector<vector<int>> grid, int k)` to solve the following problem: Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range {1, N * N} inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered vectors of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered vector of the values on the cells that the minimum path go through. Examples: Input: grid = { {1,2,3}, {4,5,6}, {7,8,9}}, k = 3 Output: {1, 2, 1} Input: grid = { {5,9,3}, {4,1,6}, {7,8,2}}, k = 1 Output: {1}
CPP/130
/* Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a vector of the first n + 1 numbers of the Tribonacci sequence. Examples: tri(3) = {1, 3, 2, 8} */ #include<stdio.h> #include<vector> using namespace std; vector<int> tri(int n){
vector<int> out={1,3}; if (n==0) return {1}; for (int i=2;i<=n;i++) { if (i%2==0) out.push_back(1+i/2); else out.push_back(out[i-1]+out[i-2]+1+(i+1)/2); } return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(tri(3) , {1, 3, 2, 8})); assert (issame(tri(4) , {1, 3, 2, 8, 3})); assert (issame(tri(5) , {1, 3, 2, 8, 3, 15})); assert (issame(tri(6) , {1, 3, 2, 8, 3, 15, 4})); assert (issame(tri(7) , {1, 3, 2, 8, 3, 15, 4, 24})); assert (issame(tri(8) , {1, 3, 2, 8, 3, 15, 4, 24, 5})); assert (issame(tri(9) , {1, 3, 2, 8, 3, 15, 4, 24, 5, 35})); assert (issame(tri(20) , {1, 3, 2, 8, 3, 15, 4, 24, 5, 35, 6, 48, 7, 63, 8, 80, 9, 99, 10, 120, 11})); assert (issame(tri(0) , {1})); assert (issame(tri(1) , {1, 3})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> tri(int n){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(tri(3) , {1, 3, 2, 8})); }
vector<int> out={1,3}; if (n==0) return {1}; for (int i=2;i<=n;i++) { if (i%2==0) out.push_back(1+i/2); else out.push_back(out[i-1]+out[i-2]+1+i+(i+1)/2); } return out; }
excess logic
incorrect output
tri
vector<int> tri(int n)
Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a vector of the first n + 1 numbers of the Tribonacci sequence. Examples: tri(3) = {1, 3, 2, 8}
Write a C++ function `vector<int> tri(int n)` to solve the following problem: Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a vector of the first n + 1 numbers of the Tribonacci sequence. Examples: tri(3) = {1, 3, 2, 8}
CPP/131
/* Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. For example: digits(1) == 1 digits(4) == 0 digits(235) == 15 */ #include<stdio.h> #include<string> using namespace std; int digits(int n){
int prod=1,has=0; string s=to_string(n); for (int i=0;i<s.length();i++) if (s[i]%2==1) { has=1; prod=prod*(s[i]-48); } if (has==0) return 0; return prod; }
#undef NDEBUG #include<assert.h> int main(){ assert (digits(5) == 5); assert (digits(54) == 5); assert (digits(120) ==1); assert (digits(5014) == 5); assert (digits(98765) == 315); assert (digits(5576543) == 2625); assert (digits(2468) == 0); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> int digits(int n){
#undef NDEBUG #include<assert.h> int main(){ assert (digits(1) == 1); assert (digits(4) == 0); assert (digits(235) ==15); }
int prod=1,has=0; string s=to_string(n); for (int i=0;i<s.length();i++) if (s[i]%2==1) { has=1; prod=48*prod*(s[i]-48); } if (has==0) return 0; return prod; }
excess logic
incorrect output
digits
int digits(int n)
Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. For example: digits(1) == 1 digits(4) == 0 digits(235) == 15
Write a C++ function `int digits(int n)` to solve the following problem: Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. For example: digits(1) == 1 digits(4) == 0 digits(235) == 15
CPP/132
/* Create a function that takes a string as input which contains only square brackets. The function should return true if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. is_nested("[[]]") ➞ true is_nested("[]]]]]]][[[[[]") ➞ false is_nested("[][]") ➞ false is_nested("[]") ➞ false is_nested("[[][]]") ➞ true is_nested("[[]][[") ➞ true */ #include<stdio.h> #include<string> using namespace std; bool is_nested(string str){
int count=0,maxcount=0; for (int i=0;i<str.length();i++) { if (str[i]=='[') count+=1; if (str[i]==']') count-=1; if (count<0) count=0; if (count>maxcount) maxcount=count; if (count<=maxcount-2) return true; } return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (is_nested("[[]]") == true); assert (is_nested("[]]]]]]][[[[[]") == false); assert (is_nested("[][]") == false); assert (is_nested(("[]")) == false); assert (is_nested("[[[[]]]]") == true); assert (is_nested("[]]]]]]]]]]") == false); assert (is_nested("[][][[]]") == true); assert (is_nested("[[]") == false); assert (is_nested("[]]") == false); assert (is_nested("[[]][[") == true); assert (is_nested("[[][]]") == true); assert (is_nested("") == false); assert (is_nested("[[[[[[[[") == false); assert (is_nested("]]]]]]]]") == false); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> bool is_nested(string str){
#undef NDEBUG #include<assert.h> int main(){ assert (is_nested("[[]]") == true); assert (is_nested("[]]]]]]][[[[[]") == false); assert (is_nested("[][]") == false); assert (is_nested("[]") == false); assert (is_nested("[[]][[") == true); assert (is_nested("[[][]]") == true); }
int count=0,maxcount=0; for (int i=0;i<str.length();i++) { if (str[i]=='(') count+=1; if (str[i]==')') count-=1; if (count<0) count=0; if (count>maxcount) maxcount=count; if (count<=maxcount-2) return true; } return false; }
value misuse
incorrect output
is_nested
bool is_nested(string str)
Create a function that takes a string as input which contains only square brackets. The function should return true if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. is_nested("[[]]") ➞ true is_nested("[]]]]]]][[[[[]") ➞ false is_nested("[][]") ➞ false is_nested("[]") ➞ false is_nested("[[][]]") ➞ true is_nested("[[]][[") ➞ true
Write a C++ function `bool is_nested(string str)` to solve the following problem: Create a function that takes a string as input which contains only square brackets. The function should return true if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. is_nested("[[]]") ➞ true is_nested("[]]]]]]][[[[[]") ➞ false is_nested("[][]") ➞ false is_nested("[]") ➞ false is_nested("[[][]]") ➞ true is_nested("[[]][[") ➞ true
CPP/133
/* You are given a vector of numbers. You need to return the sum of squared numbers in the given vector, round each element in the vector to the upper int(Ceiling) first. Examples: For lst = {1,2,3} the output should be 14 For lst = {1,4,9} the output should be 98 For lst = {1,3,5,7} the output should be 84 For lst = {1.4,4.2,0} the output should be 29 For lst = {-2.4,1,1} the output should be 6 */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; int sum_squares(vector<float> lst){
int sum=0; for (int i=0;i<lst.size();i++) sum+=ceil(lst[i])*ceil(lst[i]); return sum; }
#undef NDEBUG #include<assert.h> int main(){ assert (sum_squares({1,2,3})==14); assert (sum_squares({1.0,2,3})==14); assert (sum_squares({1,3,5,7})==84); assert (sum_squares({1.4,4.2,0})==29); assert (sum_squares({-2.4,1,1})==6); assert (sum_squares({100,1,15,2})==10230); assert (sum_squares({10000,10000})==200000000); assert (sum_squares({-1.4,4.6,6.3})==75); assert (sum_squares({-1.4,17.9,18.9,19.9})==1086); assert (sum_squares({0})==0); assert (sum_squares({-1})==1); assert (sum_squares({-1,1,0})==2); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> int sum_squares(vector<float> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (sum_squares({1,2,3})==14); assert (sum_squares({1,4,9})==98); assert (sum_squares({1,3,5,7})==84); assert (sum_squares({1.4,4.2,0})==29); assert (sum_squares({-2.4,1,1})==6); }
int sum=0; for (int i=0;i<lst.size();i++) sum+=ceil(lst[i])*2; return sum; }
operator misuse
incorrect output
sum_squares
int sum_squares(vector<float> lst)
You are given a vector of numbers. You need to return the sum of squared numbers in the given vector, round each element in the vector to the upper int(Ceiling) first. Examples: For lst = {1,2,3} the output should be 14 For lst = {1,4,9} the output should be 98 For lst = {1,3,5,7} the output should be 84 For lst = {1.4,4.2,0} the output should be 29 For lst = {-2.4,1,1} the output should be 6
Write a C++ function `int sum_squares(vector<float> lst)` to solve the following problem: You are given a vector of numbers. You need to return the sum of squared numbers in the given vector, round each element in the vector to the upper int(Ceiling) first. Examples: For lst = {1,2,3} the output should be 14 For lst = {1,4,9} the output should be 98 For lst = {1,3,5,7} the output should be 84 For lst = {1.4,4.2,0} the output should be 29 For lst = {-2.4,1,1} the output should be 6
CPP/134
/* Create a function that returns true if the last character of a given string is an alphabetical character and is not a part of a word, and false otherwise. Note: "word" is a group of characters separated by space. Examples: check_if_last_char_is_a_letter("apple pie") ➞ false check_if_last_char_is_a_letter("apple pi e") ➞ true check_if_last_char_is_a_letter("apple pi e ") ➞ false check_if_last_char_is_a_letter("") ➞ false */ #include<stdio.h> #include<string> using namespace std; bool check_if_last_char_is_a_letter(string txt){
if (txt.length()==0) return false; char chr=txt[txt.length()-1]; if (chr<65 or (chr>90 and chr<97) or chr>122) return false; if (txt.length()==1) return true; chr=txt[txt.length()-2]; if ((chr>=65 and chr<=90) or (chr>=97 and chr<=122)) return false; return true; }
#undef NDEBUG #include<assert.h> int main(){ assert (check_if_last_char_is_a_letter("apple") == false); assert (check_if_last_char_is_a_letter("apple pi e") == true); assert (check_if_last_char_is_a_letter("eeeee") == false); assert (check_if_last_char_is_a_letter("A") == true); assert (check_if_last_char_is_a_letter("Pumpkin pie ") == false); assert (check_if_last_char_is_a_letter("Pumpkin pie 1") == false); assert (check_if_last_char_is_a_letter("") == false); assert (check_if_last_char_is_a_letter("eeeee e ") == false); assert (check_if_last_char_is_a_letter("apple pie") == false); assert (check_if_last_char_is_a_letter("apple pi e ") == false); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> bool check_if_last_char_is_a_letter(string txt){
#undef NDEBUG #include<assert.h> int main(){ assert (check_if_last_char_is_a_letter("apple pi e") == true); assert (check_if_last_char_is_a_letter("") == false); assert (check_if_last_char_is_a_letter("apple pie") == false); assert (check_if_last_char_is_a_letter("apple pi e ") == false); }
if (txt.length()==0) return false; char chr=txt[txt.length()-1]; if (chr<10 or (chr>50 and chr<57) or chr>200) return false; if (txt.length()==1) return true; chr=txt[txt.length()-2]; if ((chr>=30 and chr<=37) or (chr>=21 and chr<=42)) return false; return true; }
function misuse
incorrect output
check_if_last_char_is_a_letter
bool check_if_last_char_is_a_letter(string txt)
Create a function that returns true if the last character of a given string is an alphabetical character and is not a part of a word, and false otherwise. Note: "word" is a group of characters separated by space. Examples: check_if_last_char_is_a_letter("apple pie") ➞ false check_if_last_char_is_a_letter("apple pi e") ➞ true check_if_last_char_is_a_letter("apple pi e ") ➞ false check_if_last_char_is_a_letter("") ➞ false
Write a C++ function `bool check_if_last_char_is_a_letter(string txt)` to solve the following problem: Create a function that returns true if the last character of a given string is an alphabetical character and is not a part of a word, and false otherwise. Note: "word" is a group of characters separated by space. Examples: check_if_last_char_is_a_letter("apple pie") ➞ false check_if_last_char_is_a_letter("apple pi e") ➞ true check_if_last_char_is_a_letter("apple pi e ") ➞ false check_if_last_char_is_a_letter("") ➞ false
CPP/135
/* Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given vector will not contain duplicate values. Examples: can_arrange({1,2,4,3,5}) = 3 can_arrange({1,2,3}) = -1 */ #include<stdio.h> #include<vector> using namespace std; int can_arrange(vector<int> arr){
int max=-1; for (int i=0;i<arr.size();i++) if (arr[i]<=i) max=i; return max; }
#undef NDEBUG #include<assert.h> int main(){ assert (can_arrange({1,2,4,3,5})==3); assert (can_arrange({1,2,4,5})==-1); assert (can_arrange({1,4,2,5,6,7,8,9,10})==2); assert (can_arrange({4,8,5,7,3})==4); assert (can_arrange({})==-1); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> int can_arrange(vector<int> arr){
#undef NDEBUG #include<assert.h> int main(){ assert (can_arrange({1,2,4,3,5})==3); assert (can_arrange({1,2,3})==-1); }
int max=-1; for (int i=0;i<arr.size();i++) if (arr[i]<=i) max=i+arr[i]; return max; }
excess logic
incorrect output
can_arrange
int can_arrange(vector<int> arr)
Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given vector will not contain duplicate values. Examples: can_arrange({1,2,4,3,5}) = 3 can_arrange({1,2,3}) = -1
Write a C++ function `int can_arrange(vector<int> arr)` to solve the following problem: Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given vector will not contain duplicate values. Examples: can_arrange({1,2,4,3,5}) = 3 can_arrange({1,2,3}) = -1
CPP/136
/* Create a function that returns a vector (a, b), where "a" is the largest of negative integers, and "b" is the smallest of positive integers in a vector. If there is no negative or positive integers, return them as 0. Examples: largest_smallest_integers({2, 4, 1, 3, 5, 7}) == {0, 1} largest_smallest_integers({}) == {0,0} largest_smallest_integers({0}) == {0,0} */ #include<stdio.h> #include<vector> using namespace std; vector<int> largest_smallest_integers(vector<int> lst){
int maxneg=0,minpos=0; for (int i=0;i<lst.size();i++) { if (lst[i]<0 and (maxneg==0 or lst[i]>maxneg)) maxneg=lst[i]; if (lst[i]>0 and (minpos==0 or lst[i]<minpos)) minpos=lst[i]; } return {maxneg,minpos}; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(largest_smallest_integers({2, 4, 1, 3, 5, 7}) , {0, 1})); assert (issame(largest_smallest_integers({2, 4, 1, 3, 5, 7, 0}) , {0, 1})); assert (issame(largest_smallest_integers({1, 3, 2, 4, 5, 6, -2}) , {-2, 1})); assert (issame(largest_smallest_integers({4, 5, 3, 6, 2, 7, -7}) , {-7, 2})); assert (issame(largest_smallest_integers({7, 3, 8, 4, 9, 2, 5, -9}) , {-9, 2})); assert (issame(largest_smallest_integers({}) , {0, 0})); assert (issame(largest_smallest_integers({0}) , {0, 0})); assert (issame(largest_smallest_integers({-1, -3, -5, -6}) , {-1, 0})); assert (issame(largest_smallest_integers({-1, -3, -5, -6, 0}) , {-1, 0})); assert (issame(largest_smallest_integers({-6, -4, -4, -3, 1}) , {-3, 1})); assert (issame(largest_smallest_integers({-6, -4, -4, -3, -100, 1}) , {-3, 1})); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> largest_smallest_integers(vector<int> lst){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(largest_smallest_integers({2, 4, 1, 3, 5, 7}) , {0, 1})); assert (issame(largest_smallest_integers({}) , {0, 0})); assert (issame(largest_smallest_integers({0}) , {0, 0})); }
int maxneg=0,minpos=0; for (int i=0;i<lst.size();i++) { if (lst[i]<0 and (maxneg==0 or lst[i]>maxneg)) maxneg=lst[i]; if (lst[i]>0 and (minpos==0 or lst[i]<minpos)) minpos=lst[i]; } for (int i=0;i<lst.size();i++) { if (lst[i]<0 and (minpos==0 or lst[i]>minpos)) maxneg=lst[i]; if (lst[i]>0 and (maxneg==0 or lst[i]<maxneg)) minpos=lst[i]; } return {maxneg,minpos}; }
excess logic
incorrect output
largest_smallest_integers
vector<int> largest_smallest_integers(vector<int> lst)
Create a function that returns a vector (a, b), where "a" is the largest of negative integers, and "b" is the smallest of positive integers in a vector. If there is no negative or positive integers, return them as 0. Examples: largest_smallest_integers({2, 4, 1, 3, 5, 7}) == {0, 1} largest_smallest_integers({}) == {0,0} largest_smallest_integers({0}) == {0,0}
Write a C++ function `vector<int> largest_smallest_integers(vector<int> lst)` to solve the following problem: Create a function that returns a vector (a, b), where "a" is the largest of negative integers, and "b" is the smallest of positive integers in a vector. If there is no negative or positive integers, return them as 0. Examples: largest_smallest_integers({2, 4, 1, 3, 5, 7}) == {0, 1} largest_smallest_integers({}) == {0,0} largest_smallest_integers({0}) == {0,0}
CPP/137
/* Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return "None" if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , compare_one(1, 2.5) ➞ 2.5 compare_one(1, "2,3") ➞ "2,3" compare_one("5,1", "6") ➞ "6" compare_one("1", 1) ➞ "None" */ #include<stdio.h> #include<string> #include<algorithm> #include<boost/any.hpp> using namespace std; boost::any compare_one(boost::any a,boost::any b){
double numa,numb; boost::any out; if (a.type()==typeid(string)) { string s; s=boost::any_cast<string>(a); if (find(s.begin(),s.end(),',')!=s.end()) for (int i=0;i<s.length();i++) if (s[i]==',') s=s.substr(0,i)+'.'+s.substr(i+1); numa=atof(s.c_str()); } else { if (a.type()==typeid(int)) numa=boost::any_cast<int>(a); if (a.type()==typeid(double)) numa=boost::any_cast<double>(a); } if (b.type()==typeid(string)) { string s; s=boost::any_cast<string>(b); if (find(s.begin(),s.end(),',')!=s.end()) for (int i=0;i<s.length();i++) if (s[i]==',') s=s.substr(0,i)+'.'+s.substr(i+1); numb=atof(s.c_str()); } else { if (b.type()==typeid(int)) numb=boost::any_cast<int>(b); if (b.type()==typeid(double)) numb=boost::any_cast<double>(b); } if (numa==numb) return string("None"); if (numa<numb) return b; if (numa>numb) return a; }
#undef NDEBUG #include<assert.h> int main(){ assert (boost::any_cast<int>(compare_one(1, 2)) == 2); assert (boost::any_cast<double>(compare_one(1, 2.5))== 2.5); assert (boost::any_cast<int>(compare_one(2, 3)) == 3); assert (boost::any_cast<int>(compare_one(5, 6)) == 6); assert (boost::any_cast<string>(compare_one(1, string("2,3")))== "2,3"); assert (boost::any_cast<string>(compare_one(string("5,1"), string("6"))) == "6"); assert (boost::any_cast<string>(compare_one(string("1"), string("2"))) == "2"); assert (boost::any_cast<string>(compare_one(string("1"), 1)) == "None"); }
#include<stdio.h> #include<math.h> #include<string> #include<algorithm> #include<boost/any.hpp> using namespace std; #include<stdlib.h> boost::any compare_one(boost::any a,boost::any b){
#undef NDEBUG #include<assert.h> int main(){ assert (boost::any_cast<double>(compare_one(1, 2.5))== 2.5); assert (boost::any_cast<string>(compare_one(1, string("2,3")))== "2,3"); assert (boost::any_cast<string>(compare_one(string("5,1"), string("6"))) == "6"); assert (boost::any_cast<string>(compare_one(string("1"), 1)) == "None"); }
double numa,numb; boost::any out; if (a.type()==typeid(string)) { string s; s=boost::any_cast<string>(a); if (find(s.begin(),s.end(),',')!=s.end()) for (int i=0;i<s.length();i++) if (s[i]==',') s=s.substr(0,i)+'.'+s.substr(i+1); numa=atof(s.c_str()); } else { if (a.type()==typeid(int)) numa=boost::any_cast<int>(a); if (a.type()==typeid(double)) numa=boost::any_cast<double>(a); } if (b.type()==typeid(string)) { string s; s=boost::any_cast<string>(b); if (find(s.begin(),s.end(),',')!=s.end()) for (int i=0;i<s.length();i++) if (s[i]==',') s=s.substr(0,i)+'.'+s.substr(i+1)+','; numb=atof(s.c_str()); } else { if (b.type()==typeid(int)) numb=boost::any_cast<int>(b); if (b.type()==typeid(double)) numb=boost::any_cast<double>(b); } if (numa==numb) return string("None"); if (numa<numb) return b; if (numa>numb) return a; }
excess logic
incorrect output
compare_one
boost::any compare_one(boost::any a,boost::any b)
Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return "None" if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , compare_one(1, 2.5) ➞ 2.5 compare_one(1, "2,3") ➞ "2,3" compare_one("5,1", "6") ➞ "6" compare_one("1", 1) ➞ "None"
Write a C++ function `boost::any compare_one(boost::any a,boost::any b)` to solve the following problem: Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return "None" if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , compare_one(1, 2.5) ➞ 2.5 compare_one(1, "2,3") ➞ "2,3" compare_one("5,1", "6") ➞ "6" compare_one("1", 1) ➞ "None"
CPP/138
/* Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example is_equal_to_sum_even(4) == false is_equal_to_sum_even(6) == false is_equal_to_sum_even(8) == true */ #include<stdio.h> using namespace std; bool is_equal_to_sum_even(int n){
if (n%2==0 and n>=8) return true; return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (is_equal_to_sum_even(4) == false); assert (is_equal_to_sum_even(6) == false); assert (is_equal_to_sum_even(8) == true); assert (is_equal_to_sum_even(10) == true); assert (is_equal_to_sum_even(11) == false); assert (is_equal_to_sum_even(12) == true); assert (is_equal_to_sum_even(13) == false); assert (is_equal_to_sum_even(16) == true); }
#include<stdio.h> #include<math.h> #include<algorithm> using namespace std; #include<stdlib.h> bool is_equal_to_sum_even(int n){
#undef NDEBUG #include<assert.h> int main(){ assert (is_equal_to_sum_even(4) == false); assert (is_equal_to_sum_even(6) == false); assert (is_equal_to_sum_even(8) == true); }
if (n%2==0 and n>=8 and n <=8) return true; return false; }
excess logic
incorrect output
is_equal_to_sum_even
bool is_equal_to_sum_even(int n)
Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example is_equal_to_sum_even(4) == false is_equal_to_sum_even(6) == false is_equal_to_sum_even(8) == true
Write a C++ function `bool is_equal_to_sum_even(int n)` to solve the following problem: Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example is_equal_to_sum_even(4) == false is_equal_to_sum_even(6) == false is_equal_to_sum_even(8) == true
CPP/139
/* The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. */ #include<stdio.h> using namespace std; long long special_factorial(int n){
long long fact=1,bfact=1; for (int i=1;i<=n;i++) { fact=fact*i; bfact=bfact*fact; } return bfact; }
#undef NDEBUG #include<assert.h> int main(){ assert (special_factorial(4) == 288); assert (special_factorial(5) == 34560); assert (special_factorial(7) == 125411328000); assert (special_factorial(1) == 1); }
#include<stdio.h> #include<math.h> #include<algorithm> using namespace std; #include<stdlib.h> long long special_factorial(int n){
#undef NDEBUG #include<assert.h> int main(){ assert (special_factorial(4) == 288); }
long long fact=1,bfact=1; for (int i=1;i<=n;i++) { i=i*n; fact=fact*i; bfact=bfact*fact; } return bfact; }
excess logic
incorrect output
special_factorial
long long special_factorial(int n)
The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer.
Write a C++ function `long long special_factorial(int n)` to solve the following problem: The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer.
CPP/140
/* Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fix_spaces("Example") == "Example" fix_spaces("Example 1") == "Example_1" fix_spaces(" Example 2") == "_Example_2" fix_spaces(" Example 3") == "_Example-3" */ #include<stdio.h> #include<string> using namespace std; string fix_spaces(string text){
string out=""; int spacelen=0; for (int i=0;i<text.length();i++) if (text[i]==' ') spacelen+=1; else { if (spacelen==1) out=out+'_'; if (spacelen==2) out=out+"__"; if (spacelen>2) out=out+'-'; spacelen=0; out=out+text[i]; } if (spacelen==1) out=out+'_'; if (spacelen==2) out=out+"__"; if (spacelen>2) out=out+'-'; return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (fix_spaces("Example") == "Example"); assert (fix_spaces("Mudasir Hanif ") == "Mudasir_Hanif_"); assert (fix_spaces("Yellow Yellow Dirty Fellow") == "Yellow_Yellow__Dirty__Fellow"); assert (fix_spaces("Exa mple") == "Exa-mple"); assert (fix_spaces(" Exa 1 2 2 mple") == "-Exa_1_2_2_mple"); }
#include<stdio.h> #include<string> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> string fix_spaces(string text){
#undef NDEBUG #include<assert.h> int main(){ assert (fix_spaces("Example") == "Example"); assert (fix_spaces("Example 1") == "Example_1"); assert (fix_spaces(" Example 2") == "_Example_2"); assert (fix_spaces(" Example 3") == "_Example-3"); }
string out=""; int spacelen=0; for (int i=0;i<text.length();i++) if (text[i]==' ') spacelen+=1; else { if (spacelen==2) out=out+'_'; if (spacelen==3) out=out+"_"; if (spacelen>3) out=out+'-'; spacelen=0; out=out+text[i]; } if (spacelen==1) out=out+'_'; if (spacelen==2) out=out+"_"; if (spacelen>2) out=out+'-'; return out; }
excess logic
incorrect output
fix_spaces
string fix_spaces(string text)
Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fix_spaces("Example") == "Example" fix_spaces("Example 1") == "Example_1" fix_spaces(" Example 2") == "_Example_2" fix_spaces(" Example 3") == "_Example-3"
Write a C++ function `string fix_spaces(string text)` to solve the following problem: Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fix_spaces("Example") == "Example" fix_spaces("Example 1") == "Example_1" fix_spaces(" Example 2") == "_Example_2" fix_spaces(" Example 3") == "_Example-3"
CPP/141
/* Create a function which takes a string representing a file's name, and returns "Yes" if the the file's name is valid, and returns "No" otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot "." - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: {'txt", "exe", "dll"} Examples: file_name_check("example.txt") => "Yes" file_name_check("1example.dll") => "No" // (the name should start with a latin alphapet letter) */ #include<stdio.h> #include<string> using namespace std; string file_name_check(string file_name){
int numdigit=0,numdot=0; if (file_name.length()<5) return "No"; char w=file_name[0]; if (w<65 or (w>90 and w<97) or w>122) return "No"; string last=file_name.substr(file_name.length()-4,4); if (last!=".txt" and last!=".exe" and last!=".dll") return "No"; for (int i=0;i<file_name.length();i++) { if (file_name[i]>=48 and file_name[i]<=57) numdigit+=1; if (file_name[i]=='.') numdot+=1; } if (numdigit>3 or numdot!=1) return "No"; return "Yes"; }
#undef NDEBUG #include<assert.h> int main(){ assert (file_name_check("example.txt") == "Yes"); assert (file_name_check("1example.dll") == "No"); assert (file_name_check("s1sdf3.asd") == "No"); assert (file_name_check("K.dll") == "Yes"); assert (file_name_check("MY16FILE3.exe") == "Yes"); assert (file_name_check("His12FILE94.exe") == "No"); assert (file_name_check("_Y.txt") == "No"); assert (file_name_check("?aREYA.exe") == "No"); assert (file_name_check("/this_is_valid.dll") == "No"); assert (file_name_check("this_is_valid.wow") == "No"); assert (file_name_check("this_is_valid.txt") == "Yes"); assert (file_name_check("this_is_valid.txtexe") == "No"); assert (file_name_check("#this2_i4s_5valid.ten") == "No"); assert (file_name_check("@this1_is6_valid.exe") == "No"); assert (file_name_check("this_is_12valid.6exe4.txt") == "No"); assert (file_name_check("all.exe.txt") == "No"); assert (file_name_check("I563_No.exe") == "Yes"); assert (file_name_check("Is3youfault.txt") == "Yes"); assert (file_name_check("no_one#knows.dll") == "Yes"); assert (file_name_check("1I563_Yes3.exe") == "No"); assert (file_name_check("I563_Yes3.txtt") == "No"); assert (file_name_check("final..txt") == "No"); assert (file_name_check("final132") == "No"); assert (file_name_check("_f4indsartal132.") == "No"); assert (file_name_check(".txt") == "No"); assert (file_name_check("s.") == "No"); }
#include<stdio.h> #include<string> #include<algorithm> using namespace std; #include<math.h> #include<stdlib.h> string file_name_check(string file_name){
#undef NDEBUG #include<assert.h> int main(){ assert (file_name_check("example.txt") == "Yes"); assert (file_name_check("1example.dll") == "No"); }
int numdigit=0,numdot=0; if (file_name.length()<5) return "No"; char w=file_name[0]; if (w<65 or (w>90 and w<97) or w>122) return "No"; string last=file_name.substr(file_name.length()-4,4); if (last!=".txt" and last!=".exe" and last!=".dll") return "No"; for (int i=0;i<file_name.length();i++) { if (file_name[i]>=48 and file_name[i]<=57) numdigit+=1; } if (numdigit>3 or numdot!=1) return "No"; return "Yes"; }
missing logic
incorrect output
file_name_check
string file_name_check(string file_name)
Create a function which takes a string representing a file's name, and returns "Yes" if the the file's name is valid, and returns "No" otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot "." - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: {'txt", "exe", "dll"} Examples: file_name_check("example.txt") => "Yes" file_name_check("1example.dll") => "No" // (the name should start with a latin alphapet letter)
Write a C++ function `string file_name_check(string file_name)` to solve the following problem: Create a function which takes a string representing a file's name, and returns "Yes" if the the file's name is valid, and returns "No" otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot "." - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: {'txt", "exe", "dll"} Examples: file_name_check("example.txt") => "Yes" file_name_check("1example.dll") => "No" // (the name should start with a latin alphapet letter)
CPP/142
/* " This function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. Examples: For lst = {1,2,3} the output should be 6 For lst = {} the output should be 0 For lst = {-1,-5,2,-1,-5} the output should be -126 */ #include<stdio.h> #include<vector> using namespace std; int sum_squares(vector<int> lst){
int sum=0; for (int i=0;i<lst.size();i++) if (i%3==0) sum+=lst[i]*lst[i]; else if (i%4==0) sum+=lst[i]*lst[i]*lst[i]; else sum+=lst[i]; return sum; }
#undef NDEBUG #include<assert.h> int main(){ assert (sum_squares({1,2,3}) == 6); assert (sum_squares({1,4,9}) == 14); assert (sum_squares({}) == 0); assert (sum_squares({1,1,1,1,1,1,1,1,1}) == 9); assert (sum_squares({-1,-1,-1,-1,-1,-1,-1,-1,-1}) == -3); assert (sum_squares({0}) == 0); assert (sum_squares({-1,-5,2,-1,-5}) == -126); assert (sum_squares({-56,-99,1,0,-2}) == 3030); assert (sum_squares({-1,0,0,0,0,0,0,0,-1}) == 0); assert (sum_squares({-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37}) == -14196); assert (sum_squares({-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10}) == -1448); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> int sum_squares(vector<int> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (sum_squares({1,2,3}) == 6); assert (sum_squares({}) == 0); assert (sum_squares({-1,-5,2,-1,-5}) == -126); }
int sum=0; for (int i=0;i<lst.size();i++) if (i%3==0) sum+=lst[i]*lst[i]; else sum+=lst[i]; return sum; }
missing logic
incorrect output
sum_squares
int sum_squares(vector<int> lst)
" This function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. Examples: For lst = {1,2,3} the output should be 6 For lst = {} the output should be 0 For lst = {-1,-5,2,-1,-5} the output should be -126
Write a C++ function `int sum_squares(vector<int> lst)` to solve the following problem: " This function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. Examples: For lst = {1,2,3} the output should be 6 For lst = {} the output should be 0 For lst = {-1,-5,2,-1,-5} the output should be -126
CPP/143
/* You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters */ #include<stdio.h> #include<string> using namespace std; string words_in_sentence(string sentence){
string out=""; string current=""; sentence=sentence+' '; for (int i=0;i<sentence.size();i++) if (sentence[i]!=' ') current=current+sentence[i]; else { bool isp=true; int l=current.length(); if (l<2) isp=false; for (int j=2;j*j<=l;j++) if (l%j==0) isp=false; if (isp) out=out+current+' '; current=""; } if (out.length()>0) out.pop_back(); return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (words_in_sentence("This is a test") == "is"); assert (words_in_sentence("lets go for swimming") == "go for"); assert (words_in_sentence("there is no place available here") == "there is no place"); assert (words_in_sentence("Hi I am Hussein") == "Hi am Hussein"); assert (words_in_sentence("go for it") == "go for it"); assert (words_in_sentence("here") == ""); assert (words_in_sentence("here is") == "is"); }
#include<stdio.h> #include<string> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> string words_in_sentence(string sentence){
#undef NDEBUG #include<assert.h> int main(){ assert (words_in_sentence("This is a test") == "is"); assert (words_in_sentence("lets go for swimming") == "go for"); }
string out=""; string current=""; sentence=sentence+' '; for (int i=0;i<sentence.size();i++) if (sentence[i]!=' ') current=current+sentence[i]; else { bool isp=true; int l=current.length(); if (l<2) isp=false; for (int j=2;j*j<=l;j++) if (l%j==0) isp=false; if (isp) out=out+current+' '; current=""; } return out; }
missing logic
incorrect output
words_in_sentence
string words_in_sentence(string sentence)
You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters
Write a C++ function `string words_in_sentence(string sentence)` to solve the following problem: You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters
CPP/144
/* Your task is to implement a function that will simplify the expression x * n. The function returns true if x * n evaluates to a whole number and false otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. simplify("1/5", "5/1") = true simplify("1/6", "2/1") = false simplify("7/10", "10/2") = false */ #include<stdio.h> #include<string> using namespace std; bool simplify(string x,string n){
int a,b,c,d,i; for (i=0;i<x.size();i++) if (x[i]=='/') { a=atoi(x.substr(0,i).c_str()); b=atoi(x.substr(i+1).c_str()); } for (i=0;i<n.size();i++) if (n[i]=='/') { c=atoi(n.substr(0,i).c_str()); d=atoi(n.substr(i+1).c_str()); } if ((a*c)%(b*d)==0) return true; return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (simplify("1/5", "5/1") == true); assert (simplify("1/6", "2/1") == false); assert (simplify("5/1", "3/1") == true); assert (simplify("7/10", "10/2") == false); assert (simplify("2/10", "50/10") == true); assert (simplify("7/2", "4/2") == true); assert (simplify("11/6", "6/1") == true); assert (simplify("2/3", "5/2") == false); assert (simplify("5/2", "3/5") == false); assert (simplify("2/4", "8/4") == true); assert (simplify("2/4", "4/2") == true); assert (simplify("1/5", "5/1") == true); assert (simplify("1/5", "1/5") == false); }
#include<stdio.h> #include<string> #include<algorithm> using namespace std; #include<math.h> #include<stdlib.h> bool simplify(string x,string n){
#undef NDEBUG #include<assert.h> int main(){ assert (simplify("1/5", "5/1") == true); assert (simplify("1/6", "2/1") == false); assert (simplify("7/10", "10/2") == false); }
int a,b,c,d,i; for (i=0;i<x.size();i++) if (x[i]=='/') { a=atoi(x.substr(0,i).c_str()); b=atoi(x.substr(i+1).c_str()); } for (i=0;i<n.size();i++) if (n[i]=='/') { c=atoi(n.substr(0,i).c_str()); d=atoi(n.substr(i+1).c_str()); a=atoi(n.substr(0,i).c_str()); b=atoi(n.substr(i+1).c_str()); } if ((a*c)%(b*d)==0) return true; return false; }
excess logic
incorrect output
simplify
bool simplify(string x,string n)
Your task is to implement a function that will simplify the expression x * n. The function returns true if x * n evaluates to a whole number and false otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. simplify("1/5", "5/1") = true simplify("1/6", "2/1") = false simplify("7/10", "10/2") = false
Write a C++ function `bool simplify(string x,string n)` to solve the following problem: Your task is to implement a function that will simplify the expression x * n. The function returns true if x * n evaluates to a whole number and false otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. simplify("1/5", "5/1") = true simplify("1/6", "2/1") = false simplify("7/10", "10/2") = false
CPP/145
/* Write a function which sorts the given vector of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original vector. For example: >>> order_by_points({1, 11, -1, -11, -12}) == {-1, -11, 1, -12, 11} >>> order_by_points({}) == {} */ #include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; vector<int> order_by_points(vector<int> nums){
vector<int> sumdigit={}; for (int i=0;i<nums.size();i++) { string w=to_string(abs(nums[i])); int sum=0; for (int j=1;j<w.length();j++) sum+=w[j]-48; if (nums[i]>0) sum+=w[0]-48; else sum-=w[0]-48; sumdigit.push_back(sum); } int m; for (int i=0;i<nums.size();i++) for (int j=1;j<nums.size();j++) if (sumdigit[j-1]>sumdigit[j]) { m=sumdigit[j];sumdigit[j]=sumdigit[j-1];sumdigit[j-1]=m; m=nums[j];nums[j]=nums[j-1];nums[j-1]=m; } return nums; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(order_by_points({1, 11, -1, -11, -12}) , {-1, -11, 1, -12, 11})); assert (issame(order_by_points({1234,423,463,145,2,423,423,53,6,37,3457,3,56,0,46}) , {0, 2, 3, 6, 53, 423, 423, 423, 1234, 145, 37, 46, 56, 463, 3457})); assert (issame(order_by_points({}) , {})); assert (issame(order_by_points({1, -11, -32, 43, 54, -98, 2, -3}) , {-3, -32, -98, -11, 1, 2, 43, 54})); assert (issame(order_by_points({1,2,3,4,5,6,7,8,9,10,11}) , {1, 10, 2, 11, 3, 4, 5, 6, 7, 8, 9})); assert (issame(order_by_points({0,6,6,-76,-21,23,4}) , {-76, -21, 0, 4, 23, 6, 6})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> vector<int> order_by_points(vector<int> nums){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(order_by_points({1, 11, -1, -11, -12}) , {-1, -11, 1, -12, 11})); assert (issame(order_by_points({}) , {})); }
vector<int> sumdigit={}; for (int i=0;i<nums.size();i++) { string w=to_string(abs(nums[i])); int sum=0; for (int j=1;j<w.length();j++) sum+=w[j]-48; if (nums[i]>0) sum+=w[0]-48; else sum-=w[0]-48; sumdigit.push_back(sum); } int m; for (int i=0;i<nums.size();i++) for (int j=1;j<nums.size();j++) if (sumdigit[j-1]>sumdigit[j]) { m=sumdigit[j];sumdigit[j]=sumdigit[j-1];sumdigit[j-1]=m;sumdigit[j]=m; m=nums[j];nums[j]=nums[j-1];nums[j-1]=m;nums[j]=m; } return nums; }
excess logic
incorrect output
order_by_points
vector<int> order_by_points(vector<int> nums)
Write a function which sorts the given vector of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original vector. For example: >>> order_by_points({1, 11, -1, -11, -12}) == {-1, -11, 1, -12, 11} >>> order_by_points({}) == {}
Write a C++ function `vector<int> order_by_points(vector<int> nums)` to solve the following problem: Write a function which sorts the given vector of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original vector. For example: >>> order_by_points({1, 11, -1, -11, -12}) == {-1, -11, 1, -12, 11} >>> order_by_points({}) == {}
CPP/146
/* Write a function that takes a vector of numbers as input and returns the number of elements in the vector that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: specialFilter({15, -73, 14, -15}) => 1 specialFilter({33, -2, -3, 45, 21, 109}) => 2 */ #include<stdio.h> #include<vector> #include<string> using namespace std; int specialFilter(vector<int> nums){
int num=0; for (int i=0;i<nums.size();i++) if (nums[i]>10) { string w=to_string(nums[i]); if (w[0]%2==1 and w[w.length()-1]%2==1) num+=1; } return num; }
#undef NDEBUG #include<assert.h> int main(){ assert (specialFilter({5, -2, 1, -5}) == 0 ); assert (specialFilter({15, -73, 14, -15}) == 1); assert (specialFilter({33, -2, -3, 45, 21, 109}) == 2); assert (specialFilter({43, -12, 93, 125, 121, 109}) == 4); assert (specialFilter({71, -2, -33, 75, 21, 19}) == 3); assert (specialFilter({1}) == 0 ); assert (specialFilter({}) == 0 ); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> int specialFilter(vector<int> nums){
#undef NDEBUG #include<assert.h> int main(){ assert (specialFilter({15, -73, 14, -15}) == 1); assert (specialFilter({33, -2, -3, 45, 21, 109}) == 2); }
int num=0; for (int i=0;i<nums.size();i++) if (nums[i]>10) { string w=to_string(nums[i]); if (w[0]%2==1 and w[w.length()-1]%2==1 and w[w.length()-1]%2==0) num+=1; } return num; }
excess logic
incorrect output
specialFilter
int specialFilter(vector<int> nums)
Write a function that takes a vector of numbers as input and returns the number of elements in the vector that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: specialFilter({15, -73, 14, -15}) => 1 specialFilter({33, -2, -3, 45, 21, 109}) => 2
Write a C++ function `int specialFilter(vector<int> nums)` to solve the following problem: Write a function that takes a vector of numbers as input and returns the number of elements in the vector that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: specialFilter({15, -73, 14, -15}) => 1 specialFilter({33, -2, -3, 45, 21, 109}) => 2
CPP/147
/* You are given a positive integer n. You have to create an integer vector a of length n. For each i (1 ≤ i ≤ n), the value of a{i} = i * i - i + 1. Return the number of triples (a{i}, a{j}, a{k}) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = {1, 3, 7, 13, 21} The only valid triple is (1, 7, 13). */ #include<stdio.h> #include<vector> using namespace std; int get_matrix_triples(int n){
vector<int> a; vector<vector<int>> sum={{0,0,0}}; vector<vector<int>> sum2={{0,0,0}}; for (int i=1;i<=n;i++) { a.push_back((i*i-i+1)%3); sum.push_back(sum[sum.size()-1]); sum[i][a[i-1]]+=1; } for (int times=1;times<3;times++) { for (int i=1;i<=n;i++) { sum2.push_back(sum2[sum2.size()-1]); if (i>=1) for (int j=0;j<=2;j++) sum2[i][(a[i-1]+j)%3]+=sum[i-1][j]; } sum=sum2; sum2={{0,0,0}}; } return sum[n][0]; }
#undef NDEBUG #include<assert.h> int main(){ assert (get_matrix_triples(5) == 1); assert (get_matrix_triples(6) == 4); assert (get_matrix_triples(10) == 36); assert (get_matrix_triples(100) == 53361); }
#include<stdio.h> #include<vector> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> int get_matrix_triples(int n){
#undef NDEBUG #include<assert.h> int main(){ assert (get_matrix_triples(5) == 1); }
vector<int> a; vector<vector<int>> sum={{0,0,0}}; vector<vector<int>> sum2={{0,0,0}}; for (int i=1;i<=n;i++) { a.push_back((i*i)%3); sum.push_back(sum[sum.size()-1]); sum[i][a[i-1]]+=1; } for (int times=1;times<3;times++) { for (int i=1;i<=n;i++) { sum2.push_back(sum2[sum2.size()-1]); if (i>=1) for (int j=0;j<=2;j++) sum2[i][(a[i-1]+j)%3]+=sum[i-1][j]; } sum=sum2; sum2={{0,0,0}}; } return sum[n][0]; }
missing logic
incorrect output
get_matrix_triples
int get_matrix_triples(int n)
You are given a positive integer n. You have to create an integer vector a of length n. For each i (1 ≤ i ≤ n), the value of a{i} = i * i - i + 1. Return the number of triples (a{i}, a{j}, a{k}) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = {1, 3, 7, 13, 21} The only valid triple is (1, 7, 13).
Write a C++ function `int get_matrix_triples(int n)` to solve the following problem: You are given a positive integer n. You have to create an integer vector a of length n. For each i (1 ≤ i ≤ n), the value of a{i} = i * i - i + 1. Return the number of triples (a{i}, a{j}, a{k}) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = {1, 3, 7, 13, 21} The only valid triple is (1, 7, 13).
CPP/148
/* There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a vector containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty vector if planet1 or planet2 are not correct planet names. Examples bf("Jupiter", "Neptune") ==> {"Saturn", "Uranus"} bf("Earth", "Mercury") ==> {"Venus"} bf("Mercury", "Uranus") ==> {"Venus", "Earth", "Mars", "Jupiter", "Saturn"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> bf(string planet1,string planet2){
vector<string> planets={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"}; int pos1=-1,pos2=-1,m; for (m=0;m<planets.size();m++) { if (planets[m]==planet1) pos1=m; if (planets[m]==planet2) pos2=m; } if (pos1==-1 or pos2==-1) return {}; if (pos1>pos2) {m=pos1;pos1=pos2;pos2=m;} vector<string> out={}; for (m=pos1+1;m<pos2;m++) out.push_back(planets[m]); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(bf("Jupiter", "Neptune") , {"Saturn", "Uranus"})); assert (issame(bf("Earth", "Mercury") , {"Venus",})); assert (issame(bf("Mercury", "Uranus") , {"Venus", "Earth", "Mars", "Jupiter", "Saturn"})); assert (issame(bf("Neptune", "Venus") , {"Earth", "Mars", "Jupiter", "Saturn", "Uranus"})); assert (issame(bf("Earth", "Earth") , {})); assert (issame(bf("Mars", "Earth") , {})); assert (issame(bf("Jupiter", "Makemake") , {})); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> vector<string> bf(string planet1,string planet2){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(bf("Jupiter", "Neptune") , {"Saturn", "Uranus"})); assert (issame(bf("Earth", "Mercury") , {"Venus",})); assert (issame(bf("Mercury", "Uranus") , {"Venus", "Earth", "Mars", "Jupiter", "Saturn"})); }
vector<string> planets={"Mercury","Venus","Earth","Mars","Jupyter","Saturn","Uranus","Neptune"}; int pos1=-1,pos2=-1,m; for (m=0;m<planets.size();m++) { if (planets[m]==planet1) pos1=m; if (planets[m]==planet2) pos2=m; } if (pos1==-1 or pos2==-1) return {}; if (pos1>pos2) {m=pos1;pos1=pos2;pos2=m;} vector<string> out={}; for (m=pos1+1;m<pos2;m++) out.push_back(planets[m]); return out; }
value misuse
incorrect output
bf
vector<string> bf(string planet1,string planet2)
There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a vector containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty vector if planet1 or planet2 are not correct planet names. Examples bf("Jupiter", "Neptune") ==> {"Saturn", "Uranus"} bf("Earth", "Mercury") ==> {"Venus"} bf("Mercury", "Uranus") ==> {"Venus", "Earth", "Mars", "Jupiter", "Saturn"}
Write a C++ function `vector<string> bf(string planet1,string planet2)` to solve the following problem: There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a vector containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty vector if planet1 or planet2 are not correct planet names. Examples bf("Jupiter", "Neptune") ==> {"Saturn", "Uranus"} bf("Earth", "Mercury") ==> {"Venus"} bf("Mercury", "Uranus") ==> {"Venus", "Earth", "Mars", "Jupiter", "Saturn"}
CPP/149
/* Write a function that accepts a vector of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted vector with a sorted order, The vector is always a vector of strings and never a vector of numbers, and it may contain duplicates. The order of the vector should be ascending by length of each word, and you should return the vector sorted by that rule. If two words have the same length, sort the vector alphabetically. The function should return a vector of strings in sorted order. You may assume that all words will have the same length. For example: assert vector_sort({"aa", "a", "aaa"}) => {"aa"} assert vector_sort({"ab", "a", "aaa", "cd"}) => {"ab", "cd"} */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; vector<string> sorted_list_sum(vector<string> lst){
vector<string> out={}; for (int i=0;i<lst.size();i++) if (lst[i].length()%2==0) out.push_back(lst[i]); string mid; sort(out.begin(),out.end()); for (int i=0;i<out.size();i++) for (int j=1;j<out.size();j++) if (out[j].length()<out[j-1].length()) { mid=out[j];out[j]=out[j-1];out[j-1]=mid; } return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(sorted_list_sum({"aa", "a", "aaa"}) , {"aa"})); assert (issame(sorted_list_sum({"school", "AI", "asdf", "b"}) , {"AI", "asdf", "school"})); assert (issame(sorted_list_sum({"d", "b", "c", "a"}) , {})); assert (issame(sorted_list_sum({"d", "dcba", "abcd", "a"}) , {"abcd", "dcba"})); assert (issame(sorted_list_sum({"AI", "ai", "au"}) , {"AI", "ai", "au"})); assert (issame(sorted_list_sum({"a", "b", "b", "c", "c", "a"}) , {})); assert (issame(sorted_list_sum({"aaaa", "bbbb", "dd", "cc"}) , {"cc", "dd", "aaaa", "bbbb"})); }
#include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<math.h> #include<stdlib.h> vector<string> sorted_list_sum(vector<string> lst){
#undef NDEBUG #include<assert.h> bool issame(vector<string> a,vector<string>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(sorted_list_sum({"aa", "a", "aaa"}) , {"aa"})); assert (issame(sorted_list_sum({"ab", "a", "aaa", "cd"}) , {"ab", "cd"})); }
vector<string> out={}; for (int i=0;i<lst.size();i++) if (lst[i].length()%2==0) out.push_back(lst[i]); string mid; for (int i=0;i<out.size();i++) for (int j=1;j<out.size();j++) if (out[j].length()<out[j-1].length()) { mid=out[j];out[j]=out[j-1];out[j-1]=mid; } return out; }
missing logic
incorrect output
sorted_list_sum
vector<string> sorted_list_sum(vector<string> lst)
Write a function that accepts a vector of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted vector with a sorted order, The vector is always a vector of strings and never a vector of numbers, and it may contain duplicates. The order of the vector should be ascending by length of each word, and you should return the vector sorted by that rule. If two words have the same length, sort the vector alphabetically. The function should return a vector of strings in sorted order. You may assume that all words will have the same length. For example: assert vector_sort({"aa", "a", "aaa"}) => {"aa"} assert vector_sort({"ab", "a", "aaa", "cd"}) => {"ab", "cd"}
Write a C++ function `vector<string> sorted_list_sum(vector<string> lst)` to solve the following problem: Write a function that accepts a vector of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted vector with a sorted order, The vector is always a vector of strings and never a vector of numbers, and it may contain duplicates. The order of the vector should be ascending by length of each word, and you should return the vector sorted by that rule. If two words have the same length, sort the vector alphabetically. The function should return a vector of strings in sorted order. You may assume that all words will have the same length. For example: assert vector_sort({"aa", "a", "aaa"}) => {"aa"} assert vector_sort({"ab", "a", "aaa", "cd"}) => {"ab", "cd"}
CPP/150
/* A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. Examples: for x_or_y(7, 34, 12) == 34 for x_or_y(15, 8, 5) == 5 */ #include<stdio.h> using namespace std; int x_or_y(int n,int x,int y){
bool isp=true; if (n<2) isp=false; for (int i=2;i*i<=n;i++) if (n%i==0) isp=false; if (isp) return x; return y; }
#undef NDEBUG #include<assert.h> int main(){ assert (x_or_y(7, 34, 12) == 34); assert (x_or_y(15, 8, 5) == 5); assert (x_or_y(3, 33, 5212) == 33); assert (x_or_y(1259, 3, 52) == 3); assert (x_or_y(7919, -1, 12) == -1); assert (x_or_y(3609, 1245, 583) == 583); assert (x_or_y(91, 56, 129) == 129); assert (x_or_y(6, 34, 1234) == 1234); assert (x_or_y(1, 2, 0) == 0); assert (x_or_y(2, 2, 0) == 2); }
#include<stdio.h> #include<math.h> #include<algorithm> using namespace std; #include<stdlib.h> int x_or_y(int n,int x,int y){
#undef NDEBUG #include<assert.h> int main(){ assert (x_or_y(7, 34, 12) == 34); assert (x_or_y(15, 8, 5) == 5); }
bool isp=true; if (n<2) isp=false; for (int i=2;i*i<=n;i++) if (n%i-1==0) isp=false; if (isp) return x; return y; }
excess logic
incorrect output
x_or_y
int x_or_y(int n,int x,int y)
A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. Examples: for x_or_y(7, 34, 12) == 34 for x_or_y(15, 8, 5) == 5
Write a C++ function `int x_or_y(int n,int x,int y)` to solve the following problem: A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. Examples: for x_or_y(7, 34, 12) == 34 for x_or_y(15, 8, 5) == 5
CPP/151
/* Given a vector of numbers, return the sum of squares of the numbers in the vector that are odd. Ignore numbers that are negative or not integers. double_the_difference({1, 3, 2, 0}) == 1 + 9 + 0 + 0 = 10 double_the_difference({-1, -2, 0}) == 0 double_the_difference({9, -2}) == 81 double_the_difference({0}) == 0 If the input vector is empty, return 0. */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; long long double_the_difference(vector<float> lst){
long long sum=0; for (int i=0;i<lst.size();i++) if (lst[i]-round(lst[i])<1e-4) if (lst[i]>0 and (int)(round(lst[i]))%2==1) sum+=(int)(round(lst[i]))*(int)(round(lst[i])); return sum; }
#undef NDEBUG #include<assert.h> int main(){ assert (double_the_difference({}) == 0); assert (double_the_difference({5, 4}) == 25); assert (double_the_difference({0.1, 0.2, 0.3}) == 0 ); assert (double_the_difference({-10, -20, -30}) == 0 ); assert (double_the_difference({-1, -2, 8}) == 0); assert (double_the_difference({0.2, 3, 5}) == 34); long long odd_sum=0; vector<float> lst={}; for (int i=-99;i<100;i+=2) { lst.push_back(i+0.0); if (i>0 and i%2==1) odd_sum+=i*i; } assert (double_the_difference(lst) == odd_sum ); }
#include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; #include<stdlib.h> long long double_the_difference(vector<float> lst){
#undef NDEBUG #include<assert.h> int main(){ assert (double_the_difference({1, 3, 2, 0}) == 10); assert (double_the_difference({-1, -2, 0}) == 0); assert (double_the_difference({9, -2}) == 81 ); assert (double_the_difference({0}) == 0 ); }
long long sum=0; for (int i=0;i<lst.size();i++) if (lst[i]<1e-4) if (lst[i]>0 and (int)(round(lst[i]))%2==1) sum+=(int)(round(lst[i]))*(int)(round(lst[i])); return sum; }
missing logic
incorrect output
double_the_difference
long long double_the_difference(vector<float> lst)
Given a vector of numbers, return the sum of squares of the numbers in the vector that are odd. Ignore numbers that are negative or not integers. double_the_difference({1, 3, 2, 0}) == 1 + 9 + 0 + 0 = 10 double_the_difference({-1, -2, 0}) == 0 double_the_difference({9, -2}) == 81 double_the_difference({0}) == 0 If the input vector is empty, return 0.
Write a C++ function `long long double_the_difference(vector<float> lst)` to solve the following problem: Given a vector of numbers, return the sum of squares of the numbers in the vector that are odd. Ignore numbers that are negative or not integers. double_the_difference({1, 3, 2, 0}) == 1 + 9 + 0 + 0 = 10 double_the_difference({-1, -2, 0}) == 0 double_the_difference({9, -2}) == 81 double_the_difference({0}) == 0 If the input vector is empty, return 0.
CPP/152
/* I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two vectors of scores and guesses of equal length, where each index shows a match. Return a vector of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare({1,2,3,4,5,1},{1,2,3,4,2,-2}) -> {0,0,0,0,3,3} compare({0,5,0,0,0,4},{4,1,1,0,0,-2}) -> {4,4,1,0,0,6} */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; vector<int> compare(vector<int> game,vector<int> guess){
vector<int> out; for (int i=0;i<game.size();i++) out.push_back(abs(game[i]-guess[i])); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(compare({1,2,3,4,5,1},{1,2,3,4,2,-2}),{0,0,0,0,3,3})); assert (issame(compare({0,5,0,0,0,4},{4,1,1,0,0,-2}),{4,4,1,0,0,6})); assert (issame(compare({1,2,3,4,5,1},{1,2,3,4,2,-2}),{0,0,0,0,3,3})); assert (issame(compare({0,0,0,0,0,0},{0,0,0,0,0,0}),{0,0,0,0,0,0})); assert (issame(compare({1,2,3},{-1,-2,-3}),{2,4,6})); assert (issame(compare({1,2,3,5},{-1,2,3,4}),{2,0,0,1})); }
#include<stdio.h> #include<math.h> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> vector<int> compare(vector<int> game,vector<int> guess){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(compare({1,2,3,4,5,1},{1,2,3,4,2,-2}),{0,0,0,0,3,3})); assert (issame(compare({0,5,0,0,0,4},{4,1,1,0,0,-2}),{4,4,1,0,0,6})); }
vector<int> out; for (int i=0;i<game.size();i++) out.push_back(abs(game[i]-guess[i])+abs(guess[i]-game[i])); return out; }
excess logic
incorrect output
compare
vector<int> compare(vector<int> game,vector<int> guess)
I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two vectors of scores and guesses of equal length, where each index shows a match. Return a vector of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare({1,2,3,4,5,1},{1,2,3,4,2,-2}) -> {0,0,0,0,3,3} compare({0,5,0,0,0,4},{4,1,1,0,0,-2}) -> {4,4,1,0,0,6}
Write a C++ function `vector<int> compare(vector<int> game,vector<int> guess)` to solve the following problem: I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two vectors of scores and guesses of equal length, where each index shows a match. Return a vector of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare({1,2,3,4,5,1},{1,2,3,4,2,-2}) -> {0,0,0,0,3,3} compare({0,5,0,0,0,4},{4,1,1,0,0,-2}) -> {4,4,1,0,0,6}
CPP/153
/* You will be given the name of a class (a string) and a vector of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the vector. For example, if you are given "Slices" as the class and a vector of the extensions: {"SErviNGSliCes", "Cheese", "StuFfed"} then you should return "Slices.SErviNGSliCes" since "SErviNGSliCes" is the strongest extension (its strength is -1). Example: for Strongest_Extension("my_class", {"AA", "Be", "CC"}) == "my_class.AA" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string Strongest_Extension(string class_name,vector<string> extensions){
string strongest=""; int max=-1000; for (int i=0;i<extensions.size();i++) { int strength=0; for (int j=0;j<extensions[i].length();j++) { char chr=extensions[i][j]; if (chr>=65 and chr<=90) strength+=1; if (chr>=97 and chr<=122) strength-=1; } if (strength>max) { max=strength; strongest=extensions[i]; } } return class_name+'.'+strongest; }
#undef NDEBUG #include<assert.h> int main(){ assert (Strongest_Extension("Watashi", {"tEN", "niNE", "eIGHt8OKe"}) == "Watashi.eIGHt8OKe"); assert (Strongest_Extension("Boku123", {"nani", "NazeDa", "YEs.WeCaNe", "32145tggg"}) == "Boku123.YEs.WeCaNe"); assert (Strongest_Extension("__YESIMHERE", {"t", "eMptY", "(nothing", "zeR00", "NuLl__", "123NoooneB321"}) == "__YESIMHERE.NuLl__"); assert (Strongest_Extension("K", {"Ta", "TAR", "t234An", "cosSo"}) == "K.TAR"); assert (Strongest_Extension("__HAHA", {"Tab", "123", "781345", "-_-"}) == "__HAHA.123"); assert (Strongest_Extension("YameRore", {"HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"}) == "YameRore.okIWILL123"); assert (Strongest_Extension("finNNalLLly", {"Die", "NowW", "Wow", "WoW"}) == "finNNalLLly.WoW"); assert (Strongest_Extension("_", {"Bb", "91245"}) == "_.Bb"); assert (Strongest_Extension("Sp", {"671235", "Bb"}) == "Sp.671235"); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<stdlib.h> string Strongest_Extension(string class_name,vector<string> extensions){
#undef NDEBUG #include<assert.h> int main(){ assert (Strongest_Extension("my_class", {"AA", "Be", "CC"}) == "my_class.AA"); }
string strongest=""; int max=-1000; for (int i=0;i<extensions.size();i++) { int strength=0; for (int j=0;j<extensions[i].length();j++) { char chr=extensions[i][j]; if (chr>=65 and chr<=90) strength+=1; if (chr>=97 and chr<=122) strength-=1; } if (strength>max) { max=strength; strongest=extensions[i]; } } return class_name+strongest; }
missing logic
incorrect output
Strongest_Extension
string Strongest_Extension(string class_name,vector<string> extensions)
You will be given the name of a class (a string) and a vector of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the vector. For example, if you are given "Slices" as the class and a vector of the extensions: {"SErviNGSliCes", "Cheese", "StuFfed"} then you should return "Slices.SErviNGSliCes" since "SErviNGSliCes" is the strongest extension (its strength is -1). Example: for Strongest_Extension("my_class", {"AA", "Be", "CC"}) == "my_class.AA"
Write a C++ function `string Strongest_Extension(string class_name,vector<string> extensions)` to solve the following problem: You will be given the name of a class (a string) and a vector of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the vector. For example, if you are given "Slices" as the class and a vector of the extensions: {"SErviNGSliCes", "Cheese", "StuFfed"} then you should return "Slices.SErviNGSliCes" since "SErviNGSliCes" is the strongest extension (its strength is -1). Example: for Strongest_Extension("my_class", {"AA", "Be", "CC"}) == "my_class.AA"
CPP/154
/* You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word cycpattern_check("abcd","abd") => false cycpattern_check("hello","ell") => true cycpattern_check("whassup","psus") => false cycpattern_check("abab","baa") => true cycpattern_check("efef","eeff") => false cycpattern_check("himenss",'simen") => true */ #include<stdio.h> #include<string> using namespace std; bool cycpattern_check(string a,string b){
for (int i=0;i<b.size();i++) { string rotate=b.substr(i)+b.substr(0,i); if (a.find(rotate)!=string::npos) return true; } return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (cycpattern_check("xyzw","xyw") == false ); assert (cycpattern_check("yello","ell") == true ); assert (cycpattern_check("whattup","ptut") == false ); assert (cycpattern_check("efef","fee") == true ); assert (cycpattern_check("abab","aabb") == false ); assert (cycpattern_check("winemtt","tinem") == true ); }
#include<stdio.h> #include<string> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> bool cycpattern_check(string a,string b){
#undef NDEBUG #include<assert.h> int main(){ assert (cycpattern_check("abcd","abd") == false ); assert (cycpattern_check("hello","ell") == true ); assert (cycpattern_check("whassup","psus") == false ); assert (cycpattern_check("abab","baa") == true ); assert (cycpattern_check("efef","eeff") == false ); assert (cycpattern_check("himenss","simen") == true ); }
for (int i=0;i<b.size();i++) { string rotate=b.substr(i)+b.substr(0); if (a.find(rotate)!=string::npos) return true; } return false; }
value misuse
incorrect output
cycpattern_check
bool cycpattern_check(string a,string b)
You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word cycpattern_check("abcd","abd") => false cycpattern_check("hello","ell") => true cycpattern_check("whassup","psus") => false cycpattern_check("abab","baa") => true cycpattern_check("efef","eeff") => false cycpattern_check("himenss",'simen") => true
Write a C++ function `bool cycpattern_check(string a,string b)` to solve the following problem: You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word cycpattern_check("abcd","abd") => false cycpattern_check("hello","ell") => true cycpattern_check("whassup","psus") => false cycpattern_check("abab","baa") => true cycpattern_check("efef","eeff") => false cycpattern_check("himenss",'simen") => true
CPP/155
/* Given an integer. return a vector that has the number of even and odd digits respectively. Example: even_odd_count(-12) ==> {1, 1} even_odd_count(123) ==> {1, 2} */ #include<stdio.h> #include<math.h> #include<string> #include<vector> using namespace std; vector<int> even_odd_count(int num){
string w=to_string(abs(num)); int n1=0,n2=0; for (int i=0;i<w.length();i++) if (w[i]%2==1) n1+=1; else n2+=1; return {n2,n1}; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(even_odd_count(7) , {0, 1})); assert (issame(even_odd_count(-78) , {1, 1})); assert (issame(even_odd_count(3452) , {2, 2})); assert (issame(even_odd_count(346211) , {3, 3})); assert (issame(even_odd_count(-345821) , {3, 3})); assert (issame(even_odd_count(-2) , {1, 0})); assert (issame(even_odd_count(-45347) , {2, 3})); assert (issame(even_odd_count(0) , {1, 0})); }
#include<stdio.h> #include<math.h> #include<string> #include<vector> using namespace std; #include<algorithm> #include<stdlib.h> vector<int> even_odd_count(int num){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(even_odd_count(-12) , {1, 1})); assert (issame(even_odd_count(123) , {1, 2})); }
string w=to_string(abs(num)); int n1=0,n2=0; for (int i=0;i<w.length();i++) if (w[i]%2==1) n1+=1; return {n2,n1}; }
missing logic
incorrect output
even_odd_count
vector<int> even_odd_count(int num)
Given an integer. return a vector that has the number of even and odd digits respectively. Example: even_odd_count(-12) ==> {1, 1} even_odd_count(123) ==> {1, 2}
Write a C++ function `vector<int> even_odd_count(int num)` to solve the following problem: Given an integer. return a vector that has the number of even and odd digits respectively. Example: even_odd_count(-12) ==> {1, 1} even_odd_count(123) ==> {1, 2}
CPP/156
/* Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) == "xix" >>> int_to_mini_roman(152) == "clii" >>> int_to_mini_roman(426) == "cdxxvi" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string int_to_mini_romank(int number){
string current=""; vector<string> rep={"m","cm","d","cd","c","xc","l","xl","x","ix","v","iv","i"}; vector<int> num={1000,900,500,400,100,90,50,40,10,9,5,4,1}; int pos=0; while(number>0) { while (number>=num[pos]) { current=current+rep[pos]; number-=num[pos]; } if (number>0) pos+=1; } return current; }
#undef NDEBUG #include<assert.h> int main(){ assert (int_to_mini_romank(19) == "xix"); assert (int_to_mini_romank(152) == "clii"); assert (int_to_mini_romank(251) == "ccli"); assert (int_to_mini_romank(426) == "cdxxvi"); assert (int_to_mini_romank(500) == "d"); assert (int_to_mini_romank(1) == "i"); assert (int_to_mini_romank(4) == "iv"); assert (int_to_mini_romank(43) == "xliii"); assert (int_to_mini_romank(90) == "xc"); assert (int_to_mini_romank(94) == "xciv"); assert (int_to_mini_romank(532) == "dxxxii"); assert (int_to_mini_romank(900) == "cm"); assert (int_to_mini_romank(994) == "cmxciv"); assert (int_to_mini_romank(1000) == "m"); }
#include<stdio.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> string int_to_mini_romank(int number){
#undef NDEBUG #include<assert.h> int main(){ assert (int_to_mini_romank(19) == "xix"); assert (int_to_mini_romank(152) == "clii"); assert (int_to_mini_romank(426) == "cdxxvi"); }
string current=""; vector<string> rep={"m","cm","d","cd","c","xc","l","xl","x","ix","v","iv","i"}; vector<int> num={1000,900,500,400,100,90,50,40,10,9,5,4,1}; int pos=0; while(number>0) { while (number>=num[pos]) { current=current+rep[pos]; } if (number>0) pos+=1; } return current; }
missing logic
infinite loop
int_to_mini_roman
string int_to_mini_romank(int number)
Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) == "xix" >>> int_to_mini_roman(152) == "clii" >>> int_to_mini_roman(426) == "cdxxvi"
Write a C++ function `string int_to_mini_romank(int number)` to solve the following problem: Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) == "xix" >>> int_to_mini_roman(152) == "clii" >>> int_to_mini_roman(426) == "cdxxvi"
CPP/157
/* Given the lengths of the three sides of a triangle. Return true if the three sides form a right-angled triangle, false otherwise. A right-angled triangle is a triangle in which one angle is right angle or 90 degree. Example: right_angle_triangle(3, 4, 5) == true right_angle_triangle(1, 2, 3) == false */ #include<stdio.h> #include<math.h> using namespace std; bool right_angle_triangle(float a,float b,float c){
if (abs(a*a+b*b-c*c)<1e-4 or abs(a*a+c*c-b*b)<1e-4 or abs(b*b+c*c-a*a)<1e-4) return true; return false; }
#undef NDEBUG #include<assert.h> int main(){ assert (right_angle_triangle(3, 4, 5) == true); assert (right_angle_triangle(1, 2, 3) == false); assert (right_angle_triangle(10, 6, 8) == true); assert (right_angle_triangle(2, 2, 2) == false); assert (right_angle_triangle(7, 24, 25) == true); assert (right_angle_triangle(10, 5, 7) == false); assert (right_angle_triangle(5, 12, 13) == true); assert (right_angle_triangle(15, 8, 17) == true); assert (right_angle_triangle(48, 55, 73) == true); assert (right_angle_triangle(1, 1, 1) == false); assert (right_angle_triangle(2, 2, 10) == false); }
#include<stdio.h> #include<math.h> using namespace std; #include<algorithm> #include<stdlib.h> bool right_angle_triangle(float a,float b,float c){
#undef NDEBUG #include<assert.h> int main(){ assert (right_angle_triangle(3, 4, 5) == true); assert (right_angle_triangle(1, 2, 3) == false); }
if (abs(a*a+b*b-c*c)<1e-4) return true; return false; }
missing logic
incorrect output
right_angle_triangle
bool right_angle_triangle(float a,float b,float c)
Given the lengths of the three sides of a triangle. Return true if the three sides form a right-angled triangle, false otherwise. A right-angled triangle is a triangle in which one angle is right angle or 90 degree. Example: right_angle_triangle(3, 4, 5) == true right_angle_triangle(1, 2, 3) == false
Write a C++ function `bool right_angle_triangle(float a,float b,float c)` to solve the following problem: Given the lengths of the three sides of a triangle. Return true if the three sides form a right-angled triangle, false otherwise. A right-angled triangle is a triangle in which one angle is right angle or 90 degree. Example: right_angle_triangle(3, 4, 5) == true right_angle_triangle(1, 2, 3) == false
CPP/158
/* Write a function that accepts a vector of strings. The vector contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. find_max({"name", "of", 'string"}) == 'string" find_max({"name", "enam", "game"}) == "enam" find_max({"aaaaaaa", "bb" ,"cc"}) == "aaaaaaa" */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; string find_max(vector<string> words){
string max=""; int maxu=0; for (int i=0;i<words.size();i++) { string unique=""; for (int j=0;j<words[i].length();j++) if (find(unique.begin(),unique.end(),words[i][j])==unique.end()) unique=unique+words[i][j]; if (unique.length()>maxu or (unique.length()==maxu and words[i]<max)) { max=words[i]; maxu=unique.length(); } } return max; }
#undef NDEBUG #include<assert.h> int main(){ assert ((find_max({"name", "of", "string"}) == "string")); assert ((find_max({"name", "enam", "game"}) == "enam")); assert ((find_max({"aaaaaaa", "bb", "cc"}) == "aaaaaaa")); assert ((find_max({"abc", "cba"}) == "abc")); assert ((find_max({"play", "this", "game", "of","footbott"}) == "footbott")); assert ((find_max({"we", "are", "gonna", "rock"}) == "gonna")); assert ((find_max({"we", "are", "a", "mad", "nation"}) == "nation")); assert ((find_max({"this", "is", "a", "prrk"}) == "this")); assert ((find_max({"b"}) == "b")); assert ((find_max({"play", "play", "play"}) == "play")); }
#include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; #include<math.h> #include<stdlib.h> string find_max(vector<string> words){
#undef NDEBUG #include<assert.h> int main(){ assert ((find_max({"name", "of", "string"}) == "string")); assert ((find_max({"name", "enam", "game"}) == "enam")); assert ((find_max({"aaaaaaa", "bb", "cc"}) == "aaaaaaa")); }
string max=""; int maxu=0; for (int i=0;i<words.size();i++) { string unique=""; for (int j=0;j<words[i].length();j++) if (find(unique.begin(),unique.end(),words[i][j])==unique.end()) unique=unique+words[i][j]; if (unique.length()>maxu or unique.length()==maxu) { max=words[i]; maxu=unique.length(); } } return max; }
missing logic
incorrect output
find_max
string find_max(vector<string> words)
Write a function that accepts a vector of strings. The vector contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. find_max({"name", "of", 'string"}) == 'string" find_max({"name", "enam", "game"}) == "enam" find_max({"aaaaaaa", "bb" ,"cc"}) == "aaaaaaa"
Write a C++ function `string find_max(vector<string> words)` to solve the following problem: Write a function that accepts a vector of strings. The vector contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. find_max({"name", "of", 'string"}) == 'string" find_max({"name", "enam", "game"}) == "enam" find_max({"aaaaaaa", "bb" ,"cc"}) == "aaaaaaa"
CPP/159
/* You"re a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return a vector of { total number of eaten carrots after your meals, the number of carrots left after your meals } if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. Example: * eat(5, 6, 10) -> {11, 4} * eat(4, 8, 9) -> {12, 1} * eat(1, 10, 10) -> {11, 0} * eat(2, 11, 5) -> {7, 0} Variables: @number : integer the number of carrots that you have eaten. @need : integer the number of carrots that you need to eat. @remaining : integer the number of remaining carrots thet exist in stock Constrain: * 0 <= number <= 1000 * 0 <= need <= 1000 * 0 <= remaining <= 1000 Have fun :) */ #include<stdio.h> #include<vector> using namespace std; vector<int> eat(int number,int need,int remaining){
if (need>remaining) return {number+remaining, 0}; return {number+need,remaining-need}; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(eat(5, 6, 10) , {11, 4})); assert (issame(eat(4, 8, 9) , {12, 1})); assert (issame(eat(1, 10, 10) , {11, 0})); assert (issame(eat(2, 11, 5) , {7, 0})); assert (issame(eat(4, 5, 7) , {9, 2})); assert (issame(eat(4, 5, 1) , {5, 0})); }
#include<stdio.h> #include<vector> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> vector<int> eat(int number,int need,int remaining){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(eat(5, 6, 10) , {11, 4})); assert (issame(eat(4, 8, 9) , {12, 1})); assert (issame(eat(1, 10, 10) , {11, 0})); assert (issame(eat(2, 11, 5) , {7, 0})); }
if (need>remaining) return {number+need+remaining, 0}; return {number+need,number+remaining-need}; }
excess logic
incorrect output
eat
vector<int> eat(int number,int need,int remaining)
You"re a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return a vector of { total number of eaten carrots after your meals, the number of carrots left after your meals } if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. Example: * eat(5, 6, 10) -> {11, 4} * eat(4, 8, 9) -> {12, 1} * eat(1, 10, 10) -> {11, 0} * eat(2, 11, 5) -> {7, 0} Variables: @number : integer the number of carrots that you have eaten. @need : integer the number of carrots that you need to eat. @remaining : integer the number of remaining carrots thet exist in stock Constrain: * 0 <= number <= 1000 * 0 <= need <= 1000 * 0 <= remaining <= 1000 Have fun :)
Write a C++ function `vector<int> eat(int number,int need,int remaining)` to solve the following problem: You"re a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return a vector of { total number of eaten carrots after your meals, the number of carrots left after your meals } if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. Example: * eat(5, 6, 10) -> {11, 4} * eat(4, 8, 9) -> {12, 1} * eat(1, 10, 10) -> {11, 0} * eat(2, 11, 5) -> {7, 0} Variables: @number : integer the number of carrots that you have eaten. @need : integer the number of carrots that you need to eat. @remaining : integer the number of remaining carrots thet exist in stock Constrain: * 0 <= number <= 1000 * 0 <= need <= 1000 * 0 <= remaining <= 1000 Have fun :)
CPP/160
/* Given two vectors operator, and operand. The first vector has basic algebra operations, and the second vector is a vector of integers. Use the two given vectors to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator{"+", "*", "-"} vector = {2, 3, 4, 5} result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator vector is equal to the length of operand vector minus one. Operand is a vector of of non-negative integers. Operator vector has at least one operator, and operand vector has at least two operands. */ #include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> int do_algebra(vector<string> operato, vector<int> operand){
vector<int> num={}; vector<int> posto={}; for (int i=0;i<operand.size();i++) posto.push_back(i); for (int i=0;i<operato.size();i++) if (operato[i]=="**") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; operand[posto[i]]=pow(operand[posto[i]],operand[posto[i+1]]); posto[i+1]=posto[i]; } for (int i=0;i<operato.size();i++) if (operato[i]=="*" or operato[i]=="//") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; if (operato[i]=="*") operand[posto[i]]=operand[posto[i]]*operand[posto[i+1]]; else operand[posto[i]]=operand[posto[i]]/operand[posto[i+1]]; posto[i+1]=posto[i]; } for (int i=0;i<operato.size();i++) if (operato[i]=="+" or operato[i]=="-") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; if (operato[i]=="+") operand[posto[i]]=operand[posto[i]]+operand[posto[i+1]]; else operand[posto[i]]=operand[posto[i]]-operand[posto[i+1]]; posto[i+1]=posto[i]; } return operand[0]; }
#undef NDEBUG #include<assert.h> int main(){ assert (do_algebra({"**", "*", "+"}, {2, 3, 4, 5}) == 37); assert (do_algebra({"+", "*", "-"}, {2, 3, 4, 5}) == 9); assert (do_algebra({"//", "*"}, {7, 3, 4}) == 8); }
#include<stdio.h> #include<math.h> #include<vector> #include<string> using namespace std; #include<algorithm> #include<stdlib.h> int do_algebra(vector<string> operato, vector<int> operand){
vector<int> num={}; vector<int> posto={}; for (int i=0;i<operand.size();i++) posto.push_back(i); for (int i=0;i<operato.size();i++) if (operato[i]=="**") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; operand[posto[i]]=pow(operand[posto[i+1]],operand[posto[i+1]]); posto[i+1]=posto[i]; } for (int i=0;i<operato.size();i++) if (operato[i]=="*" or operato[i]=="//") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; if (operato[i]=="*") operand[posto[i]]=operand[posto[i]]*operand[posto[i+1]]; else operand[posto[i]]=operand[posto[i]]/operand[posto[i+1]]; posto[i+1]=posto[i]; } for (int i=0;i<operato.size();i++) if (operato[i]=="+" or operato[i]=="-") { while (posto[posto[i]]!=posto[i]) posto[i]=posto[posto[i]]; while (posto[posto[i+1]]!=posto[i+1]) posto[i+1]=posto[posto[i+1]]; if (operato[i]=="+") operand[posto[i]]=operand[posto[i]]+operand[posto[i+1]]; else operand[posto[i]]=operand[posto[i]]-operand[posto[i+1]]; posto[i+1]=posto[i]; } return operand[0]; }
excess logic
incorrect output
do_algebra
int do_algebra(vector<string> operato, vector<int> operand)
Given two vectors operator, and operand. The first vector has basic algebra operations, and the second vector is a vector of integers. Use the two given vectors to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator{"+", "*", "-"} vector = {2, 3, 4, 5} result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator vector is equal to the length of operand vector minus one. Operand is a vector of of non-negative integers. Operator vector has at least one operator, and operand vector has at least two operands.
Write a C++ function `int do_algebra(vector<string> operato, vector<int> operand)` to solve the following problem: Given two vectors operator, and operand. The first vector has basic algebra operations, and the second vector is a vector of integers. Use the two given vectors to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator{"+", "*", "-"} vector = {2, 3, 4, 5} result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator vector is equal to the length of operand vector minus one. Operand is a vector of of non-negative integers. Operator vector has at least one operator, and operand vector has at least two operands.
CPP/161
/* You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c" */ #include<stdio.h> #include<string> using namespace std; string solve(string s){
int nletter=0; string out=""; for (int i=0;i<s.length();i++) { char w=s[i]; if (w>=65 and w<=90) w=w+32; else if (w>=97 and w<=122) w=w-32; else nletter+=1; out=out+w; } if (nletter==s.length()) { string p(s.rbegin(),s.rend()); return p; } else return out; }
#undef NDEBUG #include<assert.h> int main(){ assert (solve("AsDf") == "aSdF"); assert (solve("1234") == "4321"); assert (solve("ab") == "AB"); assert (solve("#a@C") == "#A@c"); assert (solve("#AsdfW^45") == "#aSDFw^45"); assert (solve("#6@2") == "2@6#"); assert (solve("#$a^D") == "#$A^d"); assert (solve("#ccc") == "#CCC"); }
#include<stdio.h> #include<string> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> string solve(string s){
#undef NDEBUG #include<assert.h> int main(){ assert (solve("1234") == "4321"); assert (solve("ab") == "AB"); assert (solve("#a@C") == "#A@c"); }
int nletter=0; string out=""; for (int i=0;i<s.length();i++) { char w=s[i]; if (w>=65 and w<=90) w=w+32; else nletter+=1; out=out+w; } if (nletter==s.length()) { string p(s.rbegin(),s.rend()); return p; } else return out; }
missing logic
incorrect output
solve
string solve(string s)
You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c"
Write a C++ function `string solve(string s)` to solve the following problem: You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c"
CPP/162
/* Given a string 'text", return its md5 hash equivalent string. If 'text" is an empty string, return None. >>> string_to_md5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62" */ #include<stdio.h> #include<string> #include<openssl/md5.h> using namespace std; string string_to_md5(string text){
unsigned char md[16]; if (text.length()==0) return "None"; MD5_CTX c; int i; MD5_Init(&c); MD5_Update(&c, (unsigned char*)text.c_str(), text.length()); MD5_Final(md, &c); string out_str=""; for (int i=0;i<16;i++) { char w; if (md[i]<160) w=48+md[i]/16; else w=87+md[i]/16; out_str=out_str+w; if (md[i]%16<10) w=48+md[i]%16; else w=87+md[i]%16; out_str=out_str+w; } return out_str; }
#undef NDEBUG #include<assert.h> int main(){ assert (string_to_md5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"); assert (string_to_md5("") == "None"); assert (string_to_md5("A B C") == "0ef78513b0cb8cef12743f5aeb35f888"); assert (string_to_md5("password") == "5f4dcc3b5aa765d61d8327deb882cf99"); }
#include<stdio.h> #include<string> #include<openssl/md5.h> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> string string_to_md5(string text){
#undef NDEBUG #include<assert.h> int main(){ assert (string_to_md5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"); }
unsigned char md[16]; if (text.length()==0) return "None"; MD5_CTX c; int i; MD5_Init(&c); MD5_Update(&c, (unsigned char*)text.c_str(), text.length()); MD5_Final(md, &c); string out_str=""; for (int i=0;i<16;i++) { char w; if (md[i]<160) w=48+md[i]/16; else w=87+md[i]/16; out_str=out_str+w; if (md[i]%16<87) w=48+md[i]%16; else w=48+md[i]%16; out_str=out_str+w; } return out_str; }
function misuse
incorrect output
string_to_md5
string string_to_md5(string text)
Given a string 'text", return its md5 hash equivalent string. If 'text" is an empty string, return None. >>> string_to_md5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
Write a C++ function `string string_to_md5(string text)` to solve the following problem: Given a string 'text", return its md5 hash equivalent string. If 'text" is an empty string, return None. >>> string_to_md5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
CPP/163
/* Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generate_integers(2, 8) => {2, 4, 6, 8} generate_integers(8, 2) => {2, 4, 6, 8} generate_integers(10, 14) => {} */ #include<stdio.h> #include<vector> using namespace std; vector<int> generate_integers(int a,int b){
int m; if (b<a) { m=a;a=b;b=m; } vector<int> out={}; for (int i=a;i<=b;i++) if (i<10 and i%2==0) out.push_back(i); return out; }
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(generate_integers(2, 10) , {2, 4, 6, 8})); assert (issame(generate_integers(10, 2) , {2, 4, 6, 8})); assert (issame(generate_integers(132, 2) , {2, 4, 6, 8})); assert (issame(generate_integers(17,89) , {})); }
#include<stdio.h> #include<vector> using namespace std; #include<algorithm> #include<math.h> #include<stdlib.h> vector<int> generate_integers(int a,int b){
#undef NDEBUG #include<assert.h> bool issame(vector<int> a,vector<int>b){ if (a.size()!=b.size()) return false; for (int i=0;i<a.size();i++) { if (a[i]!=b[i]) return false; } return true; } int main(){ assert (issame(generate_integers(2, 8) , {2, 4, 6, 8})); assert (issame(generate_integers(8, 2) , {2, 4, 6, 8})); assert (issame(generate_integers(10,14) , {})); }
int m; if (b<a) { m=a;a=b;b=m; } vector<int> out={}; for (int i=a;i<b;i++) if (i>10 and i%2==0) out.push_back(i); return out; }
value misuse
incorrect output
generate_integers
vector<int> generate_integers(int a,int b)
Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generate_integers(2, 8) => {2, 4, 6, 8} generate_integers(8, 2) => {2, 4, 6, 8} generate_integers(10, 14) => {}
Write a C++ function `vector<int> generate_integers(int a,int b)` to solve the following problem: Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generate_integers(2, 8) => {2, 4, 6, 8} generate_integers(8, 2) => {2, 4, 6, 8} generate_integers(10, 14) => {}
Go/0
import ( "math" ) // Check if in given list of numbers, are any two numbers closer to each other than given threshold. // >>> HasCloseElements([]float64{1.0, 2.0, 3.0}, 0.5) // false // >>> HasCloseElements([]float64{1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3) // true func HasCloseElements(numbers []float64, threshold float64) bool {
for i := 0; i < len(numbers); i++ { for j := i + 1; j < len(numbers); j++ { var distance float64 = math.Abs(numbers[i] - numbers[j]) if distance < threshold { return true } } } return false }
func TestHasCloseElements(t *testing.T) { assert := assert.New(t) assert.Equal(true, HasCloseElements([]float64{11.0, 2.0, 3.9, 4.0, 5.0, 2.2}, 0.3)) assert.Equal(false, HasCloseElements([]float64{1.0, 2.0, 3.9, 4.0, 5.0, 2.2}, 0.05)) assert.Equal(true, HasCloseElements([]float64{1.0, 2.0, 5.9, 4.0, 5.0}, 0.95)) assert.Equal(false, HasCloseElements([]float64{1.0, 2.0, 5.9, 4.0, 5.0}, 0.8)) assert.Equal(true, HasCloseElements([]float64{1.0, 2.0, 3.0, 4.0, 5.0, 2.0}, 0.1)) assert.Equal(true, HasCloseElements([]float64{1.1, 2.2, 3.1, 4.1, 5.1}, 1.0)) assert.Equal(false, HasCloseElements([]float64{1.1, 2.2, 3.1, 4.1, 5.1}, 0.5)) }
func HasCloseElements(numbers []float64, threshold float64) bool {
func TestHasCloseElements(t *testing.T) { assert := assert.New(t) assert.Equal(false, HasCloseElements([]float64{1.0, 2.0, 3.0}, 0.5)) assert.Equal(true, HasCloseElements([]float64{1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3)) }
for i := 0; i < len(numbers); i++ { for j := i + 1; j < len(numbers); j++ { var distance float64 = numbers[i] - numbers[j] if distance < threshold { return true } } } return false }
missing logic
incorrect output
HasCloseElements
func HasCloseElements(numbers []float64, threshold float64) bool
Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> HasCloseElements([]float64{1.0, 2.0, 3.0}, 0.5) false >>> HasCloseElements([]float64{1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3) true
Write a Go function `func HasCloseElements(numbers []float64, threshold float64) bool` to solve the following problem: Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> HasCloseElements([]float64{1.0, 2.0, 3.0}, 0.5) false >>> HasCloseElements([]float64{1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3) true
Java/0
import java.util.*; import java.lang.*; class Solution { /** Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> hasCloseElements(Arrays.asList(1.0, 2.0, 3.0), 0.5) false >>> hasCloseElements(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3) true */ public boolean hasCloseElements(List<Double> numbers, double threshold) {
for (int i = 0; i < numbers.size(); i++) { for (int j = i + 1; j < numbers.size(); j++) { double distance = Math.abs(numbers.get(i) - numbers.get(j)); if (distance < threshold) return true; } } return false; } }
public class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.hasCloseElements(new ArrayList<>(Arrays.asList(11.0, 2.0, 3.9, 4.0, 5.0, 2.2)), 0.3), !s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.9, 4.0, 5.0, 2.2)), 0.05), s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 5.9, 4.0, 5.0)), 0.95), !s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 5.9, 4.0, 5.0)), 0.8), s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.0)), 0.1), s.hasCloseElements(new ArrayList<>(Arrays.asList(1.1, 2.2, 3.1, 4.1, 5.1)), 1.0), !s.hasCloseElements(new ArrayList<>(Arrays.asList(1.1, 2.2, 3.1, 4.1, 5.1)), 0.5) ); if (correct.contains(false)) { throw new AssertionError(); } } }
import java.util.*; import java.lang.*; class Solution { public boolean hasCloseElements(List<Double> numbers, double threshold) {
public class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( !s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0)), 0.5), s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0)), 0.3) ); if (correct.contains(false)) { throw new AssertionError(); } } }
for (int i = 0; i < numbers.size(); i++) { for (int j = i + 1; j < numbers.size(); j++) { double distance = numbers.get(i) - numbers.get(j); if (distance < threshold) return true; } } return false; } }
missing logic
incorrect output
hasCloseElements
public boolean hasCloseElements(List<Double> numbers, double threshold)
Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> hasCloseElements(Arrays.asList(1.0, 2.0, 3.0), 0.5) false >>> hasCloseElements(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3) true
Write a Java function `public boolean hasCloseElements(List<Double> numbers, double threshold)` to solve the following problem: Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> hasCloseElements(Arrays.asList(1.0, 2.0, 3.0), 0.5) false >>> hasCloseElements(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3) true
JavaScript/163
/* Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generateIntegers(2, 8) => [2, 4, 6, 8] generateIntegers(8, 2) => [2, 4, 6, 8] generateIntegers(10, 14) => [] */ const generateIntegers = (a, b) => {
if (a > b) { let tmp = a; a = b; b = tmp; } let y = [] for (let i = a; i <= b; i++) { if (i == 2 || i == 4 || i == 6 || i == 8) { y.push(i) } } return y }
const testGenerateIntegers = () => { console.assert( JSON.stringify(generateIntegers(2, 10)) === JSON.stringify([2, 4, 6, 8]) ) console.assert( JSON.stringify(generateIntegers(10, 2)) === JSON.stringify([2, 4, 6, 8]) ) console.assert( JSON.stringify(generateIntegers(132, 2)) === JSON.stringify([2, 4, 6, 8]) ) console.assert( JSON.stringify(generateIntegers(17, 89)) === JSON.stringify([]) ) } testGenerateIntegers()
const generateIntegers = (a, b) => {
const testGenerateIntegers = () => { console.assert( JSON.stringify(generateIntegers(2, 8)) === JSON.stringify([2, 4, 6, 8]) ) console.assert( JSON.stringify(generateIntegers(8, 2)) === JSON.stringify([2, 4, 6, 8]) ) console.assert( JSON.stringify(generateIntegers(10, 14)) === JSON.stringify([]) ) } testGenerateIntegers()
if (a > b) { let tmp = a; a = b; b = tmp; } let y = [] for (let i = a; i > b; i++) { if (i == 2 || i == 4 || i == 6 || i == 8) { y.push(i) } } return y }
value misuse
incorrect output
generateIntegers
const generateIntegers = (a, b)
Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generateIntegers(2, 8) => [2, 4, 6, 8] generateIntegers(8, 2) => [2, 4, 6, 8] generateIntegers(10, 14) => []
Write a JavaScript function `const generateIntegers = (a, b)` to solve the following problem: Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generateIntegers(2, 8) => [2, 4, 6, 8] generateIntegers(8, 2) => [2, 4, 6, 8] generateIntegers(10, 14) => []
JavaScript/28
/* Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' */ const concatenate = (strings) => {
return strings.join(''); }
const testConcatenate = () => { console.assert(concatenate([]) === '') console.assert(concatenate(['x', 'y', 'z']) === 'xyz') console.assert(concatenate(['x', 'y', 'z', 'w', 'k']) === 'xyzwk') } testConcatenate()
const concatenate = (strings) => {
const testConcatenate = () => { console.assert(concatenate([]) === '') console.assert(concatenate(['a', 'b', 'c']) === 'abc') } testConcatenate()
return strings.join(' '); }
excess logic
incorrect output
concatenate
const concatenate = (strings)
Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc'
Write a JavaScript function `const concatenate = (strings)` to solve the following problem: Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc'
JavaScript/6
/* Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parseNestedParens('(()()) ((())) () ((())()())') [2, 3, 1, 3] */ const parseNestedParens = (paren_string) => {
var parseParenGroup = function (s) { let depth = 0, max_depth = 0; for (const c of s) { if (c == '(') { depth += 1; max_depth = Math.max(max_depth, depth); } else { depth -= 1; } } return max_depth; } return paren_string.split(' ') .filter(x => x != '') .map(x => parseParenGroup(x)); }
const testParseNestedParens = () => { console.assert( JSON.stringify(parseNestedParens('(()()) ((())) () ((())()())')) === JSON.stringify([2, 3, 1, 3]) ) console.assert( JSON.stringify(parseNestedParens('() (()) ((())) (((())))')) === JSON.stringify([1, 2, 3, 4]) ) console.assert( JSON.stringify(parseNestedParens('(()(())((())))')) === JSON.stringify([4]) ) } testParseNestedParens()
const parseNestedParens = (paren_string) => {
const testParseNestedParens = () => { console.assert( JSON.stringify(parseNestedParens('(()()) ((())) () ((())()())')) === JSON.stringify([2, 3, 1, 3]) ) } testParseNestedParens()
var parseParenGroup = function (s) { let depth = 0, max_depth = 0; for (const c of s) { if (c == '(') { depth += 1; max_depth = Math.max(max_depth, depth); } else { max_depth -= 1; } } return max_depth; } return paren_string.split(' ') .filter(x => x != '') .map(x => parseParenGroup(x)); }
variable misuse
incorrect output
parseNestedParens
const parseNestedParens = (paren_string)
Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parseNestedParens('(()()) ((())) () ((())()())') [2, 3, 1, 3]
Write a JavaScript function `const parseNestedParens = (paren_string)` to solve the following problem: Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parseNestedParens('(()()) ((())) () ((())()())') [2, 3, 1, 3]
JavaScript/70
/* Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strangeSortList([1, 2, 3, 4]) == [1, 4, 2, 3] strangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5] strangeSortList([]) == [] */ const strangeSortList = (lst) => {
var res = [], sw = true; while (lst.length) { res.push(sw ? Math.min(...lst) : Math.max(...lst)); lst.splice(lst.indexOf(res.at(-1)), 1); sw = !sw; } return res; }
const testStrangeSortList = () => { console.assert( JSON.stringify(strangeSortList([1, 2, 3, 4])) === JSON.stringify([1, 4, 2, 3]) ) console.assert( JSON.stringify(strangeSortList([5, 6, 7, 8, 9])) === JSON.stringify([5, 9, 6, 8, 7]) ) console.assert( JSON.stringify(strangeSortList([1, 2, 3, 4, 5])) === JSON.stringify([1, 5, 2, 4, 3]) ) console.assert( JSON.stringify(strangeSortList([5, 6, 7, 8, 9, 1])) === JSON.stringify([1, 9, 5, 8, 6, 7]) ) console.assert( JSON.stringify(strangeSortList([5, 5, 5, 5])) === JSON.stringify([5, 5, 5, 5]) ) console.assert(JSON.stringify(strangeSortList([])) === JSON.stringify([])) console.assert( JSON.stringify(strangeSortList([1, 2, 3, 4, 5, 6, 7, 8])) === JSON.stringify([1, 8, 2, 7, 3, 6, 4, 5]) ) console.assert( JSON.stringify(strangeSortList([0, 2, 2, 2, 5, 5, -5, -5])) === JSON.stringify([-5, 5, -5, 5, 0, 2, 2, 2]) ) console.assert( JSON.stringify(strangeSortList([111111])) === JSON.stringify([111111]) ) } testStrangeSortList()
const strangeSortList = (lst) => {
const testStrangeSortList = () => { console.assert( JSON.stringify(strangeSortList([1, 2, 3, 4])) === JSON.stringify([1, 4, 2, 3]) ) console.assert( JSON.stringify(strangeSortList([5, 5, 5, 5])) === JSON.stringify([5, 5, 5, 5]) ) console.assert(JSON.stringify(strangeSortList([])) === JSON.stringify([])) } testStrangeSortList()
var res = [], sw = false; while (lst.length) { res.push(sw ? Math.min(...lst) : Math.max(...lst)); lst.splice(lst.indexOf(res.at(-1)), 1); sw = !sw; } return res; }
operator misuse
incorrect output
strangeSortList
const strangeSortList = (lst)
Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strangeSortList([1, 2, 3, 4]) == [1, 4, 2, 3] strangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5] strangeSortList([]) == []
Write a JavaScript function `const strangeSortList = (lst)` to solve the following problem: Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strangeSortList([1, 2, 3, 4]) == [1, 4, 2, 3] strangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5] strangeSortList([]) == []
JavaScript/62
/* xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] */ const derivative = (xs) => {
return xs.map((x, i) => x * i).slice(1); }
const testDerivative = () => { console.assert( JSON.stringify(derivative([3, 1, 2, 4, 5])) === JSON.stringify([1, 4, 12, 20]) ) console.assert( JSON.stringify(derivative([1, 2, 3])) === JSON.stringify([2, 6]) ) console.assert( JSON.stringify(derivative([3, 2, 1])) === JSON.stringify([2, 2]) ) console.assert( JSON.stringify(derivative([3, 2, 1, 0, 4])) === JSON.stringify([2, 2, 0, 16]) ) console.assert(JSON.stringify(derivative([1])) === JSON.stringify([])) } testDerivative()
const derivative = (xs) => {
const testDerivative = () => { console.assert( JSON.stringify(derivative([3, 1, 2, 4, 5])) === JSON.stringify([1, 4, 12, 20]) ) console.assert( JSON.stringify(derivative([1, 2, 3])) === JSON.stringify([2, 6]) ) } testDerivative()
return xs.map((x, i) => x * i); }
value misuse
incorrect output
derivative
const derivative = (xs)
xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6]
Write a JavaScript function `const derivative = (xs)` to solve the following problem: xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6]
JavaScript/57
/*Return true is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) true >>> monotonic([1, 20, 4, 10]) false >>> monotonic([4, 1, 0, -10]) true */ const monotonic = (l) => {
var sort1 = [...l].sort((a, b) => a - b); var sort2 = [...l].sort((a, b) => b - a); if (JSON.stringify(l) === JSON.stringify(sort1) || JSON.stringify(l) === JSON.stringify(sort2)) return true; return false; }
const testMonotonic = () => { console.assert(monotonic([1, 2, 4, 10]) === true) console.assert(monotonic([1, 2, 4, 20]) === true) console.assert(monotonic([1, 20, 4, 10]) === false) console.assert(monotonic([4, 1, 0, -10]) === true) console.assert(monotonic([4, 1, 1, 0]) === true) console.assert(monotonic([1, 2, 3, 2, 5, 60]) === false) console.assert(monotonic([1, 2, 3, 4, 5, 60]) === true) console.assert(monotonic([9, 9, 9, 9]) === true) } testMonotonic()
const monotonic = (l) => {
const testMonotonic = () => { console.assert(monotonic([1, 2, 4, 10]) === true) console.assert(monotonic([1, 20, 4, 10]) === false) console.assert(monotonic([4, 1, 0, -10]) === true) } testMonotonic()
var sort1 = [...l].sort((a, b) => a - b); var sort2 = [...l].sort((a, b) => b - a); if (JSON.stringify(l) === JSON.stringify(sort1) || JSON.stringify(l) === JSON.stringify(sort2)) return false; return true; }
operator misuse
incorrect output
monotonic
const monotonic = (l)
Return true is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) true >>> monotonic([1, 20, 4, 10]) false >>> monotonic([4, 1, 0, -10]) true
Write a JavaScript function `const monotonic = (l)` to solve the following problem: Return true is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) true >>> monotonic([1, 20, 4, 10]) false >>> monotonic([4, 1, 0, -10]) true
JavaScript/35
/*Return maximum element in the list. >>> maxElement([1, 2, 3]) 3 >>> maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 */ const maxElement = (l) => {
return Math.max(...l); }
const testMaxElement = () => { console.assert(maxElement([1, 2, 3]) === 3) console.assert(maxElement([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) === 124) } testMaxElement()
const maxElement = (l) => {
const testMaxElement = () => { console.assert(maxElement([1, 2, 3]) === 3) console.assert(maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) === 123) } testMaxElement()
return Math.min(...l); }
operator misuse
incorrect output
maxElement
const maxElement = (l)
Return maximum element in the list. >>> maxElement([1, 2, 3]) 3 >>> maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123
Write a JavaScript function `const maxElement = (l)` to solve the following problem: Return maximum element in the list. >>> maxElement([1, 2, 3]) 3 >>> maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123
JavaScript/26
/* From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> removeDuplicates([1, 2, 3, 2, 4]) [1, 3, 4] */ const removeDuplicates = (numbers) => {
var dict = new Object(); for (const num of numbers) { if (num in dict) { dict[num] += 1; } else { dict[num] = 1; } } return numbers.filter(x => dict[x] <= 1); }
const testRemoveDuplicates = () => { console.assert(JSON.stringify(removeDuplicates([])) === JSON.stringify([])) console.assert( JSON.stringify(removeDuplicates([1, 2, 3, 4])) === JSON.stringify([1, 2, 3, 4]) ) console.assert( JSON.stringify(removeDuplicates([1, 2, 3, 2, 4, 3, 5])) === JSON.stringify([1, 4, 5]) ) } testRemoveDuplicates()
const removeDuplicates = (numbers) => {
const testRemoveDuplicates = () => { console.assert( JSON.stringify(removeDuplicates([1, 2, 3, 2,4])) === JSON.stringify([1,3, 4]) ) } testRemoveDuplicates()
var dict = new Object(); for (const num of numbers) { if (num in dict) { dict[num] += 1; } else { dict[num] = 1; } } return numbers.filter(x > dict[x] < 1); }
operator misuse
incorrect output
removeDuplicates
const removeDuplicates = (numbers)
From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> removeDuplicates([1, 2, 3, 2, 4]) [1, 3, 4]
Write a JavaScript function `const removeDuplicates = (numbers)` to solve the following problem: From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> removeDuplicates([1, 2, 3, 2, 4]) [1, 3, 4]
JavaScript/139
/*The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> specialFactorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. */ const specialFactorial = (n) => {
let p = 1; let t = 1; while (n > 1) { let y = p; while (y > 0) { y--; t *= n; } p++; n--; } return t }
const testSpecialFactorial = () => { console.assert(specialFactorial(4) === 288) console.assert(specialFactorial(5) === 34560) console.assert(specialFactorial(7) === 125411328000) console.assert(specialFactorial(1) === 1) } testSpecialFactorial()
const specialFactorial = (n) => {
const testSpecialFactorial = () => { console.assert(specialFactorial(4) === 288) } testSpecialFactorial()
let p = 1; let t = 1; while (n > 1) { let y = p; while (y > 0) { y--; n *= y; t *= n; } p++; p++; n--; } return t }
excess logic
incorrect output
specialFactorial
const specialFactorial = (n)
The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> specialFactorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer.
Write a JavaScript function `const specialFactorial = (n)` to solve the following problem: The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> specialFactorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer.
JavaScript/22
/* Filter given list of any python values only for integers >>> filterIntegers(['a', 3.14, 5]) [5] >>> filterIntegers([1, 2, 3, 'abc', {}, []]) [1, 2, 3] */ const filterIntegers = (values) => {
return values.filter(x => Number.isInteger(x)); }
const testFilterIntegers = () => { console.assert(JSON.stringify(filterIntegers([])) === JSON.stringify([])) console.assert( JSON.stringify(filterIntegers([4, {}, [], 23.2, 9, 'adasd'])) === JSON.stringify([4, 9]) ) console.assert( JSON.stringify(filterIntegers([3, 'c', 3, 3, 'a', 'b'])) === JSON.stringify([3, 3, 3]) ) } testFilterIntegers()
const filterIntegers = (values) => {
const testFilterIntegers = () => { console.assert(JSON.stringify(filterIntegers(['a', 3.14, 5])) === JSON.stringify([5])) console.assert( JSON.stringify(filterIntegers([1, 2, 3, 'abc', {}, []])) === JSON.stringify([1,2,3]) ) } testFilterIntegers()
values.filter(x => Number.isInteger(x)); return values; }
variable misuse
incorrect output
filterIntegers
const filterIntegers = (values)
Filter given list of any python values only for integers >>> filterIntegers(['a', 3.14, 5]) [5] >>> filterIntegers([1, 2, 3, 'abc', {}, []]) [1, 2, 3]
Write a JavaScript function `const filterIntegers = (values)` to solve the following problem: Filter given list of any python values only for integers >>> filterIntegers(['a', 3.14, 5]) [5] >>> filterIntegers([1, 2, 3, 'abc', {}, []]) [1, 2, 3]
JavaScript/151
/* Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. doubleTheDifference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10 doubleTheDifference([-1, -2, 0]) == 0 doubleTheDifference([9, -2]) == 81 doubleTheDifference([0]) == 0 If the input list is empty, return 0. */ const doubleTheDifference = (lst) => {
let p = 0 for (let i = 0; i < lst.length; i++) { if (lst[i] % 2 == 1 && lst[i] > 0) { p += lst[i] * lst[i] } } return p }
const testDoubleTheDifference = () => { console.assert(doubleTheDifference([]) === 0) console.assert(doubleTheDifference([5, 4]) === 25) console.assert(doubleTheDifference([0.1, 0.2, 0.3]) === 0) console.assert(doubleTheDifference([-10, -20, -30]) === 0) console.assert(doubleTheDifference([-1, -2, 8]) === 0) console.assert(doubleTheDifference([0.2, 3, 5]) === 34) let lst = [] let odd_sum = 0 for (let i = -99; i < 100; i += 2) { if (i % 2 != 0 && i > 0) { odd_sum += i * i } lst.push(i) } console.assert(doubleTheDifference(lst) === odd_sum) } testDoubleTheDifference()
const doubleTheDifference = (lst) => {
const testDoubleTheDifference = () => { console.assert(doubleTheDifference([1,3,2,0]) === 10) console.assert(doubleTheDifference([-1,-2,0]) === 0) console.assert(doubleTheDifference([9,-2]) === 81) console.assert(doubleTheDifference([0]) === 0) } testDoubleTheDifference()
let p = 0 for (let i = 0; i < lst.length; i++) { if (lst[i] > 0) { p += lst[i] } } return p }
missing logic
incorrect output
doubleTheDifference
const doubleTheDifference = (lst)
Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. doubleTheDifference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10 doubleTheDifference([-1, -2, 0]) == 0 doubleTheDifference([9, -2]) == 81 doubleTheDifference([0]) == 0 If the input list is empty, return 0.
Write a JavaScript function `const doubleTheDifference = (lst)` to solve the following problem: Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. doubleTheDifference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10 doubleTheDifference([-1, -2, 0]) == 0 doubleTheDifference([9, -2]) == 81 doubleTheDifference([0]) == 0 If the input list is empty, return 0.
JavaScript/108
/* Write a function countNums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> countNums([]) == 0 >>> countNums([-1, 11, -11]) == 1 >>> countNums([1, 1, 2]) == 3 */ const countNums = (arr) => {
let p = 0 for (let i = 0; i < arr.length; i++) { let h = arr[i] if (h > 0) { p++; continue; } let k = 0 h = -h while (h >= 10) { k += h % 10; h = (h - h % 10) / 10; } k -= h; if (k > 0) { p++ } } return p }
const testCountNums = () => { console.assert(countNums([]) === 0) console.assert(countNums([-1, -2, 0]) === 0) console.assert(countNums([1, 1, 2, -2, 3, 4, 5]) === 6) console.assert(countNums([1, 6, 9, -6, 0, 1, 5]) === 5) console.assert(countNums([1, 100, 98, -7, 1, -1]) === 4) console.assert(countNums([12, 23, 34, -45, -56, 0]) === 5) console.assert(countNums([-0, 1 ** 0]) === 1) console.assert(countNums([1]) === 1) } testCountNums()
const countNums = (arr) => {
const testCountNums = () => { console.assert(countNums([]) === 0) console.assert(countNums([-1, 11, -11]) === 1) console.assert(countNums([1, 1, 2]) === 3) } testCountNums()
let p = 0 for (let i = 0; i < arr.length; i++) { let h = arr[i] if (h > 0) { p++; continue; } let k = 0 h = -h while (h >= 10) { k += h % 10 * -1; h = (h - h % 10) / 10; } k -= h; if (k > 0) { p++ } } return p }
excess logic
incorrect output
countNums
const countNums = (arr)
Write a function countNums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> countNums([]) == 0 >>> countNums([-1, 11, -11]) == 1 >>> countNums([1, 1, 2]) == 3
Write a JavaScript function `const countNums = (arr)` to solve the following problem: Write a function countNums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> countNums([]) == 0 >>> countNums([-1, 11, -11]) == 1 >>> countNums([1, 1, 2]) == 3
JavaScript/8
/* For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sumProduct([]) (0, 1) >>> sumProduct([1, 2, 3, 4]) (10, 24) */ const sumProduct = (numbers, int) => {
var sum_value = 0, prod_value = 1; for (const n of numbers) { sum_value += n; prod_value *= n; } return [sum_value, prod_value]; }
const testSumProduct = () => { console.assert(JSON.stringify(sumProduct([])) === JSON.stringify([0, 1])) console.assert( JSON.stringify(sumProduct([1, 1, 1])) === JSON.stringify([3, 1]) ) console.assert( JSON.stringify(sumProduct([100, 0])) === JSON.stringify([100, 0]) ) console.assert( JSON.stringify( sumProduct([3, 5, 7])) === JSON.stringify([3 + 5 + 7, 3 * 5 * 7]) ) console.assert(JSON.stringify(sumProduct([10])) === JSON.stringify([10, 10])) } testSumProduct()
const sumProduct = (numbers, int) => {
const testSumProduct = () => { console.assert(JSON.stringify(sumProduct([])) === JSON.stringify([0, 1])) console.assert( JSON.stringify(sumProduct([1, 2,3,4])) === JSON.stringify([10, 24]) ) } testSumProduct()
var sum_value = 0, prod_value = 0; for (const n of numbers) { sum_value += n; prod_value *= n; } return [sum_value, prod_value]; }
value misuse
incorrect output
sumProduct
const sumProduct = (numbers, int)
For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sumProduct([]) (0, 1) >>> sumProduct([1, 2, 3, 4]) (10, 24)
Write a JavaScript function `const sumProduct = (numbers, int)` to solve the following problem: For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sumProduct([]) (0, 1) >>> sumProduct([1, 2, 3, 4]) (10, 24)
JavaScript/7
/* Filter an input list of strings only for ones that contain given substring >>> filterBySubstring([], 'a') [] >>> filterBySubstring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] */ const filterBySubstring = (strings, substring) => {
return strings.filter(x => x.indexOf(substring) != -1); }
const testFilterBySubstring = () => { console.assert( JSON.stringify(filterBySubstring([], 'john')) === JSON.stringify([]) ) console.assert( JSON.stringify( filterBySubstring( ['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx' ) ) === JSON.stringify(['xxx', 'xxxAAA', 'xxx']) ) console.assert( JSON.stringify( filterBySubstring( ['xxx', 'asd', 'aaaxxy', 'john doe', 'xxxAAA', 'xxx'], 'xx' ) ) === JSON.stringify(['xxx', 'aaaxxy', 'xxxAAA', 'xxx']) ) console.assert( JSON.stringify( filterBySubstring(['grunt', 'trumpet', 'prune', 'gruesome'], 'run') ) === JSON.stringify(['grunt', 'prune']) ) } testFilterBySubstring()
const filterBySubstring = (strings, substring) => {
const testFilterBySubstring = () => { console.assert( JSON.stringify(filterBySubstring([], 'a')) === JSON.stringify([]) ) console.assert( JSON.stringify( filterBySubstring( ['abc', 'bacd', 'cde', 'array'], 'a' ) ) === JSON.stringify(['abc', 'bacd', 'array']) ) } testFilterBySubstring()
return strings.filter(x => substring.indexOf(x) != -1); }
variable misuse
incorrect output
filterBySubstring
const filterBySubstring = (strings, substring)
Filter an input list of strings only for ones that contain given substring >>> filterBySubstring([], 'a') [] >>> filterBySubstring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array']
Write a JavaScript function `const filterBySubstring = (strings, substring)` to solve the following problem: Filter an input list of strings only for ones that contain given substring >>> filterBySubstring([], 'a') [] >>> filterBySubstring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array']
JavaScript/23
/* Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 */ const strlen = (string) => {
return string.length; }
const testStrlen = () => { console.assert(strlen('') === 0) console.assert(strlen('x') === 1) console.assert(strlen('asdasnakj') === 9) } testStrlen()
const strlen = (string) => {
const testStrlen = () => { console.assert(strlen('') === 0) console.assert(strlen('abc') === 3) } testStrlen()
return string.length - 1; }
value misuse
incorrect output
strlen
const strlen = (string)
Return length of given string >>> strlen('') 0 >>> strlen('abc') 3
Write a JavaScript function `const strlen = (string)` to solve the following problem: Return length of given string >>> strlen('') 0 >>> strlen('abc') 3
JavaScript/55
/*Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 */ const fib = (n) => {
if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); }
const testFib = () => { console.assert(fib(10) === 55) console.assert(fib(1) === 1) console.assert(fib(8) === 21) console.assert(fib(11) === 89) console.assert(fib(12) === 144) } testFib()
const fib = (n) => {
const testFib = () => { console.assert(fib(10) === 55) console.assert(fib(1) === 1) console.assert(fib(8) === 21) } testFib()
if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; return fib(n - 1) + fib(n - 2); }
excess logic
incorrect output
fib
const fib = (n)
Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21
Write a JavaScript function `const fib = (n)` to solve the following problem: Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21
JavaScript/59
/*Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largestPrimeFactor(13195) 29 >>> largestPrimeFactor(2048) 2 */ const largestPrimeFactor = (n) => {
var isPrime = function (k) { if (k < 2) return false; for (let i = 2; i < k - 1; i++) if (k % i == 0) return false; return true; } var largest = 1; for (let j = 2; j < n + 1; j++) if (n % j == 0 && isPrime(j)) largest = Math.max(largest, j); return largest; }
const testLargestPrimeFactor = () => { console.assert(largestPrimeFactor(15) === 5) console.assert(largestPrimeFactor(27) === 3) console.assert(largestPrimeFactor(63) === 7) console.assert(largestPrimeFactor(330) === 11) console.assert(largestPrimeFactor(13195) === 29) } testLargestPrimeFactor()
const largestPrimeFactor = (n) => {
const testLargestPrimeFactor = () => { console.assert(largestPrimeFactor(2048) === 2) console.assert(largestPrimeFactor(13195) === 29) } testLargestPrimeFactor()
var isPrime = function (k) { if (k < 2) return false; for (let i = 2; i < k - 1; i++) if (k % i == 0) return false; return true; } var largest = 1; for (let j = 2; j < n + 1; j++) if (n % j == 0 && isPrime(n)) largest = Math.max(largest, j); return largest; }
variable misuse
incorrect output
largestPrimeFactor
const largestPrimeFactor = (n)
Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largestPrimeFactor(13195) 29 >>> largestPrimeFactor(2048) 2
Write a JavaScript function `const largestPrimeFactor = (n)` to solve the following problem: Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largestPrimeFactor(13195) 29 >>> largestPrimeFactor(2048) 2
JavaScript/129
/* Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 Output: [1, 2, 1] Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 Output: [1] */ const minPath = (grid, k) => {
let m = 0 let n = 0 for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid.length; j++) { if (grid[i][j] == 1) { m = i; n = j; break; } } } let min = grid.length * grid.length if (m > 0 && grid[m - 1][n] < min) { min = grid[m - 1][n] } if (n > 0 && grid[m][n - 1] < min) { min = grid[m][n - 1] } if (m < grid.length - 1 && grid[m + 1][n] < min) { min = grid[m + 1][n] } if (n < grid.length - 1 && grid[m][n + 1] < min) { min = grid[m][n + 1] } let p = [] for (let i = 0; i < k; i++) { if (i % 2 == 0) { p.push(1) } else { p.push(min) } } return p }
const testMinPath = () => { console.assert( JSON.stringify( minPath( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ], 3 ) ) === JSON.stringify([1, 2, 1]) ) console.assert( JSON.stringify( minPath( [ [5, 9, 3], [4, 1, 6], [7, 8, 2], ], 1 ) ) === JSON.stringify([1]) ) console.assert( JSON.stringify( minPath( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ], 4 ) ) === JSON.stringify([1, 2, 1, 2]) ) console.assert( JSON.stringify( minPath( [ [6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2], ], 7 ) ) === JSON.stringify([1, 10, 1, 10, 1, 10, 1]) ) console.assert( JSON.stringify( minPath( [ [8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16], ], 5 ) ) === JSON.stringify([1, 7, 1, 7, 1]) ) console.assert( JSON.stringify( minPath( [ [11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1], ], 9 ) ) === JSON.stringify([1, 6, 1, 6, 1, 6, 1, 6, 1]) ) console.assert( JSON.stringify( minPath( [ [12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2], ], 12 ) ) === JSON.stringify([1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]) ) console.assert( JSON.stringify( minPath( [ [2, 7, 4], [3, 1, 5], [6, 8, 9], ], 8 ) ) === JSON.stringify([1, 3, 1, 3, 1, 3, 1, 3]) ) console.assert( JSON.stringify( minPath( [ [6, 1, 5], [3, 8, 9], [2, 7, 4], ], 8 ) ) === JSON.stringify([1, 5, 1, 5, 1, 5, 1, 5]) ) console.assert( JSON.stringify( minPath( [ [1, 2], [3, 4], ], 10 ) ) === JSON.stringify([1, 2, 1, 2, 1, 2, 1, 2, 1, 2]) ) console.assert( JSON.stringify( minPath( [ [1, 3], [4, 2], ], 10 ) ) === JSON.stringify([1, 3, 1, 3, 1, 3, 1, 3, 1, 3]) ) } testMinPath()
const minPath = (grid, k) => {
const testMinPath = () => { console.assert( JSON.stringify( minPath( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ], 3 ) ) === JSON.stringify([1, 2, 1]) ) console.assert( JSON.stringify( minPath( [ [5, 9, 3], [4, 1, 6], [7, 8, 2], ], 1 ) ) === JSON.stringify([1]) ) } testMinPath()
let m = 0 let n = 0 for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid.length; j++) { if (grid[i][j] == 1) { m = i; n = j; break; } } } let min = grid.length * grid.length if (m > 0 && grid[m - 1][n] < min) { min = grid[m][n] } if (n > 0 && grid[m][n - 1] < min) { min = grid[m][n] } if (m < grid.length - 1 && grid[m + 1][n] < min) { min = grid[m][n] } if (n < grid.length - 1 && grid[m][n + 1] < min) { min = grid[m][n] } let p = [] for (let i = 0; i < k; i++) { if (i % 2 == 0) { p.push(1) } else { p.push(min) } } return p }
value misuse
incorrect output
minPath
const minPath = (grid, k)
Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 Output: [1, 2, 1] Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 Output: [1]
Write a JavaScript function `const minPath = (grid, k)` to solve the following problem: Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 Output: [1, 2, 1] Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 Output: [1]
JavaScript/161
/*You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c" */ const solve = (s) => {
let t = 0 let p = '' for (let i = 0; i < s.length; i++) { let y = s[i].charCodeAt() if (y >= 65 && y <= 90) { y += 32; t = 1; } else if (y >= 97 && y <= 122) { y -= 32; t = 1; } p += String.fromCharCode(y) } if (t == 1) { return p } let u = '' for (let i = 0; i < p.length; i++) { u += p[p.length - i - 1] } return u }
const testSolve = () => { console.assert(solve('AsDf') === 'aSdF') console.assert(solve('1234') === '4321') console.assert(solve('ab') === 'AB') console.assert(solve('#a@C') === '#A@c') console.assert(solve('#AsdfW^45') === '#aSDFw^45') console.assert(solve('#6@2') === '2@6#') console.assert(solve('#$a^D') === '#$A^d') console.assert(solve('#ccc') === '#CCC') } testSolve()
const solve = (s) => {
const testSolve = () => { console.assert(solve('1234') === '4321') console.assert(solve('ab') === 'AB') console.assert(solve('#a@C') === '#A@c') } testSolve()
let t = 0 let p = '' for (let i = 0; i < s.length; i++) { let y = s[i].charCodeAt() if (y >= 65 && y <= 90) { y += 32; t = 1; } p += String.fromCharCode(y) } if (t == 1) { return p } let u = '' for (let i = 0; i < p.length; i++) { u += p[p.length - i - 1] } return u }
missing logic
incorrect output
solve
const solve = (s)
You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c"
Write a JavaScript function `const solve = (s)` to solve the following problem: You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c"
JavaScript/143
/* You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters */ const wordsInSentence = (sentence) => {
let t = sentence.split(/\s/) let p = '' for (let j = 0; j < t.length; j++) { let len = t[j].length; let u = 1 if (len == 1 || len == 0) { continue } for (let i = 2; i * i <= len; i++) { if (len % i == 0) { u = 0 } } if (u == 0) { continue } if (p == '') { p += t[j] } else { p = p + ' ' + t[j] } } return p }
const testWordsInSentence = () => { console.assert(wordsInSentence('This is a test') === 'is') console.assert(wordsInSentence('lets go for swimming') === 'go for') console.assert( wordsInSentence('there is no place available here') === 'there is no place' ) console.assert(wordsInSentence('Hi I am Hussein') === 'Hi am Hussein') console.assert(wordsInSentence('go for it') === 'go for it') console.assert(wordsInSentence('here') === '') console.assert(wordsInSentence('here is') === 'is') } testWordsInSentence()
const wordsInSentence = (sentence) => {
const testWordsInSentence = () => { console.assert(wordsInSentence('This is a test') === 'is') console.assert(wordsInSentence('lets go for swimming') === 'go for') } testWordsInSentence()
let t = sentence.split(/\s/) let p = '' for (let j = 0; j < t.length; j++) { let len = t[j].length; let u = 1 for (let i = 2; i * i <= len; i++) { if (len % i == 0) { u = 0 } } if (u == 0) { continue } if (p == '') { p += t[j] } else { p = p + ' ' + t[j] } } return p }
missing logic
incorrect output
wordsInSentence
const wordsInSentence = (sentence)
You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters
Write a JavaScript function `const wordsInSentence = (sentence)` to solve the following problem: You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters
JavaScript/50
/* returns encoded string by shifting every character by 5 in the alphabet. */ const encodeShift = (s) => { return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) + 5 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0) )).join(""); } /* takes as input string encoded with encode_shift function. Returns decoded string. */ const decodeShift = (s) => {
return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) - 5 + 26 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0) )).join(""); }
const testDecodeShift = () => { const letters = new Array(26) .fill(null) .map((v, i) => String.fromCharCode(97 + i)) for (let i = 0; i < 100; i++) { let str = new Array(Math.floor(Math.random() * 20)).fill(null); str = str.map(item => letters[Math.floor(Math.random() * letters.length)]).join(''); let encoded_str = encodeShift(str) console.assert(decodeShift(encoded_str) === str) } } testDecodeShift()
const encodeShift = (s) => { return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) + 5 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0) )).join(""); } const decodeShift = (s) => {
return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) - 5 + 26 - "a".charCodeAt(0)) % 26) + ch.charCodeAt(0) )).join(""); }
variable misuse
incorrect output
decodeShift
const decodeShift = (s)
takes as input string encoded with encode_shift function. Returns decoded string.
Write a JavaScript function `const decodeShift = (s)` to solve the following problem: takes as input string encoded with encode_shift function. Returns decoded string.
JavaScript/155
/*Given an integer. return a tuple that has the number of even and odd digits respectively. Example: evenOddCount(-12) ==> (1, 1) evenOddCount(123) ==> (1, 2) */ const evenOddCount = (num) => {
let o = 0 let e = 0 if (num < 0) { num = -num } while (num > 0) { if (num % 2 == 0) { e++ } else { o++ } num = (num - num % 10) / 10 } return (e, o) }
const testEvenOddCount = () => { console.assert(JSON.stringify(evenOddCount(7)) === JSON.stringify((0, 1))) console.assert(JSON.stringify(evenOddCount(-78)) === JSON.stringify((1, 1))) console.assert(JSON.stringify(evenOddCount(3452)) === JSON.stringify((2, 2))) console.assert( JSON.stringify(evenOddCount(346211)) === JSON.stringify((3, 3)) ) console.assert( JSON.stringify(evenOddCount(-345821)) === JSON.stringify((3, 3)) ) console.assert(JSON.stringify(evenOddCount(-2)) === JSON.stringify((1, 0))) console.assert( JSON.stringify(evenOddCount(-45347)) === JSON.stringify((2, 3)) ) console.assert(JSON.stringify(evenOddCount(0)) === JSON.stringify((1, 0))) } testEvenOddCount()
const evenOddCount = (num) => {
const testEvenOddCount = () => { console.assert(JSON.stringify(evenOddCount(-12)) === JSON.stringify((1, 1))) console.assert(JSON.stringify(evenOddCount(123)) === JSON.stringify((1, 2))) } testEvenOddCount()
let o = 0 let e = 0 if (num < 0) { num = -num } while (num > 0) { if (num % 2 == 0) { e++ } else { o++ } num = num - num % 10 } return (e, o) }
missing logic
incorrect output
evenOddCount
const evenOddCount = (num)
Given an integer. return a tuple that has the number of even and odd digits respectively. Example: evenOddCount(-12) ==> (1, 1) evenOddCount(123) ==> (1, 2)
Write a JavaScript function `const evenOddCount = (num)` to solve the following problem: Given an integer. return a tuple that has the number of even and odd digits respectively. Example: evenOddCount(-12) ==> (1, 1) evenOddCount(123) ==> (1, 2)
JavaScript/107
/* Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. */ const evenOddPalindrome = (n) => {
let e = 0 let o = 0 for (let i = 1; i <= n; i++) { let k = i.toString() let p = 1 for (let j = 0; j < k.length; j++) { if (k[j] != k[k.length - j - 1]) { p = 0; break; } } if (p == 1) { if (k % 2 == 0) { e++ } else { o++ } } } return (e, o) }
const testEvenOddPalindrome = () => { console.assert( JSON.stringify(evenOddPalindrome(123)) === JSON.stringify((8, 13)) ) console.assert( JSON.stringify(evenOddPalindrome(12)) === JSON.stringify((4, 6)) ) console.assert( JSON.stringify(evenOddPalindrome(3)) === JSON.stringify((1, 2)) ) console.assert( JSON.stringify(evenOddPalindrome(63)) === JSON.stringify((6, 8)) ) console.assert( JSON.stringify(evenOddPalindrome(25)) === JSON.stringify((5, 6)) ) console.assert( JSON.stringify(evenOddPalindrome(19)) === JSON.stringify((4, 6)) ) console.assert( JSON.stringify(evenOddPalindrome(9)) === JSON.stringify((4, 5)) ) console.assert( JSON.stringify(evenOddPalindrome(1)) === JSON.stringify((0, 1)) ) } testEvenOddPalindrome()
const evenOddPalindrome = (n) => {
const testEvenOddPalindrome = () => { console.assert( JSON.stringify(evenOddPalindrome(12)) === JSON.stringify((4, 6)) ) console.assert( JSON.stringify(evenOddPalindrome(3)) === JSON.stringify((1, 2)) ) } testEvenOddPalindrome()
let e = 0 let o = 0 for (let i = 1; i <= n; i++) { let k = i.toString() let p = 1 for (let j = 0; j < k.length; j++) { if (k[j] != k[k.length - j - 1]) { p = 0; break; } } if (p == 1) { if (k % 2 == 1) { e++ } else { o++ } } } return (e, o) }
value misuse
incorrect output
evenOddPalindrome
const evenOddPalindrome = (n)
Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively.
Write a JavaScript function `const evenOddPalindrome = (n)` to solve the following problem: Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively.
JavaScript/56
/* brackets is a string of "<" and ">". return false if every opening bracket has a corresponding closing bracket. >>> correctBracketing("<") false >>> correctBracketing("<>") false >>> correctBracketing("<<><>>") false >>> correctBracketing("><<>") false */ const correctBracketing = (brackets) => {
var depth = 0; for (const b of brackets) { if (b == "<") depth += 1; else depth -= 1; if (depth < 0) return false; } return depth == 0; }
const testCorrectBracketing = () => { console.assert(correctBracketing('<>') === true) console.assert(correctBracketing('<<><>>') === true) console.assert(correctBracketing('<><><<><>><>') === true) console.assert(correctBracketing('<><><<<><><>><>><<><><<>>>') === true) console.assert(correctBracketing('<<<><>>>>') === false) console.assert(correctBracketing('><<>') === false) console.assert(correctBracketing('<') === false) console.assert(correctBracketing('<<<<') === false) console.assert(correctBracketing('>') === false) console.assert(correctBracketing('<<>') === false) console.assert(correctBracketing('<><><<><>><>><<>') === false) console.assert(correctBracketing('<><><<><>><>>><>') === false) } testCorrectBracketing()
const correctBracketing = (brackets) => {
const testCorrectBracketing = () => { console.assert(correctBracketing('<>') === true) console.assert(correctBracketing('<<><>>') === true) console.assert(correctBracketing('><<>') === false) console.assert(correctBracketing('<') === false) } testCorrectBracketing()
var depth = 0; for (const b of brackets) { if (b == ">") depth += 1; else depth -= 1; if (depth < 0) return false; } return depth == 0; }
operator misuse
incorrect output
correctBracketing
const correctBracketing = (brackets)
brackets is a string of "<" and ">". return false if every opening bracket has a corresponding closing bracket. >>> correctBracketing("<") false >>> correctBracketing("<>") false >>> correctBracketing("<<><>>") false >>> correctBracketing("><<>") false
Write a JavaScript function `const correctBracketing = (brackets)` to solve the following problem: brackets is a string of "<" and ">". return false if every opening bracket has a corresponding closing bracket. >>> correctBracketing("<") false >>> correctBracketing("<>") false >>> correctBracketing("<<><>>") false >>> correctBracketing("><<>") false
JavaScript/114
/* Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6 */ const minSubArraySum = (nums) => {
let min = nums[0] for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j <= nums.length; j++) { let s = 0; for (let k = i; k < j; k++) { s += nums[k] } if (s < min) { min = s } } } return min }
const testMinSubArraySum = () => { console.assert(minSubArraySum([2, 3, 4, 1, 2, 4]) === 1) console.assert(minSubArraySum([-1, -2, -3]) === -6) console.assert(minSubArraySum([-1, -2, -3, 2, -10]) === -14) console.assert(minSubArraySum([-9999999999999999]) === -9999999999999999) console.assert(minSubArraySum([0, 10, 20, 1000000]) === 0) console.assert(minSubArraySum([-1, -2, -3, 10, -5]) === -6) console.assert(minSubArraySum([100, -1, -2, -3, 10, -5]) === -6) console.assert(minSubArraySum([10, 11, 13, 8, 3, 4]) === 3) console.assert(minSubArraySum([100, -33, 32, -1, 0, -2]) === -33) console.assert(minSubArraySum([-10]) === -10) console.assert(minSubArraySum([7]) === 7) console.assert(minSubArraySum([1, -1]) === -1) } testMinSubArraySum()
const minSubArraySum = (nums) => {
const testMinSubArraySum = () => { console.assert(minSubArraySum([2, 3, 4, 1, 2, 4]) === 1) console.assert(minSubArraySum([-1, -2, -3]) === -6) } testMinSubArraySum()
let min = Math.min(nums) for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j <= nums.length; j++) { let s = 0; for (let k = i; k < j; k++) { s += nums[k] } if (s < min) { min = s } } } return min }
function misuse
incorrect output
minSubarraySum
const minSubArraySum = (nums)
Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6
Write a JavaScript function `const minSubArraySum = (nums)` to solve the following problem: Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6
JavaScript/71
/* Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangleArea(3, 4, 5) == 6.00 triangleArea(1, 2, 10) == -1 */ const triangleArea = (a, b, c) => {
if (a + b <= c || a + c <= b || b + c <= a) return -1; var s = (a + b + c) / 2; var area = Math.pow(s * (s - a) * (s - b) * (s - c), 0.5); area = area.toFixed(2); return area; }
const testTriangleArea = () => { console.assert(triangleArea(3, 4, 5) == 6.0) console.assert(triangleArea(1, 2, 10) == -1) console.assert(triangleArea(4, 8, 5) == 8.18) console.assert(triangleArea(2, 2, 2) == 1.73) console.assert(triangleArea(1, 2, 3) == -1) console.assert(triangleArea(10, 5, 7) == 16.25) console.assert(triangleArea(2, 6, 3) == -1) console.assert(triangleArea(1, 1, 1) == 0.43) console.assert(triangleArea(2, 2, 10) == -1) } testTriangleArea()
const triangleArea = (a, b, c) => {
const testTriangleArea = () => { console.assert(triangleArea(3, 4, 5) == 6.0) console.assert(triangleArea(1, 2, 10) == -1) } testTriangleArea()
if (a + b <= c || a + c <= b || b + c <= a) return -1; var s = (a + b + c); var area = Math.pow(s * (s - a) * (s - b) * (s - c), 0.5); area = area.toFixed(2); return area; }
missing logic
incorrect output
triangleArea
const triangleArea = (a, b, c)
Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangleArea(3, 4, 5) == 6.00 triangleArea(1, 2, 10) == -1
Write a JavaScript function `const triangleArea = (a, b, c)` to solve the following problem: Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangleArea(3, 4, 5) == 6.00 triangleArea(1, 2, 10) == -1
JavaScript/1
/* Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separateParenGroups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] */ const separateParenGroups = (paren_string) => {
var result = []; var current_string = []; var current_depth = 0; for (const c of paren_string) { if (c == '(') { current_depth += 1; current_string.push(c); } else if (c == ')') { current_depth -= 1; current_string.push(c); if (current_depth == 0) { result.push(current_string.join('')); current_string = []; } } } return result; }
const testSeparateParenGroups = () => { console.assert( JSON.stringify(separateParenGroups('(()()) ((())) () ((())()())')) === JSON.stringify(['(()())', '((()))', '()', '((())()())']) ) console.assert( JSON.stringify(separateParenGroups('() (()) ((())) (((())))')) === JSON.stringify(['()', '(())', '((()))', '(((())))']) ) console.assert( JSON.stringify(separateParenGroups('(()(())((())))')) === JSON.stringify(['(()(())((())))']) ) console.assert( JSON.stringify(separateParenGroups('( ) (( )) (( )( ))')) === JSON.stringify(['()', '(())', '(()())']) ) } testSeparateParenGroups()
const separateParenGroups = (paren_string) => {
const testSeparateParenGroups = () => { console.assert( JSON.stringify(separateParenGroups('( ) (( )) (( )( ))')) === JSON.stringify(['()', '(())', '(()())']) ) } testSeparateParenGroups()
var result = []; var current_string = []; var current_depth = 0; for (const c of paren_string) { if (c == '(') { current_depth += 1; current_string.push(c); } else if (c == ')') { current_depth -= 1; current_string.push(c); if (current_depth < 0) { result.push(current_string.join('')); current_string = []; } } } return result; }
operator misuse
incorrect output
separateParenGroups
const separateParenGroups = (paren_string)
Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separateParenGroups('( ) (( )) (( )( ))') ['()', '(())', '(()())']
Write a JavaScript function `const separateParenGroups = (paren_string)` to solve the following problem: Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separateParenGroups('( ) (( )) (( )( ))') ['()', '(())', '(()())']
JavaScript/40
/* triplesSumToZero takes a list of integers as an input. it returns true if there are three distinct elements in the list that sum to zero, and false otherwise. >>> triplesSumToZero([1, 3, 5, 0]) false >>> triplesSumToZero([1, 3, -2, 1]) true >>> triplesSumToZero([1, 2, 3, 7]) false >>> triplesSumToZero([2, 4, -5, 3, 9, 7]) true >>> triplesSumToZero([1]) false */ const triplesSumToZero = (l) => {
for (let i = 0; i < l.length; i++) for (let j = i + 1; j < l.length; j++) for (let k = j + 1; k < l.length; k++) if (l[i] + l[j] + l[k] == 0) return true; return false; }
const testTriplesSumToZero = () => { console.assert(triplesSumToZero([1, 3, 5, 0]) === false) console.assert(triplesSumToZero([1, 3, 5, -1]) === false) console.assert(triplesSumToZero([1, 3, -2, 1]) === true) console.assert(triplesSumToZero([1, 2, 3, 7]) === false) console.assert(triplesSumToZero([1, 2, 5, 7]) === false) console.assert(triplesSumToZero([2, 4, -5, 3, 9, 7]) === true) console.assert(triplesSumToZero([1]) === false) console.assert(triplesSumToZero([1, 3, 5, -100]) === false) console.assert(triplesSumToZero([100, 3, 5, -100]) === false) } testTriplesSumToZero()
const triplesSumToZero = (l) => {
const testTriplesSumToZero = () => { console.assert(triplesSumToZero([1, 3, 5, 0]) === false) console.assert(triplesSumToZero([1, 3, -2, 1]) === true) console.assert(triplesSumToZero([1, 2, 3, 7]) === false) console.assert(triplesSumToZero([2, 4, -5, 3, 9, 7]) === true) } testTriplesSumToZero()
for (let i = 1; i < l.length; i++) for (let j = i + 1; j < l.length; j++) for (let k = j + 1; k < l.length; k++) if (l[i] + l[j] + l[k] == 0) return true; return false; }
value misuse
incorrect output
triplesSumToZero
const triplesSumToZero = (l)
triplesSumToZero takes a list of integers as an input. it returns true if there are three distinct elements in the list that sum to zero, and false otherwise. >>> triplesSumToZero([1, 3, 5, 0]) false >>> triplesSumToZero([1, 3, -2, 1]) true >>> triplesSumToZero([1, 2, 3, 7]) false >>> triplesSumToZero([2, 4, -5, 3, 9, 7]) true >>> triplesSumToZero([1]) false
Write a JavaScript function `const triplesSumToZero = (l)` to solve the following problem: triplesSumToZero takes a list of integers as an input. it returns true if there are three distinct elements in the list that sum to zero, and false otherwise. >>> triplesSumToZero([1, 3, 5, 0]) false >>> triplesSumToZero([1, 3, -2, 1]) true >>> triplesSumToZero([1, 2, 3, 7]) false >>> triplesSumToZero([2, 4, -5, 3, 9, 7]) true >>> triplesSumToZero([1]) false
JavaScript/152
/*I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3] compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6] */ const compare = (game, guess) => {
for (let i = 0; i < guess.length; i++) { game[i] -= guess[i] if (game[i]<0) game[i]=-game[i]; } return game }
const testCompare = () => { console.assert( JSON.stringify(compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])) === JSON.stringify([0, 0, 0, 0, 3, 3]) ) console.assert( JSON.stringify(compare([0,5,0,0,0,4],[4,1,1,0,0,-2])) === JSON.stringify([4,4,1,0,0,6]) ) console.assert( JSON.stringify(compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])) === JSON.stringify([0, 0, 0, 0, 3, 3]) ) console.assert( JSON.stringify(compare([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0])) === JSON.stringify([0, 0, 0, 0, 0, 0]) ) console.assert( JSON.stringify(compare([1, 2, 3], [-1, -2, -3])) === JSON.stringify([2, 4, 6]) ) console.assert( JSON.stringify(compare([1, 2, 3, 5], [-1, 2, 3, 4])) === JSON.stringify([2, 0, 0, 1]) ) } testCompare()
const compare = (game, guess) => {
const testCompare = () => { console.assert( JSON.stringify(compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])) === JSON.stringify([0, 0, 0, 0, 3, 3]) ) console.assert( JSON.stringify(compare([0,5,0,0,0,4],[4,1,1,0,0,-2])) === JSON.stringify([4,4,1,0,0,6]) ) } testCompare()
for (let i = 0; i < guess.length; i++) { game[i] -= guess[i] if (game[i]<0) game[i]=-game[i]; if (guess[i]!=0) game[i]-=guess[i]; } return game }
excess logic
incorrect output
compare
const compare = (game, guess)
I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3] compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]
Write a JavaScript function `const compare = (game, guess)` to solve the following problem: I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3] compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]
JavaScript/87
/* You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: getRow([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] getRow([], 1) == [] getRow([[], [1], [1, 2, 3]], 3) == [(2, 2)] */ const getRow = (lst, x) => {
let t = [] for (let i = 0; i < lst.length; i++) { for (let j = lst[i].length - 1; j >= 0; j--) { if (lst[i][j] == x) { t.push((i, j)) } } } return t }
const testGetRow = () => { console.assert( JSON.stringify( getRow( [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1], ], 1 ) ) === JSON.stringify([(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]) ) console.assert( JSON.stringify( getRow( [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], ], 2 ) ) === JSON.stringify([(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]) ) console.assert( JSON.stringify( getRow( [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 1, 3, 4, 5, 6], [1, 2, 1, 4, 5, 6], [1, 2, 3, 1, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1], ], 1 ) ) === JSON.stringify([ (0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0), ]) ) console.assert(JSON.stringify(getRow([], 1)) === JSON.stringify([])) console.assert(JSON.stringify(getRow([[1]], 2)) === JSON.stringify([])) console.assert( JSON.stringify(getRow([[], [1], [1, 2, 3]], 3)) === JSON.stringify([(2, 2)]) ) } testGetRow()
const getRow = (lst, x) => {
const testGetRow = () => { console.assert( JSON.stringify( getRow( [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1], ], 1 ) ) === JSON.stringify([(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]) ) console.assert(JSON.stringify(getRow([], 1)) === JSON.stringify([])) console.assert( JSON.stringify(getRow([[], [1], [1, 2, 3]], 3)) === JSON.stringify([(2, 2)]) ) } testGetRow()
let t = [] for (let i = 0; i < lst.length; i++) { for (let j = lst[i].length - 1; j >= 0; j--) { if (lst[i][j] == x) { t.push((j, i)) } } } return t }
variable misuse
incorrect output
getRow
const getRow = (lst, x)
You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: getRow([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] getRow([], 1) == [] getRow([[], [1], [1, 2, 3]], 3) == [(2, 2)]
Write a JavaScript function `const getRow = (lst, x)` to solve the following problem: You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: getRow([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] getRow([], 1) == [] getRow([[], [1], [1, 2, 3]], 3) == [(2, 2)]
JavaScript/138
/*Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example isEqualToSumEven(4) == false isEqualToSumEven(6) == false isEqualToSumEven(8) == true */ const isEqualToSumEven = (n) => {
return (n >= 8 && n % 2 == 0) }
const testIsEqualToSumEven = () => { console.assert(isEqualToSumEven(4) === false) console.assert(isEqualToSumEven(6) === false) console.assert(isEqualToSumEven(8) === true) console.assert(isEqualToSumEven(10) === true) console.assert(isEqualToSumEven(11) === false) console.assert(isEqualToSumEven(12) === true) console.assert(isEqualToSumEven(13) === false) console.assert(isEqualToSumEven(16) === true) } testIsEqualToSumEven()
const isEqualToSumEven = (n) => {
const testIsEqualToSumEven = () => { console.assert(isEqualToSumEven(4) === false) console.assert(isEqualToSumEven(6) === false) console.assert(isEqualToSumEven(8) === true) } testIsEqualToSumEven()
return (n >= 8 && n <= 8 && n % 2 == 0) }
excess logic
incorrect output
isEqualToSumEven
const isEqualToSumEven = (n)
Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example isEqualToSumEven(4) == false isEqualToSumEven(6) == false isEqualToSumEven(8) == true
Write a JavaScript function `const isEqualToSumEven = (n)` to solve the following problem: Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example isEqualToSumEven(4) == false isEqualToSumEven(6) == false isEqualToSumEven(8) == true
JavaScript/39
/* primeFib returns n-th number that is a Fibonacci number and it's also prime. >>> primeFib(1) 2 >>> primeFib(2) 3 >>> primeFib(3) 5 >>> primeFib(4) 13 >>> primeFib(5) 89 */ const primeFib = (n) => {
var isPrime = function (p) { if (p < 2) return false; for (let k = 2; k < Math.min(Math.floor(Math.sqrt(p)) + 1, p - 1); k++) { if (p % k == 0) return false; } return true; } var f = [0, 1]; while (true) { f.push(f.at(-1) + f.at(-2)); if (isPrime(f.at(-1))) n -= 1; if (n == 0) return f.at(-1); } }
const testPrimeFib = () => { console.assert(primeFib(1) === 2) console.assert(primeFib(2) === 3) console.assert(primeFib(3) === 5) console.assert(primeFib(4) === 13) console.assert(primeFib(5) === 89) console.assert(primeFib(6) === 233) console.assert(primeFib(7) === 1597) console.assert(primeFib(8) === 28657) console.assert(primeFib(9) === 514229) console.assert(primeFib(10) === 433494437) } testPrimeFib()
const primeFib = (n) => {
const testPrimeFib = () => { console.assert(primeFib(1) === 2) console.assert(primeFib(2) === 3) console.assert(primeFib(3) === 5) console.assert(primeFib(4) === 13) console.assert(primeFib(5) === 89) } testPrimeFib()
var isPrime = function (p) { if (p < 2) return false; for (let k = 2; k < Math.min(Math.floor(Math.sqrt(p)), p); k++) { if (p % k == 0) return false; } return true; } var f = [0, 1]; while (true) { f.push(f.at(-1) + f.at(-2)); if (isPrime(f.at(-1))) n -= 1; if (n == 0) return f.at(-1); } }
value misuse
incorrect output
primeFib
const primeFib = (n)
primeFib returns n-th number that is a Fibonacci number and it's also prime. >>> primeFib(1) 2 >>> primeFib(2) 3 >>> primeFib(3) 5 >>> primeFib(4) 13 >>> primeFib(5) 89
Write a JavaScript function `const primeFib = (n)` to solve the following problem: primeFib returns n-th number that is a Fibonacci number and it's also prime. >>> primeFib(1) 2 >>> primeFib(2) 3 >>> primeFib(3) 5 >>> primeFib(4) 13 >>> primeFib(5) 89
Python/0
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool: """ Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """
for idx, elem in enumerate(numbers): for idx2, elem2 in enumerate(numbers): if idx != idx2: distance = abs(elem - elem2) if distance < threshold: return True return False
def check(has_close_elements): assert has_close_elements([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True assert has_close_elements([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False assert has_close_elements([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True assert has_close_elements([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False assert has_close_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) == True assert has_close_elements([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True assert has_close_elements([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False check(has_close_elements)
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool:
def check(has_close_elements): assert has_close_elements([1.0, 2.0, 3.0], 0.5) == False assert has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) == True check(has_close_elements)
for idx, elem in enumerate(numbers): for idx2, elem2 in enumerate(numbers): if idx != idx2: distance = elem - elem2 if distance < threshold: return True return False
missing logic
incorrect output
has_close_elements
has_close_elements(numbers: List[float], threshold: float) -> bool
Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True
Write a Python function `has_close_elements(numbers: List[float], threshold: float) -> bool` to solve the following problem: Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True
Rust/0
fn main(){} use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; /* Check if in given list of numbers, are any two numbers closer to each other than given threshold. */ fn has_close_elements(numbers:Vec<f32>, threshold: f32) -> bool{
for i in 0..numbers.len(){ for j in 1..numbers.len(){ if i != j { let distance:f32 = numbers[i] - numbers[j]; if distance.abs() < threshold{ return true; } } } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_has_close_elements() { assert_eq!(has_close_elements(vec![11.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3), true); assert_eq!(has_close_elements(vec![1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05), false); assert_eq!(has_close_elements(vec![1.0, 2.0, 5.9, 4.0, 5.0], 0.95), true); assert_eq!(has_close_elements(vec![1.0, 2.0, 5.9, 4.0, 5.0], 0.8), false); assert_eq!(has_close_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1), true); assert_eq!(has_close_elements(vec![1.1, 2.2, 3.1, 4.1, 5.1], 1.0), true); assert_eq!(has_close_elements(vec![1.1, 2.2, 3.1, 4.1, 5.1], 0.5), false); } }
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn has_close_elements(numbers:Vec<f32>, threshold: f32) -> bool{
None
for i in 0..numbers.len(){ for j in 1..numbers.len(){ if i != j { let distance:f32 = numbers[i] - numbers[j]; if distance < threshold{ return true; } } } } return false; }
missing logic
incorrect output
has_close_elements
has_close_elements(numbers:Vec<f32>, threshold: f32) -> bool
Check if in given list of numbers, are any two numbers closer to each other than given threshold.
Write a Rust function `has_close_elements(numbers:Vec<f32>, threshold: f32) -> bool` to solve the following problem: Check if in given list of numbers, are any two numbers closer to each other than given threshold.