ABC problem: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 44:
;Example:
<
True
>>> can_make_word("BARK")
Line 57:
True
>>> can_make_word("CONFUSE")
True</
{{Template:Strings}}
Line 64:
=={{header|11l}}==
{{trans|Python}}
<
I word == ‘’
R 0B
Line 79:
R 1B
print([‘’, ‘a’, ‘baRk’, ‘booK’, ‘treat’, ‘COMMON’, ‘squad’, ‘Confused’].map(w -> ‘'’w‘': ’can_make_word(w)).join(‘, ’))</
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
ABC CSECT
USING ABC,R13 base register
Line 158:
YREGS
NN EQU (BLOCKS-WORDS)/L'WORDS number of words
END ABC</
{{out}}
<pre>
Line 171:
=={{header|8080 Assembly}}==
<
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 247:
wrdcommon: db 'COMMON$'
wrdsquad: db 'SQUAD$'
wrdconfuse: db 'CONFUSE$'</
{{out}}
Line 263:
{{trans|8080 Assembly}}
<
bits 16
org 100h
Line 325:
.cmn: db 'COMMON$'
.squad: db 'SQUAD$'
.confs: db 'CONFUSE$'</
{{out}}
Line 338:
=={{header|8th}}==
<
\ ========================================================================================
\ You are given a collection of ABC blocks
Line 537:
bye
;
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program problemABC64.s */
Line 728:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 747:
</pre>
=={{header|ABAP}}==
<
REPORT z_rosetta_abc.
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 = 'CONFUSE' letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).
</syntaxhighlight>
{{out}}
<pre>
Line 833:
=={{header|Action!}}==
<
CHAR ARRAY sideA="BXDCNGRTQFJHVAOEFLPZ"
CHAR ARRAY sideB="OKQPATEGDSWUINBRSYCM"
Line 889:
Test("SQuaD")
Test("CoNfUsE")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/ABC_problem.png Screenshot from Atari 8-bit computer]
Line 906:
Using #HASH-OFF
</pre>
<
FUNCTION bCAN_MAKE_WORD(zWord: STRING): BOOLEAN
VAR sBlockCount: SHORT
Line 933:
RETURN OCCURS(zUsedBlocks, ",") = sWordLength
ENDFUNCTION
</syntaxhighlight>
{{out}}
<pre>
Line 950:
</pre>
<
use Ada.Characters.Handling;
Line 1,028:
end loop;
end Abc_Problem;
</syntaxhighlight>
{{out}}
Line 1,043:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
# construct the list of blocks #
Line 1,123:
)
</syntaxhighlight>
Output:
<pre>
Line 1,136:
=={{header|ALGOL W}}==
<
begin
% Returns true if we can spell the word using the blocks, %
Line 1,216:
testCanSpell( "confuse", 7 )
end
end.</
{{out}}
<pre>
Line 1,229:
=={{header|Apex}}==
<
if (String.isEmpty(word)) {
return true;
Line 1,273:
System.debug('"COMMON": ' + canMakeWord(blocks, 'COMMON'));
System.debug('"SQuAd": ' + canMakeWord(blocks, 'SQuAd'));
System.debug('"CONFUSE": ' + canMakeWord(blocks, 'CONFUSE'));</
{{out}}
<pre>"": true
Line 1,286:
=={{header|APL}}==
{{works with|Dyalog APL|16.0}}
<
{{out}}
<pre> )COPY dfns ucase
Line 1,296:
=={{header|AppleScript}}==
===Imperative===
<
"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"}
Line 1,323:
end repeat
return false
end canMakeWordWithBlocks</
===Functional===
<
use framework "Foundation"
Line 1,522:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre> '' -> true
Line 1,534:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program problemABC.s */
Line 1,718:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
Can_make_word: A
Line 1,737:
=={{header|Arturo}}==
<
[B O] [X K] [D Q] [C P] [N A] [G T] [R E]
[T G] [Q D] [F S] [J W] [H U] [V I] [A N]
Line 1,762:
loop ["A" "BaRk" "bOoK" "tReAt" "CoMmOn" "SqUaD" "cONfUsE"] 'wrd
-> print [wrd "=>" canMakeWord? wrd]</
{{Out}}
<pre>A => true
Line 1,773:
=={{header|Astro}}==
<
if ls.isempty:
return true
Line 1,784:
for s in test:
print "($|>8|{s} ${abc(s, list)})"</
=={{header|AutoHotkey}}==
'''Function'''
<
o := {}
loop, parse, blocks, `n, `r
Line 1,812:
added := 1
}
}</
'''Test Input''' (as per question)
<
(
BO
Line 1,852:
loop, parse, wordlist, `n
out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
msgbox % out</
{{out}}
Line 2,012:
=={{header|BaCon}}==
<
DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse"
Line 2,035:
PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n"
WEND</
{{out}}
<pre>
Line 2,049:
=={{header|BASIC}}==
Works with:VB-DOS, QB64, QBasic, QuickBASIC
<
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' ABC_Problem '
Line 2,175:
END FUNCTION
</syntaxhighlight>
==={{header|Commodore BASIC}}===
{{trans|Sinclair ZX-81 BASIC}}
<
20 W$ = "BARK" : GOSUB 100
30 W$ = "BOOK" : GOSUB 100
Line 2,203:
230 RETURN
240 PRINT W$" -> NO"
250 RETURN</
{{out}}
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:
<
110 MS=100:REM MAX STACK DEPTH
120 DIM BL$(MS):REM BLOCKS LEFT
Line 2,255:
470 DATA A, BORK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, ""
480 DATA ABABACAC,ABBA,""
490 DATA ""</
{{Out}}
Line 2,277:
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. A nice unstructured algorithm. Unfortunately the requirement that it be case-insensitive is moot, because the ZX81 does not support lower-case letters.
<
20 INPUT W$
30 FOR I=1 TO LEN W$
Line 2,287:
90 STOP
100 NEXT J
110 PRINT "NO"</
{{in}}
<pre>A</pre>
Line 2,318:
=={{header|Batch File}}==
<
@echo off
::abc.bat
Line 2,381:
:END
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PROCcan_make_word("A")
PROCcan_make_word("BARK")
Line 2,406:
ENDWHILE
IF word$>"" PRINT "False" ELSE PRINT "True"
ENDPROC</
{{out}}
Line 2,419:
=={{header|BCPL}}==
<
let canMakeWord(word) = valof
Line 2,455:
show("SQUAD")
show("CONFUSE")
$)</
{{out}}
<pre>A: yes
Line 2,466:
=={{header|BQN}}==
<
Matches ← ⊑⊸(⊑∘∊¨)˜ /⊣ # blocks matching current letter
Others ← <˘∘⍉∘(»⊸≥∨`)∘(≡⌜)/¨<∘⊣ # blocks without current matches
Line 2,481:
words←⟨"A","bark","BOOK","TrEaT","Common","Squad","Confuse"⟩
> {(<𝕩) ∾ blocks ABC 𝕩}¨ words</
{{out}}
<pre>┌─
Line 2,494:
=={{header|Bracmat}}==
<
( can-make-word
= ABC blocks
Line 2,541:
& can-make-word'SQUAD
& can-make-word'CONFUSE
);</
{{out}}
<pre>A yes
Line 2,553:
=={{header|C}}==
Recursive solution. Empty string returns true.
<
#include <ctype.h>
Line 2,593:
return 0;
}</
{{out}}
<pre>
Line 2,610:
This Method uses regular expressions to do the checking. Given that n = length of blocks string and
m = length of word string, then CheckWord's time complexity comes out to about m*(n - (m-1)/2).
<
using System.IO;
// Needed for the method.
Line 2,640:
return true;
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,652:
</pre>
'''Unoptimized'''
<
using System.Linq;
Line 2,734:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,748:
{{Works with|C++11}}
Build with:
<
<
#include <vector>
#include <string>
Line 2,782:
std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n";
}
}</
{{out}}
Line 2,799:
<b>module.ceylon</b>
<
module rosetta.abc "1.0.0" {}
</syntaxhighlight>
<b>run.ceylon</b>
<
shared void run() {
printAndCanMakeWord("A", blocks);
Line 2,880:
myRemainingLetterIndexes)
else false;
</syntaxhighlight>
{{out}}
Line 2,895:
=={{header|Clojure}}==
A translation of the Haskell solution.
<
(def blocks
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
Line 2,916:
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word)))</
{{out}}
Line 2,928:
=={{header|CLU}}==
<
rslt: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
Line 2,971:
end
end
end start_up</
{{out}}
<pre>A: yes
Line 2,982:
=={{header|CoffeeScript}}==
<
canMakeWord = (word="") ->
Line 2,999:
# Expect true, true, false, true, false, true, true, true
for word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "squad", "CONFUSE", "STORM"]
console.log word + " -> " + canMakeWord(word)</
{{out}}
Line 3,012:
=={{header|Comal}}==
<
0020 blocks$:=" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
0030 FOR i#:=1 TO LEN(word$) DO
Line 3,030:
0170 END
0180 //
0190 DATA "A","BARK","BOOK","treat","common","squad","CoNfUsE"</
{{out}}
<pre>A: yes
Line 3,041:
=={{header|Common Lisp}}==
<
(defun word-possible-p (word blocks)
(cond
Line 3,055:
collect (word-possible-p
(subseq word 1)
(remove b blocks))))))))</
{{out}}
Line 3,077:
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<
MODULE ABCProblem;
IMPORT
Line 3,162:
END ABCProblem.
</syntaxhighlight>
Execute: ^Q ABCProblem.CanMakeWord A BARK BOOK TREAT COMMON SQUAD confuse~
{{out}}
Line 3,176:
=={{header|Cowgol}}==
<
include "strings.coh";
Line 3,219:
print(resp[can_make_word(words[i])]);
i := i + 1;
end loop;</
{{out}}
Line 3,235:
{{trans|Python}}
A simple greedy algorithm is enough for the given sequence of blocks. canMakeWord is true on an empty word because you can compose it using zero blocks.
<
bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe {
Line 3,256:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</
{{out}}
<pre>"" true
Line 3,269:
===@nogc Version===
The same as the precedent version, but it avoids all heap allocations and it's lower-level and ASCII-only.
<
bool canMakeWord(in string word, in string[] blocks) nothrow @nogc
Line 3,307:
foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split)
writefln(`"%s" %s`, word, canMakeWord(word, blocks));
}</
===Recursive Version===
This version is able to find the solution for the word "abba" given the blocks AB AB AC AC.
{{trans|C}}
<
alias Block = char[2];
Line 3,349:
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</
{{out}}
<pre>"" true
Line 3,363:
===Alternative Recursive Version===
This version doesn't shuffle the input blocks, but it's more complex and it allocates an array of indexes.
<
alias Block = char[2];
Line 3,404:
immutable word = "abba";
writefln(`"%s" %s`, word, blocks2.canMakeWord(word));
}</
The output is the same.
=={{header|Delphi}}==
Just to be different I implemented a block as a set of (2) char rather than as an array of (2) char.
<
{$APPTYPE CONSOLE}
Line 3,472:
readln;
end.
</syntaxhighlight>
{{out}}
Line 3,486:
=={{header|Draco}}==
<
proc nonrec ucase(char c) char:
Line 3,538:
test("sQuAd");
test("CONFUSE")
corp</
{{out}}
<pre>A: yes
Line 3,552:
{{trans|Swift}}
<
var blocks = [
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
Line 3,577:
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
print("\"\(str)\" \(canOrNot(blockable(str))) be spelled with blocks.")
}</
{{out}}
Line 3,590:
=={{header|EchoLisp}}==
<
(lib 'list) ;; list-delete
Line 3,607:
(spell (string-rest word) (list-delete blocks block))))))
</syntaxhighlight>
{{out}}
<pre>
Line 3,626:
=={{header|Ela}}==
{{trans|Haskell}}
<
:::IO
Line 3,642:
mapM_ (\w -> putLn (w, not << null $ abc blocks (map char.upper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</
{{out}}
Line 3,656:
=={{header|Elena}}==
ELENA 5.0
<
import system'collections;
import extensions;
Line 3,700:
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
}
}</
{{out}}
<pre>
Line 3,716:
{{trans|Erlang}}
{{works with|Elixir|1.3}}
<
def can_make_word(word, avail) do
can_make_word(String.upcase(word) |> to_charlist, avail, [])
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
~w(A Bark Book Treat Common Squad Confuse) |>
Enum.map(fn(w) -> IO.puts "#{w}: #{ABC.can_make_word(w, blocks)}" end)</
{{out}}
Line 3,745:
=={{header|Erlang}}==
<
-export([can_make_word/1, can_make_word/2, blocks/0]).
Line 3,761:
main(_) -> lists:map(fun(W) -> io:fwrite("~s: ~s~n", [W, can_make_word(W)]) end,
["A","Bark","Book","Treat","Common","Squad","Confuse"]).
</syntaxhighlight>
{{Out}}
Line 3,774:
=={{header|ERRE}}==
<
PROGRAM BLOCKS
Line 3,803:
CANMAKEWORD("Confuse")
END PROGRAM
</syntaxhighlight>
=={{header|Euphoria}}==
implemented using OpenEuphoria
<
include std/text.e
Line 3,843:
if getc(0) then end if
</syntaxhighlight>
{{out}}
<pre>
Line 3,859:
=={{header|F_Sharp|F#}}==
<p>This solution does not depend on the order of the blocks, neither on the symmetry of blocks we see in the example block set. (Symmetry: if AB is a block, an A comes only with another AB|BA)</p>
<
let rec look_for_right_candidate candidates noCandidates c rest =
match candidates with
Line 3,888:
List.iter (fun w -> printfn "Using the blocks we can make the word '%s': %b" w (spell_word_with blocks w)) words
0</
{{out}}
<pre>h:\RosettaCode\ABC\Fsharp>RosettaCode "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" a bark book threat common squad confuse
Line 3,906:
=={{header|Factor}}==
<
kernel math math.statistics qw sequences sets unicode ;
IN: rosetta-code.abc-problem
Line 3,950:
show-blocks header input [ result ] each ;
MAIN: abc-problem</
{{out}}
<pre>
Line 3,972:
=={{header|FBSL}}==
This approach uses a string, blanking out the pair previously found. Probably faster than array manipulation.
<
#APPTYPE CONSOLE
SUB MAIN()
Line 4,017:
RETURN TRUE
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>
Line 4,037:
{{works with|gforth|0.7.3}}
<
variable blocks
: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;
Line 4,066:
;
: .abc abc if ." True" else ." False" then ;</
{{out}}
Line 4,081:
=={{header|Fortran}}==
Attempts to write the word read from unit 5. Please find the output, bash command, and gfortran compilation instructions as commentary at the start of the source, which starts right away!
<
!Compilation started at Thu Jun 5 01:52:03
!
Line 4,150:
end subroutine ucase
end program abc</
===But if backtracking might be needed===
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.
<
MODULE PLAYPEN !Messes with a set of alphabet blocks.
INTEGER MSG !Output unit number.
Line 4,436:
END DO
END
</syntaxhighlight>
Output: the first column of T/F is the report from CANBLOCK, the second is the expected answer from the example, and the third is whether the two are in agreement.
<pre>
Line 4,461:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 4,503:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>A true
Line 4,515:
=={{header|FutureBasic}}==
<
include "NSLog.incl"
Line 4,557:
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Line 4,571:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ae860292d4588b3627d77c85bcc634ee Click this link to run this code]'''
<
Dim sCheck As String[] = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]
Dim sBlock As String[] = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
Line 4,598:
Next
End</
Output:
<pre>
Line 4,611:
=={{header|Go}}==
<
import (
Line 4,649:
fmt.Println(word, sp(word))
}
}</
{{out}}
<pre>
Line 4,663:
=={{header|Groovy}}==
Solution:
<
def blocks
Line 4,674:
word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
}
}</
Test:
<
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"])
['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {
println "'${it}': ${a.canMakeWord(it)}"
}</
{{out}}
Line 4,696:
=={{header|Harbour}}==
Harbour Project implements a cross-platform Clipper/xBase compiler.
<
LOCAL cStr
Line 4,727:
NEXT
RETURN cFinal == cStr</
{{out}}
<pre>
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.
<
import Data.Char (toUpper)
Line 4,755:
main :: IO ()
main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w)))
["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"]</
{{out}}
Line 4,771:
Or, in terms of the bind operator:
<
import Data.List (delete)
Line 4,808:
words $
"BO XK DQ CP NA GT RE TG QD FS JW"
<> " HU VI AN OB ER FS LY PC ZM"</
{{Out}}
<pre>("",True)
Line 4,823:
Works in both languages:
<
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
Line 4,846:
}
}
end</
Sample run:
Line 4,864:
=={{header|J}}==
'''Solution:'''
<
'rows cols'=. i.&.> $y
for_c. cols do.
Line 4,874:
)
abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0:</
'''Examples:'''
<
ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
Line 4,889:
"COmMOn" F
"SqUAD" T
"CoNfuSE" T</
'''Tacit version'''
<
uppc=:(-32*96&<*.123&>)&.(3&u:)
reduc=: ] delElem 1 i.~e."0 1
forms=: (1 - '' -: (reduc L:0/ :: (a:"_)@(<"0@],<@[))&uppc) L:0</
{{out}}
Line 4,919:
Another approach might be:
<
ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE '
Line 4,928:
candidates=: word,"1>,{{relevant
+./(((#need){. #/.~)"1 candidates) */ .>:need
)</
Example use:
<
1
Blocks canform 1{::ExampleWords
Line 4,945:
1
Blocks canform 6{::ExampleWords
1</
Explanation:
Line 4,955:
For example:
<
1
word
Line 4,968:
ANN
AAA
AAN</
Here, the word is simply 'A', and we have two blocks to consider for our word: AN and NA. So we form all possible combinations of the letters of those two bocks, prefix each of them with our word and test whether any of them contain two copies of the letters of our word. (As it happens, three of the candidates are valid, for this trivial example.)
Line 4,975:
{{trans|C}}
{{works with|Java|1.6+}}
<
import java.util.Collections;
import java.util.List;
Line 5,010:
return false;
}
}</
{{out}}
<pre>"": true
Line 5,025:
====Imperative====
The following method uses regular expressions and the string replace function to allow more support for older browsers.
<
function CheckWord(blocks, word) {
Line 5,062:
for(var i = 0;i<words.length;++i)
console.log(words[i] + ": " + CheckWord(blocks, words[i]));
</syntaxhighlight>
Result:
Line 5,076:
====Functional====
<
var strBlocks =
Line 5,123:
return strWords.split(' ').map(solution).join('\n');
})('A bark BooK TReAT COMMON squAD conFUSE');</
{{Out}}
<
bark -> BO NA RE XK
BooK: [no solution]
Line 5,131:
COMMON: [no solution]
squAD -> FS DQ HU NA QD
conFUSE -> CP BO NA FS HU FS RE</
===ES6===
====Imperative====
<
let blocks = characters.split(" ").map(pair => pair.split(""));
Line 5,167:
"CONFUSE"
].forEach(word => console.log(`${word}: ${isWordPossible(word)}`));
</syntaxhighlight>
Result:
Line 5,181:
====Functional====
{{Trans|Haskell}}
<
"use strict";
Line 5,247:
// MAIN ---
return main();
})();</
{{Out}}
<pre>["",true]
Line 5,259:
=={{header|jq}}==
The problem description seems to imply that if a letter, X, appears on more than one block, its partner will be the same on all blocks. This makes the problem trivial.<
# when_index(cond;ary) returns the index of the first element in ary
# that satisfies cond; it uses a helper function that takes advantage
Line 5,288:
else .[1:] | abc($blks)
end
end;</
Task:<
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] as $blocks
| ("A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE")
| "\(.) : \( .|abc($blocks) )" ;task</
{{Out}}
A : true
Line 5,305:
=={{header|Jsish}}==
Based on Javascript ES5 imperative solution.
<
/* ABC problem, in Jsish. Can word be spelled with the given letter blocks. */
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
Line 5,341:
can spell CONFUSE
=!EXPECTEND!=
*/</
{{out}}
Line 5,358:
=={{header|Julia}}==
<
function abc(str::AbstractString, list)
Line 5,376:
@printf("%-8s | %s\n", str, abc(str, list))
end
end</
{{out}}
Line 5,389:
=={{header|Kotlin}}==
{{trans|Java}}
<
fun run() {
println("\"\": " + blocks.canMakeWord(""))
Line 5,427:
}
fun main(args: Array<String>) = ABC_block_checker.run()</
{{out}}
<pre>"": true
Line 5,440:
=={{header|Liberty BASIC}}==
===Recursive solution===
<syntaxhighlight lang=lb>
print "Rosetta Code - ABC problem (recursive solution)"
print
Line 5,483:
wend
end function
</syntaxhighlight>
{{out}}
<pre>
Line 5,505:
</pre>
===Procedural solution===
<syntaxhighlight lang=lb>
print "Rosetta Code - ABC problem (procedural solution)"
print
Line 5,639:
LetterOK=1
end sub
</syntaxhighlight>
{{out}}
<pre>
Line 5,662:
=={{header|Logo}}==
<
[J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]
Line 5,682:
]
bye</
{{Out}}
Line 5,694:
=={{header|Lua}}==
<
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
Line 5,724:
end
print(found)
end</
{{Output}}
Line 5,740:
<
Module ABC {
can_make_word("A")
Line 5,761:
}
ABC
</syntaxhighlight>
{{out}}
Line 5,775:
=={{header|Maple}}==
<
local blocks, i, j, word, letterFound;
blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
Line 5,797:
end proc:
seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]);</
{{out}}
<pre>
Line 5,810:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
ClearAll[DoStep,ABCBlockQ]
Line 5,823:
DoStep[opts_List]:=Flatten[DoStep@@@opts,1]
ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={})
</syntaxhighlight>
{{Out}}
<pre>
Line 5,843:
=={{header|MATLAB}} / {{header|Octave}}==
<
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
Line 5,868:
k = k+1;
end
end</
{{out}}
<pre>Can make word A.
Line 5,884:
Recursively checks if the word is possible if a block is removed from the array.
<
-- This is the blocks array
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
Line 5,983:
)
)
</syntaxhighlight>
'''Output:'''
<
iswordpossible "a"
true
Line 6,001:
iswordpossible "confuse"
true
</syntaxhighlight>
=== Non-recursive ===
<
fn isWordPossible2 word =
(
Line 6,036:
) else return false
)
</syntaxhighlight>
Both versions are good for this example, but the non-recursive version won't work if the blocks are more random, because it just takes the first found block, and the recursive version decides which one to use.
Line 6,042:
Then:
<
iswordpossible "water"
true
iswordpossible2 "water"
false
</syntaxhighlight>
Non-recursive version quickly decides that it's not possible, even though it clearly is.
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 6,085:
io.format("can_make_word(""%s"") :- %s.\n",
[s(W), s(if P then "true" else "fail")], !IO)),
Words, !IO).</
Note that 'P', in the foldl near the end, is not a boolean variable, but a zero-arity currying of can_make_word (i.e., it's a 'lambda' that takes no arguments and then calls can_make_word with all of the already-supplied arguments).
=={{header|MiniScript}}==
<
swap = function(list, index1, index2)
Line 6,116:
print out + ": " + canMakeWord(val, allBlocks)
end for
</syntaxhighlight>
=={{header|Nim}}==
{{works with|Nim|0.20.0}}
<
func canMakeWord(blocks: seq[string]; word: string): bool =
Line 6,145:
echo()
when isMainModule: main()</
{{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
Line 6,164:
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE ABCBlocks;
IMPORT
Line 6,248:
Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln;
END ABCBlocks.
</syntaxhighlight>
Output:
<pre>
Line 6,262:
=={{header|Objeck}}==
{{trans|Java}}
<
function : Main(args : String[]) ~ Nil {
blocks := ["BO", "XK", "DQ", "CP", "NA",
Line 6,307:
arr[j] := tmp;
}
}</
<pre>
"": true
Line 6,320:
=={{header|OCaml}}==
<
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
Line 6,359:
"SQUAD", true;
"CONFUSE", true;
]</
{{Out}}
Line 6,375:
=={{header|Oforth}}==
<
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
Line 6,388:
]
false
;</
{{out}}
Line 6,398:
=={{header|OpenEdge/Progress}}==
<
/* List of blocks */
Line 6,500:
RETURN TRUE.
END FUNCTION.
</syntaxhighlight>
{{out}}
Line 6,514:
=={{header|Order}}==
<
#include <order/lib.h>
Line 6,676:
)
</syntaxhighlight>
{{out}}
Line 6,684:
=={{header|PARI/GP}}==
<
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];
Line 6,701:
}
for (i = 1, #WORDS, printf("%s\t%d\n", WORDS[i], can_make_word(WORDS[i])));</
Output:<pre>A 1
Line 6,715:
{{works with|Free Pascal|2.6.2}}
<
#!/usr/bin/instantfpc
//program ABCProblem;
Line 6,781:
TestABCProblem('SQUAD');
TestABCProblem('CONFUSE');
END.</
{{out}}
Line 6,805:
=={{header|Perl}}==
Recursive solution that can handle characters appearing on different blocks:
<
use warnings;
use strict;
Line 6,830:
}
return
}</
<p>Testing:
<
my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);
Line 6,845:
my @blocks2 = qw(US TZ AO QA);
is(can_make_word('auto', @blocks2), 1);
</syntaxhighlight>
===Regex based alternate===
<
use strict; # https://rosettacode.org/wiki/ABC_Problem
Line 6,863:
while $blocks =~ /\w?$letter\w?/gi;
return 'False';
}</
{{out}}
<pre>
Line 6,877:
=={{header|Phix}}==
Recursive solution which also solves the extra problems on the discussion page.
<!--<
<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:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 6,930:
=={{header|PHP}}==
<
<?php
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");
Line 6,959:
echo canMakeWord($word) ? "True" : "False";
echo "\r\n";
}</
{{out}}
<pre>
Line 6,973:
=={{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.
<
test_it(check_word),
test_it(check_word2),
Line 7,082:
block(p,c).
block(z,m).
</syntaxhighlight>
{{out}}
Line 7,156:
=={{header|PicoLisp}}==
Mapping and recursion.
<
'((B O) (X K) (D Q) (C P) (N A) (G T) (R E)
(T G) (Q D) (F S) (J W) (H U) (V I) (A N)
Line 7,188:
(println Word (abc Word *Blocks) (abcR Word *Blocks)) )
(bye)</
=={{header|PL/I}}==
===version 1===
<
declare word character (20) varying, blocks character (200) varying initial
Line 7,217:
end;
end ABC;</
<pre>
A true
Line 7,229:
===version 2===
<
abc: Proc Options(main);
/* REXX --------------------------------------------------------------
Line 7,349:
End;
End;</
{{out}}
<pre>'$' cannot be spelt.
Line 7,361:
=={{header|PL/M}}==
<
/* ABC PROBLEM ON $-TERMINATED STRING */
Line 7,420:
CALL BDOS(0,0);
EOF</
{{out}}
<pre>A: YES
Line 7,433:
Works with PowerBASIC 6 Console Compiler
<
#DIM ALL
'
Line 7,588:
END IF
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>$ FALSE
Line 7,602:
=={{header|PowerShell}}==
<
.Synopsis
ABC Problem
Line 7,718:
{
test-blocks -testword $word -Verbose
}</
{{out}}
<pre>
Line 7,784:
Works with SWI-Prolog 6.5.3
<
maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
Line 7,806:
( select([H, _], L, L1); select([_, H], L, L1)),
can_makeword(L1, T).
</syntaxhighlight>
{{out}}
<pre> ?- abc_problem.
Line 7,827:
{{works with|SWI Prolog 7}}
<
abathslib(protelog/composer) ]).
Line 7,844:
%% These rules, removing remaining constraints from the store, are just cosmetic:
'clean up blocks' @ word_built \ block(_) <=> true.
'word was built' @ word_built <=> true.</
Demonstration:
<
true.
?- can_build_word("BARK").
Line 7,862:
true.
?- can_build_word("CONFUSE").
true.</
=={{header|PureBasic}}==
===PureBasic: Iterative===
<
#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "
Line 7,897:
PrintN(can_make_word("SqUAD"))
PrintN(can_make_word("COnFUSE"))
Input()</
===PureBasic: Recursive===
<
Macro test(t)
Line 7,919:
test("a") : test("BaRK") : test("BOoK") : test("TREAt")
test("cOMMON") : test("SqUAD") : test("COnFUSE")
Input()</
{{out}}
<pre>a = True
Line 7,932:
===Python: Iterative, with tests===
<
'''
Note that this code is broken, e.g., it won't work when
Line 8,001:
["", "a", "baRk", "booK", "treat",
"COMMON", "squad", "Confused"]))
</syntaxhighlight>
{{out}}
Line 8,007:
===Python: Recursive===
<
def _abc(word, blocks):
Line 8,031:
if __name__ == '__main__':
for word in [''] + 'A BARK BoOK TrEAT COmMoN SQUAD conFUsE'.split():
print('Can we spell %9r? %r' % (word, abc(word)))</
{{out}}
Line 8,044:
===Python: Recursive, telling how===
<
if not w: return []
Line 8,059:
for w in ", A, bark, book, treat, common, SQUAD, conFUsEd".split(', '):
print '\'' + w + '\'' + ' ->', abc(w, blocks)</
{{out}}
Line 8,076:
=={{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.
<
WORDS:string`A`BARK`BOOK`TREAT`COMMON`SQUAD`CONFUSE
Line 8,082:
$[0=count s; 1b; / empty string
not any found:any each b=s 0; 0b; / cannot proceed
any(1_s).z.s/:b(til count b)except/:where found] }</
{{out}}
<
1101011b</
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:
To meet the requirement for case-insensitivity and to display the results, apply the above within a wrapper.
<
cmwi:{(`$x), `false`true cmw . upper each(x;y) }</
{{out}}
<
A true
bark true
Line 8,103:
COMMON false
squad true
CONFUSE true</
* [https://code.kx.com/q/ref/ Language Reference]
* [https://code.kx.com/q/learn/pb/abc-problem/ The Q Playbook: ABC problem – analysis]
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.
<
$ "JWHUVIANOBERFSLYPCZM"
join ] constant is blocks ( --> $ )
Line 8,134:
[ drop dip not
conclude ] ]
drop echotruth ] is can_make_word ( $ --> )</
'''Testing in the Quackery shell:'''
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.
<
witheach
[ over -1 peek
Line 8,230:
bailed dup
if [ dip 2drop ]
echotruth ] is can_make_word ( $ --> )</
'''Testing in the Quackery shell:'''
Identical to iterative solution above.
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.
<
c("X","K"),
c("D","Q"),
Line 8,281:
"COMMON",
"SQUAD",
"CONFUSE"))</
{{out}}
Line 8,289:
===Without recursion===
Second version without recursion and giving every unique combination of blocks for each word:
<
x <- toupper(x)
charList <- strsplit(x, character(0))
Line 8,309:
"COMMON",
"SQUAD",
"CONFUSE"))</
{{out}}
<pre>$A
Line 8,393:
So '(can-make-word? "")' is true for me.
<
(define block-strings
(list "BO" "XK" "DQ" "CP" "NA"
Line 8,435:
(check-false (can-make-word? "COMMON"))
(check-true (can-make-word? "SQUAD"))
(check-true (can-make-word? "CONFUSE")))</
{{out}}
Line 8,451:
{{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.
<
my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }
can-spell-word $word.uc.comb.list, @regex;
Line 8,471:
for <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> {
say "$_ &can-spell-word($_, @b)";
}</
{{out}}
<pre>A True
Line 8,482:
=={{header|RapidQ}}==
<
dim InWord as string
Line 8,508:
Blocks = "BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM"
showmessage "Can make: " + InWord + " = " + iif(CanMakeWord(InWord, Blocks), "True", "False")
</syntaxhighlight>
{{out}}
<pre>Can make: A = TRUE
Line 8,520:
=={{header|Red}}==
<
test: func [ s][
p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
Line 8,536:
print reduce [ pad copy word 8 ":" test word]
]
</syntaxhighlight>
{{out}}
<pre>
Line 8,550:
=={{header|REXX}}==
===version 1===
<
list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/
blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'
Line 8,570:
end /*try*/ /* [↑] end of a "TRY" permute. */
say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.'
return</
{{out|output|text= when using the default inputs:}}
<pre>
Line 8,583:
===version 2===
<
* 10.01.2014 Walter Pachl counts the number of possible ways
* 12.01.2014 corrected date and output
Line 8,685:
used.w=1
End
Return 1</
{{out}}
<pre>'' cannot be spelt.
Line 8,766:
=={{header|Ring}}==
<
Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]
Line 8,789:
if found = false return false ok
next
return true</
{{Out}}
<pre>
Line 8,810:
=={{header|Ruby}}==
This one uses a case insensitive regular expression. The 'sub!' method substitutes the first substring it finds and returns nil if nothing is found.
<
words.each do |word|
Line 8,817:
puts "#{word.inspect}: #{res}"
end
</syntaxhighlight>
{{Out}}
<pre>
Line 8,831:
=={{header|Run BASIC}}==
<
makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse"
b = int((len(blocks$) /3) + 1)
Line 8,855:
print wrd$;chr$(9);
if n = len(wrd$) then print " True" else print " False"
next i</
<pre>A True
BARK True
Line 8,866:
=={{header|Rust}}==
This implementation uses a backtracking search.
<
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
Line 8,895:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 8,908:
=={{header|Scala}}==
{{libheader|Scala}}<
protected class Block(face1: Char, face2: Char) {
Line 8,957:
words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made."))
}</
=={{header|Scheme}}==
In R5RS:
<
'((#\B #\O) (#\X #\K) (#\D #\Q) (#\C #\P) (#\N #\A)
(#\G #\T) (#\R #\E) (#\T #\G) (#\Q #\D) (#\F #\S)
Line 9,001:
(display word)
(newline))
*words*)</
{{out}}
<pre>
Line 9,014:
=={{header|Seed7}}==
<
const func boolean: canMakeWords (in array string: blocks, in string: word) is func
Line 9,047:
writeln(word rpad 10 <& canMakeWords(word));
end for;
end func;</
{{out}}
Line 9,062:
=={{header|SenseTalk}}==
<
put [
Line 9,102:
return True
end CanMakeWord</
<
"A",
"BARK",
Line 9,114:
]
put CanMakeWord(word)
end repeat</
=={{header|SequenceL}}==
===Recursive Search Version===
<
import <Utilities/Sequence.sl>;
Line 9,146:
letter when ascii >= 65 and ascii <= 90
else
intToAscii(ascii - 32);</
{{out}}
Line 9,161:
===RegEx Version ===
<
import <Utilities/Sequence.sl>;
import <RegEx/RegEx.sl>;
Line 9,191:
letter when ascii >= 65 and ascii <= 90
else
intToAscii(ascii - 32);</
=={{header|Sidef}}==
{{trans|Perl}}
<
blocks.map! { |b| b.uc.chars.sort.join }.freq!
Line 9,211:
return false;
}(word.uc.chars, blocks)
}</
Tests:
<
var b2 = %w(US TZ AO QA)
Line 9,232:
say ("%7s -> %s" % (t[0], bool));
assert(bool == t[1])
}</
{{out}}
Line 9,247:
=={{header|Simula}}==
<
BEGIN
Line 9,343:
END.
</syntaxhighlight>
{{out}}
<pre>A => T OK
Line 9,356:
=={{header|Smalltalk}}==
Recursive solution. Tested in Pharo.
<
ABCPuzzle>>test
#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
Line 9,378:
(self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
^ false
</syntaxhighlight>
{{out}}
<pre>
Line 9,394:
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<
* Program: abc.sbl,
* To run: sbl -r abc.sbl
Line 9,463:
P C
Z M
</syntaxhighlight>
{{out}}
<pre>
Line 9,483:
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<
blocks:List Tuple Symbol:= _
[(B,O),(X,K),(D,Q),(C,P),(N,A),(G,T),(R,E),(T,G),(Q,D),(F,S), _
Line 9,508:
[canMakeWord?(s,blocks) for s in Example]
</syntaxhighlight>
Programming details:[http://fricas.github.io/book.pdf UserGuide]
Line 9,522:
=={{header|Standard ML}}==
<
val BLOCKS = [(#"B",#"O"), (#"X",#"K"), (#"D",#"Q"), (#"C",#"P"), (#"N",#"A"), (#"G",#"T"),
(#"R",#"E"), (#"T",#"G"), (#"Q",#"D"), (#"F",#"S"), (#"J",#"W"), (#"H",#"U"), (#"V",#"I"),
Line 9,556:
val words = ["A","UTAH","AutO"];
map (fn st => cando(map Char.toUpper (String.explode st),[],BLOCKS)) words;
</syntaxhighlight>
Output
<pre>val it = [true, true, false, true, false, true, true]: bool list
Line 9,563:
=={{header|Swift}}==
<
func Blockable(str: String) -> Bool {
Line 9,595:
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
println("'\(str)' \(CanOrNot(Blockable(str))) be spelled with blocks.")
}</
{{out}}
<pre>
Line 9,608:
{{works with|Swift|3.0.2}}
<
func canMake(word: String) -> Bool {
Line 9,629:
let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"]
words.forEach { print($0, canMake(word: $0)) }</
{{out}}
<pre>
Line 9,643:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} {
Line 9,663:
foreach word {"" A BARK BOOK TREAT COMMON SQUAD CONFUSE} {
puts [format "Can we spell %9s? %s" '$word' [abc $word]]
}</
{{out}}
<pre>
Line 9,677:
=={{header|TUSCRIPT}}==
<
set result = *
loop word = words
Line 9,694:
set out = concat (word, " ", cond)
set result = append (result, out)
endloop</
{{out}}
<pre>A true
Line 9,706:
=={{header|TXR}}==
<
(defvar blocks '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G)
(Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R)
Line 9,752:
@(if (can-make-word w) "True" "False")
@(end)
@(end)</
Run:
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.
<
#include <Core/Core.h>
#include <stdio.h>
Line 9,888:
}
</syntaxhighlight>
{{out}}
Line 9,915:
{{works with|bash}}
<
if [[ $1 ]]; then
can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
Line 9,953:
can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
printf "%s\t%s\n" "$word" $ans
done</
{{out}}
Line 9,969:
'''String-based solution'''
<
···
http://rosettacode.org/wiki/ABC_Problem
Line 9,997:
i: blocks.indexOf (word.substring 0, 1), i + 3
return solution
</syntaxhighlight>
'''Collection-based solution'''
<
···
http://rosettacode.org/wiki/ABC_Problem
Line 10,036:
Collections.swap blocks, 0, i
return false
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang=vb>
Option Explicit
Line 10,075:
ABC = (NbInit = (myColl.Count + Len(myWord)))
End Function
</syntaxhighlight>
{{out}}
<pre>
Line 10,089:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var r // recursive
Line 10,117:
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
System.print("%(Fmt.s(-7, word)) %(sp.call(word))")
}</
{{out}}
Line 10,131:
=={{header|XPL0}}==
<
char Side1, Side2;
Line 10,159:
Text(0, if CanMakeWord(Words(J)) then "True" else "False"); CrLf(0);
];
]</
{{out}}
Line 10,173:
=={{header|Yabasic}}==
<
sub canMake(letters$, word$)
Line 10,200:
print "common = ", canMake(letters$, "common") // 0
print "squad = ", canMake(letters$, "squad") // 1
print "confuse = ", canMake(letters$, "confuse") // 1</
=={{header|zkl}}==
{{trans|C}}
<
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
Line 10,222:
foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){
can_make_word(word).println(": ",word);
}</
{{out}}
<pre>
Line 10,237:
=={{header|zonnon}}==
<
module Main;
type
Line 10,325:
CanMakeWord("confuse");
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 10,337:
=={{header|ZX Spectrum Basic}}==
<
20 READ p
30 FOR c=1 TO p
Line 10,357:
190 REM Erase pair
200 IF j/2=INT (j/2) THEN LET u$(j-1 TO j)=" ": RETURN
210 LET u$(j TO j+1)=" ": RETURN</
{{out}}
<pre>
|