About Codewars

Powers of 2

8 kyu

Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n (inclusive).

Examples

n = 0 ==> [1] # [2^0]

n = 1 ==> [1, 2] # [2^0, 2^1]

n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2]

F#:

let powersOfTwo n = [0..n]|>List.map (fun x -> System.Convert.ToInt32((System.Math.Pow(2.0,(float)x))))

C#:

using System.Numerics;
using System;
public class Kata
{
  public static BigInteger[] PowersOfTwo(int n)
  {
    BigInteger[] res = new BigInteger[n+1]; 
    for(int i = 0;i<=n;++i)
    {
      res[i]=BigInteger.Pow(new BigInteger(2),i);
    }
    return res;
  }
}

JavaScript:

function powersOfTwo(n){
  return new Array(n+1).fill(0).map((el, i) => i).map(x => Math.pow(2,x));
}

Python:

def powers_of_two(n):
    return [2**i for i in range(n+1)]

Multiply

The code does not execute properly. Try to figure out why.

C++:

auto multiply = [](auto a, auto b) {return a * b; };

F#:

let multiply a b = a * b

Python:

multiply = lambda a, b : a * b

C:

int multiply(int a, int b) 
{
  return a*b;
}

C#:

public class CustomMath 
{
    public static int multiply(int a, int b) => a * b;
}

Java:

public class Multiply 
{
    public static Double multiply(Double a, Double b) 
    {
        return a * b;
    }
}

JavaScript:

const multiply = (a, b) => a * b;

PHP:

function multiply($a, $b) 
{
  return $a * $b;
}

PowerShell:

function Multiply($a, $b) 
{
  $a * $b
}

Shell:

#!/bin/bash -e
a=$1
b=$2
echo $((a*b))

Erlang:

-module(bug_fix).
-export([multiply/2]).

-spec multiply(integer(), integer()) -> integer().
multiply(A, B) -> A*B.

Sum of two lowest positive integers

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

F#:

let sumTwoSmallestNumbers numbers = 
    [
        numbers 
        |> Array.sort 
        |> Array.head; 
        numbers 
        |> Array.sort 
        |> Array.tail 
        |> Array.head
    ] 
    |> List.sum

C++:

auto sumTwoSmallestNumbers = [](std::vector<int> numbers)
{
	std::sort(numbers.begin(), numbers.end());
	return (long)numbers[0] + numbers[1];
};

C#:

using System.Linq;
public static class Kata
{
	public static int sumTwoSmallestNumbers(int[] numbers) => numbers.OrderBy(i => i).Take(2).Sum();
}

Playing with digits

Some numbers have funny properties. For example:

89 –> 8¹ + 9² = 89 * 1

695 –> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 –> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd… (a, b, c, d… being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + …) = n * k

If it is the case we will return k, if not return -1.

Note: n, p will always be given as strictly positive integers.

digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1

digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k

digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2

digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

F#:

let digPow n p =
    match (n.ToString().ToCharArray() 
        |> Array.mapi (fun i t -> 
            pown (int64(t.ToString())) (i+p))
        |> Array.sum) with
    | r when r % int64(n) = 0L -> r / int64(n)
    | _ -> -1L

Disemvowel Trolls

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”.

Note: for this kata y isn’t considered a vowel.

F#:

let disemvowel (s:string) = 
    Array.reduce (+) (s.Split([|'a';'e';'i';'o';'u';'A';'E';'I';'O';'U'|]))

JavaScript:

disemvowel = (str) => str.replace(/[aeiouAEIOU]/g,'');

Count the smiley faces!

Description:
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.

Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]

Example cases:

countSmileys([‘:)’, ‘;(‘, ‘;}’, ‘:-D’]); // should return 2;

countSmileys([‘;D’, ‘:-(‘, ‘:-)’, ‘;~)’]); // should return 3;

countSmileys([‘;]’, ‘:[‘, ‘;*’, ‘:$’, ‘;-D’]); // should return 1;

Note: In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same

Happy coding!

JavaScript:

countSmileys = (arr) => arr.filter(i => i.match(/^[:;][-~]?[)D]$/g) != null).length

Is this a triangle?

Implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.

(In this case, all triangles must have surface greater than 0 to be accepted).

JavaScript:

isTriangle = (a,b,c) => (a+b>c&&a+c>b&&b+c>a) ? true : false;

Find the unique number

There is an array with some numbers. All numbers are equal except for one. Try to find it!

findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2

findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55

It’s guaranteed that array contains more than 3 numbers.

The tests contain some very huge arrays, so think about performance.

JavaScript:

findUniq = (arr) => arr.sort()[0] == arr.sort()[1] ? arr.sort()[arr.length - 1] : arr.sort()[0];

Short Long Short

Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length0).

For example:

solution(“1”, “22”) // returns “1221”

solution(“22”, “1”) // returns “1221”

JavaScript:

solution = (a, b) => a.length > b.length ? b + a + b : a + b + a;

getNames()

The following code is not giving the expected results. Can you figure out what the issue is?

The following is an example of data that would be passed in to the function.

var data = [ {name: ‘Joe’, age: 20}, {name: ‘Bill’, age: 30}, {name: ‘Kate’, age: 23} ]

getNames(data) // should return [‘Joe’, ‘Bill’, ‘Kate’]

function getNames(data){
  return data.map((item) => item.name);
}

Esolang Interpreters #1 – Introduction to Esolangs and My First Interpreter (MiniStringFuck)

For the rest of this Kata, I would recommend considering “fuck” to be non-profane.

About this Kata Series

“Esolang Interpreters” is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by @donaldsebleung which all shared a similar format and were all somewhat inter-related. Under the influence of a fellow Codewarrior, these three high-level inter-related Kata gradually evolved into what is known today as the “Esolang Interpreters” series.

This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various esoteric programming languages/Esolangs, mainly Brainfuck derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.

What is an esoteric programming language?

An esoteric programming language, otherwise known as an Esolang, is an informal computer programming language that is generally not designed for serious practical use. There are a few main aims/themes among the vast majority of such languages:

  1. Achieve Turing-completeness in as few commands (instructions) as possible. There are currently a number of implemented Esolangs that have been proven to be Turing-complete, Brainfuck being the most popular of them all, comprised of no more than 8 distinct commands. Despite having only 8 commands, it has been objectively proven to be Turing-complete. However, Brainfuck is not the Turing-complete programming language with the fewest commands. Boolfuck, a derivative of Brainfuck which operates on bits (0s and 1s) and contains 7 commands only, has also been proven to be Turing-complete through reduction from Brainfuck. Another less-known Esolang called Etre contains as few as 3 commands yet has been proven to be Turing-complete through the translation of a Minsky Machine to Etre.
  2. To be as hard to program in as possible. The famous Brainfuck Esolang is well known as a Turing tarpit – that is, a Turing-complete programming language where it is very hard to write a useful program in reality. However, Brainfuck is most definitely not the hardest Esolang to program in. For example, its close cousin, Boolfuck, which operates on bits (mentioned above) is even harder to program in. There have also been a small number of implemented Esolangs which are so difficult to program in that no one has ever successfully written a single program in it from scratch – the only programs generated from these languages came from computers!
  3. As a joke. Many Esolangs out there have been invented solely as a joke. Examples include Ook! and Bitxtreme.

Although there is no clear-cut definition as to when a programming language is esoteric (or not), Esolangs can generally be identified by the following features/traits:

  1. Minimalistic – having as few instructions as possible
  2. Plays with new concepts – for example, Befunge, another very popular Esolang, is interpreted in two dimensions as opposed to the usual linear way of interpreting code
  3. Themed – this is a trait of many joke Esolangs. For example, some may be fashioned like Shakespearean plays and others like cooking recipes
  4. Not clearly documented – Many Esolangs out there have not been described in great detail with perhaps only a few code examples on the entire Internet. Some Esolangs have not even been implemented yet!
  5. Contain incomplete specs – New Esolangs are being invented every day. Some Esolangs on the Internet are still a work-in-progress and their commands and behaviour have not been finalised yet.

Nevertheless, Esolangs are generally fun to program in, experiment with and write interpreters for. A great deal can be learned about certain concepts and theories in Computer Science just by studying and programming in a well-designed Esolang such as Brainfuck or Befunge.

Next off, I will introduce you to a simple, minimalistic Esolang called MiniStringFuck.

The Language

MiniStringFuck is a derivative of the famous Brainfuck which contains a memory cell as its only form of data storage as opposed to a memory tape of 30,000 cells in Brainfuck. The memory cell in MiniStringFuck initially starts at 0. MiniStringFuck contains only 2 commands as opposed to 8:

  • + – Increment the memory cell. If it reaches 256, wrap to 0.
  • . – Output the ASCII value of the memory cell

For example, here is a MiniStringFuck program that outputs the string "Hello, World!":

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.

And here is another program that prints the uppercase English alphabet:

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.

Any characters in a MiniStringFuck program other than + or . are simply non-command characters (no-ops, i.e. do nothing) and therefore can serve as comments in the program.

The Task

Time to write your first Esolang interpreter 😀

Your task is to implement a MiniStringFuck interpreter myFirstInterpreter()/my_first_interpreter()/Interpreter()/interpret() (depending on your language) which accepts exactly 1 required argument code/$code which is the MiniStringFuck program to be executed. The output of the program should then be returned by your interpreter as a string.

Since this is the first time you are about to write an interpreter for an Esolang, here are a few quick tips:

  • If you are afraid that your interpreter will be confused by non-command characters appearing in the MiniStringFuck program, you can try to remove all non-command characters from the code input before letting your interpreter interpret it
  • The memory cell in MiniStringFuck only ever contains a single integer value – think of how it can be modelled in your interpreter
  • If you are stuck as to how to interpret the string as a program, try thinking of strings as an array of characters. Try looping through the “program” like you would an array
  • Writing an interpreter for an Esolang can sometimes be quite confusing! It never hurts to add a few comments in your interpreter as you implement it to remind yourself of what is happening within the interpreter at every stage

NOTE: If you would not like to name your interpreter as myFirstInterpreter()/my_first_interpreter(), you can optionally rename it to either miniStringFuck()/mini_string_fuck() or interpreter() instead – the test cases will handle the rest for you. Not available in Java, Go, Swift, TypeScript, Haskell, Elixir, C++, C#, Rust, R, Erlang, F# and NASMirrelevant to Brainfuck solvers 😉

Good luck 😀

Erlang:

-module(mini_string_fuck).
-export([my_first_interpreter/1]).

my_first_interpreter(Code) ->
    interpreter(Code,0,[]).

interpreter(Code, Value, Output) ->
    case Code of
        [] -> Output;
        [Head | Tail] when Head == 43 -> interpreter(Tail, 
            case Value > 254 of
                true -> 0;
                _ -> Value + 1
            end ,Output);
        [Head | Tail] when Head == 46 -> interpreter(Tail,Value,lists:append(Output,[Value]));
        [_ | Tail] -> interpreter(Tail,Value,Output)
    end.

F#:

let interpret (code: string) =
    let rec inter code value output =
        match code with
        | [] -> output
        | '+'::tail -> inter tail (match value > 254 with | true -> 0 | _ -> value + 1) output
        | '.'::tail -> inter tail value (((string)((char)value))::output)
        | _::tail -> inter tail value output
    (inter (code.ToCharArray() |> List.ofArray) 0 []) |> List.rev |> String.concat ""

PHP in Action #1 – Introduction to Superglobals [Fundamentals]

About this Kata Series

“PHP in Action” is a Kata Series authored by donaldsebleung which is specifically aimed at novice PHP programmers who have learnt the basic syntax and features of the PHP programming language in online courses such as Codecademy but do not know how to apply it in real-world situations. Hence, this Kata Series will focus on the practical aspects of PHP such as sending emails, form validation and setting cookies.

This Kata Series assumes that you have already learnt the fundamentals of PHP such as data types (e.g. strings, numbers, booleans), functions and basic OOP. A good indicator that you are ready for this Kata Series is if you can complete Multiply (8kyu) in PHP and the first four Kata in my Object-Oriented PHP Series without hesitation and without referring to external sources in the process. Since real-world PHP is commonly used in conjunction with HTML and CSS (and sometimes even Javascript), you will also be expected to have a basic understanding of the following programming languages. In certain Kata in this Series where form validation is involved, you may also be expected to be familiar with HTML forms, what attributes they have and how they work.

Lesson

As you may already be aware, each function has its own scope in PHP. What this means is if two separate functions both declared a variable with the exact same name, neither function will be aware that the other function contains a variable with the same name so neither function can affect the variable declared and defined in the other function in any way. This is also true concerning variables in the global scope – PHP code in the global scope cannot alter variables defined in functions and functions cannot alter variables defined in the global scope unless there is an explicit declaration:

$x = 13;
function increment_x() {
  $x++; // Will this increment the global variable $x every time the function is called?  We shall see ;)
}
increment_x();
echo $x; // 13
increment_x();
increment_x();
increment_x();
echo $x; // 13
for ($i = 0; $i < 100; $i++) increment_x();
echo $x; // Still 13

If you would like to remind yourself of how function scope works in PHP, you may want to complete this Kata before proceeding with this Kata.

However, in PHP, there are certain predefined variables that are superglobal. Superglobal variables (or more commonly called superglobals) are special variables that defy the laws of function scope in PHP – they can be accessed from any function in PHP, no matter how deeply nested, without having to explicitly declare them as global in the function. For example:

$GLOBALS['x'] = 1; // $GLOBALS is one of few superglobals in PHP - we will learn more about it later
function increment_x() {
  $GLOBALS['x']++;
}
echo $GLOBALS['x']; // 1
increment_x();
echo $GLOBALS['x']; // 2
increment_x();
increment_x();
increment_x();
echo $GLOBALS['x']; // 5

The following predefined variables in PHP are superglobals (according to W3Schools):

  1. $GLOBALS
  2. $_SERVER
  3. $_REQUEST
  4. $_POST
  5. $_GET
  6. $_FILES
  7. $_ENV
  8. $_COOKIE
  9. $_SESSION

We will learn more about each superglobal mentioned above in later Kata in this Series but for now you must be aware of what $GLOBALS is and what it does. As the name suggests, $GLOBALS is an associative array which contains all of the variables declared and defined in the global scope and the name of each key of the $GLOBALS array corresponds to the name of each global variable itself:

$x = 2;
$y = 5;
$hello_world = "Hello World";
echo $GLOBALS['x']; // 2
echo $GLOBALS['y']; // 5
echo $GLOBALS['hello_world']l // "Hello World"

The superglobal nature of $GLOBALS means that functions can directly access variables in the global scope via the $GLOBALSsuperglobal instead of declaring certain variables global before using it:

// This ... 
function increment_global_x() {
  global $x;
  $x++;
}

// ... is the same as this
function increment_global_x() {
  $GLOBALS['x']++;
}

Strictly speaking, directly accessing global variables using the superglobal $GLOBALS is not identical to accessing global variables by declaring it global in the function and then using it because by using $GLOBALS one can still declare/define a local variable with the same name within the function.

Task

Note: The lesson provided in this Kata is designed to teach you most, if not all, of the key concepts required to complete the Task in this Kata. However, if in doubt, you are strongly encouraged to conduct your own research.

Using your knowledge of superglobals, declare and define the following functions as instructed:

  1. double_global_num() – This function should receive no arguments and double the value of the global variable $num, preferably through accessing the superglobal $GLOBALS.
  2. set_query() – This function should receive an argument $query and set $_GET['query'] equal to $query.
  3. set_email() – This function should receive an argument $email and set $_POST['email'] equal to $email.

PHP:

function double_global_num() {
  $GLOBALS['num'] *= 2;
}
function set_query($query) {
  $_GET['query'] = $query;
}
function set_email($email) {
  $_POST['email'] = $email;
}

Reflection in PHP #1 – Introduction

About this Kata Series

This Kata Series explores a core API in PHP called Reflection which allows a developer to reverse-engineer classes, interfaces, functions, methods and extensions. It is assumed that the user undertaking this Kata Series is already familiar with both functional and object-oriented programming in PHP. A good indicator that you are ready for this Kata Series is if you are able to complete at least 6 out of 8 topics/Kata in my PHP Functions series without hesitation and are at least moderately familiar with all the topics covered in the first 7 Kata in my Object-Oriented PHP series. Certain Kata in this Series may also require slightly more advanced OOP knowledge such as the awareness of what an interface is, but if such extra knowledge is required, it will be mentioned under a “Prerequisites” subtitle.

Most Kata in this Series will consist of two main parts – a “Lesson” and a “Task”. However, unlike either of “Object-Oriented PHP” and “PHP Functions”, the “Lesson” will only teach the fundamental concepts required to understand the “Task” presented in each Kata. In most cases, you will be expected to look up on the official Reflection documentation in order to figure out the details of how to actually complete the Kata “Task” (e.g. which methods to call or even what class to use!). If you are still in doubt after referring to the official documentation, you are strongly encouraged to conduct your own research and use whatever resources are available to you on the Internet or otherwise.

Lesson

What is Reflection?

Reflection is a core API in the PHP language which means no extra installation is required (other than the PHP language itself). As its name suggests, it provides a useful way for developers to extract information on classes, interfaces, functions, methods and extensions through reverse-engineering. The Reflection API in PHP does not exist as a single function or class; rather, it exists as a set of classes whose names all start with Reflection and the term following it indicates what type of structure it is able to “reflect”. For example, ReflectionFunction can provide information about the selected function(s) (covered in this lesson), ReflectionClass can provide information on the selected class(es), ReflectionParameter information on (function/method) parameters and so on.

How is it useful?

It can possibly be used by developers to either check their own code or the code of other developers. For example, you may have wondered how Codecademy checks that the bark() method you defined in your Dog class is static and not just any ordinary public method. Is it through try/catch blocks? Through attempting to directly invoke Dog::bark() (mind you, even non-static methods of classes can be directly invoked like that)? The most likely thing they did in that Lesson to check for your static method (not saying that this is the way they did it!) is through Reflection (ReflectionClass and ReflectionMethod to be precise).

However, in a Codewars context, it gets even more exciting. Once you learn how to properly use Reflection in PHP, you can utilise Reflection in your PHP test cases to detect whether a user has cheated by changing the original function signature, for example. If you’ve completed most of my Kata in my “PHP Functions” and/or “Object-Oriented PHP” series and have taken a sneak peek at my test cases after completion, you would have probably noticed that I have used Reflection in some of my Kata.

ReflectionFunction

ReflectionFunction is a class that allows you to extract information about certain functions, whether internal or user-defined. It has a class constructor that receives exactly one argument which can either be the name of the function in the form of a string (if it is a named function) or the function itself (if it is a closure). Once you create an instance of ReflectionFunctionby passing the (name of the) function into the class constructor, you can then call its methods to extract useful information about it. For example, given a function multiply():

function multiply($a, $b) {
  return $a * $b;
}

… we can obtain information about this function by instantiating an instance of ReflectionFunction with 'multiply' as argument:

$multiply = new ReflectionFunction('multiply');

… and call on its getName() method to get its name (which, in this case, would of course be just 'multiply'):

echo $multiply->getName(); // 'multiply'

Before we move onto our Task, you will find the official documentation on ReflectionFunction useful. To find more information about a particular property, method or constant of this class, simply click on the name of said property/method/constant and it will link you to a page which explains that property/method/constant in detail.

Task

While we get familiar with reading and understanding the official Reflection documentation on php.net, let’s start with something simple by practicing how to call different methods of the ReflectionFunction class in order to learn a bit about our function(s). Write a function get_info() which accepts exactly 1 argument $fn which could either be the name of a named function (as a string) or the actual function itself (if it is a closure). Your function should then return a non-associative array with the following elements (in the given order):

  1. The total number of parameters of the function as an integer. You may assume that all functions (or their names) passed into your function has a fixed amount of parameters.
  2. The total number of required parameters of the function (i.e. those without a default value) as an integer. Again, you may assume that this is always fixed and finite.
  3. A boolean specifying whether the function has declared a return type.
  4. A boolean specifying whether the function is a closure.
  5. A boolean specifying whether the function is internal (i.e. not user-defined)
  6. A boolean specifying whether the function is user-defined (i.e. not part of PHP itself).

For example, for the multiply function in our “Lesson”, your function should produce the following output:

[2, 2, false, false, false, true]

This test case has been included for you.

PHP:

function get_info($fn)
{
    $r = new ReflectionFunction($fn);
    return [$r->getNumberOfParameters(),
        $r->getNumberOfRequiredParameters(),
        $r->hasReturnType(),
        $r->isClosure(),
        $r->isInternal(),
        $r->isUserDefined()];
}

Is a number prime?

Is Prime

Define a function isPrime/is_prime() that takes one integer argument and returns true/True or false/Falsedepending on if the integer is a prime.

Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Example

Assumptions

  • You can assume you will be given an integer input.
  • You can not assume that the integer will be only positive. You may be given negative numbers as well (or 0).

NASM:

global is_prime

section .text

is_prime:
    cmp edi, 1
    jle false
    cmp edi, 2
    je true
    mov ebx, 2
    jmp forif
for:
    mov eax, edi
    cdq
    idiv ebx
    mov eax, edx
    test eax, eax
    jne forloop
    jmp false
forloop:
    inc ebx
forif:
    mov eax, edi
    mov edx, eax
    shr edx, 0x1f
    add eax, edx
    sar eax, 1
    cmp ebx, eax
    jle for
true:
    mov eax, 1
    ret
false:
    mov eax, 0
    ret

Return Negative

In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?

Example:

makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0

Notes:

  • The number can be negative already, in which case no change is required.
  • Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.

NASM:

SECTION .text
global make_negative

make_negative: 
    mov eax, edi
    cdq
    mov eax, edx
    xor eax, edi
    sub eax, edx
    neg eax
    ret

Opposite number

Very simple, given a number, find its opposite.

Examples:

1: -1
14: -14
-34: 34

NASM:

SECTION .text
global opposite

opposite:
  mov eax, edi
  neg eax
  ret

Simple Fun #74: Growing Plant

Task

Each day a plant is growing by upSpeed meters. Each night that plant’s height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.

Example

For upSpeed = 100, downSpeed = 10 and desiredHeight = 910, the output should be 10.

 After day 1 --> 100
 After night 1 --> 90
 After day 2 --> 190
 After night 2 --> 180
 After day 3 --> 280
 After night 3 --> 270
 After day 4 --> 370
 After night 4 --> 360
 After day 5 --> 460
 After night 5 --> 450
 After day 6 --> 550
 After night 6 --> 540
 After day 7 --> 640
 After night 7 --> 630
 After day 8 --> 730
 After night 8 --> 720
 After day 9 --> 820
 After night 9 --> 810
 After day 10 --> 910 

For upSpeed = 10, downSpeed = 9 and desiredHeight = 4, the output should be 1.

Because the plant reach to the desired height at day 1(10 meters).

 After day 1 --> 10

Input/Output

  • [input] integer upSpeedA positive integer representing the daily growth.Constraints: 5 ≤ upSpeed ≤ 100.
  • [input] integer downSpeedA positive integer representing the nightly decline.Constraints: 2 ≤ downSpeed < upSpeed.
  • [input] integer desiredHeightA positive integer representing the threshold.Constraints: 4 ≤ desiredHeight ≤ 1000.
  • [output] an integerThe number of days that it will take for the plant to reach/pass desiredHeight (including the last day in the total count).

NASM:

section .text
global growingPlant
growingPlant:
    mov rax, 1
    mov rbx, 0
.loop:
    add rbx, rdi
    cmp rbx, rdx
    jae .end
    sub rbx, rsi
    inc rax
    cmp rbx, rdx
    jbe .loop
.end:
    ret

Collision Detection

Create a function to determine whether or not two circles are colliding. You will be given the position of both circles in addition to their radii:

function collision(x1, y1, radius1, x2, y2, radius2) {
  // collision?
}

If a collision is detected, return true. If not, return false.

Here’s a geometric diagram of what the circles passed in represent:

alt text

NASM:

global is_collision
section .text
is_collision:
    mov rax, 0
    subss xmm0, xmm3
    subss xmm1, xmm4
    mulss xmm0, xmm0
    mulss xmm1, xmm1
    addss xmm0, xmm1
    addss xmm2, xmm5
    mulss xmm2, xmm2
    comiss xmm0, xmm2
    jae .end 
    mov rax, 1
.end:
    ret

Is It Negative Zero (-0)?

There exist two zeroes: +0 (or just 0) and -0.

Write a function that returns true if the input number is -0 and false otherwise (True and False for Python).

In JavaScript / TypeScript / Coffeescript the input will be a number.

In Python / Java / C / NASM / Haskell the input will be a float.

NASM

SECTION .TEXT
global isNegativeZero
isNegativeZero:
    movd edx, xmm0
    mov rax, 0
    cmp edx, 0x80000000
    jne .end 
    mov rax, 1
.end:
    ret

Ones and Zeros

Given an array of one’s and zero’s convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11

However, the arrays can have varying lengths, not just limited to 4.

NASM

SECTION .text
global binary_array_to_number
binary_array_to_number:
    mov edx, 0
    mov eax, 0
.loop:
    shl eax, 1
    add eax, [rdi + rdx]
    add edx, 4
    dec esi
    cmp esi, 0
    jne .loop
.end:
    ret

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注