ABC problem: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 44: Line 44:


;Example:
;Example:
<lang python> >>> can_make_word("A")
<syntaxhighlight lang=python> >>> can_make_word("A")
True
True
>>> can_make_word("BARK")
>>> can_make_word("BARK")
Line 57: Line 57:
True
True
>>> can_make_word("CONFUSE")
>>> can_make_word("CONFUSE")
True</lang>
True</syntaxhighlight>


{{Template:Strings}}
{{Template:Strings}}
Line 64: Line 64:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>F can_make_word(word)
<syntaxhighlight lang=11l>F can_make_word(word)
I word == ‘’
I word == ‘’
R 0B
R 0B
Line 79: Line 79:
R 1B
R 1B


print([‘’, ‘a’, ‘baRk’, ‘booK’, ‘treat’, ‘COMMON’, ‘squad’, ‘Confused’].map(w -> ‘'’w‘': ’can_make_word(w)).join(‘, ’))</lang>
print([‘’, ‘a’, ‘baRk’, ‘booK’, ‘treat’, ‘COMMON’, ‘squad’, ‘Confused’].map(w -> ‘'’w‘': ’can_make_word(w)).join(‘, ’))</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<lang 360asm>* ABC Problem 21/07/2016
<syntaxhighlight lang=360asm>* ABC Problem 21/07/2016
ABC CSECT
ABC CSECT
USING ABC,R13 base register
USING ABC,R13 base register
Line 158: Line 158:
YREGS
YREGS
NN EQU (BLOCKS-WORDS)/L'WORDS number of words
NN EQU (BLOCKS-WORDS)/L'WORDS number of words
END ABC</lang>
END ABC</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 171: Line 171:


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
<lang 8080asm> org 100h
<syntaxhighlight lang=8080asm> org 100h
jmp test
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 247: Line 247:
wrdcommon: db 'COMMON$'
wrdcommon: db 'COMMON$'
wrdsquad: db 'SQUAD$'
wrdsquad: db 'SQUAD$'
wrdconfuse: db 'CONFUSE$'</lang>
wrdconfuse: db 'CONFUSE$'</syntaxhighlight>


{{out}}
{{out}}
Line 263: Line 263:
{{trans|8080 Assembly}}
{{trans|8080 Assembly}}


<lang asm> cpu 8086
<syntaxhighlight lang=asm> cpu 8086
bits 16
bits 16
org 100h
org 100h
Line 325: Line 325:
.cmn: db 'COMMON$'
.cmn: db 'COMMON$'
.squad: db 'SQUAD$'
.squad: db 'SQUAD$'
.confs: db 'CONFUSE$'</lang>
.confs: db 'CONFUSE$'</syntaxhighlight>


{{out}}
{{out}}
Line 338: Line 338:


=={{header|8th}}==
=={{header|8th}}==
<lang 360asm>
<syntaxhighlight lang=360asm>
\ ========================================================================================
\ ========================================================================================
\ You are given a collection of ABC blocks
\ You are given a collection of ABC blocks
Line 537: Line 537:
bye
bye
;
;
</syntaxhighlight>
</lang>
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program problemABC64.s */
/* program problemABC64.s */
Line 728: Line 728:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 747: Line 747:
</pre>
</pre>
=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>
<syntaxhighlight lang=ABAP>
REPORT z_rosetta_abc.
REPORT z_rosetta_abc.


Line 820: Line 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 = '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' ).
WRITE:/ COND string( WHEN word_maker=>can_make_word( word = 'CONFUSE' letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 833: Line 833:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE COUNT="20"
<syntaxhighlight lang=Action!>DEFINE COUNT="20"
CHAR ARRAY sideA="BXDCNGRTQFJHVAOEFLPZ"
CHAR ARRAY sideA="BXDCNGRTQFJHVAOEFLPZ"
CHAR ARRAY sideB="OKQPATEGDSWUINBRSYCM"
CHAR ARRAY sideB="OKQPATEGDSWUINBRSYCM"
Line 889: Line 889:
Test("SQuaD")
Test("SQuaD")
Test("CoNfUsE")
Test("CoNfUsE")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/ABC_problem.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/ABC_problem.png Screenshot from Atari 8-bit computer]
Line 906: Line 906:
Using #HASH-OFF
Using #HASH-OFF
</pre>
</pre>
<lang acurity architect>
<syntaxhighlight lang=acurity architect>
FUNCTION bCAN_MAKE_WORD(zWord: STRING): BOOLEAN
FUNCTION bCAN_MAKE_WORD(zWord: STRING): BOOLEAN
VAR sBlockCount: SHORT
VAR sBlockCount: SHORT
Line 933: Line 933:
RETURN OCCURS(zUsedBlocks, ",") = sWordLength
RETURN OCCURS(zUsedBlocks, ",") = sWordLength
ENDFUNCTION
ENDFUNCTION
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 950: Line 950:
</pre>
</pre>


<lang ada>with Ada.Characters.Handling;
<syntaxhighlight lang=ada>with Ada.Characters.Handling;
use Ada.Characters.Handling;
use Ada.Characters.Handling;


Line 1,028: Line 1,028:
end loop;
end loop;
end Abc_Problem;
end Abc_Problem;
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,043: Line 1,043:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># determine whether we can spell words with a set of blocks #
<syntaxhighlight lang=algol68># determine whether we can spell words with a set of blocks #


# construct the list of blocks #
# construct the list of blocks #
Line 1,123: Line 1,123:


)
)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,136: Line 1,136:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>% determine whether we can spell words with a set of blocks %
<syntaxhighlight lang=algolw>% determine whether we can spell words with a set of blocks %
begin
begin
% Returns true if we can spell the word using the blocks, %
% Returns true if we can spell the word using the blocks, %
Line 1,216: Line 1,216:
testCanSpell( "confuse", 7 )
testCanSpell( "confuse", 7 )
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,229: Line 1,229:


=={{header|Apex}}==
=={{header|Apex}}==
<lang Java>static Boolean canMakeWord(List<String> src_blocks, String word) {
<syntaxhighlight lang=Java>static Boolean canMakeWord(List<String> src_blocks, String word) {
if (String.isEmpty(word)) {
if (String.isEmpty(word)) {
return true;
return true;
Line 1,273: Line 1,273:
System.debug('"COMMON": ' + canMakeWord(blocks, 'COMMON'));
System.debug('"COMMON": ' + canMakeWord(blocks, 'COMMON'));
System.debug('"SQuAd": ' + canMakeWord(blocks, 'SQuAd'));
System.debug('"SQuAd": ' + canMakeWord(blocks, 'SQuAd'));
System.debug('"CONFUSE": ' + canMakeWord(blocks, 'CONFUSE'));</lang>
System.debug('"CONFUSE": ' + canMakeWord(blocks, 'CONFUSE'));</syntaxhighlight>
{{out}}
{{out}}
<pre>"": true
<pre>"": true
Line 1,286: Line 1,286:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
{{works with|Dyalog APL|16.0}}
<lang APL>abc←{{0=⍴⍵:1 ⋄ 0=⍴h←⊃⍵:0 ⋄ ∇(t←1↓⍵)~¨⊃h:1 ⋄ ∇(⊂1↓h),t}⍸¨↓⍵∘.∊⍺}</lang>
<syntaxhighlight lang=APL>abc←{{0=⍴⍵:1 ⋄ 0=⍴h←⊃⍵:0 ⋄ ∇(t←1↓⍵)~¨⊃h:1 ⋄ ∇(⊂1↓h),t}⍸¨↓⍵∘.∊⍺}</syntaxhighlight>
{{out}}
{{out}}
<pre> )COPY dfns ucase
<pre> )COPY dfns ucase
Line 1,296: Line 1,296:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
===Imperative===
===Imperative===
<lang AppleScript>set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", ¬
<syntaxhighlight lang=AppleScript>set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", ¬
"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"}
"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"}


Line 1,323: Line 1,323:
end repeat
end repeat
return false
return false
end canMakeWordWithBlocks</lang>
end canMakeWordWithBlocks</syntaxhighlight>


===Functional===
===Functional===
<lang AppleScript>use AppleScript version "2.4"
<syntaxhighlight lang=AppleScript>use AppleScript version "2.4"
use framework "Foundation"
use framework "Foundation"


Line 1,522: Line 1,522:
set my text item delimiters to dlm
set my text item delimiters to dlm
s
s
end unlines</lang>
end unlines</syntaxhighlight>
{{Out}}
{{Out}}
<pre> '' -> true
<pre> '' -> true
Line 1,534: Line 1,534:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program problemABC.s */
/* program problemABC.s */
Line 1,718: Line 1,718:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Can_make_word: A
Can_make_word: A
Line 1,737: Line 1,737:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>blocks: map [
<syntaxhighlight lang=rebol>blocks: map [
[B O] [X K] [D Q] [C P] [N A] [G T] [R E]
[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]
[T G] [Q D] [F S] [J W] [H U] [V I] [A N]
Line 1,762: Line 1,762:


loop ["A" "BaRk" "bOoK" "tReAt" "CoMmOn" "SqUaD" "cONfUsE"] 'wrd
loop ["A" "BaRk" "bOoK" "tReAt" "CoMmOn" "SqUaD" "cONfUsE"] 'wrd
-> print [wrd "=>" canMakeWord? wrd]</lang>
-> print [wrd "=>" canMakeWord? wrd]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>A => true
<pre>A => true
Line 1,773: Line 1,773:


=={{header|Astro}}==
=={{header|Astro}}==
<lang python>fun abc(s, ls):
<syntaxhighlight lang=python>fun abc(s, ls):
if ls.isempty:
if ls.isempty:
return true
return true
Line 1,784: Line 1,784:


for s in test:
for s in test:
print "($|>8|{s} ${abc(s, list)})"</lang>
print "($|>8|{s} ${abc(s, list)})"</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


'''Function'''
'''Function'''
<lang autohotkey>isWordPossible(blocks, word){
<syntaxhighlight lang=autohotkey>isWordPossible(blocks, word){
o := {}
o := {}
loop, parse, blocks, `n, `r
loop, parse, blocks, `n, `r
Line 1,812: Line 1,812:
added := 1
added := 1
}
}
}</lang>
}</syntaxhighlight>


'''Test Input''' (as per question)
'''Test Input''' (as per question)
<lang autohotkey>blocks := "
<syntaxhighlight lang=autohotkey>blocks := "
(
(
BO
BO
Line 1,852: Line 1,852:
loop, parse, wordlist, `n
loop, parse, wordlist, `n
out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
msgbox % out</lang>
msgbox % out</syntaxhighlight>


{{out}}
{{out}}
Line 2,012: Line 2,012:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>CONST info$ = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
<syntaxhighlight lang=qbasic>CONST info$ = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"


DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
Line 2,035: Line 2,035:


PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n"
PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n"
WEND</lang>
WEND</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,049: Line 2,049:
=={{header|BASIC}}==
=={{header|BASIC}}==
Works with:VB-DOS, QB64, QBasic, QuickBASIC
Works with:VB-DOS, QB64, QBasic, QuickBASIC
<lang qbasic>
<syntaxhighlight lang=qbasic>
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ABC_Problem '
' ABC_Problem '
Line 2,175: Line 2,175:


END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
{{trans|Sinclair ZX-81 BASIC}}
{{trans|Sinclair ZX-81 BASIC}}
<lang basic>10 W$ = "A" : GOSUB 100
<syntaxhighlight lang=basic>10 W$ = "A" : GOSUB 100
20 W$ = "BARK" : GOSUB 100
20 W$ = "BARK" : GOSUB 100
30 W$ = "BOOK" : GOSUB 100
30 W$ = "BOOK" : GOSUB 100
Line 2,203: Line 2,203:
230 RETURN
230 RETURN
240 PRINT W$" -> NO"
240 PRINT W$" -> NO"
250 RETURN</lang>
250 RETURN</syntaxhighlight>


{{out}}
{{out}}
Line 2,216: Line 2,216:
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:
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:


<lang basic>100 REM RECURSIVE SOLUTION
<syntaxhighlight lang=basic>100 REM RECURSIVE SOLUTION
110 MS=100:REM MAX STACK DEPTH
110 MS=100:REM MAX STACK DEPTH
120 DIM BL$(MS):REM BLOCKS LEFT
120 DIM BL$(MS):REM BLOCKS LEFT
Line 2,255: Line 2,255:
470 DATA A, BORK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, ""
470 DATA A, BORK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, ""
480 DATA ABABACAC,ABBA,""
480 DATA ABABACAC,ABBA,""
490 DATA ""</lang>
490 DATA ""</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,277: Line 2,277:
==={{header|Sinclair ZX81 BASIC}}===
==={{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.
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.
<lang basic> 10 LET B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
<syntaxhighlight lang=basic> 10 LET B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
20 INPUT W$
20 INPUT W$
30 FOR I=1 TO LEN W$
30 FOR I=1 TO LEN W$
Line 2,287: Line 2,287:
90 STOP
90 STOP
100 NEXT J
100 NEXT J
110 PRINT "NO"</lang>
110 PRINT "NO"</syntaxhighlight>
{{in}}
{{in}}
<pre>A</pre>
<pre>A</pre>
Line 2,318: Line 2,318:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang=dos>
@echo off
@echo off
::abc.bat
::abc.bat
Line 2,381: Line 2,381:


:END
:END
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> BLOCKS$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
<syntaxhighlight lang=bbcbasic> BLOCKS$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
PROCcan_make_word("A")
PROCcan_make_word("A")
PROCcan_make_word("BARK")
PROCcan_make_word("BARK")
Line 2,406: Line 2,406:
ENDWHILE
ENDWHILE
IF word$>"" PRINT "False" ELSE PRINT "True"
IF word$>"" PRINT "False" ELSE PRINT "True"
ENDPROC</lang>
ENDPROC</syntaxhighlight>


{{out}}
{{out}}
Line 2,419: Line 2,419:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang=bcpl>get "libhdr"


let canMakeWord(word) = valof
let canMakeWord(word) = valof
Line 2,455: Line 2,455:
show("SQUAD")
show("SQUAD")
show("CONFUSE")
show("CONFUSE")
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>A: yes
<pre>A: yes
Line 2,466: Line 2,466:


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>ABC ← {
<syntaxhighlight lang=bqn>ABC ← {
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
Line 2,481: Line 2,481:
words←⟨"A","bark","BOOK","TrEaT","Common","Squad","Confuse"⟩
words←⟨"A","bark","BOOK","TrEaT","Common","Squad","Confuse"⟩


> {(<𝕩) ∾ blocks ABC 𝕩}¨ words</lang>
> {(<𝕩) ∾ blocks ABC 𝕩}¨ words</syntaxhighlight>
{{out}}
{{out}}
<pre>┌─
<pre>┌─
Line 2,494: Line 2,494:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>(
<syntaxhighlight lang=bracmat>(
( can-make-word
( can-make-word
= ABC blocks
= ABC blocks
Line 2,541: Line 2,541:
& can-make-word'SQUAD
& can-make-word'SQUAD
& can-make-word'CONFUSE
& can-make-word'CONFUSE
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>A yes
<pre>A yes
Line 2,553: Line 2,553:
=={{header|C}}==
=={{header|C}}==
Recursive solution. Empty string returns true.
Recursive solution. Empty string returns true.
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <ctype.h>
#include <ctype.h>


Line 2,593: Line 2,593:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,610: Line 2,610:
This Method uses regular expressions to do the checking. Given that n = length of blocks string and
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).
m = length of word string, then CheckWord's time complexity comes out to about m*(n - (m-1)/2).
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.IO;
using System.IO;
// Needed for the method.
// Needed for the method.
Line 2,640: Line 2,640:
return true;
return true;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,652: Line 2,652:
</pre>
</pre>
'''Unoptimized'''
'''Unoptimized'''
<lang csharp>using System.Collections.Generic;
<syntaxhighlight lang=csharp>using System.Collections.Generic;
using System.Linq;
using System.Linq;


Line 2,734: Line 2,734:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,748: Line 2,748:
{{Works with|C++11}}
{{Works with|C++11}}
Build with:
Build with:
<lang sh>g++-4.7 -Wall -std=c++0x abc.cpp</lang>
<syntaxhighlight lang=sh>g++-4.7 -Wall -std=c++0x abc.cpp</syntaxhighlight>
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <vector>
#include <vector>
#include <string>
#include <string>
Line 2,782: Line 2,782:
std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n";
std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n";
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,799: Line 2,799:
<b>module.ceylon</b>
<b>module.ceylon</b>


<lang ceylon>
<syntaxhighlight lang=ceylon>
module rosetta.abc "1.0.0" {}
module rosetta.abc "1.0.0" {}
</syntaxhighlight>
</lang>


<b>run.ceylon</b>
<b>run.ceylon</b>


<lang ceylon>
<syntaxhighlight lang=ceylon>
shared void run() {
shared void run() {
printAndCanMakeWord("A", blocks);
printAndCanMakeWord("A", blocks);
Line 2,880: Line 2,880:
myRemainingLetterIndexes)
myRemainingLetterIndexes)
else false;
else false;
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,895: Line 2,895:
=={{header|Clojure}}==
=={{header|Clojure}}==
A translation of the Haskell solution.
A translation of the Haskell solution.
<lang clojure>
<syntaxhighlight lang=clojure>
(def blocks
(def blocks
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
Line 2,916: Line 2,916:
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word)))</lang>
(->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word)))</syntaxhighlight>


{{out}}
{{out}}
Line 2,928: Line 2,928:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>ucase = proc (s: string) returns (string)
<syntaxhighlight lang=clu>ucase = proc (s: string) returns (string)
rslt: array[char] := array[char]$predict(1,string$size(s))
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
for c: char in string$chars(s) do
Line 2,971: Line 2,971:
end
end
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>A: yes
<pre>A: yes
Line 2,982: Line 2,982:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang CoffeeScript>blockList = [ 'BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS', 'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM' ]
<syntaxhighlight lang=CoffeeScript>blockList = [ 'BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS', 'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM' ]


canMakeWord = (word="") ->
canMakeWord = (word="") ->
Line 2,999: Line 2,999:
# Expect true, true, false, true, false, true, true, true
# Expect true, true, false, true, false, true, true, true
for word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "squad", "CONFUSE", "STORM"]
for word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "squad", "CONFUSE", "STORM"]
console.log word + " -> " + canMakeWord(word)</lang>
console.log word + " -> " + canMakeWord(word)</syntaxhighlight>


{{out}}
{{out}}
Line 3,012: Line 3,012:


=={{header|Comal}}==
=={{header|Comal}}==
<lang comal>0010 FUNC can'make'word#(word$) CLOSED
<syntaxhighlight lang=comal>0010 FUNC can'make'word#(word$) CLOSED
0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
0030 FOR i#:=1 TO LEN(word$) DO
0030 FOR i#:=1 TO LEN(word$) DO
Line 3,030: Line 3,030:
0170 END
0170 END
0180 //
0180 //
0190 DATA "A","BARK","BOOK","treat","common","squad","CoNfUsE"</lang>
0190 DATA "A","BARK","BOOK","treat","common","squad","CoNfUsE"</syntaxhighlight>
{{out}}
{{out}}
<pre>A: yes
<pre>A: yes
Line 3,041: Line 3,041:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang=lisp>
(defun word-possible-p (word blocks)
(defun word-possible-p (word blocks)
(cond
(cond
Line 3,055: Line 3,055:
collect (word-possible-p
collect (word-possible-p
(subseq word 1)
(subseq word 1)
(remove b blocks))))))))</lang>
(remove b blocks))))))))</syntaxhighlight>


{{out}}
{{out}}
Line 3,077: Line 3,077:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
{{Works with|BlackBox Component Builder}}
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE ABCProblem;
MODULE ABCProblem;
IMPORT
IMPORT
Line 3,162: Line 3,162:
END ABCProblem.
END ABCProblem.
</syntaxhighlight>
</lang>
Execute: ^Q ABCProblem.CanMakeWord A BARK BOOK TREAT COMMON SQUAD confuse~
Execute: ^Q ABCProblem.CanMakeWord A BARK BOOK TREAT COMMON SQUAD confuse~
{{out}}
{{out}}
Line 3,176: Line 3,176:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang=cowgol>include "cowgol.coh";
include "strings.coh";
include "strings.coh";


Line 3,219: Line 3,219:
print(resp[can_make_word(words[i])]);
print(resp[can_make_word(words[i])]);
i := i + 1;
i := i + 1;
end loop;</lang>
end loop;</syntaxhighlight>


{{out}}
{{out}}
Line 3,235: Line 3,235:
{{trans|Python}}
{{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.
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.
<lang d>import std.stdio, std.algorithm, std.string;
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.string;


bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
Line 3,256: Line 3,256:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>"" true
<pre>"" true
Line 3,269: Line 3,269:
===@nogc Version===
===@nogc Version===
The same as the precedent version, but it avoids all heap allocations and it's lower-level and ASCII-only.
The same as the precedent version, but it avoids all heap allocations and it's lower-level and ASCII-only.
<lang d>import std.ascii, core.stdc.stdlib;
<syntaxhighlight lang=d>import std.ascii, core.stdc.stdlib;


bool canMakeWord(in string word, in string[] blocks) nothrow @nogc
bool canMakeWord(in string word, in string[] blocks) nothrow @nogc
Line 3,307: Line 3,307:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</lang>
}</syntaxhighlight>


===Recursive Version===
===Recursive Version===
This version is able to find the solution for the word "abba" given the blocks AB AB AC AC.
This version is able to find the solution for the word "abba" given the blocks AB AB AC AC.
{{trans|C}}
{{trans|C}}
<lang d>import std.stdio, std.ascii, std.algorithm, std.array;
<syntaxhighlight lang=d>import std.stdio, std.ascii, std.algorithm, std.array;


alias Block = char[2];
alias Block = char[2];
Line 3,349: Line 3,349:
immutable word = "abba";
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>"" true
<pre>"" true
Line 3,363: Line 3,363:
===Alternative Recursive Version===
===Alternative Recursive Version===
This version doesn't shuffle the input blocks, but it's more complex and it allocates an array of indexes.
This version doesn't shuffle the input blocks, but it's more complex and it allocates an array of indexes.
<lang d>import std.stdio, std.ascii, std.algorithm, std.array, std.range;
<syntaxhighlight lang=d>import std.stdio, std.ascii, std.algorithm, std.array, std.range;


alias Block = char[2];
alias Block = char[2];
Line 3,404: Line 3,404:
immutable word = "abba";
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</lang>
}</syntaxhighlight>
The output is the same.
The output is the same.


=={{header|Delphi}}==
=={{header|Delphi}}==
Just to be different I implemented a block as a set of (2) char rather than as an array of (2) char.
Just to be different I implemented a block as a set of (2) char rather than as an array of (2) char.
<lang Delphi>program ABC;
<syntaxhighlight lang=Delphi>program ABC;
{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}


Line 3,472: Line 3,472:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,486: Line 3,486:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>\util.g
<syntaxhighlight lang=draco>\util.g


proc nonrec ucase(char c) char:
proc nonrec ucase(char c) char:
Line 3,538: Line 3,538:
test("sQuAd");
test("sQuAd");
test("CONFUSE")
test("CONFUSE")
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>A: yes
<pre>A: yes
Line 3,552: Line 3,552:
{{trans|Swift}}
{{trans|Swift}}


<lang dyalect>func blockable(str) {
<syntaxhighlight lang=dyalect>func blockable(str) {
var blocks = [
var blocks = [
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
Line 3,577: Line 3,577:
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
print("\"\(str)\" \(canOrNot(blockable(str))) be spelled with blocks.")
print("\"\(str)\" \(canOrNot(blockable(str))) be spelled with blocks.")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,590: Line 3,590:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
(lib 'list) ;; list-delete
(lib 'list) ;; list-delete


Line 3,607: Line 3,607:
(spell (string-rest word) (list-delete blocks block))))))
(spell (string-rest word) (list-delete blocks block))))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,626: Line 3,626:
=={{header|Ela}}==
=={{header|Ela}}==
{{trans|Haskell}}
{{trans|Haskell}}
<lang ela>open list monad io char
<syntaxhighlight lang=ela>open list monad io char


:::IO
:::IO
Line 3,642: Line 3,642:


mapM_ (\w -> putLn (w, not << null $ abc blocks (map char.upper w)))
mapM_ (\w -> putLn (w, not << null $ abc blocks (map char.upper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</lang>
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</syntaxhighlight>


{{out}}
{{out}}
Line 3,656: Line 3,656:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0
ELENA 5.0
<lang elena>import system'routines;
<syntaxhighlight lang=elena>import system'routines;
import system'collections;
import system'collections;
import extensions;
import extensions;
Line 3,700: Line 3,700:
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,716: Line 3,716:
{{trans|Erlang}}
{{trans|Erlang}}
{{works with|Elixir|1.3}}
{{works with|Elixir|1.3}}
<lang elixir>defmodule ABC do
<syntaxhighlight lang=elixir>defmodule ABC do
def can_make_word(word, avail) do
def can_make_word(word, avail) do
can_make_word(String.upcase(word) |> to_charlist, avail, [])
can_make_word(String.upcase(word) |> to_charlist, avail, [])
Line 3,731: Line 3,731:
blocks = ~w(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM)c
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) |>
~w(A Bark Book Treat Common Squad Confuse) |>
Enum.map(fn(w) -> IO.puts "#{w}: #{ABC.can_make_word(w, blocks)}" end)</lang>
Enum.map(fn(w) -> IO.puts "#{w}: #{ABC.can_make_word(w, blocks)}" end)</syntaxhighlight>


{{out}}
{{out}}
Line 3,745: Line 3,745:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(abc).
<syntaxhighlight lang=erlang>-module(abc).
-export([can_make_word/1, can_make_word/2, blocks/0]).
-export([can_make_word/1, can_make_word/2, blocks/0]).


Line 3,761: Line 3,761:
main(_) -> lists:map(fun(W) -> io:fwrite("~s: ~s~n", [W, can_make_word(W)]) end,
main(_) -> lists:map(fun(W) -> io:fwrite("~s: ~s~n", [W, can_make_word(W)]) end,
["A","Bark","Book","Treat","Common","Squad","Confuse"]).
["A","Bark","Book","Treat","Common","Squad","Confuse"]).
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,774: Line 3,774:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>
<syntaxhighlight lang=ERRE>
PROGRAM BLOCKS
PROGRAM BLOCKS


Line 3,803: Line 3,803:
CANMAKEWORD("Confuse")
CANMAKEWORD("Confuse")
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
implemented using OpenEuphoria
implemented using OpenEuphoria
<lang Euphoria>
<syntaxhighlight lang=Euphoria>
include std/text.e
include std/text.e


Line 3,843: Line 3,843:


if getc(0) then end if
if getc(0) then end if
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,859: Line 3,859:
=={{header|F_Sharp|F#}}==
=={{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>
<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>
<lang fsharp>let rec spell_word_with blocks w =
<syntaxhighlight lang=fsharp>let rec spell_word_with blocks w =
let rec look_for_right_candidate candidates noCandidates c rest =
let rec look_for_right_candidate candidates noCandidates c rest =
match candidates with
match candidates with
Line 3,888: Line 3,888:


List.iter (fun w -> printfn "Using the blocks we can make the word '%s': %b" w (spell_word_with blocks w)) words
List.iter (fun w -> printfn "Using the blocks we can make the word '%s': %b" w (spell_word_with blocks w)) words
0</lang>
0</syntaxhighlight>
{{out}}
{{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
<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,906: Line 3,906:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: assocs combinators.short-circuit formatting grouping io
<syntaxhighlight lang=factor>USING: assocs combinators.short-circuit formatting grouping io
kernel math math.statistics qw sequences sets unicode ;
kernel math math.statistics qw sequences sets unicode ;
IN: rosetta-code.abc-problem
IN: rosetta-code.abc-problem
Line 3,950: Line 3,950:
show-blocks header input [ result ] each ;
show-blocks header input [ result ] each ;


MAIN: abc-problem</lang>
MAIN: abc-problem</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,972: Line 3,972:
=={{header|FBSL}}==
=={{header|FBSL}}==
This approach uses a string, blanking out the pair previously found. Probably faster than array manipulation.
This approach uses a string, blanking out the pair previously found. Probably faster than array manipulation.
<lang qbasic>
<syntaxhighlight lang=qbasic>
#APPTYPE CONSOLE
#APPTYPE CONSOLE
SUB MAIN()
SUB MAIN()
Line 4,017: Line 4,017:
RETURN TRUE
RETURN TRUE
END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,037: Line 4,037:
{{works with|gforth|0.7.3}}
{{works with|gforth|0.7.3}}


<lang forth>: blockslist s" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" ;
<syntaxhighlight lang=forth>: blockslist s" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" ;
variable blocks
variable blocks
: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;
: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;
Line 4,066: Line 4,066:
;
;


: .abc abc if ." True" else ." False" then ;</lang>
: .abc abc if ." True" else ." False" then ;</syntaxhighlight>


{{out}}
{{out}}
Line 4,081: Line 4,081:
=={{header|Fortran}}==
=={{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!
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!
<lang Fortran>!-*- mode: compilation; default-directory: "/tmp/" -*-
<syntaxhighlight lang=Fortran>!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Thu Jun 5 01:52:03
!Compilation started at Thu Jun 5 01:52:03
!
!
Line 4,150: Line 4,150:
end subroutine ucase
end subroutine ucase


end program abc</lang>
end program abc</syntaxhighlight>


===But if backtracking might be needed===
===But if backtracking might be needed===
Line 4,158: Line 4,158:


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.
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.
<lang Fortran>
<syntaxhighlight lang=Fortran>
MODULE PLAYPEN !Messes with a set of alphabet blocks.
MODULE PLAYPEN !Messes with a set of alphabet blocks.
INTEGER MSG !Output unit number.
INTEGER MSG !Output unit number.
Line 4,436: Line 4,436:
END DO
END DO
END
END
</syntaxhighlight>
</lang>
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.
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>
<pre>
Line 4,461: Line 4,461:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 28-01-2019
<syntaxhighlight lang=freebasic>' version 28-01-2019
' compile with: fbc -s console
' compile with: fbc -s console


Line 4,503: Line 4,503:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>A true
<pre>A true
Line 4,515: Line 4,515:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang=futurebasic>
include "NSLog.incl"
include "NSLog.incl"


Line 4,557: Line 4,557:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 4,571: Line 4,571:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ae860292d4588b3627d77c85bcc634ee Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=ae860292d4588b3627d77c85bcc634ee Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang=gambas>Public Sub Main()
Dim sCheck As String[] = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]
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"]
Dim sBlock As String[] = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
Line 4,598: Line 4,598:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 4,611: Line 4,611:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 4,649: Line 4,649:
fmt.Println(word, sp(word))
fmt.Println(word, sp(word))
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,663: Line 4,663:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>class ABCSolver {
<syntaxhighlight lang=groovy>class ABCSolver {
def blocks
def blocks


Line 4,674: Line 4,674:
word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
}
}
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def a = new ABCSolver(["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
<syntaxhighlight lang=groovy>def a = new ABCSolver(["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])


['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {
['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {
println "'${it}': ${a.canMakeWord(it)}"
println "'${it}': ${a.canMakeWord(it)}"
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,696: Line 4,696:
=={{header|Harbour}}==
=={{header|Harbour}}==
Harbour Project implements a cross-platform Clipper/xBase compiler.
Harbour Project implements a cross-platform Clipper/xBase compiler.
<lang visualfoxpro>PROCEDURE Main()
<syntaxhighlight lang=visualfoxpro>PROCEDURE Main()


LOCAL cStr
LOCAL cStr
Line 4,727: Line 4,727:
NEXT
NEXT


RETURN cFinal == cStr</lang>
RETURN cFinal == cStr</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,741: Line 4,741:


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.
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.
<lang haskell>import Data.List (delete)
<syntaxhighlight lang=haskell>import Data.List (delete)
import Data.Char (toUpper)
import Data.Char (toUpper)


Line 4,755: Line 4,755:
main :: IO ()
main :: IO ()
main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w)))
main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</lang>
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</syntaxhighlight>


{{out}}
{{out}}
Line 4,771: Line 4,771:
Or, in terms of the bind operator:
Or, in terms of the bind operator:


<lang haskell>import Data.Char (toUpper)
<syntaxhighlight lang=haskell>import Data.Char (toUpper)
import Data.List (delete)
import Data.List (delete)


Line 4,808: Line 4,808:
words $
words $
"BO XK DQ CP NA GT RE TG QD FS JW"
"BO XK DQ CP NA GT RE TG QD FS JW"
<> " HU VI AN OB ER FS LY PC ZM"</lang>
<> " HU VI AN OB ER FS LY PC ZM"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>("",True)
<pre>("",True)
Line 4,823: Line 4,823:


Works in both languages:
Works in both languages:
<lang unicon>procedure main(A)
<syntaxhighlight lang=unicon>procedure main(A)
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
Line 4,846: Line 4,846:
}
}
}
}
end</lang>
end</syntaxhighlight>


Sample run:
Sample run:
Line 4,864: Line 4,864:
=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>reduce=: verb define
<syntaxhighlight lang=j>reduce=: verb define
'rows cols'=. i.&.> $y
'rows cols'=. i.&.> $y
for_c. cols do.
for_c. cols do.
Line 4,874: Line 4,874:
)
)


abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0:</lang>
abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0:</syntaxhighlight>
'''Examples:'''
'''Examples:'''
<lang j> Blocks=: ];._2 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
<syntaxhighlight lang=j> Blocks=: ];._2 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '


Line 4,889: Line 4,889:
"COmMOn" F
"COmMOn" F
"SqUAD" T
"SqUAD" T
"CoNfuSE" T</lang>
"CoNfuSE" T</syntaxhighlight>


'''Tacit version'''
'''Tacit version'''
<lang j>delElem=: {~<@<@<
<syntaxhighlight lang=j>delElem=: {~<@<@<
uppc=:(-32*96&<*.123&>)&.(3&u:)
uppc=:(-32*96&<*.123&>)&.(3&u:)
reduc=: ] delElem 1 i.~e."0 1
reduc=: ] delElem 1 i.~e."0 1
forms=: (1 - '' -: (reduc L:0/ :: (a:"_)@(<"0@],<@[))&uppc) L:0</lang>
forms=: (1 - '' -: (reduc L:0/ :: (a:"_)@(<"0@],<@[))&uppc) L:0</syntaxhighlight>


{{out}}
{{out}}
Line 4,919: Line 4,919:
Another approach might be:
Another approach might be:


<lang J>Blocks=: >;:'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
<syntaxhighlight lang=J>Blocks=: >;:'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM '
ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '


Line 4,928: Line 4,928:
candidates=: word,"1>,{{relevant
candidates=: word,"1>,{{relevant
+./(((#need){. #/.~)"1 candidates) */ .>:need
+./(((#need){. #/.~)"1 candidates) */ .>:need
)</lang>
)</syntaxhighlight>


Example use:
Example use:


<lang J> Blocks canform 0{::ExampleWords
<syntaxhighlight lang=J> Blocks canform 0{::ExampleWords
1
1
Blocks canform 1{::ExampleWords
Blocks canform 1{::ExampleWords
Line 4,945: Line 4,945:
1
1
Blocks canform 6{::ExampleWords
Blocks canform 6{::ExampleWords
1</lang>
1</syntaxhighlight>


Explanation:
Explanation:
Line 4,955: Line 4,955:
For example:
For example:


<lang J> Blocks canform 0{::ExampleWords
<syntaxhighlight lang=J> Blocks canform 0{::ExampleWords
1
1
word
word
Line 4,968: Line 4,968:
ANN
ANN
AAA
AAA
AAN</lang>
AAN</syntaxhighlight>


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, three of the candidates are valid, for this trivial example.)
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, three of the candidates are valid, for this trivial example.)
Line 4,975: Line 4,975:
{{trans|C}}
{{trans|C}}
{{works with|Java|1.6+}}
{{works with|Java|1.6+}}
<lang java5>import java.util.Arrays;
<syntaxhighlight lang=java5>import java.util.Arrays;
import java.util.Collections;
import java.util.Collections;
import java.util.List;
import java.util.List;
Line 5,010: Line 5,010:
return false;
return false;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>"": true
<pre>"": true
Line 5,025: Line 5,025:
====Imperative====
====Imperative====
The following method uses regular expressions and the string replace function to allow more support for older browsers.
The following method uses regular expressions and the string replace function to allow more support for older browsers.
<lang javascript>var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
<syntaxhighlight lang=javascript>var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";


function CheckWord(blocks, word) {
function CheckWord(blocks, word) {
Line 5,062: Line 5,062:
for(var i = 0;i<words.length;++i)
for(var i = 0;i<words.length;++i)
console.log(words[i] + ": " + CheckWord(blocks, words[i]));
console.log(words[i] + ": " + CheckWord(blocks, words[i]));
</syntaxhighlight>
</lang>


Result:
Result:
Line 5,076: Line 5,076:


====Functional====
====Functional====
<lang JavaScript>(function (strWords) {
<syntaxhighlight lang=JavaScript>(function (strWords) {


var strBlocks =
var strBlocks =
Line 5,123: Line 5,123:
return strWords.split(' ').map(solution).join('\n');
return strWords.split(' ').map(solution).join('\n');


})('A bark BooK TReAT COMMON squAD conFUSE');</lang>
})('A bark BooK TReAT COMMON squAD conFUSE');</syntaxhighlight>
{{Out}}
{{Out}}
<lang JavaScript>A -> NA
<syntaxhighlight lang=JavaScript>A -> NA
bark -> BO NA RE XK
bark -> BO NA RE XK
BooK: [no solution]
BooK: [no solution]
Line 5,131: Line 5,131:
COMMON: [no solution]
COMMON: [no solution]
squAD -> FS DQ HU NA QD
squAD -> FS DQ HU NA QD
conFUSE -> CP BO NA FS HU FS RE</lang>
conFUSE -> CP BO NA FS HU FS RE</syntaxhighlight>


===ES6===
===ES6===
====Imperative====
====Imperative====
<lang javascript>let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
<syntaxhighlight lang=javascript>let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
let blocks = characters.split(" ").map(pair => pair.split(""));
let blocks = characters.split(" ").map(pair => pair.split(""));
Line 5,167: Line 5,167:
"CONFUSE"
"CONFUSE"
].forEach(word => console.log(`${word}: ${isWordPossible(word)}`));
].forEach(word => console.log(`${word}: ${isWordPossible(word)}`));
</syntaxhighlight>
</lang>


Result:
Result:
Line 5,181: Line 5,181:
====Functional====
====Functional====
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang JavaScript>(() => {
<syntaxhighlight lang=JavaScript>(() => {
"use strict";
"use strict";


Line 5,247: Line 5,247:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>["",true]
<pre>["",true]
Line 5,259: Line 5,259:


=={{header|jq}}==
=={{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.<lang jq>
The problem description seems to imply that if a letter, X, appears on more than one block, its partner will be the same on all blocks. This makes the problem trivial.<syntaxhighlight lang=jq>
# when_index(cond;ary) returns the index of the first element in ary
# when_index(cond;ary) returns the index of the first element in ary
# that satisfies cond; it uses a helper function that takes advantage
# that satisfies cond; it uses a helper function that takes advantage
Line 5,288: Line 5,288:
else .[1:] | abc($blks)
else .[1:] | abc($blks)
end
end
end;</lang>
end;</syntaxhighlight>
Task:<lang jq>def task:
Task:<syntaxhighlight lang=jq>def task:
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] as $blocks
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] as $blocks
| ("A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE")
| ("A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE")
| "\(.) : \( .|abc($blocks) )" ;task</lang>
| "\(.) : \( .|abc($blocks) )" ;task</syntaxhighlight>
{{Out}}
{{Out}}
A : true
A : true
Line 5,305: Line 5,305:
=={{header|Jsish}}==
=={{header|Jsish}}==
Based on Javascript ES5 imperative solution.
Based on Javascript ES5 imperative solution.
<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang=javascript>#!/usr/bin/env jsish
/* ABC problem, in Jsish. Can word be spelled with the given letter blocks. */
/* 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";
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
Line 5,341: Line 5,341:
can spell CONFUSE
can spell CONFUSE
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 5,358: Line 5,358:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Printf
<syntaxhighlight lang=julia>using Printf


function abc(str::AbstractString, list)
function abc(str::AbstractString, list)
Line 5,376: Line 5,376:
@printf("%-8s | %s\n", str, abc(str, list))
@printf("%-8s | %s\n", str, abc(str, list))
end
end
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 5,389: Line 5,389:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>object ABC_block_checker {
<syntaxhighlight lang=scala>object ABC_block_checker {
fun run() {
fun run() {
println("\"\": " + blocks.canMakeWord(""))
println("\"\": " + blocks.canMakeWord(""))
Line 5,427: Line 5,427:
}
}


fun main(args: Array<String>) = ABC_block_checker.run()</lang>
fun main(args: Array<String>) = ABC_block_checker.run()</syntaxhighlight>
{{out}}
{{out}}
<pre>"": true
<pre>"": true
Line 5,440: Line 5,440:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
===Recursive solution===
===Recursive solution===
<syntaxhighlight lang=lb>
<lang lb>
print "Rosetta Code - ABC problem (recursive solution)"
print "Rosetta Code - ABC problem (recursive solution)"
print
print
Line 5,483: Line 5,483:
wend
wend
end function
end function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,505: Line 5,505:
</pre>
</pre>
===Procedural solution===
===Procedural solution===
<syntaxhighlight lang=lb>
<lang lb>
print "Rosetta Code - ABC problem (procedural solution)"
print "Rosetta Code - ABC problem (procedural solution)"
print
print
Line 5,639: Line 5,639:
LetterOK=1
LetterOK=1
end sub
end sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,662: Line 5,662:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>make "blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S]
<syntaxhighlight lang=logo>make "blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S]
[J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]
[J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]


Line 5,682: Line 5,682:
]
]


bye</lang>
bye</syntaxhighlight>


{{Out}}
{{Out}}
Line 5,694: Line 5,694:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>blocks = {
<syntaxhighlight lang=lua>blocks = {
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
Line 5,724: Line 5,724:
end
end
print(found)
print(found)
end</lang>
end</syntaxhighlight>


{{Output}}
{{Output}}
Line 5,740: Line 5,740:




<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module ABC {
Module ABC {
can_make_word("A")
can_make_word("A")
Line 5,761: Line 5,761:
}
}
ABC
ABC
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,775: Line 5,775:


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>canSpell := proc(w)
<syntaxhighlight lang=maple>canSpell := proc(w)
local blocks, i, j, word, letterFound;
local blocks, i, j, word, letterFound;
blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
Line 5,797: Line 5,797:
end proc:
end proc:


seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]);</lang>
seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,810: Line 5,810:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>
<syntaxhighlight lang=Mathematica>
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
ClearAll[DoStep,ABCBlockQ]
ClearAll[DoStep,ABCBlockQ]
Line 5,823: Line 5,823:
DoStep[opts_List]:=Flatten[DoStep@@@opts,1]
DoStep[opts_List]:=Flatten[DoStep@@@opts,1]
ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={})
ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={})
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 5,843: Line 5,843:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function testABC
<syntaxhighlight lang=MATLAB>function testABC
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
Line 5,868: Line 5,868:
k = k+1;
k = k+1;
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>Can make word A.
<pre>Can make word A.
Line 5,884: Line 5,884:
Recursively checks if the word is possible if a block is removed from the array.
Recursively checks if the word is possible if a block is removed from the array.


<lang MAXScript>
<syntaxhighlight lang=MAXScript>
-- This is the blocks array
-- This is the blocks array
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
Line 5,983: Line 5,983:
)
)
)
)
</syntaxhighlight>
</lang>


'''Output:'''
'''Output:'''
<lang MAXScript>
<syntaxhighlight lang=MAXScript>
iswordpossible "a"
iswordpossible "a"
true
true
Line 6,001: Line 6,001:
iswordpossible "confuse"
iswordpossible "confuse"
true
true
</syntaxhighlight>
</lang>




=== Non-recursive ===
=== Non-recursive ===
<lang MAXScript>
<syntaxhighlight lang=MAXScript>
fn isWordPossible2 word =
fn isWordPossible2 word =
(
(
Line 6,036: Line 6,036:
) else return false
) else return false
)
)
</syntaxhighlight>
</lang>


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.
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 6,042: Line 6,042:
Then:
Then:


<lang MAXScript>
<syntaxhighlight lang=MAXScript>
iswordpossible "water"
iswordpossible "water"
true
true
iswordpossible2 "water"
iswordpossible2 "water"
false
false
</syntaxhighlight>
</lang>


Non-recursive version quickly decides that it's not possible, even though it clearly is.
Non-recursive version quickly decides that it's not possible, even though it clearly is.


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang Mercury>:- module abc.
<syntaxhighlight lang=Mercury>:- module abc.
:- interface.
:- interface.
:- import_module io.
:- import_module io.
Line 6,085: Line 6,085:
io.format("can_make_word(""%s"") :- %s.\n",
io.format("can_make_word(""%s"") :- %s.\n",
[s(W), s(if P then "true" else "fail")], !IO)),
[s(W), s(if P then "true" else "fail")], !IO)),
Words, !IO).</lang>
Words, !IO).</syntaxhighlight>


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).
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}}==
=={{header|MiniScript}}==
<lang MiniScript>allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
<syntaxhighlight lang=MiniScript>allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
swap = function(list, index1, index2)
swap = function(list, index1, index2)
Line 6,116: Line 6,116:
print out + ": " + canMakeWord(val, allBlocks)
print out + ": " + canMakeWord(val, allBlocks)
end for
end for
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
{{works with|Nim|0.20.0}}
{{works with|Nim|0.20.0}}
<lang nim>import std / strutils
<syntaxhighlight lang=nim>import std / strutils


func canMakeWord(blocks: seq[string]; word: string): bool =
func canMakeWord(blocks: seq[string]; word: string): bool =
Line 6,145: Line 6,145:
echo()
echo()


when isMainModule: main()</lang>
when isMainModule: main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Using the blocks BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
<pre>Using the blocks BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
Line 6,164: Line 6,164:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c Version 2
Works with oo2c Version 2
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE ABCBlocks;
MODULE ABCBlocks;
IMPORT
IMPORT
Line 6,248: Line 6,248:
Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln;
Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln;
END ABCBlocks.
END ABCBlocks.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 6,262: Line 6,262:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang objeck>class Abc {
<syntaxhighlight lang=objeck>class Abc {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
blocks := ["BO", "XK", "DQ", "CP", "NA",
blocks := ["BO", "XK", "DQ", "CP", "NA",
Line 6,307: Line 6,307:
arr[j] := tmp;
arr[j] := tmp;
}
}
}</lang>
}</syntaxhighlight>
<pre>
<pre>
"": true
"": true
Line 6,320: Line 6,320:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let blocks = [
<syntaxhighlight lang=ocaml>let blocks = [
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
Line 6,359: Line 6,359:
"SQUAD", true;
"SQUAD", true;
"CONFUSE", true;
"CONFUSE", true;
]</lang>
]</syntaxhighlight>


{{Out}}
{{Out}}
Line 6,375: Line 6,375:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: mapping
<syntaxhighlight lang=Oforth>import: mapping


["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
Line 6,388: Line 6,388:
]
]
false
false
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 6,398: Line 6,398:
=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==


<lang Progress (Openedge ABL)>FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER) FORWARD.
<syntaxhighlight lang=Progress (Openedge ABL)>FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER) FORWARD.


/* List of blocks */
/* List of blocks */
Line 6,500: Line 6,500:
RETURN TRUE.
RETURN TRUE.
END FUNCTION.
END FUNCTION.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,514: Line 6,514:


=={{header|Order}}==
=={{header|Order}}==
<lang Order>#include <order/interpreter.h>
<syntaxhighlight lang=Order>#include <order/interpreter.h>
#include <order/lib.h>
#include <order/lib.h>


Line 6,676: Line 6,676:
)
)


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,684: Line 6,684:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>BLOCKS = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM";
<syntaxhighlight lang=parigp>BLOCKS = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM";
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];


Line 6,701: Line 6,701:
}
}


for (i = 1, #WORDS, printf("%s\t%d\n", WORDS[i], can_make_word(WORDS[i])));</lang>
for (i = 1, #WORDS, printf("%s\t%d\n", WORDS[i], can_make_word(WORDS[i])));</syntaxhighlight>


Output:<pre>A 1
Output:<pre>A 1
Line 6,715: Line 6,715:
{{works with|Free Pascal|2.6.2}}
{{works with|Free Pascal|2.6.2}}


<lang Pascal>
<syntaxhighlight lang=Pascal>
#!/usr/bin/instantfpc
#!/usr/bin/instantfpc
//program ABCProblem;
//program ABCProblem;
Line 6,781: Line 6,781:
TestABCProblem('SQUAD');
TestABCProblem('SQUAD');
TestABCProblem('CONFUSE');
TestABCProblem('CONFUSE');
END.</lang>
END.</syntaxhighlight>


{{out}}
{{out}}
Line 6,805: Line 6,805:
=={{header|Perl}}==
=={{header|Perl}}==
Recursive solution that can handle characters appearing on different blocks:
Recursive solution that can handle characters appearing on different blocks:
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use warnings;
use strict;
use strict;
Line 6,830: Line 6,830:
}
}
return
return
}</lang>
}</syntaxhighlight>
<p>Testing:
<p>Testing:
<lang perl>use Test::More tests => 8;
<syntaxhighlight lang=perl>use Test::More tests => 8;


my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);
my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);
Line 6,845: Line 6,845:
my @blocks2 = qw(US TZ AO QA);
my @blocks2 = qw(US TZ AO QA);
is(can_make_word('auto', @blocks2), 1);
is(can_make_word('auto', @blocks2), 1);
</syntaxhighlight>
</lang>
===Regex based alternate===
===Regex based alternate===
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang=perl>#!/usr/bin/perl


use strict; # https://rosettacode.org/wiki/ABC_Problem
use strict; # https://rosettacode.org/wiki/ABC_Problem
Line 6,863: Line 6,863:
while $blocks =~ /\w?$letter\w?/gi;
while $blocks =~ /\w?$letter\w?/gi;
return 'False';
return 'False';
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,877: Line 6,877:
=={{header|Phix}}==
=={{header|Phix}}==
Recursive solution which also solves the extra problems on the discussion page.
Recursive solution which also solves the extra problems on the discussion page.
<!--<lang Phix>-->
<!--<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: #004080;">sequence</span> <span style="color: #000000;">blocks</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">used</span>
Line 6,913: Line 6,913:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 6,930: Line 6,930:
=={{header|PHP}}==
=={{header|PHP}}==


<lang PHP>
<syntaxhighlight lang=PHP>
<?php
<?php
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");
Line 6,959: Line 6,959:
echo canMakeWord($word) ? "True" : "False";
echo canMakeWord($word) ? "True" : "False";
echo "\r\n";
echo "\r\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,973: Line 6,973:
=={{header|Picat}}==
=={{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.
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.
<lang Picat>go =>
<syntaxhighlight lang=Picat>go =>
test_it(check_word),
test_it(check_word),
test_it(check_word2),
test_it(check_word2),
Line 7,082: Line 7,082:
block(p,c).
block(p,c).
block(z,m).
block(z,m).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 7,156: Line 7,156:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Mapping and recursion.
Mapping and recursion.
<lang PicoLisp>(setq *Blocks
<syntaxhighlight lang=PicoLisp>(setq *Blocks
'((B O) (X K) (D Q) (C P) (N A) (G T) (R E)
'((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)
(T G) (Q D) (F S) (J W) (H U) (V I) (A N)
Line 7,188: Line 7,188:
(println Word (abc Word *Blocks) (abcR Word *Blocks)) )
(println Word (abc Word *Blocks) (abcR Word *Blocks)) )
(bye)</lang>
(bye)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
===version 1===
===version 1===
<lang pli>ABC: procedure options (main); /* 12 January 2014 */
<syntaxhighlight lang=pli>ABC: procedure options (main); /* 12 January 2014 */


declare word character (20) varying, blocks character (200) varying initial
declare word character (20) varying, blocks character (200) varying initial
Line 7,217: Line 7,217:
end;
end;


end ABC;</lang>
end ABC;</syntaxhighlight>
<pre>
<pre>
A true
A true
Line 7,229: Line 7,229:


===version 2===
===version 2===
<lang pli>*process source attributes xref or(!) options nest;
<syntaxhighlight lang=pli>*process source attributes xref or(!) options nest;
abc: Proc Options(main);
abc: Proc Options(main);
/* REXX --------------------------------------------------------------
/* REXX --------------------------------------------------------------
Line 7,349: Line 7,349:
End;
End;


End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>'$' cannot be spelt.
<pre>'$' cannot be spelt.
Line 7,361: Line 7,361:


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang plm>100H:
<syntaxhighlight lang=plm>100H:


/* ABC PROBLEM ON $-TERMINATED STRING */
/* ABC PROBLEM ON $-TERMINATED STRING */
Line 7,420: Line 7,420:


CALL BDOS(0,0);
CALL BDOS(0,0);
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>A: YES
<pre>A: YES
Line 7,433: Line 7,433:
Works with PowerBASIC 6 Console Compiler
Works with PowerBASIC 6 Console Compiler


<lang PowerBASIC>#COMPILE EXE
<syntaxhighlight lang=PowerBASIC>#COMPILE EXE
#DIM ALL
#DIM ALL
'
'
Line 7,588: Line 7,588:
END IF
END IF
END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>$ FALSE
<pre>$ FALSE
Line 7,602: Line 7,602:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell><#
<syntaxhighlight lang=powershell><#
.Synopsis
.Synopsis
ABC Problem
ABC Problem
Line 7,718: Line 7,718:
{
{
test-blocks -testword $word -Verbose
test-blocks -testword $word -Verbose
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,784: Line 7,784:
Works with SWI-Prolog 6.5.3
Works with SWI-Prolog 6.5.3


<lang Prolog>abc_problem :-
<syntaxhighlight lang=Prolog>abc_problem :-
maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).


Line 7,806: Line 7,806:
( select([H, _], L, L1); select([_, H], L, L1)),
( select([H, _], L, L1); select([_, H], L, L1)),
can_makeword(L1, T).
can_makeword(L1, T).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> ?- abc_problem.
<pre> ?- abc_problem.
Line 7,827: Line 7,827:
{{works with|SWI Prolog 7}}
{{works with|SWI Prolog 7}}


<lang Prolog>:- use_module([ library(chr),
<syntaxhighlight lang=Prolog>:- use_module([ library(chr),
abathslib(protelog/composer) ]).
abathslib(protelog/composer) ]).


Line 7,844: Line 7,844:
%% These rules, removing remaining constraints from the store, are just cosmetic:
%% These rules, removing remaining constraints from the store, are just cosmetic:
'clean up blocks' @ word_built \ block(_) <=> true.
'clean up blocks' @ word_built \ block(_) <=> true.
'word was built' @ word_built <=> true.</lang>
'word was built' @ word_built <=> true.</syntaxhighlight>




Demonstration:
Demonstration:


<lang Prolog>?- can_build_word("A").
<syntaxhighlight lang=Prolog>?- can_build_word("A").
true.
true.
?- can_build_word("BARK").
?- can_build_word("BARK").
Line 7,862: Line 7,862:
true.
true.
?- can_build_word("CONFUSE").
?- can_build_word("CONFUSE").
true.</lang>
true.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
===PureBasic: Iterative===
===PureBasic: Iterative===
<lang purebasic>EnableExplicit
<syntaxhighlight lang=purebasic>EnableExplicit
#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "


Line 7,897: Line 7,897:
PrintN(can_make_word("SqUAD"))
PrintN(can_make_word("SqUAD"))
PrintN(can_make_word("COnFUSE"))
PrintN(can_make_word("COnFUSE"))
Input()</lang>
Input()</syntaxhighlight>


===PureBasic: Recursive===
===PureBasic: Recursive===
<lang purebasic>#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
<syntaxhighlight lang=purebasic>#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "


Macro test(t)
Macro test(t)
Line 7,919: Line 7,919:
test("a") : test("BaRK") : test("BOoK") : test("TREAt")
test("a") : test("BaRK") : test("BOoK") : test("TREAt")
test("cOMMON") : test("SqUAD") : test("COnFUSE")
test("cOMMON") : test("SqUAD") : test("COnFUSE")
Input()</lang>
Input()</syntaxhighlight>
{{out}}
{{out}}
<pre>a = True
<pre>a = True
Line 7,932: Line 7,932:


===Python: Iterative, with tests===
===Python: Iterative, with tests===
<lang python>
<syntaxhighlight lang=python>
'''
'''
Note that this code is broken, e.g., it won't work when
Note that this code is broken, e.g., it won't work when
Line 8,001: Line 8,001:
["", "a", "baRk", "booK", "treat",
["", "a", "baRk", "booK", "treat",
"COMMON", "squad", "Confused"]))
"COMMON", "squad", "Confused"]))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,007: Line 8,007:


===Python: Recursive===
===Python: Recursive===
<lang python>BLOCKS = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'.split()
<syntaxhighlight lang=python>BLOCKS = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'.split()


def _abc(word, blocks):
def _abc(word, blocks):
Line 8,031: Line 8,031:
if __name__ == '__main__':
if __name__ == '__main__':
for word in [''] + 'A BARK BoOK TrEAT COmMoN SQUAD conFUsE'.split():
for word in [''] + 'A BARK BoOK TrEAT COmMoN SQUAD conFUsE'.split():
print('Can we spell %9r? %r' % (word, abc(word)))</lang>
print('Can we spell %9r? %r' % (word, abc(word)))</syntaxhighlight>


{{out}}
{{out}}
Line 8,044: Line 8,044:


===Python: Recursive, telling how===
===Python: Recursive, telling how===
<lang python>def mkword(w, b):
<syntaxhighlight lang=python>def mkword(w, b):
if not w: return []
if not w: return []


Line 8,059: Line 8,059:


for w in ", A, bark, book, treat, common, SQUAD, conFUsEd".split(', '):
for w in ", A, bark, book, treat, common, SQUAD, conFUsEd".split(', '):
print '\'' + w + '\'' + ' ->', abc(w, blocks)</lang>
print '\'' + w + '\'' + ' ->', abc(w, blocks)</syntaxhighlight>


{{out}}
{{out}}
Line 8,076: Line 8,076:
=={{header|q}}==
=={{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.
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.
<lang q>BLOCKS:string`BO`XK`DQ`CP`NA`GT`RE`TG`QD`FS`JW`HU`VI`AN`OB`ER`FS`LY`PC`ZM
<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
WORDS:string`A`BARK`BOOK`TREAT`COMMON`SQUAD`CONFUSE


Line 8,082: Line 8,082:
$[0=count s; 1b; / empty string
$[0=count s; 1b; / empty string
not any found:any each b=s 0; 0b; / cannot proceed
not any found:any each b=s 0; 0b; / cannot proceed
any(1_s).z.s/:b(til count b)except/:where found] }</lang>
any(1_s).z.s/:b(til count b)except/:where found] }</syntaxhighlight>
{{out}}
{{out}}
<lang q>q)WORDS cmw\:BLOCKS
<syntaxhighlight lang=q>q)WORDS cmw\:BLOCKS
1101011b</lang>
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 first expression tests whether the string <code>s</code> is empty. If so, the result is true. This matches two cases: either the string is empty and can be made from any set of blocks; or all its letters have been matched and there is nothing more to check.


Line 8,093: Line 8,093:


To meet the requirement for case-insensitivity and to display the results, apply the above within a wrapper.
To meet the requirement for case-insensitivity and to display the results, apply the above within a wrapper.
<lang q>Words:string`A`bark`BOOK`Treat`COMMON`squad`CONFUSE
<syntaxhighlight lang=q>Words:string`A`bark`BOOK`Treat`COMMON`squad`CONFUSE
cmwi:{(`$x), `false`true cmw . upper each(x;y) }</lang>
cmwi:{(`$x), `false`true cmw . upper each(x;y) }</syntaxhighlight>
{{out}}
{{out}}
<lang q>q)Words cmwi\:BLOCKS
<syntaxhighlight lang=q>q)Words cmwi\:BLOCKS
A true
A true
bark true
bark true
Line 8,103: Line 8,103:
COMMON false
COMMON false
squad true
squad true
CONFUSE true</lang>
CONFUSE true</syntaxhighlight>
* [https://code.kx.com/q/ref/ Language Reference]
* [https://code.kx.com/q/ref/ Language Reference]
* [https://code.kx.com/q/learn/pb/abc-problem/ The Q Playbook: ABC problem – analysis]
* [https://code.kx.com/q/learn/pb/abc-problem/ The Q Playbook: ABC problem – analysis]
Line 8,115: Line 8,115:
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.
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.


<lang Quackery>[ $ "BOXKDQCPNAGTRETGQDFS"
<syntaxhighlight lang=Quackery>[ $ "BOXKDQCPNAGTRETGQDFS"
$ "JWHUVIANOBERFSLYPCZM"
$ "JWHUVIANOBERFSLYPCZM"
join ] constant is blocks ( --> $ )
join ] constant is blocks ( --> $ )
Line 8,134: Line 8,134:
[ drop dip not
[ drop dip not
conclude ] ]
conclude ] ]
drop echotruth ] is can_make_word ( $ --> )</lang>
drop echotruth ] is can_make_word ( $ --> )</syntaxhighlight>


'''Testing in the Quackery shell:'''
'''Testing in the Quackery shell:'''
Line 8,179: Line 8,179:
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.
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.


<lang Quackery>[ ' [ 0 ] swap
<syntaxhighlight lang=Quackery>[ ' [ 0 ] swap
witheach
witheach
[ over -1 peek
[ over -1 peek
Line 8,230: Line 8,230:
bailed dup
bailed dup
if [ dip 2drop ]
if [ dip 2drop ]
echotruth ] is can_make_word ( $ --> )</lang>
echotruth ] is can_make_word ( $ --> )</syntaxhighlight>
'''Testing in the Quackery shell:'''
'''Testing in the Quackery shell:'''
Identical to iterative solution above.
Identical to iterative solution above.
Line 8,239: Line 8,239:
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.
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.


<lang R>blocks <- rbind(c("B","O"),
<syntaxhighlight lang=R>blocks <- rbind(c("B","O"),
c("X","K"),
c("X","K"),
c("D","Q"),
c("D","Q"),
Line 8,281: Line 8,281:
"COMMON",
"COMMON",
"SQUAD",
"SQUAD",
"CONFUSE"))</lang>
"CONFUSE"))</syntaxhighlight>


{{out}}
{{out}}
Line 8,289: Line 8,289:
===Without recursion===
===Without recursion===
Second version without recursion and giving every unique combination of blocks for each word:
Second version without recursion and giving every unique combination of blocks for each word:
<lang R>canMakeNoRecursion <- function(x) {
<syntaxhighlight lang=R>canMakeNoRecursion <- function(x) {
x <- toupper(x)
x <- toupper(x)
charList <- strsplit(x, character(0))
charList <- strsplit(x, character(0))
Line 8,309: Line 8,309:
"COMMON",
"COMMON",
"SQUAD",
"SQUAD",
"CONFUSE"))</lang>
"CONFUSE"))</syntaxhighlight>
{{out}}
{{out}}
<pre>$A
<pre>$A
Line 8,393: Line 8,393:
So '(can-make-word? "")' is true for me.
So '(can-make-word? "")' is true for me.


<lang racket>#lang racket
<syntaxhighlight lang=racket>#lang racket
(define block-strings
(define block-strings
(list "BO" "XK" "DQ" "CP" "NA"
(list "BO" "XK" "DQ" "CP" "NA"
Line 8,435: Line 8,435:
(check-false (can-make-word? "COMMON"))
(check-false (can-make-word? "COMMON"))
(check-true (can-make-word? "SQUAD"))
(check-true (can-make-word? "SQUAD"))
(check-true (can-make-word? "CONFUSE")))</lang>
(check-true (can-make-word? "CONFUSE")))</syntaxhighlight>


{{out}}
{{out}}
Line 8,451: Line 8,451:
{{works with|rakudo|6.0.c}}
{{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.
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.
<lang perl6>multi can-spell-word(Str $word, @blocks) {
<syntaxhighlight lang=perl6>multi can-spell-word(Str $word, @blocks) {
my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }
my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }
can-spell-word $word.uc.comb.list, @regex;
can-spell-word $word.uc.comb.list, @regex;
Line 8,471: Line 8,471:
for <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> {
for <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> {
say "$_ &can-spell-word($_, @b)";
say "$_ &can-spell-word($_, @b)";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A True
<pre>A True
Line 8,482: Line 8,482:


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<lang vb>dim Blocks as string
<syntaxhighlight lang=vb>dim Blocks as string
dim InWord as string
dim InWord as string


Line 8,508: Line 8,508:
Blocks = "BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM"
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")
showmessage "Can make: " + InWord + " = " + iif(CanMakeWord(InWord, Blocks), "True", "False")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Can make: A = TRUE
<pre>Can make: A = TRUE
Line 8,520: Line 8,520:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red []
<syntaxhighlight lang=Red>Red []
test: func [ s][
test: func [ s][
p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
Line 8,536: Line 8,536:
print reduce [ pad copy word 8 ":" test word]
print reduce [ pad copy word 8 ":" test word]
]
]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 8,550: Line 8,550:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/
<syntaxhighlight lang=rexx>/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/
list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/
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'
blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'
Line 8,570: Line 8,570:
end /*try*/ /* [↑] end of a "TRY" permute. */
end /*try*/ /* [↑] end of a "TRY" permute. */
say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.'
say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.'
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 8,583: Line 8,583:


===version 2===
===version 2===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang=rexx>/* REXX ---------------------------------------------------------------
* 10.01.2014 Walter Pachl counts the number of possible ways
* 10.01.2014 Walter Pachl counts the number of possible ways
* 12.01.2014 corrected date and output
* 12.01.2014 corrected date and output
Line 8,685: Line 8,685:
used.w=1
used.w=1
End
End
Return 1</lang>
Return 1</syntaxhighlight>
{{out}}
{{out}}
<pre>'' cannot be spelt.
<pre>'' cannot be spelt.
Line 8,766: Line 8,766:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>Blocks = [ :BO, :XK, :DQ, :CP, :NA, :GT, :RE, :TG, :QD, :FS, :JW, :HU, :VI, :AN, :OB, :ER, :FS, :LY, :PC, :ZM ]
<syntaxhighlight lang=ring>Blocks = [ :BO, :XK, :DQ, :CP, :NA, :GT, :RE, :TG, :QD, :FS, :JW, :HU, :VI, :AN, :OB, :ER, :FS, :LY, :PC, :ZM ]
Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]
Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]


Line 8,789: Line 8,789:
if found = false return false ok
if found = false return false ok
next
next
return true</lang>
return true</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 8,810: Line 8,810:
=={{header|Ruby}}==
=={{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.
This one uses a case insensitive regular expression. The 'sub!' method substitutes the first substring it finds and returns nil if nothing is found.
<lang ruby>words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << ""
<syntaxhighlight lang=ruby>words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << ""


words.each do |word|
words.each do |word|
Line 8,817: Line 8,817:
puts "#{word.inspect}: #{res}"
puts "#{word.inspect}: #{res}"
end
end
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 8,831: Line 8,831:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang unbasic>blocks$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
<syntaxhighlight lang=unbasic>blocks$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
b = int((len(blocks$) /3) + 1)
b = int((len(blocks$) /3) + 1)
Line 8,855: Line 8,855:
print wrd$;chr$(9);
print wrd$;chr$(9);
if n = len(wrd$) then print " True" else print " False"
if n = len(wrd$) then print " True" else print " False"
next i</lang>
next i</syntaxhighlight>
<pre>A True
<pre>A True
BARK True
BARK True
Line 8,866: Line 8,866:
=={{header|Rust}}==
=={{header|Rust}}==
This implementation uses a backtracking search.
This implementation uses a backtracking search.
<lang rust>use std::iter::repeat;
<syntaxhighlight lang=rust>use std::iter::repeat;


fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
Line 8,895: Line 8,895:
}
}
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 8,908: Line 8,908:


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang Scala>object AbcBlocks extends App {
{{libheader|Scala}}<syntaxhighlight lang=Scala>object AbcBlocks extends App {


protected class Block(face1: Char, face2: Char) {
protected class Block(face1: Char, face2: Char) {
Line 8,957: Line 8,957:


words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made."))
words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made."))
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
In R5RS:
In R5RS:
<lang scheme>(define *blocks*
<syntaxhighlight lang=scheme>(define *blocks*
'((#\B #\O) (#\X #\K) (#\D #\Q) (#\C #\P) (#\N #\A)
'((#\B #\O) (#\X #\K) (#\D #\Q) (#\C #\P) (#\N #\A)
(#\G #\T) (#\R #\E) (#\T #\G) (#\Q #\D) (#\F #\S)
(#\G #\T) (#\R #\E) (#\T #\G) (#\Q #\D) (#\F #\S)
Line 9,001: Line 9,001:
(display word)
(display word)
(newline))
(newline))
*words*)</lang>
*words*)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 9,014: Line 9,014:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const func boolean: canMakeWords (in array string: blocks, in string: word) is func
const func boolean: canMakeWords (in array string: blocks, in string: word) is func
Line 9,047: Line 9,047:
writeln(word rpad 10 <& canMakeWords(word));
writeln(word rpad 10 <& canMakeWords(word));
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 9,062: Line 9,062:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>function CanMakeWord word
<syntaxhighlight lang=sensetalk>function CanMakeWord word


put [
put [
Line 9,102: Line 9,102:
return True
return True
end CanMakeWord</lang>
end CanMakeWord</syntaxhighlight>


<lang sensetalk>repeat with each item word in [
<syntaxhighlight lang=sensetalk>repeat with each item word in [
"A",
"A",
"BARK",
"BARK",
Line 9,114: Line 9,114:
]
]
put CanMakeWord(word)
put CanMakeWord(word)
end repeat</lang>
end repeat</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
===Recursive Search Version===
===Recursive Search Version===
<lang sequencel>import <Utilities/Conversion.sl>;
<syntaxhighlight lang=sequencel>import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
import <Utilities/Sequence.sl>;


Line 9,146: Line 9,146:
letter when ascii >= 65 and ascii <= 90
letter when ascii >= 65 and ascii <= 90
else
else
intToAscii(ascii - 32);</lang>
intToAscii(ascii - 32);</syntaxhighlight>


{{out}}
{{out}}
Line 9,161: Line 9,161:


===RegEx Version ===
===RegEx Version ===
<lang sequencel>import <Utilities/Conversion.sl>;
<syntaxhighlight lang=sequencel>import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
import <Utilities/Sequence.sl>;
import <RegEx/RegEx.sl>;
import <RegEx/RegEx.sl>;
Line 9,191: Line 9,191:
letter when ascii >= 65 and ascii <= 90
letter when ascii >= 65 and ascii <= 90
else
else
intToAscii(ascii - 32);</lang>
intToAscii(ascii - 32);</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>func can_make_word(word, blocks) {
<syntaxhighlight lang=ruby>func can_make_word(word, blocks) {


blocks.map! { |b| b.uc.chars.sort.join }.freq!
blocks.map! { |b| b.uc.chars.sort.join }.freq!
Line 9,211: Line 9,211:
return false;
return false;
}(word.uc.chars, blocks)
}(word.uc.chars, blocks)
}</lang>
}</syntaxhighlight>


Tests:
Tests:
<lang ruby>var b1 = %w(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM)
<syntaxhighlight lang=ruby>var b1 = %w(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM)
var b2 = %w(US TZ AO QA)
var b2 = %w(US TZ AO QA)


Line 9,232: Line 9,232:
say ("%7s -> %s" % (t[0], bool));
say ("%7s -> %s" % (t[0], bool));
assert(bool == t[1])
assert(bool == t[1])
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 9,247: Line 9,247:


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>COMMENT ABC PROBLEM;
<syntaxhighlight lang=simula>COMMENT ABC PROBLEM;
BEGIN
BEGIN


Line 9,343: Line 9,343:


END.
END.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>A => T OK
<pre>A => T OK
Line 9,356: Line 9,356:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Recursive solution. Tested in Pharo.
Recursive solution. Tested in Pharo.
<lang smalltalk>
<syntaxhighlight lang=smalltalk>
ABCPuzzle>>test
ABCPuzzle>>test
#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
Line 9,378: Line 9,378:
(self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
(self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
^ false
^ false
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 9,394: Line 9,394:
=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
{{works with|SNOBOL4, SPITBOL for Linux}}
<lang SNOBOL4>
<syntaxhighlight lang=SNOBOL4>
* Program: abc.sbl,
* Program: abc.sbl,
* To run: sbl -r abc.sbl
* To run: sbl -r abc.sbl
Line 9,463: Line 9,463:
P C
P C
Z M
Z M
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 9,483: Line 9,483:
=={{header|SPAD}}==
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
{{works with|FriCAS, OpenAxiom, Axiom}}
<lang SPAD>
<syntaxhighlight lang=SPAD>
blocks:List Tuple Symbol:= _
blocks:List Tuple Symbol:= _
[(B,O),(X,K),(D,Q),(C,P),(N,A),(G,T),(R,E),(T,G),(Q,D),(F,S), _
[(B,O),(X,K),(D,Q),(C,P),(N,A),(G,T),(R,E),(T,G),(Q,D),(F,S), _
Line 9,508: Line 9,508:
[canMakeWord?(s,blocks) for s in Example]
[canMakeWord?(s,blocks) for s in Example]


</syntaxhighlight>
</lang>


Programming details:[http://fricas.github.io/book.pdf UserGuide]
Programming details:[http://fricas.github.io/book.pdf UserGuide]
Line 9,522: Line 9,522:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang OCaML>
<syntaxhighlight lang=OCaML>
val BLOCKS = [(#"B",#"O"), (#"X",#"K"), (#"D",#"Q"), (#"C",#"P"), (#"N",#"A"), (#"G",#"T"),
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"),
(#"R",#"E"), (#"T",#"G"), (#"Q",#"D"), (#"F",#"S"), (#"J",#"W"), (#"H",#"U"), (#"V",#"I"),
Line 9,556: Line 9,556:
val words = ["A","UTAH","AutO"];
val words = ["A","UTAH","AutO"];
map (fn st => cando(map Char.toUpper (String.explode st),[],BLOCKS)) words;
map (fn st => cando(map Char.toUpper (String.explode st),[],BLOCKS)) words;
</syntaxhighlight>
</lang>
Output
Output
<pre>val it = [true, true, false, true, false, true, true]: bool list
<pre>val it = [true, true, false, true, false, true, true]: bool list
Line 9,563: Line 9,563:


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang=Swift>import Foundation


func Blockable(str: String) -> Bool {
func Blockable(str: String) -> Bool {
Line 9,595: Line 9,595:
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
println("'\(str)' \(CanOrNot(Blockable(str))) be spelled with blocks.")
println("'\(str)' \(CanOrNot(Blockable(str))) be spelled with blocks.")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 9,608: Line 9,608:


{{works with|Swift|3.0.2}}
{{works with|Swift|3.0.2}}
<lang Swift>import Swift
<syntaxhighlight lang=Swift>import Swift


func canMake(word: String) -> Bool {
func canMake(word: String) -> Bool {
Line 9,629: Line 9,629:
let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"]
let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"]


words.forEach { print($0, canMake(word: $0)) }</lang>
words.forEach { print($0, canMake(word: $0)) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 9,643: Line 9,643:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang=tcl>package require Tcl 8.6


proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} {
proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} {
Line 9,663: Line 9,663:
foreach word {"" A BARK BOOK TREAT COMMON SQUAD CONFUSE} {
foreach word {"" A BARK BOOK TREAT COMMON SQUAD CONFUSE} {
puts [format "Can we spell %9s? %s" '$word' [abc $word]]
puts [format "Can we spell %9s? %s" '$word' [abc $word]]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 9,677: Line 9,677:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>set words = "A'BARK'BOOK'TREAT'COMMON'SQUAD'CONFUSE"
<syntaxhighlight lang=tuscript>set words = "A'BARK'BOOK'TREAT'COMMON'SQUAD'CONFUSE"
set result = *
set result = *
loop word = words
loop word = words
Line 9,694: Line 9,694:
set out = concat (word, " ", cond)
set out = concat (word, " ", cond)
set result = append (result, out)
set result = append (result, out)
endloop</lang>
endloop</syntaxhighlight>
{{out}}
{{out}}
<pre>A true
<pre>A true
Line 9,706: Line 9,706:
=={{header|TXR}}==
=={{header|TXR}}==


<lang txr>@(do
<syntaxhighlight lang=txr>@(do
(defvar blocks '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G)
(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)
(Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R)
Line 9,752: Line 9,752:
@(if (can-make-word w) "True" "False")
@(if (can-make-word w) "True" "False")
@(end)
@(end)
@(end)</lang>
@(end)</syntaxhighlight>


Run:
Run:
Line 9,785: Line 9,785:
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.
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.


<lang Cpp>
<syntaxhighlight lang=Cpp>
#include <Core/Core.h>
#include <Core/Core.h>
#include <stdio.h>
#include <stdio.h>
Line 9,888: Line 9,888:


}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 9,915: Line 9,915:
{{works with|bash}}
{{works with|bash}}


<lang bash>can_build_word() {
<syntaxhighlight lang=bash>can_build_word() {
if [[ $1 ]]; then
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
can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
Line 9,953: Line 9,953:
can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
printf "%s\t%s\n" "$word" $ans
printf "%s\t%s\n" "$word" $ans
done</lang>
done</syntaxhighlight>


{{out}}
{{out}}
Line 9,969: Line 9,969:
'''String-based solution'''
'''String-based solution'''


<lang UTFool>
<syntaxhighlight lang=UTFool>
···
···
http://rosettacode.org/wiki/ABC_Problem
http://rosettacode.org/wiki/ABC_Problem
Line 9,997: Line 9,997:
i: blocks.indexOf (word.substring 0, 1), i + 3
i: blocks.indexOf (word.substring 0, 1), i + 3
return solution
return solution
</syntaxhighlight>
</lang>


'''Collection-based solution'''
'''Collection-based solution'''


<lang UTFool>
<syntaxhighlight lang=UTFool>
···
···
http://rosettacode.org/wiki/ABC_Problem
http://rosettacode.org/wiki/ABC_Problem
Line 10,036: Line 10,036:
Collections.swap blocks, 0, i
Collections.swap blocks, 0, i
return false
return false
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
Option Explicit


Line 10,075: Line 10,075:
ABC = (NbInit = (myColl.Count + Len(myWord)))
ABC = (NbInit = (myColl.Count + Len(myWord)))
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 10,089: Line 10,089:
{{trans|Go}}
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt


var r // recursive
var r // recursive
Line 10,117: Line 10,117:
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
System.print("%(Fmt.s(-7, word)) %(sp.call(word))")
System.print("%(Fmt.s(-7, word)) %(sp.call(word))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 10,131: Line 10,131:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0;
<syntaxhighlight lang=XPL0>string 0;


char Side1, Side2;
char Side1, Side2;
Line 10,159: Line 10,159:
Text(0, if CanMakeWord(Words(J)) then "True" else "False"); CrLf(0);
Text(0, if CanMakeWord(Words(J)) then "True" else "False"); CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 10,173: Line 10,173:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>letters$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
<syntaxhighlight lang=Yabasic>letters$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"


sub canMake(letters$, word$)
sub canMake(letters$, word$)
Line 10,200: Line 10,200:
print "common = ", canMake(letters$, "common") // 0
print "common = ", canMake(letters$, "common") // 0
print "squad = ", canMake(letters$, "squad") // 1
print "squad = ", canMake(letters$, "squad") // 1
print "confuse = ", canMake(letters$, "confuse") // 1</lang>
print "confuse = ", canMake(letters$, "confuse") // 1</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
{{trans|C}}
{{trans|C}}
<lang zkl>var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
<syntaxhighlight lang=zkl>var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );


Line 10,222: Line 10,222:
foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){
foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){
can_make_word(word).println(": ",word);
can_make_word(word).println(": ",word);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 10,237: Line 10,237:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang=zonnon>
module Main;
module Main;
type
type
Line 10,325: Line 10,325:
CanMakeWord("confuse");
CanMakeWord("confuse");
end Main.
end Main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 10,337: Line 10,337:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 LET b$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
<syntaxhighlight lang=zxbasic>10 LET b$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
20 READ p
20 READ p
30 FOR c=1 TO p
30 FOR c=1 TO p
Line 10,357: Line 10,357:
190 REM Erase pair
190 REM Erase pair
200 IF j/2=INT (j/2) THEN LET u$(j-1 TO j)=" ": RETURN
200 IF j/2=INT (j/2) THEN LET u$(j-1 TO j)=" ": RETURN
210 LET u$(j TO j+1)=" ": RETURN</lang>
210 LET u$(j TO j+1)=" ": RETURN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>