Skip to content

Instantly share code, notes, and snippets.

@karlosmid
Last active October 23, 2020 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlosmid/70febbb783ab4ba339e70fc56b6b22c2 to your computer and use it in GitHub Desktop.
Save karlosmid/70febbb783ab4ba339e70fc56b6b22c2 to your computer and use it in GitHub Desktop.
Introduction to software testing section 1.2
defmodule IntroToSoftwareTesting.FaultyPrograms do
@moduledoc """
Supports exercises from the book Introduction To Sofware Testing, section 1.2
"""
@doc """
findLast returns index of last element in x list that is equal to y.
If there is no such element, returns -1
"""
@doc """
findLast returns index of last element in x list that is equal to y.
If there is no such element, returns -1
"""
@spec findLast(list(), integer()) :: integer()
def findLast(x, y), do: findLastRecursive(x, y, 0, -1)
defp findLastRecursive([], _y, _index, result), do: result
defp findLastRecursive([head | tail], y, index, _result) when head == y, do: findLastRecursive(tail, y, index + 1, index)
defp findLastRecursive([head | tail], y, index, result), do: findLastRecursive(tail, y, index + 1, result)
@doc """
lastZero returns index of last zero element in x.
If there is no such element, returns -1
"""
@spec lastZero(list()) :: integer()
def lastZero(x), do: lastZeroRecursive(x, 0)
defp lastZeroRecursive([], _index), do: -1
defp lastZeroRecursive([head | _tail] = _x, index) when head == 0, do: index
defp lastZeroRecursive([_head | tail] = _x, index), do: lastZeroRecursive(tail, index + 1)
@doc """
countPositive returns number of positive elements in x.
"""
@spec countPositive(list()) :: integer()
def countPositive(x), do: countPositiveRecursive(x, 0)
defp countPositiveRecursive([], count), do: count
defp countPositiveRecursive([head | tail] = _x, count) when head >= 0, do: countPositiveRecursive(tail, count + 1)
defp countPositiveRecursive([_head | tail] = _x, count), do: countPositiveRecursive(tail, count)
@doc """
countOddOrPositive returns number of odd or positive elements in x.
"""
@spec countOddOrPositive(list()) :: integer()
def countOddOrPositive(x), do: countOddOrPositiveRecursive(x, 0)
defp countOddOrPositiveRecursive([], count), do: count
defp countOddOrPositiveRecursive([head | tail] = _x, count) when head >= 0 or rem(head,2) == 1, do: countOddOrPositiveRecursive(tail, count + 1)
defp countOddOrPositiveRecursive([_head | tail] = _x, count), do: countOddOrPositiveRecursive(tail, count)
end
@karlosmid
Copy link
Author

1. Install Elixir with Erlang
2. download faulty programs
3. in same folder run iex --erl "-kernel shell_history enabled"
4. from iex run c "faulty_programs.ex"
5. run functions with full module namespaces, e.g. IntroToSoftwareTesting.FaultyPrograms.countOddOrPositive([-3,-2,0,1,"a"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment