Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,14 @@
"prerequisites": [],
"difficulty": 3
},
{
"slug": "anagram",
"name": "Anagram",
"uuid": "097e1e3b-4118-4c23-ac85-eecb9a4c1cdb",
"practices": [],
"prerequisites": [],
"difficulty": 5
},
{
"slug": "protein-translation",
"name": "Protein Translation",
Expand Down
12 changes: 12 additions & 0 deletions exercises/practice/anagram/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Instructions

Given a target word and one or more candidate words, your task is to find the candidates that are anagrams of the target.

An anagram is a rearrangement of letters to form a new word: for example `"owns"` is an anagram of `"snow"`.
A word is _not_ its own anagram: for example, `"stop"` is not an anagram of `"stop"`.

The target word and candidate words are made up of one or more ASCII alphabetic characters (`A`-`Z` and `a`-`z`).
Lowercase and uppercase characters are equivalent: for example, `"PoTS"` is an anagram of `"sTOp"`, but `"StoP"` is not an anagram of `"sTOp"`.
The words you need to find should be taken from the candidate words, using the same letter case.

Given the target `"stone"` and the candidate words `"stone"`, `"tones"`, `"banana"`, `"tons"`, `"notes"`, and `"Seton"`, the anagram words you need to find are `"tones"`, `"notes"`, and `"Seton"`.
12 changes: 12 additions & 0 deletions exercises/practice/anagram/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Introduction

At a garage sale, you find a lovely vintage typewriter at a bargain price!
Excitedly, you rush home, insert a sheet of paper, and start typing away.
However, your excitement wanes when you examine the output: all words are garbled!
For example, it prints "stop" instead of "post" and "least" instead of "stale."
Carefully, you try again, but now it prints "spot" and "slate."
After some experimentation, you find there is a random delay before each letter is printed, which messes up the order.
You now understand why they sold it for so little money!

You realize this quirk allows you to generate anagrams, which are words formed by rearranging the letters of another word.
Pleased with your finding, you spend the rest of the day generating hundreds of anagrams.
19 changes: 19 additions & 0 deletions exercises/practice/anagram/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"colinleach"
],
"files": {
"solution": [
"anagram.f90"
],
"test": [
"anagram_test.f90"
],
"example": [
".meta/example.f90"
]
},
"blurb": "Find the words that use the same letters as another word.",
"source": "Inspired by the Extreme Startup game",
"source_url": "https://github.com/rchatley/extreme_startup"
}
93 changes: 93 additions & 0 deletions exercises/practice/anagram/.meta/example.f90
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
module anagram
implicit none
private
public :: findAnagrams
contains

function findAnagrams(subject, candidates) result(matches)
character(len=*), intent(in) :: subject
character(len=*), dimension(:), intent(in) :: candidates
character(len=len(candidates)), allocatable :: matches(:)
integer, allocatable :: subject_cps(:), word_cps(:)
logical :: keep(size(candidates))
integer :: i

subject_cps = lower_codepoints(subject)
do i = 1, size(candidates)
word_cps = lower_codepoints(candidates(i))
keep(i) = .false.
if (size(word_cps) /= size(subject_cps)) cycle
! a word is not an anagram of itself
if (all(word_cps == subject_cps)) cycle
keep(i) = all(sorted(word_cps) == sorted(subject_cps))
end do
matches = pack(candidates, keep)
end function

! Decode UTF-8 bytes into lowercased Unicode code points
function lower_codepoints(str) result(cps)
character(len=*), intent(in) :: str
integer, allocatable :: cps(:)
integer :: buffer(len_trim(str))
integer :: i, n, b, cp, extra

n = 0
i = 1
do while (i <= len_trim(str))
b = ichar(str(i:i))
if (b >= 240) then
cp = b - 240
extra = 3
else if (b >= 224) then
cp = b - 224
extra = 2
else if (b >= 192) then
cp = b - 192
extra = 1
else
cp = b
extra = 0
end if
do while (extra > 0 .and. i < len_trim(str))
i = i + 1
cp = cp * 64 + (ichar(str(i:i)) - 128)
extra = extra - 1
end do
n = n + 1
buffer(n) = to_lower(cp)
i = i + 1
end do
cps = buffer(1:n)
end function

! Lowercase ASCII and Greek capital letters
pure integer function to_lower(cp)
integer, intent(in) :: cp

to_lower = cp
if (cp >= 65 .and. cp <= 90) then
to_lower = cp + 32
else if (cp >= 913 .and. cp <= 937 .and. cp /= 930) then
to_lower = cp + 32
end if
end function

! Insertion sort
pure function sorted(arr) result(res)
integer, intent(in) :: arr(:)
integer :: res(size(arr))
integer :: i, j, tmp

res = arr
do i = 2, size(res)
tmp = res(i)
j = i - 1
do while (j >= 1)
if (res(j) <= tmp) exit
res(j + 1) = res(j)
j = j - 1
end do
res(j + 1) = tmp
end do
end function
end module
16 changes: 16 additions & 0 deletions exercises/practice/anagram/.meta/template.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{{ header }}

program {{ name }}_test_main
use TesterMain
use {{ name }}

implicit none
{% for case in cases %}
! Test {{ loop.index }}: {{ case["description"] }}
call assert_equal([character(len=20) :: {% for word in case["expected"] %}"{{ word }}"{{ ", " if not loop.last }}{% endfor %}], &
{{ case["property"] }}("{{ case.input.subject }}", [character(len=20) :: {% for word in case.input.candidates %}"{{ word }}"{{ ", " if not loop.last }}{% endfor %}]), &
"{{ case["description"] }}")
{% endfor %}
call test_report()

end program
86 changes: 86 additions & 0 deletions exercises/practice/anagram/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[dd40c4d2-3c8b-44e5-992a-f42b393ec373]
description = "no matches"

[b3cca662-f50a-489e-ae10-ab8290a09bdc]
description = "detects two anagrams"
include = false

[03eb9bbe-8906-4ea0-84fa-ffe711b52c8b]
description = "detects two anagrams"
reimplements = "b3cca662-f50a-489e-ae10-ab8290a09bdc"

[a27558ee-9ba0-4552-96b1-ecf665b06556]
description = "does not detect anagram subsets"

[64cd4584-fc15-4781-b633-3d814c4941a4]
description = "detects anagram"

[99c91beb-838f-4ccd-b123-935139917283]
description = "detects three anagrams"

[78487770-e258-4e1f-a646-8ece10950d90]
description = "detects multiple anagrams with different case"

[1d0ab8aa-362f-49b7-9902-3d0c668d557b]
description = "does not detect non-anagrams with identical checksum"

[9e632c0b-c0b1-4804-8cc1-e295dea6d8a8]
description = "detects anagrams case-insensitively"

[b248e49f-0905-48d2-9c8d-bd02d8c3e392]
description = "detects anagrams using case-insensitive subject"

[f367325c-78ec-411c-be76-e79047f4bd54]
description = "detects anagrams using case-insensitive possible matches"

[7cc195ad-e3c7-44ee-9fd2-d3c344806a2c]
description = "does not detect an anagram if the original word is repeated"
include = false

[630abb71-a94e-4715-8395-179ec1df9f91]
description = "does not detect an anagram if the original word is repeated"
reimplements = "7cc195ad-e3c7-44ee-9fd2-d3c344806a2c"

[9878a1c9-d6ea-4235-ae51-3ea2befd6842]
description = "anagrams must use all letters exactly once"

[85757361-4535-45fd-ac0e-3810d40debc1]
description = "words are not anagrams of themselves (case-insensitive)"
include = false

[68934ed0-010b-4ef9-857a-20c9012d1ebf]
description = "words are not anagrams of themselves"
reimplements = "85757361-4535-45fd-ac0e-3810d40debc1"

[589384f3-4c8a-4e7d-9edc-51c3e5f0c90e]
description = "words are not anagrams of themselves even if letter case is partially different"
reimplements = "85757361-4535-45fd-ac0e-3810d40debc1"

[ba53e423-7e02-41ee-9ae2-71f91e6d18e6]
description = "words are not anagrams of themselves even if letter case is completely different"
reimplements = "85757361-4535-45fd-ac0e-3810d40debc1"

[a0705568-628c-4b55-9798-82e4acde51ca]
description = "words other than themselves can be anagrams"
include = false

[33d3f67e-fbb9-49d3-a90e-0beb00861da7]
description = "words other than themselves can be anagrams"
reimplements = "a0705568-628c-4b55-9798-82e4acde51ca"

[a6854f66-eec1-4afd-a137-62ef2870c051]
description = "handles case of greek letters"

[fd3509e5-e3ba-409d-ac3d-a9ac84d13296]
description = "different characters may have the same bytes"
71 changes: 71 additions & 0 deletions exercises/practice/anagram/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Get the exercise name from the current directory
get_filename_component(exercise ${CMAKE_CURRENT_SOURCE_DIR} NAME)

# Basic CMake project
cmake_minimum_required(VERSION 3.31.6)

# Name the project after the exercise
project(${exercise} Fortran)

# set debug build default
set(CMAKE_BUILD_TYPE Debug)

# Get a source filename from the exercise name by replacing -'s with _'s
string(REPLACE "-" "_" file ${exercise})

# Activate Fortran compiler warnings
if(CMAKE_Fortran_COMPILER_ID MATCHES "Intel") # Intel fortran
if(WIN32)
add_compile_options(/warn:all)
else()
add_compile_options(-warn all)
endif()
endif()
if(CMAKE_Fortran_COMPILER_ID MATCHES "GNU") # GFortran
add_compile_options(-std=f2008 -W -Wall -Wextra -pedantic -fbacktrace)
endif()

# Configure to run all the tests?
if(${EXERCISM_RUN_ALL_TESTS})
add_definitions(-DEXERCISM_RUN_ALL_TESTS)
set(exercise_f90 ${file}_build_all.f90)
else()
# if building in exercise folder add testlib
set(testlib_path ${CMAKE_CURRENT_SOURCE_DIR}/testlib)
if (NOT EXISTS ${testlib_path})
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../../../testlib) # in git repo locally?
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/../../../testlib DESTINATION ${CMAKE_CURRENT_SOURCE_DIR} PATTERN *)
else() # get from git with http
message("Downloading testlib from https://raw.githubusercontent.com/exercism/fortran/main")
file(MAKE_DIRECTORY ${testlib_path} )
file(DOWNLOAD https://raw.githubusercontent.com/exercism/fortran/main/testlib/TesterMain.f90 ${testlib_path}/TesterMain.f90 SHOW_PROGRESS)
file(DOWNLOAD https://raw.githubusercontent.com/exercism/fortran/main/testlib/CMakeLists.txt ${testlib_path}/CMakeLists.txt SHOW_PROGRESS)
endif()
endif()
# add lib to build
add_subdirectory(testlib)
include_directories(testlib ${CMAKE_CURRENT_BINARY_DIR}/testlib)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}.f90)
set(exercise_f90 ${file}.f90)
endif()
endif()

# Get test_files if exercise needs it
file(GLOB test_files test_files/*.*)
foreach(test_file ${test_files})
message("Copying ${test_file} to binary directory for example ${file}")
configure_file(${test_file} . COPYONLY)
endforeach()

# Build executable from sources and headers
add_executable(${exercise} ${exercise_f90} ${file}_test.f90 )

target_link_libraries(${exercise} TesterMain)

include(CTest)

add_test (${exercise}_test ${exercise} )

# Run the tests on every build
#add_custom_target(test_${exercise} ALL DEPENDS ${exercise} COMMAND ${exercise})

13 changes: 13 additions & 0 deletions exercises/practice/anagram/anagram.f90
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module anagram
implicit none
contains

function findAnagrams(subject, candidates) result(matches)
character(len=*), intent(in) :: subject
character(len=*), dimension(:), intent(in) :: candidates
character(len=len(candidates)), allocatable :: matches(:)

! implement me!
allocate(matches(0))
end function
end module
Loading
Loading