I am new to Wolfram language. I am also learning some Bash and Perl as well.
https://theweeklychallenge.org/
I was wondering if anyone has ideas on solving the weekly challenge above using the Wolfram language.
Here are my "solutions" - credit to Claude.
TASK #1 - Popular Word You are given a string paragraph and an array of the banned words. Write a script to return the most popular word that is not banned. It is guaranteed there is at least one word that is not banned and the answer is unique. The words in paragraph are case-insensitive and the answer should be in lowercase. The words can not contain punctuation symbols.
(* Task 1: Popular Word — PWC Week 370 *)
popularWord[paragraph_String, banned_List] := Module[
{words, bannedSet, filtered, counts},
(* Normalise: lower-case, strip non-alpha chars, split on whitespace *)
words = StringSplit[
StringReplace[ToLowerCase[paragraph],
RegularExpression["[^a-z ]"] -> ""]
];
bannedSet = ToLowerCase /@ banned;
(* Keep only words that are not banned *)
filtered = Select[words, !MemberQ[bannedSet, #] &];
(* Tally frequencies, sort descending, return top word *)
counts = ReverseSort[Counts[filtered]];
First[Keys[counts]]
];
(* ── Examples ── *)
popularWord[
"Bob hit a ball, the hit BALL flew far after it was hit.",
{"hit", "far"}
]
(* → "ball" *)
popularWord[
"the deer make a home in the woods",
{"the", "a"}
]
(* → "deer" *)
TASK #2 Scramble String
You are given two strings A and B of the same length. Write a script to return true if string B is a scramble of string A otherwise return false. String B is a scramble of string A if A can be transformed into B by a single (recursive) scramble operation.
(* Task 2: Scramble String — PWC Week 370 *)
(* Memoised recursive check — essential for performance *)
scrambleQ[a_String, b_String] := scrambleQ[a, b] = Module[
{n, aChars, bChars},
n = StringLength[a];
(* Base cases *)
Which[
a === b, True,
n == 1, False,
Sort[Characters[a]] =!= Sort[Characters[b]], False,
(* Try every split point 1 .. n-1 *)
True,
AnyTrue[
Range[1, n - 1],
Function[k,
With[{aL = StringTake[a, k], aR = StringDrop[a, k],
bL = StringTake[b, k], bR = StringDrop[b, k],
bL2= StringTake[b, -k], bR2= StringDrop[b, -(n-k)]},
(* No swap: left↔left, right↔right *)
(scrambleQ[aL, bL] && scrambleQ[aR, bR]) ||
(* Swap: left↔right-tail, right↔left-tail *)
(scrambleQ[aL, bL2] && scrambleQ[aR, bR2])
]
]
]
]
];
(* ── Examples ── *)
scrambleQ["great", "rgtae"] (* → True *)
scrambleQ["abcde", "caebd"] (* → True *)
scrambleQ["abcde", "abced"] (* → True *)
scrambleQ["great", "rgeat"] (* → True *)
scrambleQ["abcd", "bdca"] (* → False *)