ABC problem: Difference between revisions

26,375 bytes added ,  2 months ago
Add ABC
m (syntax highlighting fixup automation)
(Add ABC)
 
(43 intermediate revisions by 25 users not shown)
Line 44:
 
;Example:
<syntaxhighlight lang="python"> >>> can_make_word("A")
True
>>> can_make_word("BARK")
Line 64:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F can_make_word(word)
I word == ‘’
R 0B
Line 83:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<syntaxhighlight lang="360asm">* ABC Problem 21/07/2016
ABC CSECT
USING ABC,R13 base register
Line 171:
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm"> org 100h
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 263:
{{trans|8080 Assembly}}
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 338:
 
=={{header|8th}}==
<syntaxhighlight lang="360asm">
\ ========================================================================================
\ You are given a collection of ABC blocks
Line 540:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program problemABC64.s */
Line 747:
</pre>
=={{header|ABAP}}==
<syntaxhighlight lang=ABAP"abap">
REPORT z_rosetta_abc.
 
Line 831:
True
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO REPORT word can.be.made.with blocks:
FOR letter IN upper word:
IF NO block IN blocks HAS letter in block: FAIL
REMOVE block FROM blocks
SUCCEED
 
PUT {"BO";"XK";"DQ";"CP";"NA";"GT";"RE";"TG";"QD";"FS"} IN blocks
PUT {"JW";"HU";"VI";"AN";"OB";"ER";"FS";"LY";"PC";"ZM"} IN blocks2
FOR block IN blocks2: INSERT block IN blocks
 
PUT {"A";"BARK";"BOOK";"treat";"common";"Squad";"CoNfUsE"} IN words
 
FOR word IN words:
WRITE word, ": "
SELECT:
word can.be.made.with blocks: WRITE "yes"/
ELSE: WRITE "no"/</syntaxhighlight>
{{out}}
<pre>A: yes
BARK: yes
BOOK: no
CoNfUsE: yes
Squad: yes
common: no
treat: yes</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">DEFINE COUNT="20"
CHAR ARRAY sideA="BXDCNGRTQFJHVAOEFLPZ"
CHAR ARRAY sideB="OKQPATEGDSWUINBRSYCM"
Line 906 ⟶ 933:
Using #HASH-OFF
</pre>
<syntaxhighlight lang="acurity architect">
FUNCTION bCAN_MAKE_WORD(zWord: STRING): BOOLEAN
VAR sBlockCount: SHORT
Line 950 ⟶ 977:
</pre>
 
<syntaxhighlight lang="ada">with Ada.Characters.Handling;
use Ada.Characters.Handling;
 
Line 1,043 ⟶ 1,070:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<syntaxhighlight lang="algol68"># determine whether we can spell words with a set of blocks #
 
# construct the list of blocks #
Line 1,136 ⟶ 1,163:
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">% determine whether we can spell words with a set of blocks %
begin
% Returns true if we can spell the word using the blocks, %
Line 1,229 ⟶ 1,256:
 
=={{header|Apex}}==
<syntaxhighlight lang=Java"java">static Boolean canMakeWord(List<String> src_blocks, String word) {
if (String.isEmpty(word)) {
return true;
Line 1,286 ⟶ 1,313:
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
<syntaxhighlight lang=APL"apl">abc←{{0=⍴⍵:1 ⋄ 0=⍴h←⊃⍵:0 ⋄ ∇(t←1↓⍵)~¨⊃h:1 ⋄ ∇(⊂1↓h),t}⍸¨↓⍵∘.∊⍺}</syntaxhighlight>
{{out}}
<pre> )COPY dfns ucase
Line 1,296 ⟶ 1,323:
=={{header|AppleScript}}==
===Imperative===
<syntaxhighlight lang=AppleScript"applescript">set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", ¬
"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"}
 
Line 1,324 ⟶ 1,351:
return false
end canMakeWordWithBlocks</syntaxhighlight>
----
An alternative version of the above, avoiding list-coercion and case vulnerabilities and unnecessary extra lists and substrings. Also observing the task's third rule!
 
<syntaxhighlight lang="applescript">on canMakeWordWithBlocks(theString, theBlocks)
set stringLen to (count theString)
copy theBlocks to theBlocks
script o
on cmw(c, theBlocks)
set i to 1
repeat until (i > (count theBlocks))
if (character c of theString is in item i of theBlocks) then
if (c = stringLen) then return true
set item i of theBlocks to missing value
set theBlocks to text of theBlocks
if (cmw(c + 1, theBlocks)) then return true
end if
set i to i + 1
end repeat
return false
end cmw
end script
ignoring case -- Make the default case insensitivity explicit.
return ((theString = "") or (o's cmw(1, theBlocks)))
end ignoring
end canMakeWordWithBlocks
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set blocks to {"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", ¬
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"}
set output to {}
repeat with testWord in {"a", "bark", "book", "treat", "common", "squad", "confuse"}
set end of output to "Can make “" & testWord & "”: " & ¬
canMakeWordWithBlocks(testWord's contents, blocks)
end repeat
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"Can make “a”: true
Can make “bark”: true
Can make “book”: false
Can make “treat”: true
Can make “common”: false
Can make “squad”: true
Can make “confuse”: true"</syntaxhighlight>
----
 
===Functional===
<syntaxhighlight lang=AppleScript"applescript">use AppleScript version "2.4"
use framework "Foundation"
 
Line 1,534 ⟶ 1,619:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program problemABC.s */
Line 1,737 ⟶ 1,822:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">blocks: map [
[B O] [X K] [D Q] [C P] [N A] [G T] [R E]
[T G] [Q D] [F S] [J W] [H U] [V I] [A N]
Line 1,773 ⟶ 1,858:
 
=={{header|Astro}}==
<syntaxhighlight lang="python">fun abc(s, ls):
if ls.isempty:
return true
Line 1,789 ⟶ 1,874:
 
'''Function'''
<syntaxhighlight lang="autohotkey">isWordPossible(blocks, word){
o := {}
loop, parse, blocks, `n, `r
Line 1,815 ⟶ 1,900:
 
'''Test Input''' (as per question)
<syntaxhighlight lang="autohotkey">blocks := "
(
BO
Line 2,012 ⟶ 2,097:
 
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">CONST info$ = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
 
DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
Line 2,049 ⟶ 2,134:
=={{header|BASIC}}==
Works with:VB-DOS, QB64, QBasic, QuickBASIC
<syntaxhighlight lang="qbasic">
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ABC_Problem '
Line 2,179 ⟶ 2,264:
==={{header|Commodore BASIC}}===
{{trans|Sinclair ZX-81 BASIC}}
<syntaxhighlight lang="basic">10 W$ = "A" : GOSUB 100
20 W$ = "BARK" : GOSUB 100
30 W$ = "BOOK" : GOSUB 100
Line 2,216 ⟶ 2,301:
The above greedy algorithm works on the sample data, but fails on other data - for example, it will declare that you cannot spell the word ABBA using the blocks (AB),(AB),(AC),(AC), because it will use the two AB blocks for the first two letters "AB", leaving none for the second "B". This recursive solution is more thorough about confirming negatives and handles that case correctly:
 
<syntaxhighlight lang="basic">100 REM RECURSIVE SOLUTION
110 MS=100:REM MAX STACK DEPTH
120 DIM BL$(MS):REM BLOCKS LEFT
Line 2,277 ⟶ 2,362:
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. A nice unstructured algorithm. Unfortunately the requirement that it be case-insensitive is moot, because the ZX81 does not support lower-case letters.
<syntaxhighlight lang="basic"> 10 LET B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
20 INPUT W$
30 FOR I=1 TO LEN W$
Line 2,316 ⟶ 2,401:
{{out}}
<pre>YES</pre>
 
=={{header|BASIC256}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">arraybase 1
blocks$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
b = int((length(blocks$) /3) + 1)
dim blk$(b)
 
for i = 1 to length(makeWord$)
wrd$ = word$(makeWord$,i,",")
dim hit(b)
n = 0
if wrd$ = "" then exit for
for k = 1 to length(wrd$)
w$ = upper(mid(wrd$,k,1))
for j = 1 to b
if hit[j] = 0 then
if w$ = left(word$(blocks$,j,","),1) or w$ = right(word$(blocks$,j,","),1) then
hit[j] = 1
n += 1
exit for
end if
end if
next j
next k
print wrd$; chr(9);
if n = length(wrd$) then print " True" else print " False"
next i
end
 
function word$(sr$, wn, delim$)
j = wn
if j = 0 then j += 1
res$ = "" : s$ = sr$ : d$ = delim$
if d$ = "" then d$ = " "
sd = length(d$) : sl = length(s$)
while true
n = instr(s$,d$) : j -= 1
if j = 0 then
if n = 0 then res$ = s$ else res$ = mid(s$,1,n-1)
return res$
end if
if n = 0 then return res$
if n = sl - sd then res$ = "" : return res$
sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2
end while
return res$
end function</syntaxhighlight>
{{out}}
<pre>Same as Run BASIC entry.</pre>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
::abc.bat
Line 2,385 ⟶ 2,521:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> BLOCKS$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
PROCcan_make_word("A")
PROCcan_make_word("BARK")
Line 2,419 ⟶ 2,555:
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let canMakeWord(word) = valof
Line 2,466 ⟶ 2,602:
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">ABC ← {
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
Line 2,494 ⟶ 2,630:
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">(
( can-make-word
= ABC blocks
Line 2,553 ⟶ 2,689:
=={{header|C}}==
Recursive solution. Empty string returns true.
<syntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
 
Line 2,610 ⟶ 2,746:
This Method uses regular expressions to do the checking. Given that n = length of blocks string and
m = length of word string, then CheckWord's time complexity comes out to about m*(n - (m-1)/2).
<syntaxhighlight lang="csharp">using System;
using System.IO;
// Needed for the method.
Line 2,652 ⟶ 2,788:
</pre>
'''Unoptimized'''
<syntaxhighlight lang="csharp">using System.Collections.Generic;
using System.Linq;
 
Line 2,748 ⟶ 2,884:
{{Works with|C++11}}
Build with:
<syntaxhighlight lang="sh">g++-4.7 -Wall -std=c++0x abc.cpp</syntaxhighlight>
<syntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <string>
Line 2,799 ⟶ 2,935:
<b>module.ceylon</b>
 
<syntaxhighlight lang="ceylon">
module rosetta.abc "1.0.0" {}
</syntaxhighlight>
Line 2,805 ⟶ 2,941:
<b>run.ceylon</b>
 
<syntaxhighlight lang="ceylon">
shared void run() {
printAndCanMakeWord("A", blocks);
Line 2,895 ⟶ 3,031:
=={{header|Clojure}}==
A translation of the Haskell solution.
<syntaxhighlight lang="clojure">
(def blocks
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
Line 2,928 ⟶ 3,064:
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">ucase = proc (s: string) returns (string)
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
Line 2,982 ⟶ 3,118:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang=CoffeeScript"coffeescript">blockList = [ 'BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS', 'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM' ]
 
canMakeWord = (word="") ->
Line 3,012 ⟶ 3,148:
 
=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 FUNC can'make'word#(word$) CLOSED
0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
0030 FOR i#:=1 TO LEN(word$) DO
Line 3,041 ⟶ 3,177:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun word-possible-p (word blocks)
(cond
Line 3,077 ⟶ 3,213:
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<syntaxhighlight lang="oberon2">
MODULE ABCProblem;
IMPORT
Line 3,176 ⟶ 3,312:
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
Line 3,235 ⟶ 3,371:
{{trans|Python}}
A simple greedy algorithm is enough for the given sequence of blocks. canMakeWord is true on an empty word because you can compose it using zero blocks.
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.string;
 
bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
Line 3,269 ⟶ 3,405:
===@nogc Version===
The same as the precedent version, but it avoids all heap allocations and it's lower-level and ASCII-only.
<syntaxhighlight lang="d">import std.ascii, core.stdc.stdlib;
 
bool canMakeWord(in string word, in string[] blocks) nothrow @nogc
Line 3,312 ⟶ 3,448:
This version is able to find the solution for the word "abba" given the blocks AB AB AC AC.
{{trans|C}}
<syntaxhighlight lang="d">import std.stdio, std.ascii, std.algorithm, std.array;
 
alias Block = char[2];
Line 3,363 ⟶ 3,499:
===Alternative Recursive Version===
This version doesn't shuffle the input blocks, but it's more complex and it allocates an array of indexes.
<syntaxhighlight lang="d">import std.stdio, std.ascii, std.algorithm, std.array, std.range;
 
alias Block = char[2];
Line 3,409 ⟶ 3,545:
=={{header|Delphi}}==
Just to be different I implemented a block as a set of (2) char rather than as an array of (2) char.
<syntaxhighlight lang=Delphi"delphi">program ABC;
{$APPTYPE CONSOLE}
 
Line 3,486 ⟶ 3,622:
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">\util.g
 
proc nonrec ucase(char c) char:
Line 3,552 ⟶ 3,688:
{{trans|Swift}}
 
<syntaxhighlight lang="dyalect">func blockable(str) {
var blocks = [
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
Line 3,588 ⟶ 3,724:
"sQuAd" can be spelled with blocks.
"Confuse" can be spelled with blocks.</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
b$[][] = [ [ "B" "O" ] [ "X" "K" ] [ "D" "Q" ] [ "C" "P" ] [ "N" "A" ] [ "G" "T" ] [ "R" "E" ] [ "T" "G" ] [ "Q" "D" ] [ "F" "S" ] [ "J" "W" ] [ "H" "U" ] [ "V" "I" ] [ "A" "N" ] [ "O" "B" ] [ "E" "R" ] [ "F" "S" ] [ "L" "Y" ] [ "P" "C" ] [ "Z" "M" ] ]
len b[] len b$[][]
global w$[] cnt .
#
proc backtr wi . .
if wi > len w$[]
cnt += 1
return
.
for i = 1 to len b$[][]
if b[i] = 0 and (b$[i][1] = w$[wi] or b$[i][2] = w$[wi])
b[i] = 1
backtr wi + 1
b[i] = 0
.
.
.
for s$ in [ "A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE" ]
w$[] = strchars s$
cnt = 0
backtr 1
print s$ & " can be spelled in " & cnt & " ways"
.
</syntaxhighlight>
 
{{out}}
<pre>
A can be spelled in 2 ways
BARK can be spelled in 8 ways
BOOK can be spelled in 0 ways
TREAT can be spelled in 8 ways
COMMON can be spelled in 0 ways
SQUAD can be spelled in 8 ways
CONFUSE can be spelled in 32 ways
</pre>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'list) ;; list-delete
 
Line 3,626 ⟶ 3,800:
=={{header|Ela}}==
{{trans|Haskell}}
<syntaxhighlight lang="ela">open list monad io char
 
:::IO
Line 3,655 ⟶ 3,829:
 
=={{header|Elena}}==
ELENA 56.0
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
import system'culture;
import extensions;
import extensions'routines;
Line 3,667 ⟶ 3,842:
var list := ArrayList.load(blocks);
^ nil == (cast string(self)).upperCasetoUpper().seekEach::(ch)
{
var index := list.indexOfElement
Line 3,696 ⟶ 3,871:
e.next();
words.forEach::(word)
{
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
Line 3,716 ⟶ 3,891:
{{trans|Erlang}}
{{works with|Elixir|1.3}}
<syntaxhighlight lang="elixir">defmodule ABC do
def can_make_word(word, avail) do
can_make_word(String.upcase(word) |> to_charlist, avail, [])
Line 3,742 ⟶ 3,917:
Squad: true
Confuse: true
</pre>
 
=={{header|Elm}}==
{{works with|Elm|0.19.1}}
<syntaxhighlight lang="elm">
import Html exposing (div, p, text)
 
 
type alias Block = (Char, Char)
 
 
writtenWithBlock : Char -> Block -> Bool
writtenWithBlock letter (firstLetter, secondLetter) =
letter == firstLetter || letter == secondLetter
 
 
canMakeWord : List Block -> String -> Bool
canMakeWord blocks word =
let
checkWord w examinedBlocks blocksToExamine =
case (String.uncons w, blocksToExamine) of
(Nothing, _) -> True
(Just _, []) -> False
(Just (firstLetter, restOfWord), firstBlock::restOfBlocks) ->
if writtenWithBlock firstLetter firstBlock
then checkWord restOfWord [] (examinedBlocks ++ restOfBlocks)
else checkWord w (firstBlock::examinedBlocks) restOfBlocks
in
checkWord (String.toUpper word) [] blocks
exampleBlocks =
[ ('B', 'O')
, ('X', 'K')
, ('D', 'Q')
, ('C', 'P')
, ('N', 'A')
, ('G', 'T')
, ('R', 'E')
, ('T', 'G')
, ('Q', 'D')
, ('F', 'S')
, ('J', 'W')
, ('H', 'U')
, ('V', 'I')
, ('A', 'N')
, ('O', 'B')
, ('E', 'R')
, ('F', 'S')
, ('L', 'Y')
, ('P', 'C')
, ('Z', 'M')
]
 
exampleWords =
["", "A", "bark", "BoOK", "TrEAT", "COmMoN", "Squad", "conFUsE"]
 
 
main =
let resultStr (word, canBeWritten) = "\"" ++ word ++ "\"" ++ ": " ++ if canBeWritten then "True" else "False" in
List.map (\ word -> (word, canMakeWord exampleBlocks word) |> resultStr) exampleWords
|> List.map (\result -> p [] [ text result ])
|> div []
</syntaxhighlight>
 
{{out}}
<pre>
"": True
 
"A": True
 
"bark": True
 
"BoOK": False
 
"TrEAT": True
 
"COmMoN": False
 
"Squad": True
 
"conFUsE": True
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">-module(abc).
-export([can_make_word/1, can_make_word/2, blocks/0]).
 
Line 3,774 ⟶ 4,032:
 
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE"erre">
PROGRAM BLOCKS
 
Line 3,807 ⟶ 4,065:
=={{header|Euphoria}}==
implemented using OpenEuphoria
<syntaxhighlight lang=Euphoria"euphoria">
include std/text.e
 
Line 3,859 ⟶ 4,117:
=={{header|F_Sharp|F#}}==
<p>This solution does not depend on the order of the blocks, neither on the symmetry of blocks we see in the example block set. (Symmetry: if AB is a block, an A comes only with another AB|BA)</p>
<syntaxhighlight lang="fsharp">let rec spell_word_with blocks w =
let rec look_for_right_candidate candidates noCandidates c rest =
match candidates with
Line 3,904 ⟶ 4,162:
h:\RosettaCode\ABC\Fsharp>RosettaCode "US TZ AO QA" Auto
Using the blocks we can make the word 'AUTO': true</pre>
 
{{trans|OCaml}}
<syntaxhighlight lang="fsharp">
let blocks = [
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
('Q', 'D'); ('F', 'S'); ('J', 'W'); ('H', 'U');
('V', 'I'); ('A', 'N'); ('O', 'B'); ('E', 'R');
('F', 'S'); ('L', 'Y'); ('P', 'C'); ('Z', 'M');
]
 
let find_letter blocks c =
let found, remaining =
List.partition (fun (c1, c2) -> c1 = c || c2 = c) blocks
in
match found with
| _ :: res -> Some (res @ remaining)
| _ -> None
 
let can_make_word w =
let n = String.length w in
let rec aux i _blocks =
if i >= n then true else
match find_letter _blocks w.[i] with
| None -> false
| Some rem_blocks ->
aux (i+1) rem_blocks
in
aux 0 blocks
 
let test label f (word, should) =
printfn "- %s %s = %A (should: %A)" label word (f word) should
 
let () =
List.iter (test "can make word" can_make_word) [
"A", true;
"BARK", true;
"BOOK", false;
"TREAT", true;
"COMMON", false;
"SQUAD", true;
"CONFUSE", true;
]
</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: assocs combinators.short-circuit formatting grouping io
kernel math math.statistics qw sequences sets unicode ;
IN: rosetta-code.abc-problem
Line 3,972 ⟶ 4,274:
=={{header|FBSL}}==
This approach uses a string, blanking out the pair previously found. Probably faster than array manipulation.
<syntaxhighlight lang="qbasic">
#APPTYPE CONSOLE
SUB MAIN()
Line 4,037 ⟶ 4,339:
{{works with|gforth|0.7.3}}
 
<syntaxhighlight lang="forth">: blockslist s" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" ;
variable blocks
: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;
Line 4,081 ⟶ 4,383:
=={{header|Fortran}}==
Attempts to write the word read from unit 5. Please find the output, bash command, and gfortran compilation instructions as commentary at the start of the source, which starts right away!
<syntaxhighlight lang=Fortran"fortran">!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Thu Jun 5 01:52:03
!
Line 4,158 ⟶ 4,460:
 
The following source begins with some support routines. Subroutine PLAY inspects the collection of blocks to make various remarks, and function CANBLOCK reports on whether a word can be spelled out with the supplied blocks. The source requires only a few of the F90 features. The MODULE protocol eases communication, but the key feature is that subprograms can now declare arrays of a size determined on entry via parameters. Previously, a constant with the largest-possible size would be required.
<syntaxhighlight lang=Fortran"fortran">
MODULE PLAYPEN !Messes with a set of alphabet blocks.
INTEGER MSG !Output unit number.
Line 4,461 ⟶ 4,763:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 28-01-2019
' compile with: fbc -s console
 
Line 4,515 ⟶ 4,817:
 
=={{header|FutureBasic}}==
Here are two FutureBasic solutions for the "ABC Problem" task. The first is a straightforward function based on CFStrings, giving the standard YES or NO response.
<syntaxhighlight lang=futurebasic>
 
The second is based on Pascal Strings, and offers a unique graphic presentation of the results, all in 18 lines of code. It accepts a word list delimited by spaces, commas, and/or semicolons.
 
'''FIRST SOLUTION:'''
 
Requires FB 7.0.23 or later
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn CanBlocksSpell( w as CFStringRef ) as CFStringRef
NSUInteger i, j
CFStringRef s = @"", t1, t2 : if fn StringIsEqual( w, @"" ) then exit fn = @"YES" else w = ucase(w)
CFStringRef cFinal = @"", result = @"NO"
CFMutableArrayRef blocks
blocks = fn MutableArrayWithArray( @[@"BO", @"XK", @"DQ", @"CP",¬
@"NA", @"GT", @"RE", @"TG", @"QD", @"FS", @"JW", @"HU", @"VI",¬
@"AN", @"OB", @"ER", @"FS", @"LY", @"PC", @"ZM"] )
CFStringRef cfStr = fn StringUppercaseString( w )
NSUInteger length = fn StringLength( cfStr )
NSUInteger count = fn ArrayCount( blocks )
for i = 0 to length - 1
for j = 0 to count - 1
CFStringRef charStr = mid( cfStr, i, 1 )
CFStringRef compareStr = fn ArrayObjectAtIndex( blocks, j )
CFStringRef testStr1 = mid( compareStr, 0, 1 )
CFStringRef testStr2 = mid( compareStr, 1, 1 )
if ( fn StringIsEqual( charStr, testStr1 ) == YES )
cFinal = fn StringByAppendingString( cFinal, testStr1 ) : MutableArrayReplaceObjectAtIndex( blocks, @" ", j ) : exit for
end if
if ( fn StringIsEqual( charStr, testStr2 ) == YES )
cFinal = fn StringByAppendingString( cFinal, testStr2 ) : MutableArrayReplaceObjectAtIndex( blocks, @" ", j ) : exit for
end if
next
next
if fn StringIsEqual( cFinal, cfStr ) == YES then result = @"YES"
end fn = result
 
mda(0) = {@"BO",@"XK",@"DQ",@"CP",@"NA",@"GT",@"RE",@"TG",@"QD",¬
NSLog( @"a: Can blocks spell? %@", fn CanBlocksSpell( @"a" ) )
@"FS",@"JW",@"HU",@"VI",@"AN",@"OB",@"ER",@"FS",@"LY",@"PC",@"ZM"}
NSLog( @"Bark: Can blocks spell? %@", fn CanBlocksSpell( @"Bark" ) )
 
NSLog( @"BOOK: Can blocks spell? %@", fn CanBlocksSpell( @"BOOK" ) )
for i = 0 to len(w) - 1
NSLog( @"TrEaT: Can blocks spell? %@", fn CanBlocksSpell( @"TrEaT" ) )
for j = 0 to mda_count - 1
NSLog( @"COMMON: Can blocks spell? %@", fn CanBlocksSpell( @"COMMON" ) )
t1 = mid( mda(j), 0, 1 ) : t2 = mid( mda(j), 1, 1 )
NSLog( @"Squad: Can blocks spell? %@", fn CanBlocksSpell( @"Squad" ) )
if ( fn StringIsEqual( mid( w, i, 1 ), t1 ) ) then s = fn StringByAppendingString( s, t1 ) : mda(j) = @" " : break
NSLog( @"conFUse: Can blocks spell? %@", fn CanBlocksSpell( @"conFUse" ) )
if ( fn StringIsEqual( mid( w, i, 1 ), t2 ) ) then s = fn StringByAppendingString( s, t2 ) : mda(j) = @" " : break
next
next
if fn StringIsEqual( s, w ) then exit fn = @"YES"
end fn = @"NO"
 
NSUInteger i
CFArrayRef words
CFStringRef w
words = @[@"", @"a",@"Bark",@"BOOK",@"TrEaT",@"COMMON",@"Squad",@"conFUse",@"ABBA",@"aUtO"]
for w in words
printf @"Can blocks spell %7s : %@", fn StringUTF8String( w ), fn CanBlocksSpell( w )
next
 
NSLog( @"%@", fn WindowPrintViewString( 1 ) )
 
HandleEvents
Line 4,560 ⟶ 4,858:
{{output}}
<pre>
a:Can blocks spell Can blocks spell? : YES
Bark:Can blocks spell Can blocks spell? a : YES
Can blocks spell Bark : YES
BOOK: Can blocks spell? NO
TrEaT: Can blocks spell? YES BOOK : NO
COMMON: Can blocks spell? NO TrEaT : YES
Squad: Can blocks spell? YES COMMON : NO
conFUse: Can blocks spell? Squad : YES
Can blocks spell conFUse : YES
Can blocks spell ABBA : YES
Can blocks spell aUtO : YES
</pre>
 
'''SECOND SOLUTION:'''
<syntaxhighlight lang="futurebasic">
 
local fn blocks( wordList as str255 )
sint16 found, r, x = 3, y = -9 : str63 ch, blocks : ch = " " : blocks = " "
for r = 1 to len$( wordList ) +1
found = instr$( 1, blocks, ch )
select found
case > 3: mid$( blocks, found and -2, 2 ) = "__" : text , , fn ColorYellow
rect fill ( x, y + 5.5, 15, 15 ), fn ColorBrown
case 0: text , , fn ColorLightGray
case < 4: blocks=" ,;BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM": x=3: y+=26: ch=""
end select
text @"Courier New Bold", 16 : print %( x + 2.5, y ) ch : x += 17
ch = ucase$( mid$( wordList, r, 1 ) )
next
end fn
 
window 1, @"ABC problem in FutureBasic", ( 0, 0, 300, 300 )
fn blocks( "a baRk booK;treat,COMMON squad Confused comparable incomparable nondeductibles" )
handleevents
 
</syntaxhighlight>
{{output}}
[[File:FB output for ABC--W on Br.png]]
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ae860292d4588b3627d77c85bcc634ee Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sCheck As String[] = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]
Dim sBlock As String[] = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
Line 4,611 ⟶ 4,938:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 4,663 ⟶ 4,990:
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">class ABCSolver {
def blocks
 
Line 4,677 ⟶ 5,004:
 
Test:
<syntaxhighlight lang="groovy">def a = new ABCSolver(["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])
 
Line 4,696 ⟶ 5,023:
=={{header|Harbour}}==
Harbour Project implements a cross-platform Clipper/xBase compiler.
<syntaxhighlight lang="visualfoxpro">PROCEDURE Main()
 
LOCAL cStr
Line 4,741 ⟶ 5,068:
 
The following function returns a list of all the solutions. Since Haskell is lazy, testing whether the list is null will only do the minimal amount of work necessary to determine whether a solution exists.
<syntaxhighlight lang="haskell">import Data.List (delete)
import Data.Char (toUpper)
 
Line 4,771 ⟶ 5,098:
Or, in terms of the bind operator:
 
<syntaxhighlight lang="haskell">import Data.Char (toUpper)
import Data.List (delete)
 
Line 4,823 ⟶ 5,150:
 
Works in both languages:
<syntaxhighlight lang="unicon">procedure main(A)
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
Line 4,860 ⟶ 5,187:
"CONFUSE" can be spelled with blocks.
->
</pre>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">
(function in-block? c
(when (let block-idx (find-idx (substr? (upper-case c)) rem-blocks))
(var! rem-blocks drop block-idx)))
 
(function can-make-word word
(var rem-blocks ["BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS" "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM"])
(.. and (map in-block? word)))
 
(-> ["A" "bark" "Book" "TREAT" "Common" "squaD" "CoNFuSe"] ; Notice case insensitivity
(map #(str % " => " (can-make-word %)))
(join ", "))
</syntaxhighlight>
{{out}}
<pre>
A => true, bark => true, Book => false, TREAT => true, Common => false, squaD => true, CoNFuSe => true
</pre>
 
=={{header|J}}==
'''Solution:'''
<syntaxhighlight lang="j">reduce=: verb define
'rows cols'=. i.&.> $y
for_c. cols do.
Line 4,876 ⟶ 5,222:
abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0:</syntaxhighlight>
'''Examples:'''
<syntaxhighlight lang="j"> Blocks=: ];._2 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
 
Line 4,892 ⟶ 5,238:
 
'''Tacit version'''
<syntaxhighlight lang="j">delElem=: {~<@<@<
uppc=:(-32*96&<*.123&>)&.(3&u:)
reduc=: ] delElem 1 i.~e."0 1
Line 4,919 ⟶ 5,265:
Another approach might be:
 
<syntaxhighlight lang=J"j">Blocks=: >;:'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
 
Line 4,926 ⟶ 5,272:
need=: #/.~ word,word
relevant=: (x +./@e."1 word) # x
candidates=: word,"1>,{ {relevant
+./(((#need){. #/.~)"1 candidates) */ .>:need
)</syntaxhighlight>
Line 4,932 ⟶ 5,278:
Example use:
 
<syntaxhighlight lang=J"j"> Blocks canform 0{::ExampleWords
1
Blocks canform 1{::ExampleWords
Line 4,955 ⟶ 5,301:
For example:
 
<syntaxhighlight lang=J"j"> Blocks canform 0{::ExampleWords
1
word
Line 4,975 ⟶ 5,321:
{{trans|C}}
{{works with|Java|1.6+}}
<syntaxhighlight lang="java5">import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Line 5,025 ⟶ 5,371:
====Imperative====
The following method uses regular expressions and the string replace function to allow more support for older browsers.
<syntaxhighlight lang="javascript">var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
 
function CheckWord(blocks, word) {
Line 5,076 ⟶ 5,422:
 
====Functional====
<syntaxhighlight lang=JavaScript"javascript">(function (strWords) {
 
var strBlocks =
Line 5,125 ⟶ 5,471:
})('A bark BooK TReAT COMMON squAD conFUSE');</syntaxhighlight>
{{Out}}
<syntaxhighlight lang=JavaScript"javascript">A -> NA
bark -> BO NA RE XK
BooK: [no solution]
Line 5,135 ⟶ 5,481:
===ES6===
====Imperative====
<syntaxhighlight lang="javascript">let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
let blocks = characters.split(" ").map(pair => pair.split(""));
Line 5,181 ⟶ 5,527:
====Functional====
{{Trans|Haskell}}
<syntaxhighlight lang=JavaScript"javascript">(() => {
"use strict";
 
Line 5,259 ⟶ 5,605:
 
=={{header|jq}}==
The problem description seems to imply that if a letter, X, appears on more than one block, its partner will be the same on all blocks. This makes the problem trivial.<syntaxhighlight lang="jq">
# when_index(cond;ary) returns the index of the first element in ary
# that satisfies cond; it uses a helper function that takes advantage
Line 5,289 ⟶ 5,635:
end
end;</syntaxhighlight>
Task:<syntaxhighlight lang="jq">def task:
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] as $blocks
Line 5,305 ⟶ 5,651:
=={{header|Jsish}}==
Based on Javascript ES5 imperative solution.
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* ABC problem, in Jsish. Can word be spelled with the given letter blocks. */
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
Line 5,358 ⟶ 5,704:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Printf
 
function abc(str::AbstractString, list)
Line 5,387 ⟶ 5,733:
CONFUSE | true</pre>
 
=={{header|Koka}}==
{{trans|Python}}with some Koka specific updates
<syntaxhighlight lang="koka">
val blocks = [("B", "O"),
("X", "K"),
("D", "Q"),
("C", "P"),
("N", "A"),
("G", "T"),
("R", "E"),
("T", "G"),
("Q", "D"),
("F", "S"),
("J", "W"),
("H", "U"),
("V", "I"),
("A", "N"),
("O", "B"),
("E", "R"),
("F", "S"),
("L", "Y"),
("P", "C"),
("Z", "M")]
 
pub fun get-remove( xs : list<a>, pred : a -> bool, acc: ctx<list<a>>) : (maybe<a>, list<a>)
match xs
Cons(x,xx) -> if !pred(x) then xx.get-remove(pred, acc ++ ctx Cons(x, _)) else (Just(x), acc ++. xx)
Nil -> (Nothing, acc ++. Nil)
 
fun check-word(word: string, blocks: list<(string, string)>)
match word.head
"" -> True
x ->
val (a, l) = blocks.get-remove(fn(a) a.fst == x || a.snd == x, ctx _)
match a
Nothing -> False
Just(_) -> check-word(word.tail, l)
 
fun can-make-word(word, blocks: list<(string, string)>)
check-word(word.to-upper, blocks)
 
fun main()
val words = ["", "a", "baRk", "booK", "treat", "COMMON", "squad", "Confused"]
words.map(fn(a) (a, can-make-word(a, blocks))).foreach fn((w, b))
println(w.show ++ " " ++ (if b then "can" else "cannot") ++ " be made")
</syntaxhighlight>
{{out}}
<pre>"": true
"" can be made
"a" can be made
"baRk" can be made
"booK" cannot be made
"treat" can be made
"COMMON" cannot be made
"squad" can be made
"Confused" can be made
</pre>
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">object ABC_block_checker {
fun run() {
println("\"\": " + blocks.canMakeWord(""))
Line 5,437 ⟶ 5,840:
SQuAd: true
CONFUSE: true</pre>
 
=={{header|Lang}}==
{{trans|Java}}
<syntaxhighlight lang="lang">
fp.canMakeWord = ($word, $blocks) -> {
if(!$word) {
return 1
}
$word = fn.toLower($word)
$c $= $word[0]
$i = 0
while($i < @$blocks) {
$block $= fn.toLower($blocks[$i])
if($block[0] != $c && $block[1] != $c) {
$i += 1
con.continue
}
$blocksCopy $= ^$blocks
fn.listRemoveAt($blocksCopy, $i)
if(fp.canMakeWord(fn.substring($word, 1), $blocksCopy)) {
return 1
}
$i += 1
}
return 0
}
 
$blocks = fn.listOf(BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM)
 
$word
foreach($[word], [\e, A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, Treat, cOmMoN]) {
fn.printf(%s: %s%n, $word, fp.canMakeWord($word, $blocks))
}
</syntaxhighlight>
{{out}}
<pre>
: 1
A: 1
BARK: 1
BOOK: 0
TREAT: 1
COMMON: 0
SQUAD: 1
CONFUSE: 1
Treat: 1
cOmMoN: 0
</pre>
 
=={{header|Liberty BASIC}}==
===Recursive solution===
<syntaxhighlight lang="lb">
print "Rosetta Code - ABC problem (recursive solution)"
print
Line 5,505 ⟶ 5,963:
</pre>
===Procedural solution===
<syntaxhighlight lang="lb">
print "Rosetta Code - ABC problem (procedural solution)"
print
Line 5,662 ⟶ 6,120:
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">make "blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S]
[J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]
 
Line 5,692 ⟶ 6,150:
SQUAD: true
CONFUSE: true</pre>
 
=={{header|Logtalk}}==
 
A possible Logtalk implementation of this problem could look like this:
 
<syntaxhighlight lang="logtalk">
:- object(blocks(_Block_Set_)).
 
:- public(can_spell/1).
:- public(spell_no_spell/3).
 
:- uses(character, [lower_upper/2, is_upper_case/1]).
% public interface
 
can_spell(Atom) :-
atom_chars(Atom, Chars),
to_lower(Chars, Lower),
can_spell(_Block_Set_, Lower).
 
spell_no_spell(Words, Spellable, Unspellable) :-
meta::partition(can_spell, Words, Spellable, Unspellable).
 
% local helper predicates
 
can_spell(_, []).
can_spell(Blocks0, [H|T]) :-
( list::selectchk(b(H,_), Blocks0, Blocks1)
; list::selectchk(b(_,H), Blocks0, Blocks1)
),
can_spell(Blocks1, T).
 
to_lower(Chars, Lower) :-
meta::map(
[C,L] >> (is_upper_case(C) -> lower_upper(L, C); C = L),
Chars,
Lower
).
 
:- end_object.
</syntaxhighlight>
 
The object is a parameterized object, allowing different block sets to be tested against word lists with trivial ease. It exposes two predicates in its public interface: <code>can_spell/1</code>, which succeeds if the provided argument is an atom which can be spelled with the block set, and <code>spell_no_spell</code>, which partitions a list of words into two lists: a list of words which can be spelled by the blocks, and a list of words which cannot be spelled by the blocks.
 
A test object driving <code>blocks</code> could look something like this:
 
<syntaxhighlight lang="logtalk">
:- object(blocks_test).
 
:- public(run/0).
 
:- uses(logtalk, [print_message(information, blocks, Message) as print(Message)]).
 
run :-
block_set(BlockSet),
word_list(WordList),
blocks(BlockSet)::spell_no_spell(WordList, S, U),
print('The following words can be spelled by this block set'::S),
print('The following words cannot be spelled by this block set'::U).
 
% test configuration data
 
block_set([b(b,o), b(x,k), b(d,q), b(c,p), b(n,a),
b(g,t), b(r,e), b(t,g), b(q,d), b(f,s),
b(j,w), b(h,u), b(v,i), b(a,n), b(o,b),
b(e,r), b(f,s), b(l,y), b(p,c), b(z,m)]).
 
word_list(['', 'A', 'bark', 'bOOk', 'treAT', 'COmmon', 'sQuaD', 'CONFUSE']).
 
:- end_object.
</syntaxhighlight>
 
Before running the test, some libraries will have to be loaded (typically found in a file called <code>loader.lgt</code>). Presuming the object and the test are both in a file called <code>blocks.lgt</code> the loader file could look something like this:
 
<syntaxhighlight lang="logtalk">
:- initialization((
% libraries
logtalk_load(meta(loader)),
logtalk_load(types(loader)),
% application
logtalk_load([blocks, blocks_test])
)).
</syntaxhighlight>
 
{{Out}}
 
Putting this all together, a session testing the object would look like this:
 
<pre>
?- {loader}.
% ... messages elided ...
true.
 
?- blocks_test::run.
% The following words can be spelled by this block set:
% - ''
% - 'A'
% - bark
% - treAT
% - sQuaD
% - 'CONFUSE'
% The following words cannot be spelled by this block set:
% - bOOk
% - 'COmmon'
true.
 
?-
</pre>
 
Of course in this simple example only the lists of words in each category gets printed. Better-formatted output is possible (and likely desirable) but out of scope for the problem.
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">blocks = {
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
Line 5,740 ⟶ 6,308:
 
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module ABC {
can_make_word("A")
Line 5,773 ⟶ 6,341:
CONFUSE True
</pre >
 
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE ABC
.MCALL .TTYOUT,.EXIT
ABC:: JMP DEMO
 
; SEE IF R0 CAN BE MADE WITH THE BLOCKS
BLOCKS: MOV #7$,R1
MOV #6$,R2
1$: MOVB (R1)+,(R2)+ ; INITIALIZE BLOCKS
BNE 1$
BR 4$
2$: BIC #40,R1 ; MAKE UPPERCASE
MOV #6$,R2
3$: MOVB (R2)+,R3 ; GET BLOCK
BEQ 5$ ; OUT OF BLOCKS: NO MATCH
CMP R1,R3 ; MATCHING BLOCK?
BNE 3$ ; NO: CHECK NEXT BLOCK
DEC R2 ; FOUND BLOCK: CLEAR BLOCK
BIC #1,R2
MOV #-1,(R2)
4$: MOVB (R0)+,R1
BNE 2$
RTS PC ; END OF STRING: RETURN WITH Z SET
5$: CCC ; FAIL: RETURN WITH Z CLEAR
RTS PC
6$: .ASCIZ / /
7$: .ASCIZ /BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM/
 
DEMO: MOV #WORDS,R4
1$: MOV (R4)+,R5
BEQ 4$
MOV R5,R1
JSR PC,5$
MOV R5,R0
JSR PC,BLOCKS
BNE 2$
MOV #6$,R1
BR 3$
2$: MOV #7$,R1
3$: JSR PC,5$
BR 1$
4$: .EXIT
5$: MOVB (R1)+,R0
.TTYOUT
BNE 5$
RTS PC
6$: .ASCIZ /: YES/<15><12>
7$: .ASCIZ /: NO/<15><12>
.EVEN
 
WORDS: .WORD 1$,2$,3$,4$,5$,6$,7$,0
1$: .ASCIZ /A/
2$: .ASCIZ /BARK/
3$: .ASCIZ /book/
4$: .ASCIZ /TREAT/
5$: .ASCIZ /common/
6$: .ASCIZ /SqUaD/
7$: .ASCIZ /cOnFuSe/
.END ABC</syntaxhighlight>
{{out}}
<pre>A: YES
BARK: YES
book: NO
TREAT: YES
common: NO
SqUaD: YES
cOnFuSe: YES</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">canSpell := proc(w)
local blocks, i, j, word, letterFound;
blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
Line 5,810 ⟶ 6,446:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
ClearAll[DoStep,ABCBlockQ]
Line 5,843 ⟶ 6,479:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=MATLAB"matlab">function testABC
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
Line 5,884 ⟶ 6,520:
Recursively checks if the word is possible if a block is removed from the array.
 
<syntaxhighlight lang=MAXScript"maxscript">
-- This is the blocks array
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
Line 5,986 ⟶ 6,622:
 
'''Output:'''
<syntaxhighlight lang=MAXScript"maxscript">
iswordpossible "a"
true
Line 6,005 ⟶ 6,641:
 
=== Non-recursive ===
<syntaxhighlight lang=MAXScript"maxscript">
fn isWordPossible2 word =
(
Line 6,042 ⟶ 6,678:
Then:
 
<syntaxhighlight lang=MAXScript"maxscript">
iswordpossible "water"
true
Line 6,052 ⟶ 6,688:
 
=={{header|Mercury}}==
<syntaxhighlight lang=Mercury"mercury">:- module abc.
:- interface.
:- import_module io.
Line 6,090 ⟶ 6,726:
 
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript"miniscript">allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
swap = function(list, index1, index2)
Line 6,118 ⟶ 6,754:
</syntaxhighlight>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay [word ++ ": " ++ show (canmakeword blocks word) | word <- tests])]
 
tests :: [[char]]
tests = ["A","BARK","BOOK","TREAT","common","SqUaD","cOnFuSe"]
 
canmakeword :: [[char]]->[char]->bool
canmakeword [] word = False
canmakeword blocks [] = True
canmakeword blocks (a:as) = #match ~= 0 & canmakeword rest as
where match = [b | b<-blocks; ucase a $in b]
rest = hd match $del blocks
 
del :: *->[*]->[*]
del item [] = []
del item (a:as) = a:del item as, if a ~= item
= as, otherwise
 
in :: *->[*]->bool
in item [] = False
in item (a:as) = a = item \/ item $in as
 
ucase :: char->char
ucase ch = ch, if n<code 'a' \/ n>code 'z'
= decode (n-32), otherwise
where n = code ch
 
blocks :: [[char]]
blocks = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]</syntaxhighlight>
{{out}}
<pre>A: True
BARK: True
BOOK: False
TREAT: True
common: False
SqUaD: True
cOnFuSe: True</pre>
=={{header|Nim}}==
{{works with|Nim|0.20.0}}
<syntaxhighlight lang="nim">import std / strutils
 
func canMakeWord(blocks: seq[string]; word: string): bool =
Line 6,164 ⟶ 6,839:
=={{header|Oberon-2}}==
Works with oo2c Version 2
<syntaxhighlight lang="oberon2">
MODULE ABCBlocks;
IMPORT
Line 6,262 ⟶ 6,937:
=={{header|Objeck}}==
{{trans|Java}}
<syntaxhighlight lang="objeck">class Abc {
function : Main(args : String[]) ~ Nil {
blocks := ["BO", "XK", "DQ", "CP", "NA",
Line 6,320 ⟶ 6,995:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let blocks = [
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
Line 6,375 ⟶ 7,050:
=={{header|Oforth}}==
 
<syntaxhighlight lang=Oforth"oforth">import: mapping
 
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
Line 6,398 ⟶ 7,073:
=={{header|OpenEdge/Progress}}==
 
<syntaxhighlight lang=Progress"progress (Openedgeopenedge ABLabl)">FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER) FORWARD.
 
/* List of blocks */
Line 6,514 ⟶ 7,189:
 
=={{header|Order}}==
<syntaxhighlight lang=Order"order">#include <order/interpreter.h>
#include <order/lib.h>
 
Line 6,684 ⟶ 7,359:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">BLOCKS = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM";
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];
 
Line 6,715 ⟶ 7,390:
{{works with|Free Pascal|2.6.2}}
 
<syntaxhighlight lang=Pascal"pascal">
#!/usr/bin/instantfpc
//program ABCProblem;
Line 6,805 ⟶ 7,480:
=={{header|Perl}}==
Recursive solution that can handle characters appearing on different blocks:
<syntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 6,832 ⟶ 7,507:
}</syntaxhighlight>
<p>Testing:
<syntaxhighlight lang="perl">use Test::More tests => 8;
 
my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);
Line 6,847 ⟶ 7,522:
</syntaxhighlight>
===Regex based alternate===
<syntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/ABC_Problem
Line 6,877 ⟶ 7,552:
=={{header|Phix}}==
Recursive solution which also solves the extra problems on the discussion page.
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">blocks</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">used</span>
Line 6,930 ⟶ 7,605:
=={{header|PHP}}==
 
<syntaxhighlight lang=PHP"php">
<?php
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");
Line 6,973 ⟶ 7,648:
=={{header|Picat}}==
Showing both a Picat style version (check_word/2) and a Prolog style recursive version (check_word2/2). go2/0 generates all possible solutions (using fail/0) to backtrack.
<syntaxhighlight lang=Picat"picat">go =>
test_it(check_word),
test_it(check_word2),
Line 7,156 ⟶ 7,831:
=={{header|PicoLisp}}==
Mapping and recursion.
<syntaxhighlight lang=PicoLisp"picolisp">(setq *Blocks
'((B O) (X K) (D Q) (C P) (N A) (G T) (R E)
(T G) (Q D) (F S) (J W) (H U) (V I) (A N)
Line 7,192 ⟶ 7,867:
=={{header|PL/I}}==
===version 1===
<syntaxhighlight lang="pli">ABC: procedure options (main); /* 12 January 2014 */
 
declare word character (20) varying, blocks character (200) varying initial
Line 7,229 ⟶ 7,904:
 
===version 2===
<syntaxhighlight lang="pli">*process source attributes xref or(!) options nest;
abc: Proc Options(main);
/* REXX --------------------------------------------------------------
Line 7,361 ⟶ 8,036:
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
 
/* ABC PROBLEM ON $-TERMINATED STRING */
Line 7,433 ⟶ 8,108:
Works with PowerBASIC 6 Console Compiler
 
<syntaxhighlight lang=PowerBASIC"powerbasic">#COMPILE EXE
#DIM ALL
'
Line 7,602 ⟶ 8,277:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell"><#
.Synopsis
ABC Problem
Line 7,784 ⟶ 8,459:
Works with SWI-Prolog 6.5.3
 
<syntaxhighlight lang=Prolog"prolog">abc_problem :-
maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
 
Line 7,827 ⟶ 8,502:
{{works with|SWI Prolog 7}}
 
<syntaxhighlight lang=Prolog"prolog">:- use_module([ library(chr),
abathslib(protelog/composer) ]).
 
Line 7,849 ⟶ 8,524:
Demonstration:
 
<syntaxhighlight lang=Prolog"prolog">?- can_build_word("A").
true.
?- can_build_word("BARK").
Line 7,866 ⟶ 8,541:
=={{header|PureBasic}}==
===PureBasic: Iterative===
<syntaxhighlight lang="purebasic">EnableExplicit
#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
 
Line 7,900 ⟶ 8,575:
 
===PureBasic: Recursive===
<syntaxhighlight lang="purebasic">#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
 
Macro test(t)
Line 7,932 ⟶ 8,607:
 
===Python: Iterative, with tests===
<syntaxhighlight lang="python">
'''
Note that this code is broken, e.g., it won't work when
Line 8,007 ⟶ 8,682:
 
===Python: Recursive===
<syntaxhighlight lang="python">BLOCKS = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'.split()
 
def _abc(word, blocks):
Line 8,044 ⟶ 8,719:
 
===Python: Recursive, telling how===
<syntaxhighlight lang="python">def mkword(w, b):
if not w: return []
 
Line 8,076 ⟶ 8,751:
=={{header|q}}==
The possibility of ‘backtracking’, discussed in the FORTRAN solution above (and not tested by the example set) makes this a classic tree search: wherever there is a choice of blocks from which to pick the next letter, each choice must be tested.
<syntaxhighlight lang="q">BLOCKS:string`BO`XK`DQ`CP`NA`GT`RE`TG`QD`FS`JW`HU`VI`AN`OB`ER`FS`LY`PC`ZM
WORDS:string`A`BARK`BOOK`TREAT`COMMON`SQUAD`CONFUSE
 
Line 8,084 ⟶ 8,759:
any(1_s).z.s/:b(til count b)except/:where found] }</syntaxhighlight>
{{out}}
<syntaxhighlight lang="q">q)WORDS cmw\:BLOCKS
1101011b</syntaxhighlight>
The first expression tests whether the string <code>s</code> is empty. If so, the result is true. This matches two cases: either the string is empty and can be made from any set of blocks; or all its letters have been matched and there is nothing more to check.
Line 8,093 ⟶ 8,768:
 
To meet the requirement for case-insensitivity and to display the results, apply the above within a wrapper.
<syntaxhighlight lang="q">Words:string`A`bark`BOOK`Treat`COMMON`squad`CONFUSE
cmwi:{(`$x), `false`true cmw . upper each(x;y) }</syntaxhighlight>
{{out}}
<syntaxhighlight lang="q">q)Words cmwi\:BLOCKS
A true
bark true
Line 8,115 ⟶ 8,790:
This solution assumes the constraint that if a letter appears on more than one block those blocks are identical (as in the example set) so backtracking is not required.
 
<syntaxhighlight lang=Quackery"quackery">[ $ "BOXKDQCPNAGTRETGQDFS"
$ "JWHUVIANOBERFSLYPCZM"
join ] constant is blocks ( --> $ )
Line 8,179 ⟶ 8,854:
This solution does not assume the constraint that if a letter appears on more than one block those blocks are identical (as in the example set) so backtracking is required.
 
<syntaxhighlight lang=Quackery"quackery">[ ' [ 0 ] swap
witheach
[ over -1 peek
Line 8,239 ⟶ 8,914:
Vectorised function for R which will take a character vector and return a logical vector of equal length with TRUE and FALSE as appropriate for words which can/cannot be made with the blocks.
 
<syntaxhighlight lang=R"r">blocks <- rbind(c("B","O"),
c("X","K"),
c("D","Q"),
Line 8,289 ⟶ 8,964:
===Without recursion===
Second version without recursion and giving every unique combination of blocks for each word:
<syntaxhighlight lang=R"r">canMakeNoRecursion <- function(x) {
x <- toupper(x)
charList <- strsplit(x, character(0))
Line 8,393 ⟶ 9,068:
So '(can-make-word? "")' is true for me.
 
<syntaxhighlight lang="racket">#lang racket
(define block-strings
(list "BO" "XK" "DQ" "CP" "NA"
Line 8,451 ⟶ 9,126:
{{works with|rakudo|6.0.c}}
Blocks are stored as precompiled regexes. We do an initial pass on the blockset to include in the list only those regexes that match somewhere in the current word. Conveniently, regexes scan the word for us.
<syntaxhighlight lang=perl6"raku" line>multi can-spell-word(Str $word, @blocks) {
my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }
can-spell-word $word.uc.comb.list, @regex;
Line 8,482 ⟶ 9,157:
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">dim Blocks as string
dim InWord as string
 
Line 8,520 ⟶ 9,195:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">Red []
test: func [ s][
p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
Line 8,547 ⟶ 9,222:
conFUsE : true
</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Each Show (<Blocks>) <Words>>;
};
 
Each {
s.F (e.Arg) = ;
s.F (e.Arg) t.I e.R = <Mu s.F t.I e.Arg> <Each s.F (e.Arg) e.R>;
};
 
Show {
(e.Word) e.Blocks = <Prout e.Word ': ' <CanMakeWord (e.Word) e.Blocks>>;
};
 
Blocks {
= ('BO') ('XK') ('DQ') ('CP') ('NA')
('GT') ('RE') ('TG') ('QD') ('FS')
('JW') ('HU') ('VI') ('AN') ('OB')
('ER') ('FS') ('LY') ('PC') ('ZM');
};
 
Words {
= ('A') ('BARK') ('BOOK') ('TREAT')
('common') ('squad') ('CoNfUsE');
};
 
CanMakeWord {
(e.Word) e.Blocks = <CanMakeWord1 (<Upper e.Word>) e.Blocks>;
}
 
CanMakeWord1 {
() e.Blocks = T;
(s.Ltr e.Word) e.Blocks1 (e.X s.Ltr e.Y) e.Blocks2
= <CanMakeWord1 (e.Word) e.Blocks1 e.Blocks2>;
(e.Word) e.Blocks = F;
};</syntaxhighlight>
{{out}}
<pre>A: T
BARK: T
BOOK: F
TREAT: T
common: F
squad: T
CoNfUsE: T</pre>
 
=={{header|REXX}}==
===version 1===
<syntaxhighlight lang="rexx">/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/
list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/
blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'
Line 8,583 ⟶ 9,303:
 
===version 2===
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 10.01.2014 Walter Pachl counts the number of possible ways
* 12.01.2014 corrected date and output
Line 8,766 ⟶ 9,486:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">Blocks = [ :BO, :XK, :DQ, :CP, :NA, :GT, :RE, :TG, :QD, :FS, :JW, :HU, :VI, :AN, :OB, :ER, :FS, :LY, :PC, :ZM ]
Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]
 
Line 8,806 ⟶ 9,526:
>>> can_make_word("CONFUSE")
True
</pre>
 
=={{header|RPL}}==
Recursion provides an easy way to solve the task. RPL can manage recursive functions, provided that they don't use local variables. All the data must then be managed in the stack, which makes the code somehow difficult to read: one third of the words used by the program are about stack handling: <code>DUP</code>, <code>DROP(N)</code>, <code>PICK</code>, <code>SWAP</code>, <code>ROLL</code> etc.
Recursive search is here systematic: the program does check that ABBA can be written with 2 cubes AB and 2 cubes AC, whatever their order.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ SWAP LIST→ → n
≪ n DUP 2 + ROLL - 1 + ROLL n ROLLD
n 1 - →LIST SWAP
≫ ≫ ''''PICKL'''' STO
≪ 1 1 SUB → cubes letter
≪ { } 1 cubes SIZE '''FOR''' j
'''IF''' cubes j GET letter POS
'''THEN''' j + '''END NEXT'''
≫ ≫ ''''GetCubeList'''' STO
DUP2 '''GetCubeList'''
'''IF''' DUP SIZE '''THEN'''
'''IF''' OVER SIZE 1 ==
'''THEN''' 3 DROPN 1
'''ELSE'''
SWAP 2 OVER SIZE SUB
0 SWAP ROT DUP SIZE
'''DO'''
DUP2 GET
6 PICK SWAP '''PICKL''' DROP
4 PICK '''ABC?'''
5 ROLL OR 4 ROLLD
1 -
'''UNTIL''' DUP NOT '''END'''
3 DROPN SWAP DROP
'''END'''
'''ELSE''' 3 DROPN 0 '''END'''
≫ ''''ABC?'''' STO
≪ 1 Words SIZE '''FOR''' w
Words w GET Cubes Words w GET '''ABC?'''
": true" ": false" IFTE + '''NEXT'''
≫ ''''TASK'''' STO
|
'''PICKL''' ''( { x1..xm..xn } m -- { x1..xn } xm )''
put selected item at bottom of stack
make a new list with the rest of the stack
'''GetCubeList''' ''( { cubes } "word" -- { match_cubes } )''
Scan cubes
Retain those matching with 1st letter of word
'''ABC?''' ''( { cubes } "word" -- boolean )''
Get the list of cubes matching the 1st letter
if list not empty
if word size = 1 letter
return true
else
initialize stack:
( {cubes} false "ord" { CubeList } index -- )
repeat
get a matching cube index
remove cube from cube list
search cubes for "ord"
update boolean value
back to previous cube index
until all matching cubes checked
clear stack except boolean value
return false if no matching cube
|}
 
{{in}}
<pre>
{ "BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS" "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM" } 'Cubes' STO
{ "A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE" } 'Words' STO
TASK
{ "AB" "AB" "AC" "AC" } "ABBA" ABC?
</pre>
{{out}}
<pre>
8: "A: true"
7: "BARK: true"
6: "BOOK: false"
5: TREAT: true"
4: "COMMON: false"
3: "SQUAD: true"
2: "CONFUSE: true"
1: 1
</pre>
 
=={{header|Ruby}}==
This one uses a case insensitive regular expression. The 'sub!' method substitutes the first substring it finds and returns nil if nothing is found.
<syntaxhighlight lang="ruby">words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << ""
 
words.each do |word|
Line 8,831 ⟶ 9,652:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="unbasic">blocks$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
b = int((len(blocks$) /3) + 1)
Line 8,866 ⟶ 9,687:
=={{header|Rust}}==
This implementation uses a backtracking search.
<syntaxhighlight lang="rust">use std::iter::repeat;
 
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
Line 8,908 ⟶ 9,729:
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang=Scala"scala">object AbcBlocks extends App {
 
protected class Block(face1: Char, face2: Char) {
Line 8,961 ⟶ 9,782:
=={{header|Scheme}}==
In R5RS:
<syntaxhighlight lang="scheme">(define *blocks*
'((#\B #\O) (#\X #\K) (#\D #\Q) (#\C #\P) (#\N #\A)
(#\G #\T) (#\R #\E) (#\T #\G) (#\Q #\D) (#\F #\S)
Line 9,014 ⟶ 9,835:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: canMakeWords (in array string: blocks, in string: word) is func
Line 9,062 ⟶ 9,883:
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">function CanMakeWord word
 
put [
Line 9,104 ⟶ 9,925:
end CanMakeWord</syntaxhighlight>
 
<syntaxhighlight lang="sensetalk">repeat with each item word in [
"A",
"BARK",
Line 9,116 ⟶ 9,937:
end repeat</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program ABC_problem;
blocks := ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"];
 
words := ["A","BARK","BOOK","treat","common","Squad","CoNfUsE"];
 
loop for word in words do
print(rpad(word, 8), can_make_word(word, blocks));
end loop;
 
proc can_make_word(word, blocks);
loop for letter in word do
if exists block = blocks(i) | to_upper(letter) in block then
blocks(i) := "";
else
return false;
end if;
end loop;
return true;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>A #T
BARK #T
BOOK #F
treat #T
common #F
Squad #T
CoNfUsE #T</pre>
=={{header|SequenceL}}==
===Recursive Search Version===
<syntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
 
Line 9,161 ⟶ 10,012:
 
===RegEx Version ===
<syntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
import <RegEx/RegEx.sl>;
Line 9,195 ⟶ 10,046:
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func can_make_word(word, blocks) {
 
blocks.map! { |b| b.uc.chars.sort.join }.freq!
Line 9,214 ⟶ 10,065:
 
Tests:
<syntaxhighlight lang="ruby">var b1 = %w(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM)
var b2 = %w(US TZ AO QA)
 
Line 9,247 ⟶ 10,098:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">COMMENT ABC PROBLEM;
BEGIN
 
Line 9,356 ⟶ 10,207:
=={{header|Smalltalk}}==
Recursive solution. Tested in Pharo.
<syntaxhighlight lang="smalltalk">
ABCPuzzle>>test
#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
Line 9,394 ⟶ 10,245:
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang=SNOBOL4"snobol4">
* Program: abc.sbl,
* To run: sbl -r abc.sbl
Line 9,483 ⟶ 10,334:
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang=SPAD"spad">
blocks:List Tuple Symbol:= _
[(B,O),(X,K),(D,Q),(C,P),(N,A),(G,T),(R,E),(T,G),(Q,D),(F,S), _
Line 9,522 ⟶ 10,373:
 
=={{header|Standard ML}}==
<syntaxhighlight lang=OCaML"ocaml">
val BLOCKS = [(#"B",#"O"), (#"X",#"K"), (#"D",#"Q"), (#"C",#"P"), (#"N",#"A"), (#"G",#"T"),
(#"R",#"E"), (#"T",#"G"), (#"Q",#"D"), (#"F",#"S"), (#"J",#"W"), (#"H",#"U"), (#"V",#"I"),
Line 9,563 ⟶ 10,414:
 
=={{header|Swift}}==
<syntaxhighlight lang=Swift"swift">import Foundation
 
func Blockable(str: String) -> Bool {
Line 9,608 ⟶ 10,459:
 
{{works with|Swift|3.0.2}}
<syntaxhighlight lang=Swift"swift">import Swift
 
func canMake(word: String) -> Bool {
Line 9,643 ⟶ 10,494:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<syntaxhighlight lang="tcl">package require Tcl 8.6
 
proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} {
Line 9,674 ⟶ 10,525:
Can we spell 'SQUAD'? true
Can we spell 'CONFUSE'? true
</pre>
 
=={{header|Transd}}==
The code properly handles the backtracking issue (see the note in the Fortran solution).
 
<syntaxhighlight lang="Scheme">#lang transd
 
MainModule: {
blocks: ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"],
words: ["A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"],
 
testMake: Lambda<String Vector<String> Bool>(λ
w String() v Vector<String>()
locals: c (toupper (subn w 0))
(for bl in v do
(if (contains bl c)
(if (== (size w) 1) (ret true))
(if (exec testMake (sub w 1) (erase (cp v) @idx))
(ret true)))
)
(ret false)
),
_start: (lambda
(for word in words do
(lout :boolalpha word " : "
(exec testMake word blocks))
)
)
}</syntaxhighlight>
{{out}}
<pre>
A : true
BARK : true
BOOK : false
TREAT : true
COMMON : false
SQUAD : true
CONFUSE : true
</pre>
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">set words = "A'BARK'BOOK'TREAT'COMMON'SQUAD'CONFUSE"
set result = *
loop word = words
Line 9,706 ⟶ 10,596:
=={{header|TXR}}==
 
<syntaxhighlight lang="txr">@(do
(defvar blocks '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G)
(Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R)
Line 9,781 ⟶ 10,671:
 
 
 
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="uBasic/4tH">Dim @b(40) ' holds the blocks
Dim @d(20)
' load blocks from string in lower case
a := "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
For x = 0 To Len (a)-1 : @b(x) = Or(Peek(a, x), Ord(" ")) : Next
' push words onto stack
Push "A", "Bark", "Book", "Treat", "Common", "Squad", "Confuse"
 
Do While Used() ' as long as words on the stack
w = Pop() ' get a word
p = 1 ' assume it's possible
For x = 0 To 19 : @d(x) = 0 : Next ' zero the @d-array
 
For i = 0 To Len(w) - 1 ' test the entire word
c = Or(Peek(w, i), Ord(" ")) ' get a lower case char
For x = 0 To 19 ' now test all the blocks
If @d(x) = 0 Then If (@b(x*2)=c) + (@b(x*2+1)=c) Then @d(x) = 1 : Break
Next
If x = 20 Then p = 0 : Break ' we've tried all the blocks - no fit
Next
' show the result
Print Show(w), Show(Iif(p, "True", "False"))
Loop</syntaxhighlight>
{{Out}}
<pre>Confuse True
Squad True
Common False
Treat True
Book False
Bark True
A True
 
0 OK, 0:1144</pre>
 
=={{header|Ultimate++}}==
This is example is a slight modification of the C and C++ examples. To avoid warning "<bold>warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]</bold> the strings added to char were individually prefixed with (char*). Swap is used instead of SWAP. Return 0 was not not needed.
 
<syntaxhighlight lang=Cpp"cpp">
#include <Core/Core.h>
#include <stdio.h>
Line 9,915 ⟶ 10,841:
{{works with|bash}}
 
<syntaxhighlight lang="bash">can_build_word() {
if [[ $1 ]]; then
can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
Line 9,969 ⟶ 10,895:
'''String-based solution'''
 
<syntaxhighlight lang=UTFool"utfool">
···
http://rosettacode.org/wiki/ABC_Problem
Line 10,001 ⟶ 10,927:
'''Collection-based solution'''
 
<syntaxhighlight lang=UTFool"utfool">
···
http://rosettacode.org/wiki/ABC_Problem
Line 10,040 ⟶ 10,966:
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Line 10,085 ⟶ 11,011:
>>> can_make_word SQUAD => True
>>> can_make_word CONFUSE => True</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const
(
blocks = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
words = ["A", BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
)
 
fn main() {
for word in words {
println('>>> can_make_word("${word.to_upper()}"): ')
if check_word(word, blocks) == true {println('True')} else {println('False')}
}
}
 
fn check_word(word string, blocks []string) bool {
mut tblocks := blocks.clone()
mut found := false
for chr in word {
found = false
for idx, _ in tblocks {
if tblocks[idx].contains(chr.ascii_str()) == true {
tblocks[idx] =''
found = true
break
}
}
if found == false {return found}
}
return found
}
</syntaxhighlight>
 
{{out}}
<pre>
>>> can_make_word("A"):
True
>>> can_make_word("BARK"):
True
>>> can_make_word("BOOK"):
False
>>> can_make_word("TREAT"):
True
>>> can_make_word("COMMON"):
False
>>> can_make_word("SQUAD"):
True
>>> can_make_word("CONFUSE"):
True
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript"wren">import "./fmt" for Fmt
 
var r // recursive
Line 10,116 ⟶ 11,093:
var sp = newSpeller.call("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
SystemFmt.print("%(Fmt.$-7s $s(-7", word)), %(sp.call(word))")
}</syntaxhighlight>
 
Line 10,131 ⟶ 11,108:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">string 0;
 
char Side1, Side2;
Line 10,173 ⟶ 11,150:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">letters$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
 
sub canMake(letters$, word$)
Line 10,204 ⟶ 11,181:
=={{header|zkl}}==
{{trans|C}}
<syntaxhighlight lang="zkl">var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
 
Line 10,237 ⟶ 11,214:
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Main;
type
Line 10,337 ⟶ 11,314:
 
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">10 LET b$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
20 READ p
30 FOR c=1 TO p
2,093

edits