ABC problem: Difference between revisions
Add ABC
m (→{{header|C++}}: use template) |
Not a robot (talk | contribs) (Add ABC) |
||
(101 intermediate revisions by 45 users not shown) | |||
Line 44:
;Example:
<
True
>>> can_make_word("BARK")
Line 57:
True
>>> can_make_word("CONFUSE")
True</
{{Template:Strings}}
Line 64:
=={{header|11l}}==
{{trans|Python}}
<
I word == ‘’
R 0B
Line 79:
R 1B
print([‘’, ‘a’, ‘baRk’, ‘booK’, ‘treat’, ‘COMMON’, ‘squad’, ‘Confused’].map(w -> ‘'’w‘': ’can_make_word(w)).join(‘, ’))</
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
ABC CSECT
USING ABC,R13 base register
Line 158:
YREGS
NN EQU (BLOCKS-WORDS)/L'WORDS number of words
END ABC</
{{out}}
<pre>
Line 171:
=={{header|8080 Assembly}}==
<
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 247:
wrdcommon: db 'COMMON$'
wrdsquad: db 'SQUAD$'
wrdconfuse: db 'CONFUSE$'</
{{out}}
Line 263:
{{trans|8080 Assembly}}
<
bits 16
org 100h
Line 325:
.cmn: db 'COMMON$'
.squad: db 'SQUAD$'
.confs: db 'CONFUSE$'</
{{out}}
Line 338:
=={{header|8th}}==
<
\ ========================================================================================
\ You are given a collection of ABC blocks
Line 537:
bye
;
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program problemABC64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ TRUE, 1
.equ FALSE, 0
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre1: .asciz "Can_make_word: @ \n"
szMessTrue: .asciz "True.\n"
szMessFalse: .asciz "False.\n"
szCarriageReturn: .asciz "\n"
szTablBloc: .asciz "BO"
.asciz "XK"
.asciz "DQ"
.asciz "CP"
.asciz "NA"
.asciz "GT"
.asciz "RE"
.asciz "TG"
.asciz "QD"
.asciz "FS"
.asciz "JW"
.asciz "HU"
.asciz "VI"
.asciz "AN"
.asciz "OB"
.asciz "ER"
.asciz "FS"
.asciz "LY"
.asciz "PC"
.asciz "ZM"
.equ NBBLOC, (. - szTablBloc) / 3
szWord1: .asciz "A"
szWord2: .asciz "BARK"
szWord3: .asciz "BOOK"
szWord4: .asciz "TREAT"
szWord5: .asciz "COMMON"
szWord6: .asciz "SQUAD"
szWord7: .asciz "CONFUSE"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
qtabTopBloc: .skip 8 * NBBLOC
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszWord1
bl traitBlock // control word
ldr x0,qAdrszWord2
bl traitBlock // control word
ldr x0,qAdrszWord3
bl traitBlock // control word
ldr x0,qAdrszWord4
bl traitBlock // control word
ldr x0,qAdrszWord5
bl traitBlock // control word
ldr x0,qAdrszWord6
bl traitBlock // control word
ldr x0,qAdrszWord7
bl traitBlock // control word
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszWord1: .quad szWord1
qAdrszWord2: .quad szWord2
qAdrszWord3: .quad szWord3
qAdrszWord4: .quad szWord4
qAdrszWord5: .quad szWord5
qAdrszWord6: .quad szWord6
qAdrszWord7: .quad szWord7
/******************************************************************/
/* traitement */
/******************************************************************/
/* x0 contains word */
traitBlock:
stp x1,lr,[sp,-16]! // save registres
mov x1,x0
ldr x0,qAdrszMessTitre1 // insertion word in message
bl strInsertAtCharInc
bl affichageMess // display title message
mov x0,x1
bl controlBlock // control
cmp x0,#TRUE // ok ?
bne 1f
ldr x0,qAdrszMessTrue // yes
bl affichageMess
b 100f
1: // no
ldr x0,qAdrszMessFalse
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessTitre1: .quad szMessTitre1
qAdrszMessFalse: .quad szMessFalse
qAdrszMessTrue: .quad szMessTrue
/******************************************************************/
/* control if letters are in block */
/******************************************************************/
/* x0 contains word */
controlBlock:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x5,x0 // save word address
ldr x4,qAdrqtabTopBloc
ldr x6,qAdrszTablBloc
mov x2,#0
mov x3,#0
1: // init table top block used
str x3,[x4,x2,lsl #3]
add x2,x2,#1
cmp x2,#NBBLOC
blt 1b
mov x2,#0
2: // loop to load letters
ldrb w3,[x5,x2]
cbz w3,10f // end
mov x0,0xDF
and x3,x3,x0 // transform in capital letter
mov x8,#0
3: // begin loop control block
ldr x7,[x4,x8,lsl #3] // block already used ?
cbnz x7,5f // yes
add x9,x8,x8,lsl #1 // no -> index * 3
ldrb w7,[x6,x9] // first block letter
cmp w3,w7 // equal ?
beq 4f
add x9,x9,#1
ldrb w7,[x6,x9] // second block letter
cmp w3,w7 // equal ?
beq 4f
b 5f
4:
mov x7,#1 // top block
str x7,[x4,x8,lsl #3] // block used
add x2,x2,#1
b 2b // next letter
5:
add x8,x8,#1
cmp x8,#NBBLOC
blt 3b
mov x0,#FALSE // no letter find on block -> false
b 100f
10: // all letters are ok
mov x0,#TRUE
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrqtabTopBloc: .quad qtabTopBloc
qAdrszTablBloc: .quad szTablBloc
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<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|ABAP}}==
<syntaxhighlight lang="abap">
REPORT z_rosetta_abc.
Line 613 ⟶ 820:
WRITE:/ COND string( WHEN word_maker=>can_make_word( word = 'SQUAD' letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).
WRITE:/ COND string( WHEN word_maker=>can_make_word( word = 'CONFUSE' letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).
</syntaxhighlight>
{{out}}
<pre>
Line 623 ⟶ 830:
True
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!">DEFINE COUNT="20"
CHAR ARRAY sideA="BXDCNGRTQFJHVAOEFLPZ"
CHAR ARRAY sideB="OKQPATEGDSWUINBRSYCM"
BYTE ARRAY used(COUNT)
BYTE FUNC ToUpper(BYTE c)
IF c>='a AND c<='z THEN
RETURN (c-'a+'A)
FI
RETURN (c)
BYTE FUNC CanBeUsed(CHAR c)
BYTE i
FOR i=0 TO COUNT-1
DO
IF used(i)=0 AND (sideA(i+1)=c OR sideB(i+1)=c) THEN
used(i)=1
RETURN (1)
FI
OD
RETURN (0)
BYTE FUNC Check(CHAR ARRAY s)
BYTE i
CHAR c
FOR i=0 TO COUNT-1
DO used(i)=0 OD
FOR i=1 TO s(0)
DO
c=ToUpper(s(i))
IF CanBeUsed(c)=0 THEN
RETURN (0)
FI
OD
RETURN (1)
PROC Test(CHAR ARRAY s)
Print(s) Print(": ")
IF Check(s) THEN
PrintE("can be made")
ELSE
PrintE("can not be made")
FI
RETURN
PROC Main()
Test("a")
Test("bARk")
Test("book")
Test("TReat")
Test("coMMon")
Test("SQuaD")
Test("CoNfUsE")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/ABC_problem.png Screenshot from Atari 8-bit computer]
<pre>
a: can be made
bARk: can be made
book: can not be made
TReat: can be made
coMMon: can not be made
SQuaD: can be made
CoNfUsE: can be made
</pre>
Line 629 ⟶ 933:
Using #HASH-OFF
</pre>
<
FUNCTION bCAN_MAKE_WORD(zWord: STRING): BOOLEAN
VAR sBlockCount: SHORT
Line 656 ⟶ 960:
RETURN OCCURS(zUsedBlocks, ",") = sWordLength
ENDFUNCTION
</syntaxhighlight>
{{out}}
<pre>
Line 673 ⟶ 977:
</pre>
<
use Ada.Characters.Handling;
Line 751 ⟶ 1,055:
end loop;
end Abc_Problem;
</syntaxhighlight>
{{out}}
Line 766 ⟶ 1,070:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
# construct the list of blocks #
Line 846 ⟶ 1,150:
)
</syntaxhighlight>
Output:
<pre>
Line 859 ⟶ 1,163:
=={{header|ALGOL W}}==
<
begin
% Returns true if we can spell the word using the blocks, %
Line 939 ⟶ 1,243:
testCanSpell( "confuse", 7 )
end
end.</
{{out}}
<pre>
Line 952 ⟶ 1,256:
=={{header|Apex}}==
<
if (String.isEmpty(word)) {
return true;
Line 996 ⟶ 1,300:
System.debug('"COMMON": ' + canMakeWord(blocks, 'COMMON'));
System.debug('"SQuAd": ' + canMakeWord(blocks, 'SQuAd'));
System.debug('"CONFUSE": ' + canMakeWord(blocks, 'CONFUSE'));</
{{out}}
<pre>"": true
Line 1,009 ⟶ 1,313:
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
<
{{out}}
<pre> )COPY dfns ucase
Line 1,019 ⟶ 1,323:
=={{header|AppleScript}}==
===Imperative===
<
"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"}
Line 1,046 ⟶ 1,350:
end repeat
return false
end canMakeWordWithBlocks</
----
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===
<
use framework "Foundation"
Line 1,245 ⟶ 1,607:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre> '' -> true
Line 1,255 ⟶ 1,617:
'SQUAD' -> true
'conFUsE' -> true</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program problemABC.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ TRUE, 1
.equ FALSE, 0
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessTitre1: .asciz "Can_make_word: @ \n"
szMessTrue: .asciz "True.\n"
szMessFalse: .asciz "False.\n"
szCarriageReturn: .asciz "\n"
szTablBloc: .asciz "BO"
.asciz "XK"
.asciz "DQ"
.asciz "CP"
.asciz "NA"
.asciz "GT"
.asciz "RE"
.asciz "TG"
.asciz "QD"
.asciz "FS"
.asciz "JW"
.asciz "HU"
.asciz "VI"
.asciz "AN"
.asciz "OB"
.asciz "ER"
.asciz "FS"
.asciz "LY"
.asciz "PC"
.asciz "ZM"
.equ NBBLOC, (. - szTablBloc) / 3
szWord1: .asciz "A"
szWord2: .asciz "BARK"
szWord3: .asciz "BOOK"
szWord4: .asciz "TREAT"
szWord5: .asciz "COMMON"
szWord6: .asciz "SQUAD"
szWord7: .asciz "CONFUSE"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
itabTopBloc: .skip 4 * NBBLOC
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszWord1
bl traitBlock @ control word
ldr r0,iAdrszWord2
bl traitBlock @ control word
ldr r0,iAdrszWord3
bl traitBlock @ control word
ldr r0,iAdrszWord4
bl traitBlock @ control word
ldr r0,iAdrszWord5
bl traitBlock @ control word
ldr r0,iAdrszWord6
bl traitBlock @ control word
ldr r0,iAdrszWord7
bl traitBlock @ control word
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszWord1: .int szWord1
iAdrszWord2: .int szWord2
iAdrszWord3: .int szWord3
iAdrszWord4: .int szWord4
iAdrszWord5: .int szWord5
iAdrszWord6: .int szWord6
iAdrszWord7: .int szWord7
/******************************************************************/
/* traitement */
/******************************************************************/
/* r0 contains word */
traitBlock:
push {r1,lr} @ save registers
mov r1,r0
ldr r0,iAdrszMessTitre1 @ insertion word in message
bl strInsertAtCharInc
bl affichageMess @ display title message
mov r0,r1
bl controlBlock @ control
cmp r0,#TRUE @ ok ?
bne 1f
ldr r0,iAdrszMessTrue @ yes
bl affichageMess
b 100f
1: @ no
ldr r0,iAdrszMessFalse
bl affichageMess
100:
pop {r1,lr}
bx lr @ return
iAdrszMessTitre1: .int szMessTitre1
iAdrszMessFalse: .int szMessFalse
iAdrszMessTrue: .int szMessTrue
/******************************************************************/
/* control if letters are in block */
/******************************************************************/
/* r0 contains word */
controlBlock:
push {r1-r9,lr} @ save registers
mov r5,r0 @ save word address
ldr r4,iAdritabTopBloc
ldr r6,iAdrszTablBloc
mov r2,#0
mov r3,#0
1: @ init table top block used
str r3,[r4,r2,lsl #2]
add r2,r2,#1
cmp r2,#NBBLOC
blt 1b
mov r2,#0
2: @ loop to load letters
ldrb r3,[r5,r2]
cmp r3,#0
beq 10f @ end
and r3,r3,#0xDF @ transform in capital letter
mov r8,#0
3: @ begin loop control block
ldr r7,[r4,r8,lsl #2] @ block already used ?
cmp r7,#0
bne 5f @ yes
add r9,r8,r8,lsl #1 @ no -> index * 3
ldrb r7,[r6,r9] @ first block letter
cmp r3,r7 @ equal ?
beq 4f
add r9,r9,#1
ldrb r7,[r6,r9] @ second block letter
cmp r3,r7 @ equal ?
beq 4f
b 5f
4:
mov r7,#1 @ top block
str r7,[r4,r8,lsl #2] @ block used
add r2,r2,#1
b 2b @ next letter
5:
add r8,r8,#1
cmp r8,#NBBLOC
blt 3b
mov r0,#FALSE @ no letter find on block -> false
b 100f
10: @ all letters are ok
mov r0,#TRUE
100:
pop {r1-r9,lr}
bx lr @ return
iAdritabTopBloc: .int itabTopBloc
iAdrszTablBloc: .int szTablBloc
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<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|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]
[O B] [E R] [F S] [L Y] [P C] [Z M]
] => [ join map & => [to :string &]]
charInBlock: function [ch,bl][
loop.with:'i bl 'b ->
if contains? b upper ch [
return i
]
return ø
]
canMakeWord?: function [wrd][
ref: new blocks
loop split wrd 'chr [
cib: charInBlock chr ref
if? cib = ø [ return false ]
else [ ref: remove ref .index cib ]
]
return true
]
loop ["A" "BaRk" "bOoK" "tReAt" "CoMmOn" "SqUaD" "cONfUsE"] 'wrd
-> print [wrd "=>" canMakeWord? wrd]</syntaxhighlight>
{{Out}}
<pre>A => true
BaRk => true
bOoK => false
tReAt => true
CoMmOn => false
SqUaD => true
cONfUsE => true</pre>
=={{header|Astro}}==
<
if ls.isempty:
return true
Line 1,268 ⟶ 1,869:
for s in test:
print "($|>8|{s} ${abc(s, list)})"</
=={{header|AutoHotkey}}==
'''Function'''
<
o := {}
loop, parse, blocks, `n, `r
Line 1,296 ⟶ 1,897:
added := 1
}
}</
'''Test Input''' (as per question)
<
(
BO
Line 1,336 ⟶ 1,937:
loop, parse, wordlist, `n
out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
msgbox % out</
{{out}}
Line 1,496 ⟶ 2,097:
=={{header|BaCon}}==
<
DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
Line 1,519 ⟶ 2,120:
PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n"
WEND</
{{out}}
<pre>
Line 1,533 ⟶ 2,134:
=={{header|BASIC}}==
Works with:VB-DOS, QB64, QBasic, QuickBASIC
<
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ABC_Problem '
Line 1,659 ⟶ 2,260:
END FUNCTION
</syntaxhighlight>
==={{header|Commodore BASIC}}===
{{trans|Sinclair ZX-81 BASIC}}
<
20 W$ = "BARK" : GOSUB 100
30 W$ = "BOOK" : GOSUB 100
Line 1,674 ⟶ 2,275:
100 B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
110 FOR I=1 TO LEN(W$)
120
130
140
150
160
170
180
190
200
210 NEXT I
220 PRINT W$" -> YES"
230 RETURN
240 PRINT W$" -> NO"
250 RETURN</
{{out}}
<pre>A -> YES
Line 1,696 ⟶ 2,298:
SQUAD -> YES
CONFUSE -> YES</pre>
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
130 DIM W$(MS):REM REMAINING LETTERS
140 DIM I(MS):REM LOOP CONTROL VARIABLE
150 DIM RV(MS):REM RETURN VALUE
160 SP=-1:REM STACK POINTER
170 READ BL$
180 PRINT "USING BLOCKS: "
190 FOR I=1 TO LEN(BL$) STEP 2
200 : PRINT"("MID$(BL$,I,2)")";
210 NEXT I
220 PRINT CHR$(13)
230 READ W$
240 IF W$="" THEN 320
250 PRINT W$;"->";
260 SP=SP+1:BL$(SP)=BL$:W$(SP)=W$
270 GOSUB 350
280 IF RV(SP) THEN PRINT "YES": GOTO 300
290 PRINT "NO"
300 SP=SP-1
310 GOTO 230
320 READ BL$
330 IF BL$ THEN PRINT:GOTO 180
340 END
350 IF LEN(W$(SP))=0 THEN RV(SP)=-1:RETURN
360 I(SP)=1
370 IF I(SP)>=LEN(BL$(SP)) THEN RV(SP)=0:RETURN
380 IF MID$(BL$(SP),I(SP),1) = LEFT$(W$(SP),1) THEN 410
390 IF MID$(BL$(SP),I(SP)+1,1) = LEFT$(W$(SP),1) THEN 410
400 GOTO 450
410 W$(SP+1)=MID$(W$(SP),2)
420 BL$(SP+1)=LEFT$(BL$(SP),I(SP)-1)+MID$(BL$(SP),I(SP)+2)
430 SP=SP+1:GOSUB 350:SP=SP-1
440 IF RV(SP+1) THEN RV(SP)=-1:RETURN
450 I(SP)=I(SP)+2:GOTO 370
460 DATA BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM
470 DATA A, BORK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, ""
480 DATA ABABACAC,ABBA,""
490 DATA ""</syntaxhighlight>
{{Out}}
<pre>USING BLOCKS:
(BO)(XK)(DQ)(CP)(NA)(GT)(RE)(TG)(QD)(FS)
(JW)(HU)(VI)(AN)(OB)(ER)(FS)(LY)(PC)(ZM)
A->YES
BORK->YES
BOOK->NO
TREAT->YES
COMMON->NO
SQUAD->YES
CONFUSE->YES
USING BLOCKS:
(AB)(AB)(AC)(AC)
ABBA->YES</pre>
==={{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.
<
20 INPUT W$
30 FOR I=1 TO LEN W$
Line 1,709 ⟶ 2,372:
90 STOP
100 NEXT J
110 PRINT "NO"</
{{in}}
<pre>A</pre>
Line 1,738 ⟶ 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}}==
<
@echo off
::abc.bat
Line 1,803 ⟶ 2,517:
:END
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PROCcan_make_word("A")
PROCcan_make_word("BARK")
Line 1,828 ⟶ 2,542:
ENDWHILE
IF word$>"" PRINT "False" ELSE PRINT "True"
ENDPROC</
{{out}}
Line 1,839 ⟶ 2,553:
Confuse -> True
</pre>
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
let canMakeWord(word) = valof
$( let blocks = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
let avl = vec 40/BYTESPERWORD
for i=0 to 39 do avl%i := blocks%(i+1)
for i=1 to word%0
$( for j=0 to 39
$( let ch = word%i
// make letter uppercase
if 'a' <= ch <= 'z' then ch := ch - 32
if ch = avl%j then
$( // this block is no longer available
avl%j := 0
avl%(j neqv 1) := 0
// but we did find a block
goto next
$)
$)
resultis false // no block found
next: loop
$)
resultis true
$)
let show(word) be
writef("%S: %S*N", word, canMakeWord(word) -> "yes", "no")
let start() be
$( show("A")
show("BARK")
show("book")
show("Treat")
show("CoMmOn")
show("SQUAD")
show("CONFUSE")
$)</syntaxhighlight>
{{out}}
<pre>A: yes
BARK: yes
book: no
Treat: yes
CoMmOn: no
SQUAD: yes
CONFUSE: yes</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">ABC ← {
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
𝕨(×∘≠∘⊢ ◶ ⟨1˙, # if the word is empty, it can be made
Matches(×∘≠∘⊣ ◶ ⟨0˙, # if no matching blocks, it cannot
∨´(𝕨 Others⊣) 𝕊¨ 1<∘↓⊢ # otherwise, remove block and try remaining letters
⟩)⊢
⟩) (⊢-32×1="a{"⍋⊢)𝕩
}
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"⟩
> {(<𝕩) ∾ blocks ABC 𝕩}¨ words</syntaxhighlight>
{{out}}
<pre>┌─
╵ "A" 1
"bark" 1
"BOOK" 0
"TrEaT" 1
"Common" 0
"Squad" 1
"Confuse" 1
┘</pre>
=={{header|Bracmat}}==
<
( can-make-word
= ABC blocks
Line 1,888 ⟶ 2,677:
& can-make-word'SQUAD
& can-make-word'CONFUSE
);</
{{out}}
<pre>A yes
Line 1,900 ⟶ 2,689:
=={{header|C}}==
Recursive solution. Empty string returns true.
<
#include <ctype.h>
Line 1,940 ⟶ 2,729:
return 0;
}</
{{out}}
<pre>
Line 1,953 ⟶ 2,742:
</pre>
=={{header|C sharp|C#}}==
===Regex===
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).
<
using System.IO;
// Needed for the method.
Line 1,987 ⟶ 2,776:
return true;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,999 ⟶ 2,788:
</pre>
'''Unoptimized'''
<
using System.Linq;
Line 2,081 ⟶ 2,870:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,095 ⟶ 2,884:
{{Works with|C++11}}
Build with:
<
<
#include <vector>
#include <string>
Line 2,129 ⟶ 2,918:
std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n";
}
}</
{{out}}
Line 2,146 ⟶ 2,935:
<b>module.ceylon</b>
<
module rosetta.abc "1.0.0" {}
</syntaxhighlight>
<b>run.ceylon</b>
<
shared void run() {
printAndCanMakeWord("A", blocks);
Line 2,227 ⟶ 3,016:
myRemainingLetterIndexes)
else false;
</syntaxhighlight>
{{out}}
Line 2,242 ⟶ 3,031:
=={{header|Clojure}}==
A translation of the Haskell solution.
<
(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,263 ⟶ 3,052:
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word)))</
{{out}}
Line 2,273 ⟶ 3,062:
SQUAD: true
CONFUSE: true</pre>
=={{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
if c>='a' & c<='z' then
c := char$i2c(char$c2i(c) - 32)
end
array[char]$addh(rslt,c)
end
return(string$ac2s(rslt))
end ucase
abc = proc (s: string) returns (bool)
own collection: sequence[string] := sequence[string]$
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
blocks: array[string] := sequence[string]$s2a(collection)
for c: char in string$chars(ucase(s)) do
begin
for i: int in array[string]$indexes(blocks) do
if string$indexc(c, blocks[i]) ~= 0 then
blocks[i] := ""
exit found
end
end
return(false)
end
except when found: end
end
return(true)
end abc
start_up = proc ()
po: stream := stream$primary_output()
words: sequence[string] := sequence[string]$
["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]
for word: string in sequence[string]$elements(words) do
stream$puts(po, word || ": ")
if abc(word) then stream$putl(po, "yes")
else stream$putl(po, "no")
end
end
end start_up</syntaxhighlight>
{{out}}
<pre>A: yes
BARK: yes
BOOK: no
TREAT: yes
COMMON: no
SQUAD: yes
CONFUSE: yes</pre>
=={{header|CoffeeScript}}==
<
canMakeWord = (word="") ->
Line 2,292 ⟶ 3,135:
# Expect true, true, false, true, false, true, true, true
for word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "squad", "CONFUSE", "STORM"]
console.log word + " -> " + canMakeWord(word)</
{{out}}
Line 2,303 ⟶ 3,146:
CONFUSE -> true
STORM -> true</pre>
=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 FUNC can'make'word#(word$) CLOSED
0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
0030 FOR i#:=1 TO LEN(word$) DO
0040 pos#:=UPPER$(word$(i#)) IN blocks$
0050 IF NOT pos# THEN RETURN FALSE
0060 blocks$(pos#):="";blocks$(pos# BITXOR 1):=""
0070 ENDFOR i#
0080 RETURN TRUE
0090 ENDFUNC
0100 //
0110 DIM yesno$(0:1) OF 3
0120 yesno$(FALSE):="no";yesno$(TRUE):="yes"
0130 WHILE NOT EOD DO
0140 READ w$
0150 PRINT w$,": ",yesno$(can'make'word#(w$))
0160 ENDWHILE
0170 END
0180 //
0190 DATA "A","BARK","BOOK","treat","common","squad","CoNfUsE"</syntaxhighlight>
{{out}}
<pre>A: yes
BARK: yes
BOOK: no
treat: yes
common: no
squad: yes
CoNfUsE: yes</pre>
=={{header|Common Lisp}}==
<
(defun word-possible-p (word blocks)
(cond
Line 2,319 ⟶ 3,191:
collect (word-possible-p
(subseq word 1)
(remove b blocks))))))))</
{{out}}
Line 2,341 ⟶ 3,213:
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<
MODULE ABCProblem;
IMPORT
Line 2,426 ⟶ 3,298:
END ABCProblem.
</syntaxhighlight>
Execute: ^Q ABCProblem.CanMakeWord A BARK BOOK TREAT COMMON SQUAD confuse~
{{out}}
Line 2,438 ⟶ 3,310:
confuse:> $TRUE
</pre>
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
sub can_make_word(word: [uint8]): (r: uint8) is
var blocks: [uint8] := "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM";
# Initialize blocks array
var avl: uint8[41];
CopyString(blocks, &avl[0]);
r := 1;
loop
var letter := [word];
word := @next word;
if letter == 0 then break; end if;
# find current letter in blocks
var i: @indexof avl := 0;
loop
var block := avl[i];
if block == 0 then
# no block, this word cannot be formed
r := 0;
return;
elseif block == letter then
# we found it, blank it out
avl[i] := ' ';
avl[i^1] := ' '; # and the other letter on the block too
break;
end if;
i := i + 1;
end loop;
end loop;
end sub;
# test a list of words
var words: [uint8][] := {"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"};
var resp: [uint8][] := {": No\n", ": Yes\n"};
var i: @indexof words := 0;
while i < @sizeof words loop
print(words[i]);
print(resp[can_make_word(words[i])]);
i := i + 1;
end loop;</syntaxhighlight>
{{out}}
<pre>A: Yes
BARK: Yes
BOOK: No
TREAT: Yes
COMMON: No
SQUAD: Yes
CONFUSE: Yes</pre>
=={{header|D}}==
Line 2,443 ⟶ 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.
<
bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
Line 2,464 ⟶ 3,392:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</
{{out}}
<pre>"" true
Line 2,477 ⟶ 3,405:
===@nogc Version===
The same as the precedent version, but it avoids all heap allocations and it's lower-level and ASCII-only.
<
bool canMakeWord(in string word, in string[] blocks) nothrow @nogc
Line 2,515 ⟶ 3,443:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</
===Recursive Version===
This version is able to find the solution for the word "abba" given the blocks AB AB AC AC.
{{trans|C}}
<
alias Block = char[2];
Line 2,557 ⟶ 3,485:
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</
{{out}}
<pre>"" true
Line 2,571 ⟶ 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.
<
alias Block = char[2];
Line 2,612 ⟶ 3,540:
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</
The output is the same.
=={{header|Delphi}}==
Just to be different I implemented a block as a set of (2) char rather than as an array of (2) char.
<
{$APPTYPE CONSOLE}
Line 2,680 ⟶ 3,608:
readln;
end.
</syntaxhighlight>
{{out}}
Line 2,692 ⟶ 3,620:
Can make CONFUSE
</pre>
=={{header|Draco}}==
<syntaxhighlight lang="draco">\util.g
proc nonrec ucase(char c) char:
byte b;
b := pretend(c, byte);
b := b & ~32;
pretend(b, char)
corp
proc nonrec can_make_word(*char w) bool:
[41] char blocks;
word i;
char ch;
bool found, ok;
CharsCopy(&blocks[0], "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM");
ok := true;
while
ch := ucase(w*);
w := w + 1;
ok and ch ~= '\e'
do
found := false;
i := 0;
while not found and i < 40 do
if blocks[i] = ch then found := true fi;
i := i + 1;
od;
if found then
i := i - 1;
blocks[i] := '\e';
blocks[i >< 1] := '\e'
else
ok := false
fi
od;
ok
corp
proc nonrec test(*char w) void:
writeln(w, ": ", if can_make_word(w) then "yes" else "no" fi)
corp
proc nonrec main() void:
test("A");
test("BARK");
test("book");
test("treat");
test("CoMmOn");
test("sQuAd");
test("CONFUSE")
corp</syntaxhighlight>
{{out}}
<pre>A: yes
BARK: yes
book: no
treat: yes
CoMmOn: no
sQuAd: yes
CONFUSE: yes</pre>
=={{header|Dyalect}}==
Line 2,697 ⟶ 3,688:
{{trans|Swift}}
<
var blocks = [
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" ]
var strUp = str.
var
for c in strUp {
for j in blocks.
if blocks[j].
blocks[j] = ""
break
Line 2,715 ⟶ 3,706:
}
return
}
func canOrNot(can)
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
print("\"\(str)\" \(canOrNot(blockable(str))) be spelled with blocks.")
}</
{{out}}
Line 2,735 ⟶ 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}}==
<
(lib 'list) ;; list-delete
Line 2,754 ⟶ 3,781:
(spell (string-rest word) (list-delete blocks block))))))
</syntaxhighlight>
{{out}}
<pre>
Line 2,773 ⟶ 3,800:
=={{header|Ela}}==
{{trans|Haskell}}
<
:::IO
Line 2,789 ⟶ 3,816:
mapM_ (\w -> putLn (w, not << null $ abc blocks (map char.upper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</
{{out}}
Line 2,802 ⟶ 3,829:
=={{header|Elena}}==
ELENA
<
import system'collections;
import system'culture;
import extensions;
import extensions'routines;
Line 2,814 ⟶ 3,842:
var list := ArrayList.load(blocks);
^ nil == (cast string(self)).
{
var index := list.indexOfElement
Line 2,843 ⟶ 3,871:
e.next();
words.forEach::(word)
{
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
}
}</
{{out}}
<pre>
Line 2,863 ⟶ 3,891:
{{trans|Erlang}}
{{works with|Elixir|1.3}}
<
def can_make_word(word, avail) do
can_make_word(String.upcase(word) |> to_charlist, avail, [])
Line 2,878 ⟶ 3,906:
blocks = ~w(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM)c
~w(A Bark Book Treat Common Squad Confuse) |>
Enum.map(fn(w) -> IO.puts "#{w}: #{ABC.can_make_word(w, blocks)}" end)</
{{out}}
Line 2,889 ⟶ 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}}==
<
-export([can_make_word/1, can_make_word/2, blocks/0]).
Line 2,908 ⟶ 4,019:
main(_) -> lists:map(fun(W) -> io:fwrite("~s: ~s~n", [W, can_make_word(W)]) end,
["A","Bark","Book","Treat","Common","Squad","Confuse"]).
</syntaxhighlight>
{{Out}}
Line 2,921 ⟶ 4,032:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM BLOCKS
Line 2,950 ⟶ 4,061:
CANMAKEWORD("Confuse")
END PROGRAM
</syntaxhighlight>
=={{header|Euphoria}}==
implemented using OpenEuphoria
<syntaxhighlight lang="euphoria">
include std/text.e
Line 2,990 ⟶ 4,101:
if getc(0) then end if
</syntaxhighlight>
{{out}}
<pre>
Line 3,006 ⟶ 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>
<
let rec look_for_right_candidate candidates noCandidates c rest =
match candidates with
Line 3,035 ⟶ 4,146:
List.iter (fun w -> printfn "Using the blocks we can make the word '%s': %b" w (spell_word_with blocks w)) words
0</
{{out}}
<pre>h:\RosettaCode\ABC\Fsharp>RosettaCode "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" a bark book threat common squad confuse
Line 3,051 ⟶ 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}}==
<
kernel math math.statistics qw sequences sets unicode ;
IN: rosetta-code.abc-problem
Line 3,097 ⟶ 4,252:
show-blocks header input [ result ] each ;
MAIN: abc-problem</
{{out}}
<pre>
Line 3,119 ⟶ 4,274:
=={{header|FBSL}}==
This approach uses a string, blanking out the pair previously found. Probably faster than array manipulation.
<
#APPTYPE CONSOLE
SUB MAIN()
Line 3,164 ⟶ 4,319:
RETURN TRUE
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>
Line 3,177 ⟶ 4,332:
Press any key to continue...
</pre>
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<syntaxhighlight lang="forth">: blockslist s" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" ;
variable blocks
: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;
: freeblocks blockslist nip negate allot ;
: toupper 223 and ;
: clearblock ( addr-block -- )
dup '_' swap c!
dup blocks @ - 1 and if 1- else 1+ then
'_' swap c!
;
: pickblock ( addr-input -- addr-input+1 f )
dup 1+ swap c@ toupper ( -- addr-input+1 c )
blockslist nip 0 do
blocks @ i + dup c@ 2 pick ( -- addr-input+1 c addri ci c )
= if clearblock drop true unloop exit else drop then
loop drop false
;
: abc ( addr-input u -- f )
allotblocks
0 do
pickblock
invert if drop false unloop exit cr then
loop drop true
freeblocks
;
: .abc abc if ." True" else ." False" then ;</syntaxhighlight>
{{out}}
<pre>s" A" .abc True ok
s" BarK" .abc True ok
s" BOOK" .abc False ok
s" TrEaT" .abc True ok
s" COMMON" .abc False ok
s" SQUAD" .abc True ok
s" CONFUSE" .abc True ok
</pre>
=={{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!
<
!Compilation started at Thu Jun 5 01:52:03
!
Line 3,249 ⟶ 4,452:
end subroutine ucase
end program abc</
===But if backtracking might be needed===
Line 3,257 ⟶ 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">
MODULE PLAYPEN !Messes with a set of alphabet blocks.
INTEGER MSG !Output unit number.
Line 3,535 ⟶ 4,738:
END DO
END
</syntaxhighlight>
Output: the first column of T/F is the report from CANBLOCK, the second is the expected answer from the example, and the third is whether the two are in agreement.
<pre>
Line 3,560 ⟶ 4,763:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 3,602 ⟶ 4,805:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>A true
Line 3,611 ⟶ 4,814:
SQUAD true
CONFUSE true</pre>
=={{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.
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)
mda(0) = {@"BO",@"XK",@"DQ",@"CP",@"NA",@"GT",@"RE",@"TG",@"QD",¬
@"FS",@"JW",@"HU",@"VI",@"AN",@"OB",@"ER",@"FS",@"LY",@"PC",@"ZM"}
for i = 0 to len(w) - 1
for j = 0 to mda_count - 1
t1 = mid( mda(j), 0, 1 ) : t2 = mid( mda(j), 1, 1 )
if ( fn StringIsEqual( mid( w, i, 1 ), t1 ) ) then s = fn StringByAppendingString( s, t1 ) : mda(j) = @" " : break
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
</syntaxhighlight>
{{output}}
<pre>
Can blocks spell : YES
Can blocks spell a : YES
Can blocks spell Bark : YES
Can blocks spell BOOK : NO
Can blocks spell TrEaT : YES
Can blocks spell COMMON : NO
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]'''
<
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 3,641 ⟶ 4,925:
Next
End</
Output:
<pre>
Line 3,654 ⟶ 4,938:
=={{header|Go}}==
<
import (
Line 3,692 ⟶ 4,976:
fmt.Println(word, sp(word))
}
}</
{{out}}
<pre>
Line 3,706 ⟶ 4,990:
=={{header|Groovy}}==
Solution:
<
def blocks
Line 3,717 ⟶ 5,001:
word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
}
}</
Test:
<
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])
['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {
println "'${it}': ${a.canMakeWord(it)}"
}</
{{out}}
Line 3,739 ⟶ 5,023:
=={{header|Harbour}}==
Harbour Project implements a cross-platform Clipper/xBase compiler.
<
LOCAL cStr
Line 3,770 ⟶ 5,054:
NEXT
RETURN cFinal == cStr</
{{out}}
<pre>
Line 3,784 ⟶ 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.
<
import Data.Char (toUpper)
Line 3,798 ⟶ 5,082:
main :: IO ()
main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</
{{out}}
Line 3,814 ⟶ 5,098:
Or, in terms of the bind operator:
<
import Data.
----------------------- ABC PROBLEM ----------------------
spellWith :: [String] -> String -> [[String]]
spellWith _ [] = [[]]
spellWith blocks (x : xs) = blocks >>= go
where
go b
Line 3,825 ⟶ 5,112:
| otherwise = []
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( print
. ((,) <*>)
(not . null . spellWith blocks . fmap toUpper)
)
[ "",
"A",
"BARK",
"BoOK",
"TrEAT",
"COmMoN",
"SQUAD",
"conFUsE"
]
blocks :: [String]
blocks =
words $
"BO XK DQ CP NA GT RE TG QD FS JW"
<> " HU VI AN OB ER FS LY PC ZM"</syntaxhighlight>
{{Out}}
<pre>("",True)
Line 3,847 ⟶ 5,150:
Works in both languages:
<
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
Line 3,870 ⟶ 5,173:
}
}
end</
Sample run:
Line 3,884 ⟶ 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:'''
<
'rows cols'=. i.&.> $y
for_c. cols do.
Line 3,898 ⟶ 5,220:
)
abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0:</
'''Examples:'''
<
ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
Line 3,913 ⟶ 5,235:
"COmMOn" F
"SqUAD" T
"CoNfuSE" T</
'''Tacit version'''
<
uppc=:(-32*96&<*.123&>)&.(3&u:)
reduc=: ] delElem 1 i.~e."0 1
forms=: (1 - '' -: (reduc L:0/ :: (a:"_)@(<"0@],<@[))&uppc) L:0</
{{out}}
Line 3,943 ⟶ 5,265:
Another approach might be:
<
ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
Line 3,950 ⟶ 5,272:
need=: #/.~ word,word
relevant=: (x +./@e."1 word) # x
candidates=: word,"1>,{ {relevant
+./(((#need){. #/.~)"1 candidates) */ .>:need
)</
Example use:
<
1
Blocks canform 1{::ExampleWords
Line 3,969 ⟶ 5,291:
1
Blocks canform 6{::ExampleWords
1</
Explanation:
Line 3,979 ⟶ 5,301:
For example:
<
1
word
Line 3,992 ⟶ 5,314:
ANN
AAA
AAN</
Here, the word is simply 'A', and we have two blocks to consider for our word: AN and NA. So we form all possible combinations of the letters of those two bocks, prefix each of them with our word and test whether any of them contain two copies of the letters of our word. (As it happens,
=={{header|Java}}==
{{trans|C}}
{{works with|Java|1.6+}}
<
import java.util.Collections;
import java.util.List;
Line 4,034 ⟶ 5,356:
return false;
}
}</
{{out}}
<pre>"": true
Line 4,049 ⟶ 5,371:
====Imperative====
The following method uses regular expressions and the string replace function to allow more support for older browsers.
<
function CheckWord(blocks, word) {
Line 4,086 ⟶ 5,408:
for(var i = 0;i<words.length;++i)
console.log(words[i] + ": " + CheckWord(blocks, words[i]));
</syntaxhighlight>
Result:
Line 4,100 ⟶ 5,422:
====Functional====
<
var strBlocks =
Line 4,147 ⟶ 5,469:
return strWords.split(' ').map(solution).join('\n');
})('A bark BooK TReAT COMMON squAD conFUSE');</
{{Out}}
<
bark -> BO NA RE XK
BooK: [no solution]
Line 4,155 ⟶ 5,477:
COMMON: [no solution]
squAD -> FS DQ HU NA QD
conFUSE -> CP BO NA FS HU FS RE</
===ES6===
====Imperative====
<
let blocks = characters.split(" ").map(pair => pair.split(""));
Line 4,191 ⟶ 5,513:
"CONFUSE"
].forEach(word => console.log(`${word}: ${isWordPossible(word)}`));
</syntaxhighlight>
Result:
Line 4,205 ⟶ 5,527:
====Functional====
{{Trans|Haskell}}
<
//
// spellWith :: [(Char, Char)] -> [Char] -> [[(Char, Char)]]
const spellWith =
[]
] : (() => {
return
b =>
spellWith(
deleteBy(
)
)(xs)
);
})();
// ---------------------- TEST -----------------------
const
const blocks = (
"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
).split(" ");
"", "A", "BARK", "BoOK", "TrEAT",
"COmMoN", "SQUAD", "conFUsE"
]
.map(
x => JSON.stringify([
x, !Boolean(
spellWith(blocks)(
[...x.toLocaleUpperCase()]
)
.length
)
])
)
.join("\n");
};
// ---------------- GENERIC FUNCTIONS ----------------
// deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
const deleteBy =
) : [xs[0], ...go(xs.slice(1))]
) : [];
};
return main();
})();</syntaxhighlight>
{{Out}}
<pre>["",true]
Line 4,313 ⟶ 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.<
# 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 4,342 ⟶ 5,634:
else .[1:] | abc($blks)
end
end;</
Task:<
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] as $blocks
| ("A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE")
| "\(.) : \( .|abc($blocks) )" ;task</
{{Out}}
A : true
Line 4,359 ⟶ 5,651:
=={{header|Jsish}}==
Based on Javascript ES5 imperative solution.
<
/* 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 4,395 ⟶ 5,687:
can spell CONFUSE
=!EXPECTEND!=
*/</
{{out}}
Line 4,412 ⟶ 5,704:
=={{header|Julia}}==
<
function abc(str::AbstractString, list)
Line 4,430 ⟶ 5,722:
@printf("%-8s | %s\n", str, abc(str, list))
end
end</
{{out}}
Line 4,441 ⟶ 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}}
<
fun run() {
println("\"\": " + blocks.canMakeWord(""))
for (w in words) println("$w: " + blocks.canMakeWord(w))
}
Line 4,463 ⟶ 5,808:
return true
val c =
var i = 0
forEach { b ->
Line 4,477 ⟶ 5,822:
return false
}
private val blocks = arrayOf(
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
)
private val words = arrayOf("A", "BARK", "book", "treat", "COMMON", "SQuAd", "CONFUSE")
}
fun main(args: Array<String>) = ABC_block_checker.run()</
{{out}}
<pre>"": true
Line 4,489 ⟶ 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 4,535 ⟶ 5,941:
wend
end function
</syntaxhighlight>
{{out}}
<pre>
Line 4,557 ⟶ 5,963:
</pre>
===Procedural solution===
<syntaxhighlight lang="lb">
print "Rosetta Code - ABC problem (procedural solution)"
print
Line 4,691 ⟶ 6,097:
LetterOK=1
end sub
</syntaxhighlight>
{{out}}
<pre>
Line 4,714 ⟶ 6,120:
=={{header|Logo}}==
<
[J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]
Line 4,734 ⟶ 6,140:
]
bye</
{{Out}}
Line 4,744 ⟶ 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}}==
<
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
Line 4,776 ⟶ 6,292:
end
print(found)
end</
{{Output}}
Line 4,792 ⟶ 6,308:
<syntaxhighlight lang="m2000 interpreter">
Module ABC {
can_make_word("A")
Line 4,813 ⟶ 6,329:
}
ABC
</syntaxhighlight>
{{out}}
Line 4,825 ⟶ 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}}==
<
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 4,849 ⟶ 6,433:
end proc:
seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]);</
{{out}}
<pre>
Line 4,862 ⟶ 6,446:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
ClearAll[DoStep,ABCBlockQ]
Line 4,875 ⟶ 6,459:
DoStep[opts_List]:=Flatten[DoStep@@@opts,1]
ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={})
</syntaxhighlight>
{{Out}}
<pre>
Line 4,894 ⟶ 6,478:
</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
Line 4,920 ⟶ 6,504:
k = k+1;
end
end</
{{out}}
<pre>Can make word A.
Line 4,936 ⟶ 6,520:
Recursively checks if the word is possible if a block is removed from the array.
<syntaxhighlight lang="maxscript">
-- This is the blocks array
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
Line 5,035 ⟶ 6,619:
)
)
</syntaxhighlight>
'''Output:'''
<syntaxhighlight lang="maxscript">
iswordpossible "a"
true
Line 5,053 ⟶ 6,637:
iswordpossible "confuse"
true
</syntaxhighlight>
=== Non-recursive ===
<syntaxhighlight lang="maxscript">
fn isWordPossible2 word =
(
Line 5,088 ⟶ 6,672:
) else return false
)
</syntaxhighlight>
Both versions are good for this example, but the non-recursive version won't work if the blocks are more random, because it just takes the first found block, and the recursive version decides which one to use.
Line 5,094 ⟶ 6,678:
Then:
<syntaxhighlight lang="maxscript">
iswordpossible "water"
true
iswordpossible2 "water"
false
</syntaxhighlight>
Non-recursive version quickly decides that it's not possible, even though it clearly is.
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 5,137 ⟶ 6,721:
io.format("can_make_word(""%s"") :- %s.\n",
[s(W), s(if P then "true" else "fail")], !IO)),
Words, !IO).</
Note that 'P', in the foldl near the end, is not a boolean variable, but a zero-arity currying of can_make_word (i.e., it's a 'lambda' that takes no arguments and then calls can_make_word with all of the already-supplied arguments).
=={{header|MiniScript}}==
<
swap = function(list, index1, index2)
Line 5,168 ⟶ 6,752:
print out + ": " + canMakeWord(val, allBlocks)
end for
</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
if blocks.len < word.len: return false
if word.len == 0: return true
let ch = word[0].toUpperAscii
for i, pair in blocks:
if ch in pair and
(blocks[0..<i] & blocks[i+1..^1]).canMakeWord(word[1..^1]):
return true
proc main =
for (blocks, words) in [
("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM".splitWhitespace,
@["A", "bArK", "BOOK", "treat", "common", "sQuAd", "CONFUSE"]),
("AB AB
("US TZ
echo "Using the blocks ", blocks.join(" ")
for word in words:
echo " can we make the word '$#'? $#" % [
word, if blocks.canMakeWord(word): "yes" else: "no"]
echo()
when isMainModule: main()</syntaxhighlight>
{{Out}}
<pre>
can we make the word 'CONFUSE'? yes
Using the blocks AB AB AC AC
can we make the word 'ABBa'? yes
Using the blocks US TZ AO QA
can we make the word 'Auto'? yes</pre>
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE ABCBlocks;
IMPORT
Line 5,290 ⟶ 6,923:
Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln;
END ABCBlocks.
</syntaxhighlight>
Output:
<pre>
Line 5,304 ⟶ 6,937:
=={{header|Objeck}}==
{{trans|Java}}
<
function : Main(args : String[]) ~ Nil {
blocks := ["BO", "XK", "DQ", "CP", "NA",
Line 5,349 ⟶ 6,982:
arr[j] := tmp;
}
}</
<pre>
"": true
Line 5,362 ⟶ 6,995:
=={{header|OCaml}}==
<
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
Line 5,401 ⟶ 7,034:
"SQUAD", true;
"CONFUSE", true;
]</
{{Out}}
Line 5,417 ⟶ 7,050:
=={{header|Oforth}}==
<
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
Line 5,430 ⟶ 7,063:
]
false
;</
{{out}}
Line 5,440 ⟶ 7,073:
=={{header|OpenEdge/Progress}}==
<
/* List of blocks */
Line 5,542 ⟶ 7,175:
RETURN TRUE.
END FUNCTION.
</syntaxhighlight>
{{out}}
Line 5,553 ⟶ 7,186:
SQUAD = yes
CONFUSE = yes
</pre>
=={{header|Order}}==
<syntaxhighlight lang="order">#include <order/interpreter.h>
#include <order/lib.h>
// Because of technical limitations, characters within a "string" must be separated by white spaces.
// For the sake of simplicity, only upper-case characters are supported here.
// A few lines of boiler-plate oriented programming are needed to enable character parsing and comparison.
#define ORDER_PP_TOKEN_A (A)
#define ORDER_PP_TOKEN_B (B)
#define ORDER_PP_TOKEN_C (C)
#define ORDER_PP_TOKEN_D (D)
#define ORDER_PP_TOKEN_E (E)
#define ORDER_PP_TOKEN_F (F)
#define ORDER_PP_TOKEN_G (G)
#define ORDER_PP_TOKEN_H (H)
#define ORDER_PP_TOKEN_I (I)
#define ORDER_PP_TOKEN_J (J)
#define ORDER_PP_TOKEN_K (K)
#define ORDER_PP_TOKEN_L (L)
#define ORDER_PP_TOKEN_M (M)
#define ORDER_PP_TOKEN_N (N)
#define ORDER_PP_TOKEN_O (O)
#define ORDER_PP_TOKEN_P (P)
#define ORDER_PP_TOKEN_Q (Q)
#define ORDER_PP_TOKEN_R (R)
#define ORDER_PP_TOKEN_S (S)
#define ORDER_PP_TOKEN_T (T)
#define ORDER_PP_TOKEN_U (U)
#define ORDER_PP_TOKEN_V (V)
#define ORDER_PP_TOKEN_W (W)
#define ORDER_PP_TOKEN_X (X)
#define ORDER_PP_TOKEN_Y (Y)
#define ORDER_PP_TOKEN_Z (Z)
#define ORDER_PP_SYM_A(...) __VA_ARGS__
#define ORDER_PP_SYM_B(...) __VA_ARGS__
#define ORDER_PP_SYM_C(...) __VA_ARGS__
#define ORDER_PP_SYM_D(...) __VA_ARGS__
#define ORDER_PP_SYM_E(...) __VA_ARGS__
#define ORDER_PP_SYM_F(...) __VA_ARGS__
#define ORDER_PP_SYM_G(...) __VA_ARGS__
#define ORDER_PP_SYM_H(...) __VA_ARGS__
#define ORDER_PP_SYM_I(...) __VA_ARGS__
#define ORDER_PP_SYM_J(...) __VA_ARGS__
#define ORDER_PP_SYM_K(...) __VA_ARGS__
#define ORDER_PP_SYM_L(...) __VA_ARGS__
#define ORDER_PP_SYM_M(...) __VA_ARGS__
#define ORDER_PP_SYM_N(...) __VA_ARGS__
#define ORDER_PP_SYM_O(...) __VA_ARGS__
#define ORDER_PP_SYM_P(...) __VA_ARGS__
#define ORDER_PP_SYM_Q(...) __VA_ARGS__
#define ORDER_PP_SYM_R(...) __VA_ARGS__
#define ORDER_PP_SYM_S(...) __VA_ARGS__
#define ORDER_PP_SYM_T(...) __VA_ARGS__
#define ORDER_PP_SYM_U(...) __VA_ARGS__
#define ORDER_PP_SYM_V(...) __VA_ARGS__
#define ORDER_PP_SYM_W(...) __VA_ARGS__
#define ORDER_PP_SYM_X(...) __VA_ARGS__
#define ORDER_PP_SYM_Y(...) __VA_ARGS__
#define ORDER_PP_SYM_Z(...) __VA_ARGS__
/// 8blocks_lexer (string) : Seq String -> Seq (Seq Sym)
#define ORDER_PP_DEF_8blocks_lexer ORDER_PP_FN \
(8fn (8S \
,8seq_map (8tokens_to_seq \
,8S \
) \
) \
)
// Keying the blocks makes filtering them way more efficient than by comparing their letters.
/// 8seq_keyed (sequence) : Seq a -> Seq (Pair Num a)
#define ORDER_PP_DEF_8seq_keyed ORDER_PP_FN \
(8fn (8S \
,8stream_to_seq (8stream_pair_with (8pair \
,8stream_of_naturals \
,8seq_to_stream (8S) \
) \
) \
) \
)
/// 8abc_internal (blocks, word) : Seq (Pair Num (Seq Token)) -> Seq Token -> Bool
#define ORDER_PP_DEF_8abc_internal ORDER_PP_FN \
(8fn (8B, 8W \
,8if (8seq_is_nil (8W) \
,8true \
,8lets ((8C, 8seq_head (8W)) \
(8S, 8seq_filter (8chain (8seq_exists (8same (8C)) \
,8tuple_at_1 \
) \
,8B \
) \
) \
(8T, 8seq_map (8chain (8flip (8seq_filter \
,8B \
) \
,8bin_pr (8not_eq \
,8tuple_at_0 \
) \
) \
,8S \
) \
) \
,8seq_exists (8flip (8abc_internal \
,8seq_tail (8W) \
) \
,8T \
) \
) \
) \
) \
)
/// 8abc (blocks, word) : Seq (String) -> String -> Bool
#define ORDER_PP_DEF_8abc ORDER_PP_FN \
(8fn (8B, 8W \
,8abc_internal (8seq_keyed (8blocks_lexer (8B)) \
,8tokens_to_seq (8W) \
) \
) \
)
#define ORDER_PP_DEF_8blocks ORDER_PP_CONST ( \
(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) \
)
ORDER_PP
(8seq_map (8step (8pair (8identity
,8abc (8blocks)
)
)
,8quote ((A)
(B A R K)
(B O O K)
(T R E A T)
(C O M M O N)
(S Q U A D)
(C O N F U S E)
)
)
)
</syntaxhighlight>
{{out}}
<pre>
((A,8true))((B A R K,8true))((B O O K,8false))((T R E A T,8true))((C O M M O N,8false))((S Q U A D,8true))((C O N F U S E,8true))
</pre>
=={{header|PARI/GP}}==
<
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];
Line 5,573 ⟶ 7,376:
}
for (i = 1, #WORDS, printf("%s\t%d\n", WORDS[i], can_make_word(WORDS[i])));</
Output:<pre>A 1
Line 5,587 ⟶ 7,390:
{{works with|Free Pascal|2.6.2}}
<syntaxhighlight lang="pascal">
#!/usr/bin/instantfpc
//program ABCProblem;
Line 5,653 ⟶ 7,456:
TestABCProblem('SQUAD');
TestABCProblem('CONFUSE');
END.</
{{out}}
Line 5,677 ⟶ 7,480:
=={{header|Perl}}==
Recursive solution that can handle characters appearing on different blocks:
<
use warnings;
use strict;
Line 5,702 ⟶ 7,505:
}
return
}</
<p>Testing:
<
my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);
Line 5,717 ⟶ 7,520:
my @blocks2 = qw(US TZ AO QA);
is(can_make_word('auto', @blocks2), 1);
</syntaxhighlight>
===Regex based alternate===
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/ABC_Problem
use warnings;
printf "%30s %s\n", $_, can_make_word( $_,
'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' )
for qw( A BARK BOOK TREAT COMMON SQUAD CONFUSE );
sub can_make_word
{
my ($word, $blocks) = @_;
my $letter = chop $word or return 'True';
can_make_word( $word, $` . $' ) eq 'True' and return 'True'
while $blocks =~ /\w?$letter\w?/gi;
return 'False';
}</syntaxhighlight>
{{out}}
<pre>
A True
BARK True
BOOK False
TREAT True
COMMON False
SQUAD True
CONFUSE True
</pre>
=={{header|Phix}}==
Recursive solution which also solves the extra problems on the discussion page.
<!--<syntaxhighlight lang="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>
<span style="color: #008080;">function</span> <span style="color: #000000;">ABC_Solve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000080;font-style:italic;">-- or: res = length(word)>0 -- (if "" -> false desired)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">blocks</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">used</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">and</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">blocks</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">used</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ABC_Solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">,</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">used</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{{</span><span style="color: #008000;">"BO"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XK"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"DQ"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CP"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"NA"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"GT"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TG"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"QD"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"FS"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"JW"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"HU"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VI"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AN"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"OB"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ER"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"FS"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"LY"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"PC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ZM"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"BarK"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"BOOK"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TrEaT"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"COMMON"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"SQUAD"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CONFUSE"</span><span style="color: #0000FF;">}},</span>
<span style="color: #0000FF;">{{</span><span style="color: #008000;">"US"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TZ"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AO"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"QA"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"AuTO"</span><span style="color: #0000FF;">}},</span>
<span style="color: #0000FF;">{{</span><span style="color: #008000;">"AB"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AB"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AC"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"abba"</span><span style="color: #0000FF;">}}}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</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: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">used</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">blocks</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s: %t\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">ABC_Solve</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 5,772 ⟶ 7,605:
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");
Line 5,801 ⟶ 7,634:
echo canMakeWord($word) ? "True" : "False";
echo "\r\n";
}</
{{out}}
<pre>
Line 5,812 ⟶ 7,645:
Confuse: True
</pre>
=={{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">go =>
test_it(check_word),
test_it(check_word2),
nl.
% Get all possible solutions (via fail)
go2 ?=>
test_version(check_word2),
fail,
nl.
go2 => true.
%
% Test a version.
%
test_it(Pred) =>
println(testing=Pred),
Blocks = findall([A,B], block(A,B)),
Words = findall(W,word(W)),
foreach(Word in Words)
println(word=Word),
( call(Pred,Word,Blocks) ; println("Cannot make word.")),
nl
end,
nl.
%
% Picat style: Using nth/3 for getting the chars
%
check_word(Word, Blocks) =>
WordC = atom_chars(Word), % convert atom to string
WordLen = length(WordC),
X = new_list(WordLen),
Pos = new_list(WordLen),
foreach(I in 1..WordLen)
% find a character at the specific position
nth(X[I],Blocks,XI),
nth(Pos[I],XI, WordC[I])
end,
alldiff(X), % ensure unique selection
foreach(I in 1..WordLen)
println([WordC[I], Blocks[X[I]]])
end,
nl.
%
% Prolog style (recursive) version using select/3.
% (where we don't have to worry about duplicate blocks)
%
check_word2(Word, Blocks) :-
pick_block(atom_chars(Word),Blocks,[],X),
println(X).
pick_block([], _,Res,Res).
pick_block([C|WordRest], Blocks, Res1,[Block|Res]) :-
% pick (non-deterministically) one of the blocks
select(Block,Blocks,BlocksRest),
membchk(C,Block),
pick_block(WordRest,BlocksRest,Res1,Res).
%
% alldiff(L):
% ensure that all elements in L are different
%
alldiff([]).
alldiff([_]).
alldiff([H|T]) :-
neq(H,T),
alldiff(T).
neq(_,[]).
neq(X,[H|T]) :-
X != H,
neq(X,T).
% The words to check.
word(a).
word(bark).
word(book).
word(treat).
word(common).
word(squad).
word(confuse).
word(auto).
word(abba).
word(coestablishment).
word(schoolmastering).
% The blocks
block(b,o).
block(x,k).
block(d,q).
block(c,p).
block(n,a).
block(g,t).
block(r,e).
block(t,g).
block(q,d).
block(f,s).
block(j,w).
block(h,u).
block(v,i).
block(a,n).
block(o,b).
block(e,r).
block(f,s).
block(l,y).
block(p,c).
block(z,m).
</syntaxhighlight>
{{out}}
<pre>
testing = check_word
word = a
[a,na]
word = bark
[b,bo] [a,na] [r,re] [k,xk]
word = book
Cannot make word.
word = treat
[t,gt] [r,re] [e,er] [a,na] [t,tg]
word = common
Cannot make word.
word = squad
[s,fs] [q,dq] [u,hu] [a,na] [d,qd]
word = confuse
[c,cp] [o,bo] [n,na] [f,fs] [u,hu] [s,fs] [e,re]
word = auto
[a,na] [u,hu] [t,gt] [o,bo]
word = abba
[a,na] [b,bo] [b,ob] [a,an]
word = coestablishment
[c,cp] [o,bo] [e,re] [s,fs] [t,gt] [a,na] [b,ob] [l,ly] [i,vi] [s,fs] [h,hu] [m,zm] [e,er] [n,an] [t,tg]
word = schoolmastering
[s,fs] [c,cp] [h,hu] [o,bo] [o,ob] [l,ly] [m,zm] [a,na] [s,fs] [t,gt] [e,re] [r,er] [i,vi] [n,an] [g,tg]
testing = check_word2
word = a
[na]
word = bark
[bo,na,re,xk]
word = book
Cannot make word.
word = treat
[gt,re,er,na,tg]
word = common
Cannot make word.
word = squad
[fs,dq,hu,na,qd]
word = confuse
[cp,bo,na,fs,hu,fs,re]
word = auto
[na,hu,gt,bo]
word = abba
[na,bo,ob,an]
word = coestablishment
[cp,bo,re,fs,gt,na,ob,ly,vi,fs,hu,zm,er,an,tg]
word = schoolmastering
[fs,cp,hu,bo,ob,ly,zm,na,fs,gt,re,er,vi,an,tg]</pre>
=={{header|PicoLisp}}==
Mapping and recursion.
<syntaxhighlight lang="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 5,847 ⟶ 7,863:
(println Word (abc Word *Blocks) (abcR Word *Blocks)) )
(bye)</
=={{header|PL/I}}==
===version 1===
<
declare word character (20) varying, blocks character (200) varying initial
Line 5,876 ⟶ 7,892:
end;
end ABC;</
<pre>
A true
Line 5,888 ⟶ 7,904:
===version 2===
<
abc: Proc Options(main);
/* REXX --------------------------------------------------------------
Line 6,008 ⟶ 8,024:
End;
End;</
{{out}}
<pre>'$' cannot be spelt.
Line 6,018 ⟶ 8,034:
'SQUAD' can be spelt in 8 ways.
'CONFUSE' can be spelt in 32 ways.</pre>
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
/* ABC PROBLEM ON $-TERMINATED STRING */
CAN$MAKE$WORD: PROCEDURE (STRING) BYTE;
DECLARE STRING ADDRESS, CHAR BASED STRING BYTE;
DECLARE CONST$BLOCKS DATA
('BOKXDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM');
DECLARE I BYTE, BLOCKS (40) BYTE;
DO I=0 TO 39; /* MAKE COPY OF BLOCKS */
BLOCKS(I) = CONST$BLOCKS(I);
END;
STEP: DO WHILE CHAR <> '$';
DO I=0 TO 39; /* FIND BLOCK WITH CURRENT CHAR */
IF BLOCKS(I) = CHAR THEN DO; /* FOUND IT */
BLOCKS(I) = 0; /* CLEAR OUT BOTH LETTERS ON BLOCK */
BLOCKS(I XOR 1) = 0;
STRING = STRING + 1;
GO TO STEP; /* NEXT CHARACTER */
END;
END;
RETURN 0; /* NO BLOCK WITH LETTER */
END;
RETURN 1; /* WE FOUND THEM ALL */
END CAN$MAKE$WORD;
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT: PROCEDURE (STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
/* TEST SEVERAL STRINGS */
DECLARE TEST (7) ADDRESS, I BYTE;
TEST(0) = .'A$';
TEST(1) = .'BARK$';
TEST(2) = .'BOOK$';
TEST(3) = .'TREAT$';
TEST(4) = .'COMMON$';
TEST(5) = .'SQUAD$';
TEST(6) = .'CONFUSE$';
DO I = 0 TO LAST(TEST);
CALL PRINT(TEST(I));
CALL PRINT(.': $');
IF CAN$MAKE$WORD(TEST(I))
THEN CALL PRINT(.'YES$');
ELSE CALL PRINT(.'NO$');
CALL PRINT(.(13,10,'$'));
END;
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>A: YES
BARK: YES
BOOK: NO
TREAT: YES
COMMON: NO
SQUAD: YES
CONFUSE: YES</pre>
=={{header|PowerBASIC}}==
Works with PowerBASIC 6 Console Compiler
<
#DIM ALL
'
Line 6,177 ⟶ 8,263:
END IF
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>$ FALSE
Line 6,191 ⟶ 8,277:
=={{header|PowerShell}}==
<
.Synopsis
ABC Problem
Line 6,307 ⟶ 8,393:
{
test-blocks -testword $word -Verbose
}</
{{out}}
<pre>
Line 6,373 ⟶ 8,459:
Works with SWI-Prolog 6.5.3
<
maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
Line 6,395 ⟶ 8,481:
( select([H, _], L, L1); select([_, H], L, L1)),
can_makeword(L1, T).
</syntaxhighlight>
{{out}}
<pre> ?- abc_problem.
Line 6,416 ⟶ 8,502:
{{works with|SWI Prolog 7}}
<
abathslib(protelog/composer) ]).
Line 6,433 ⟶ 8,519:
%% These rules, removing remaining constraints from the store, are just cosmetic:
'clean up blocks' @ word_built \ block(_) <=> true.
'word was built' @ word_built <=> true.</
Demonstration:
<
true.
?- can_build_word("BARK").
Line 6,451 ⟶ 8,537:
true.
?- can_build_word("CONFUSE").
true.</
=={{header|PureBasic}}==
===PureBasic: Iterative===
<
#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
Line 6,486 ⟶ 8,572:
PrintN(can_make_word("SqUAD"))
PrintN(can_make_word("COnFUSE"))
Input()</
===PureBasic: Recursive===
<
Macro test(t)
Line 6,508 ⟶ 8,594:
test("a") : test("BaRK") : test("BOoK") : test("TREAt")
test("cOMMON") : test("SqUAD") : test("COnFUSE")
Input()</
{{out}}
<pre>a = True
Line 6,521 ⟶ 8,607:
===Python: Iterative, with tests===
<
'''
Note that this code is broken, e.g., it won't work when
Line 6,590 ⟶ 8,676:
["", "a", "baRk", "booK", "treat",
"COMMON", "squad", "Confused"]))
</syntaxhighlight>
{{out}}
Line 6,596 ⟶ 8,682:
===Python: Recursive===
<
def _abc(word, blocks):
Line 6,620 ⟶ 8,706:
if __name__ == '__main__':
for word in [''] + 'A BARK BoOK TrEAT COmMoN SQUAD conFUsE'.split():
print('Can we spell %9r? %r' % (word, abc(word)))</
{{out}}
Line 6,633 ⟶ 8,719:
===Python: Recursive, telling how===
<
if not w: return []
Line 6,648 ⟶ 8,734:
for w in ", A, bark, book, treat, common, SQUAD, conFUsEd".split(', '):
print '\'' + w + '\'' + ' ->', abc(w, blocks)</
{{out}}
Line 6,662 ⟶ 8,748:
'conFUsEd' -> ['CP', 'BO', 'NA', 'FS', 'HU', 'FS', 'RE', 'DQ']
</pre>
=={{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
cmw:{[s;b] / [str;blocks]
$[0=count s; 1b; / empty string
not any found:any each b=s 0; 0b; / cannot proceed
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.
The second expression looks in the available blocks <code>b</code> for the first letter of <code>s</code>: the boolean vector <code>found</code> flags any hits. If there are none, the result is false: the string cannot be completed from the available blocks.
The last line searches further. The expression <code>til count b</code> indexes the remaining blocks; and <code>where found</code> are the indexes that have the next letter. The derived function <code>except/:</code> yields a list: each item is a copy of the list of indexes <code>til count b</code>, with one of the <code>found</code> indexes removed. The list of blocks <code>b</code> is applied to each of these index lists; the result is multiple versions of the list of blocks; each has had a different block removed. The <code>cmw</code> function is applied to each of these with the truncated string <code>1_s</code>. (The expression <code>.z.s</code> refers to the currently-running function, so <code>cmw</code> does not need to know its own name.) The result of these calls is a boolean vector; aggregator <code>any</code> reports if any have succeeded in completing the string.
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
BOOK false
Treat true
COMMON false
squad true
CONFUSE true</syntaxhighlight>
* [https://code.kx.com/q/ref/ Language Reference]
* [https://code.kx.com/q/learn/pb/abc-problem/ The Q Playbook: ABC problem – analysis]
=={{header|Quackery}}==
===Iterative, without backtracking===
See note in the FORTRAN solution and elsewhere re: backtracking. Fails the ABBA test, see "Greedy Algorithm" in the discussion for this page.
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">[ $ "BOXKDQCPNAGTRETGQDFS"
$ "JWHUVIANOBERFSLYPCZM"
join ] constant is blocks ( --> $ )
[ -2 &
tuck pluck drop
swap pluck drop ] is remove2 ( $ n --> $ )
[ iff [ say "True" ]
else [ say "False" ] ] is echotruth ( b --> )
[ true blocks rot
witheach
[ upper over find
2dup swap found
iff remove2
else
[ drop dip not
conclude ] ]
drop echotruth ] is can_make_word ( $ --> )</syntaxhighlight>
'''Testing in the Quackery shell:'''
<pre>/O> $ "A" can_make_word
...
True
Stack empty.
/O> $ "BARK" can_make_word
...
True
Stack empty.
/O> $ "BOOK" can_make_word
...
False
Stack empty.
/O> $ "TREAT" can_make_word
...
True
Stack empty.
/O> $ "COMMON" can_make_word
...
False
Stack empty.
/O> $ "SQUAD" can_make_word
...
True
Stack empty.
/O> $ "CONFUSE" can_make_word
...
True
Stack empty.</pre>
===Recursive, with backtracking===
See note in the FORTRAN solution and elsewhere re: backtracking. Passes the ABBA test, see "Greedy Algorithm" in the discussion for this page.
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">[ ' [ 0 ] swap
witheach
[ over -1 peek
+ join ]
behead drop ] is accumulate ( [ --> [ )
[ [] swap
witheach
[ swap dip
[ over + ]
swap join ]
nip ] is add ( n [ --> [ )
[ [] unrot
[ 2dup find
2dup swap
found while
1+ split
swap size
dip rot join
unrot again ]
2drop drop
accumulate
-1 swap add ] is findall ( x [ --> [ )
[ iff [ say "True" ]
else [ say "False" ] ] is echotruth ( b --> )
[ $ "BOXKDQCPNAGTRETGQDFS"
$ "JWHUVIANOBERFSLYPCZM"
join ] constant is blocks ( --> $ )
[ -2 &
tuck pluck drop
swap pluck drop ] is remove2 ( $ n --> $ )
forward is (abc)
[ dup [] = if bail
behead upper
dip over swap findall
witheach
[ dip over
remove2
over (abc) ]
2drop ] resolves (abc) ( $ $ --> )
[ blocks swap
2 backup (abc)
bailed dup
if [ dip 2drop ]
echotruth ] is can_make_word ( $ --> )</syntaxhighlight>
'''Testing in the Quackery shell:'''
Identical to iterative solution above.
=={{header|R}}==
Line 6,668 ⟶ 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.
<
c("X","K"),
c("D","Q"),
Line 6,710 ⟶ 8,956:
"COMMON",
"SQUAD",
"CONFUSE"))</
{{out}}
Line 6,718 ⟶ 8,964:
===Without recursion===
Second version without recursion and giving every unique combination of blocks for each word:
<
x <- toupper(x)
charList <- strsplit(x, character(0))
Line 6,738 ⟶ 8,984:
"COMMON",
"SQUAD",
"CONFUSE"))</
{{out}}
<pre>$A
Line 6,822 ⟶ 9,068:
So '(can-make-word? "")' is true for me.
<
(define block-strings
(list "BO" "XK" "DQ" "CP" "NA"
Line 6,864 ⟶ 9,110:
(check-false (can-make-word? "COMMON"))
(check-true (can-make-word? "SQUAD"))
(check-true (can-make-word? "CONFUSE")))</
{{out}}
Line 6,880 ⟶ 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="raku"
my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }
can-spell-word $word.uc.comb.list, @regex;
Line 6,900 ⟶ 9,146:
for <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> {
say "$_ &can-spell-word($_, @b)";
}</
{{out}}
<pre>A True
Line 6,911 ⟶ 9,157:
=={{header|RapidQ}}==
<
dim InWord as string
Line 6,937 ⟶ 9,183:
Blocks = "BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM"
showmessage "Can make: " + InWord + " = " + iif(CanMakeWord(InWord, Blocks), "True", "False")
</syntaxhighlight>
{{out}}
<pre>Can make: A = TRUE
Line 6,949 ⟶ 9,195:
=={{header|Red}}==
<
test: func [ s][
p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
Line 6,965 ⟶ 9,211:
print reduce [ pad copy word 8 ":" test word]
]
</syntaxhighlight>
{{out}}
<pre>
Line 6,976 ⟶ 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===
<
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 6,999 ⟶ 9,290:
end /*try*/ /* [↑] end of a "TRY" permute. */
say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.'
return</
{{out|output|text= when using the default inputs:}}
<pre>
Line 7,012 ⟶ 9,303:
===version 2===
<
* 10.01.2014 Walter Pachl counts the number of possible ways
* 12.01.2014 corrected date and output
Line 7,114 ⟶ 9,405:
used.w=1
End
Return 1</
{{out}}
<pre>'' cannot be spelt.
Line 7,195 ⟶ 9,486:
=={{header|Ring}}==
<
Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]
Line 7,218 ⟶ 9,509:
if found = false return false ok
next
return true</
{{Out}}
<pre>
Line 7,235 ⟶ 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.
<
words.each do |word|
Line 7,246 ⟶ 9,638:
puts "#{word.inspect}: #{res}"
end
</syntaxhighlight>
{{Out}}
<pre>
Line 7,260 ⟶ 9,652:
=={{header|Run BASIC}}==
<
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
b = int((len(blocks$) /3) + 1)
Line 7,284 ⟶ 9,676:
print wrd$;chr$(9);
if n = len(wrd$) then print " True" else print " False"
next i</
<pre>A True
BARK True
Line 7,295 ⟶ 9,687:
=={{header|Rust}}==
This implementation uses a backtracking search.
<
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
Line 7,324 ⟶ 9,716:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 7,337 ⟶ 9,729:
=={{header|Scala}}==
{{libheader|Scala}}<
protected class Block(face1: Char, face2: Char) {
Line 7,386 ⟶ 9,778:
words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made."))
}</
=={{header|Scheme}}==
In R5RS:
<
'((#\B #\O) (#\X #\K) (#\D #\Q) (#\C #\P) (#\N #\A)
(#\G #\T) (#\R #\E) (#\T #\G) (#\Q #\D) (#\F #\S)
Line 7,430 ⟶ 9,822:
(display word)
(newline))
*words*)</
{{out}}
<pre>
Line 7,443 ⟶ 9,835:
=={{header|Seed7}}==
<
const func boolean: canMakeWords (in array string: blocks, in string: word) is func
Line 7,476 ⟶ 9,868:
writeln(word rpad 10 <& canMakeWords(word));
end for;
end func;</
{{out}}
Line 7,491 ⟶ 9,883:
=={{header|SenseTalk}}==
<
put [
Line 7,531 ⟶ 9,923:
return True
end CanMakeWord</
<
"A",
"BARK",
Line 7,543 ⟶ 9,935:
]
put CanMakeWord(word)
end repeat</
=={{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===
<
import <Utilities/Sequence.sl>;
Line 7,575 ⟶ 9,997:
letter when ascii >= 65 and ascii <= 90
else
intToAscii(ascii - 32);</
{{out}}
Line 7,590 ⟶ 10,012:
===RegEx Version ===
<
import <Utilities/Sequence.sl>;
import <RegEx/RegEx.sl>;
Line 7,620 ⟶ 10,042:
letter when ascii >= 65 and ascii <= 90
else
intToAscii(ascii - 32);</
=={{header|Sidef}}==
{{trans|Perl}}
<
blocks.map! { |b| b.uc.chars.sort.join }.freq!
Line 7,640 ⟶ 10,062:
return false;
}(word.uc.chars, blocks)
}</
Tests:
<
var b2 = %w(US TZ AO QA)
Line 7,661 ⟶ 10,083:
say ("%7s -> %s" % (t[0], bool));
assert(bool == t[1])
}</
{{out}}
Line 7,676 ⟶ 10,098:
=={{header|Simula}}==
<
BEGIN
Line 7,772 ⟶ 10,194:
END.
</syntaxhighlight>
{{out}}
<pre>A => T OK
Line 7,785 ⟶ 10,207:
=={{header|Smalltalk}}==
Recursive solution. Tested in Pharo.
<
ABCPuzzle>>test
#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
Line 7,807 ⟶ 10,229:
(self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
^ false
</syntaxhighlight>
{{out}}
<pre>
Line 7,819 ⟶ 10,241:
sQUAD: true
CONFuSE: true
</pre>
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
* Program: abc.sbl,
* To run: sbl -r abc.sbl
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
* Read in blocks to construct the blocks string
in1
line = replace(input,&lcase,&ucase) :f(in1end)
line ? breakx(' ') . pre ' ' rem . post :f(in1end)
blocks = blocks "," pre post
:(in1)
in1end
* Function to determine if a word can be constructed with the given blocks
define('abc(blocks,word)s,i,let')
abcpat = (breakx(',') ',') . pre (*let len(1) | len(1) *let) rem . post
:(abc_end)
abc
eq(size(word),0) :s(abc3)
s = replace(word,&lcase,&ucase)
i = 0
abc2
i = lt(i,size(s)) i + 1 :f(abc4)
let = substr(s,i,1)
blocks ? abcpat = pre post :f(abc3)
:(abc2)
abc3
abc = 'False' :(abc5)
abc4
abc = 'True' :(abc5)
abc5
output = lpad('can_make_word("' word '"): ',26) abc
abc = ""
:(return)
abc_end
* Check words
* output = abc(blocks,"")
* output = abc(blocks," ")
output = abc(blocks,'A')
output = abc(blocks,'bark')
output = abc(blocks,'BOOK')
output = abc(blocks,'TrEAT')
output = abc(blocks,'COMMON')
output = abc(blocks,'SQUAD')
output = abc(blocks,'CONFUSE')
* The blocks are entered below, after the following END label
END
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
</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|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang="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 7,848 ⟶ 10,359:
[canMakeWord?(s,blocks) for s in Example]
</syntaxhighlight>
Programming details:[http://fricas.github.io/book.pdf UserGuide]
Line 7,862 ⟶ 10,373:
=={{header|Standard ML}}==
<syntaxhighlight lang="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"),
(#"A",#"N"),(#"O",#"B"), (#"E",#"R"), (#"F",#"S"), (#"L",#"Y"), (#"P",#"C"), (#"Z",#"M")];
val words = ["A","BARK","BOOK","TREaT","COMMON","SQUAD","CONFUSE"];
open List;
local
val remove = fn x => fn B => (fn (a,b) => (tl a)@b ) (partition ( fn a=> x=a) B)
in
fun cando ([] , Done, B ) = true
| cando (h::t, Done, []) = false
| cando (h::t, Done, B ) =
let
val S = find (fn (a,b) => a=h orelse b=h) B
in
else
let
val T = find ( fn(_,(a,b)) => a=h orelse b=h) Done
val U = if isSome T then find (fn (a,b) => a = #1 (valOf T) orelse b = #1 (valOf T) ) B else NONE
in
if isSome T andalso isSome U
then cando ( t, (#1 (valOf T),(valOf U))::(h,#2 (valOf T))::(remove (valOf T) Done), remove (valOf U) B)
else false
end
end
end;
map
val BLOCKS = [(#"U",#"S"), (#"T",#"Z"), (#"A",#"O"), (#"Q",#"A")];
val words = ["A","UTAH","AutO"];
map (fn st => cando(map Char.toUpper (String.explode st),[],BLOCKS)) words;
</syntaxhighlight>
Output
<pre>val it = [true, true, false, true, false, true, true]
val it = [true, false, true]: bool list
</pre>
=={{header|Swift}}==
<
func Blockable(str: String) -> Bool {
Line 7,914 ⟶ 10,446:
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
println("'\(str)' \(CanOrNot(Blockable(str))) be spelled with blocks.")
}</
{{out}}
<pre>
Line 7,927 ⟶ 10,459:
{{works with|Swift|3.0.2}}
<
func canMake(word: String) -> Bool {
Line 7,948 ⟶ 10,480:
let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"]
words.forEach { print($0, canMake(word: $0)) }</
{{out}}
<pre>
Line 7,962 ⟶ 10,494:
=={{header|Tcl}}==
{{works with|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 7,982 ⟶ 10,514:
foreach word {"" A BARK BOOK TREAT COMMON SQUAD CONFUSE} {
puts [format "Can we spell %9s? %s" '$word' [abc $word]]
}</
{{out}}
<pre>
Line 7,993 ⟶ 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}}==
<
set result = *
loop word = words
Line 8,013 ⟶ 10,584:
set out = concat (word, " ", cond)
set result = append (result, out)
endloop</
{{out}}
<pre>A true
Line 8,025 ⟶ 10,596:
=={{header|TXR}}==
<
(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 8,071 ⟶ 10,642:
@(if (can-make-word w) "True" "False")
@(end)
@(end)</
Run:
Line 8,098 ⟶ 10,669:
>>> can_make_word("CONFUSE")
True</pre>
=={{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">
#include <Core/Core.h>
#include <stdio.h>
#include <ctype.h>
//C++
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cctype>
//C++
typedef std::pair<char,char> item_t;
typedef std::vector<item_t> list_t;
//C
using namespace Upp;
int can_make_words(char **b, char *word)
{
int i, ret = 0, c = toupper(*word);
if (!c) return 1;
if (!b[0]) return 0;
for (i = 0; b[i] && !ret; i++) {
if (b[i][0] != c && b[i][1] != c) continue;
Swap(b[i], b[0]); // It needs to be Swap and not SWAP
ret = can_make_words(b + 1, word + 1);
Swap(b[i], b[0]); // It needs to be Swap instead of SWAP
}
return ret;
}
//C++
bool can_create_word(const std::string& w, const list_t& vals) {
std::set<uint32_t> used;
while (used.size() < w.size()) {
const char c = toupper(w[used.size()]);
uint32_t x = used.size();
for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {
if (used.find(i) == used.end()) {
if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {
used.insert(i);
break;
}
}
}
if (x == used.size()) break;
}
return used.size() == w.size();
}
// U++
CONSOLE_APP_MAIN
{
// C
char* blocks[] =
{
(char*)"BO", (char*)"XK", (char*)"DQ", (char*)"CP",
(char*)"NA", (char*)"GT", (char*)"RE", (char*)"TG",
(char*)"QD", (char*)"FS", (char*)"JW", (char*)"HU",
(char*)"VI", (char*)"AN", (char*)"OB", (char*)"ER",
(char*)"FS", (char*)"LY", (char*)"PC", (char*)"ZM", 0
};
char *words[] =
{
(char*)"", (char*)"A", (char*)"BARK", (char*)"BOOK",
(char*)"TREAT", (char*)"COMMON", (char*)"SQUAD", (char*)"Confuse", 0
};
char **w;
for (w = words; *w; w++)
printf("%s\t%d\n", *w, can_make_words(blocks, *w));
printf("\n");
// C++
list_t vals{ {'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'}
};
std::vector<std::string> wordsb{"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
for (const std::string& w : wordsb) {
std::cout << w << ": " << std::boolalpha << can_create_word(w, vals) << ".\n";
}
std::cout << "\n";
const Vector<String>& cmdline = CommandLine();
for(int i = 0; i < cmdline.GetCount(); i++) {
}
}
</syntaxhighlight>
{{out}}
<pre>
1
A 1
BARK 1
BOOK 0
TREAT 1
COMMON 0
SQUAD 1
Confuse 1
A: true.
BARK: true.
BOOK: false.
TREAT: true.
COMMON: false.
SQUAD: true.
Confuse: true.
<--- Finished in (0:00.53), exitcode: 0 --->
</pre>
=={{header|UNIX Shell}}==
{{works with|bash}}
<
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 8,140 ⟶ 10,879:
can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
printf "%s\t%s\n" "$word" $ans
done</
{{out}}
Line 8,156 ⟶ 10,895:
'''String-based solution'''
<syntaxhighlight lang="utfool">
···
http://rosettacode.org/wiki/ABC_Problem
Line 8,184 ⟶ 10,923:
i: blocks.indexOf (word.substring 0, 1), i + 3
return solution
</syntaxhighlight>
'''Collection-based solution'''
<syntaxhighlight lang="utfool">
···
http://rosettacode.org/wiki/ABC_Problem
Line 8,223 ⟶ 10,962:
Collections.swap blocks, 0, i
return false
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 8,262 ⟶ 11,001:
ABC = (NbInit = (myColl.Count + Len(myWord)))
End Function
</syntaxhighlight>
{{out}}
<pre>
Line 8,272 ⟶ 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}}
<
var r // recursive
Line 8,303 ⟶ 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"]) {
}</
{{out}}
Line 8,318 ⟶ 11,108:
=={{header|XPL0}}==
<
char Side1, Side2;
Line 8,346 ⟶ 11,136:
Text(0, if CanMakeWord(Words(J)) then "True" else "False"); CrLf(0);
];
]</
{{out}}
Line 8,360 ⟶ 11,150:
=={{header|Yabasic}}==
<
sub canMake(letters$, word$)
Line 8,387 ⟶ 11,177:
print "common = ", canMake(letters$, "common") // 0
print "squad = ", canMake(letters$, "squad") // 1
print "confuse = ", canMake(letters$, "confuse") // 1</
=={{header|zkl}}==
{{trans|C}}
<
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
Line 8,409 ⟶ 11,199:
foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){
can_make_word(word).println(": ",word);
}</
{{out}}
<pre>
Line 8,424 ⟶ 11,214:
=={{header|zonnon}}==
<
module Main;
type
Line 8,512 ⟶ 11,302:
CanMakeWord("confuse");
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 8,524 ⟶ 11,314:
=={{header|ZX Spectrum Basic}}==
<
20 READ p
30 FOR c=1 TO p
Line 8,544 ⟶ 11,334:
190 REM Erase pair
200 IF j/2=INT (j/2) THEN LET u$(j-1 TO j)=" ": RETURN
210 LET u$(j TO j+1)=" ": RETURN</
{{out}}
<pre>
|