Wordle comparison: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(19 intermediate revisions by 11 users not shown)
Line 1:
{{Draft task}}
 
;Rationale:
Line 17:
<br><br>
 
=={{header|ALGOL 68}}==
 
Test cases copied from '''C'''.
<syntaxhighlight lang="algol68"># utility functions: #
 
PROC join = ([]STRING row, STRING joiner) STRING:
BEGIN
BOOL first := TRUE;
STRING result := "";
FOR i FROM LWB row TO UPB row DO
IF NOT first THEN result +:= joiner
ELSE first := FALSE
FI;
result +:= row[i]
OD;
result
END;
 
PROC fill = (REF []STRING row, STRING s) VOID:
BEGIN
FOR i FROM LWB row TO UPB row DO row[i] := s OD
END;
 
# actual solution: #
 
PROC wordle comparison = (STRING word, guess) []STRING:
BEGIN
STRING copy := word;
# we'll just replace matched chars with NULs in copy
to avoid further matches #
[UPB guess]STRING result;
fill(result, "");
# first the greens: #
FOR i TO UPB guess DO
IF i <= UPB copy AND copy[i] = guess[i] THEN
result[i] := "green";
copy[i] := REPR 0
FI
OD;
# then the rest: #
FOR i TO UPB guess DO
IF result[i] = "" THEN
FOR j TO UPB copy DO
IF copy[j] = guess[i] THEN
result[i] := "yellow";
copy[j] := REPR 0;
next
FI
OD;
result[i] := "grey";
next: SKIP
FI
OD;
result
END;
 
[,]STRING pairs = (("ALLOW", "LOLLY"),
("BULLY", "LOLLY"),
("ROBIN", "ALERT"),
("ROBIN", "SONIC"),
("ROBIN", "ROBIN"));
FOR i TO UPB pairs DO
print((pairs[i,1], " v ", pairs[i,2], " => ",
join(wordle comparison(pairs[i,1], pairs[i,2]), ", "),
newline))
OD</syntaxhighlight>
 
{{out}}
<pre>ALLOW v LOLLY => yellow, yellow, green, grey, grey
BULLY v LOLLY => grey, grey, green, green, green
ROBIN v ALERT => grey, grey, grey, yellow, grey
ROBIN v SONIC => grey, green, yellow, green, grey
ROBIN v ROBIN => green, green, green, green, green</pre>
 
=={{header|C}}==
Line 85 ⟶ 158:
</pre>
 
=={{header|C#}}==
{{works with|.NET 8}}
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Linq;
 
public class WordleComparison
{
public static void Main(string[] args)
{
List<TwoWords> pairs = new List<TwoWords>
{
new TwoWords("ALLOW", "LOLLY"),
new TwoWords("ROBIN", "SONIC"),
new TwoWords("CHANT", "LATTE"),
new TwoWords("We're", "She's"),
new TwoWords("NOMAD", "MAMMA")
};
 
foreach (var pair in pairs)
{
Console.WriteLine(pair.Answer + " v " + pair.Guess + " -> " + string.Join(", ", Wordle(pair.Answer, pair.Guess)));
}
}
 
private static List<Colour> Wordle(string answer, string guess)
{
if (answer.Length != guess.Length)
{
throw new ArgumentException("The two words must be of the same length.");
}
 
var result = Enumerable.Repeat(Colour.GREY, guess.Length).ToList();
var answerCopy = answer;
 
for (int i = 0; i < guess.Length; i++)
{
if (answer[i] == guess[i])
{
answerCopy = answerCopy.Remove(i, 1).Insert(i, "\0");
result[i] = Colour.GREEN;
}
}
 
for (int i = 0; i < guess.Length; i++)
{
int index = answerCopy.IndexOf(guess[i]);
if (index >= 0 && result[i] != Colour.GREEN)
{
answerCopy = answerCopy.Remove(index, 1).Insert(index, "\0");
result[i] = Colour.YELLOW;
}
}
 
return result;
}
 
private enum Colour { GREEN, GREY, YELLOW }
 
private record TwoWords(string Answer, string Guess);
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> YELLOW, YELLOW, GREEN, GREY, GREY
ROBIN v SONIC -> GREY, GREEN, YELLOW, GREEN, GREY
CHANT v LATTE -> GREY, YELLOW, YELLOW, GREY, GREY
We're v She's -> GREY, GREY, YELLOW, YELLOW, GREY
NOMAD v MAMMA -> GREY, YELLOW, GREEN, GREY, GREY
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
 
enum Colour { GREEN, GREY, YELLOW };
 
const char NIL = '\0';
 
struct Two_Words {
std::string answer;
std::string guess;
};
 
std::string to_string(const Colour& colour) {
std::string result;
switch ( colour ) {
case Colour::GREEN : result = "Green"; break;
case Colour::GREY : result = "Grey"; break;
case Colour::YELLOW : result = "Yellow"; break;
}
return result;
}
 
std::vector<Colour> wordle(const std::string& answer, const std::string& guess) {
const uint32_t guess_length = guess.length();
if ( answer.length() != guess_length ) {
throw std::invalid_argument("The two words must have the same length.");
}
 
std::string answerCopy = answer;
std::vector<Colour> result(guess_length, Colour::GREY);
for ( uint32_t i = 0; i < guess_length; ++i ) {
if ( answer[i] == guess[i] ) {
answerCopy[i] = NIL;
result[i] = Colour::GREEN;
}
}
 
for ( uint32_t i = 0; i < guess_length; ++i ) {
std::string::size_type index = answerCopy.find(guess[i]);
if ( index != std::string::npos ) {
answerCopy[index] = NIL;
result[i] = Colour::YELLOW;
}
}
return result;
}
 
int main() {
const std::vector<Two_Words> pairs = { Two_Words("ALLOW", "LOLLY"), Two_Words("ROBIN", "SONIC"),
Two_Words("CHANT", "LATTE"), Two_Words("We're", "She's"), Two_Words("NOMAD", "MAMMA") };
 
for ( const Two_Words& pair : pairs ) {
std::vector<Colour> colours = wordle(pair.answer, pair.guess);
std::cout << pair.answer << " v " << pair.guess << " -> [";
for ( uint32_t i = 0; i < pair.answer.length() - 1; ++i ) {
std::cout << to_string(colours[i]) << ", ";
}
std::cout << to_string(colours.back()) << "]" << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
ALLOW v LOLLY -> [Yellow, Yellow, Green, Grey, Grey]
ROBIN v SONIC -> [Grey, Green, Yellow, Green, Grey]
CHANT v LATTE -> [Grey, Yellow, Yellow, Grey, Grey]
We're v She's -> [Grey, Grey, Yellow, Yellow, Grey]
NOMAD v MAMMA -> [Grey, Yellow, Green, Grey, Grey]
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
{Structure to hold the secret wordle word and a test word}
 
type TStringPair = record
Secret,Test: string;
end;
 
{Array of test pairs}
 
const Pairs: array [0..4] of TStringPair = (
(Secret: 'ALLOW'; Test: 'LOLLY'),
(Secret: 'BULLY'; Test: 'LOLLY'),
(Secret: 'ROBIN'; Test: 'ALERT'),
(Secret: 'ROBIN'; Test: 'SONIC'),
(Secret: 'ROBIN'; Test: 'ROBIN'));
 
{Structures holding wordle colors}
 
type TWordleColors = (wcGreen,wcYellow,wcGrey);
type TWordleArray = array [0..4] of TWordleColors;
 
 
function TestWordle(Secret,Test: string): TWordleArray;
{Compare Test string against secret wordle word}
var I,J,Inx: integer;
var SL: TStringList;
 
function LetterAvailable(C: char): boolean;
{Check to see if letter is unused}
{Decrement count every time letter used}
var Inx: integer;
begin
Result:=False;
{Is it in the list?}
Inx:=SL.IndexOf(C);
{Exit if not}
if Inx<0 then exit;
{Decrement count each time a letter is used}
SL.Objects[Inx]:=Pointer(Integer(SL.Objects[Inx])-1);
if integer(SL.Objects[Inx])=0 then SL.Delete(Inx);
Result:=True;
end;
 
 
begin
SL:=TStringList.Create;
try
{Put letters in list and count number of available}
for I:=1 to Length(Secret) do
begin
{Already in list?}
Inx:=SL.IndexOf(Secret[I]);
{Store it with a count of 1, if not in list, otherwise, increment count}
if Inx<0 then SL.AddObject(Secret[I],Pointer(1))
else SL.Objects[Inx]:=Pointer(Integer(SL.Objects[Inx])+1);
end;
{Set all words to gray}
for I:=0 to High(Result) do Result[I]:=wcGrey;
{Test for exact position match}
for I:=1 to Length(Test) do
if Test[I]=Secret[I] then
begin
{If we haven't used up the letter, mark it green}
if LetterAvailable(Test[I]) then Result[I-1]:=wcGreen;
end;
{Test for non-positional match and mark them yellow}
for I:=1 to Length(Test) do
begin
{Check of letter available and not already green}
if LetterAvailable(Test[I]) then
if Result[I-1]<>wcGreen then Result[I-1]:=wcYellow;
end;
finally SL.Free; end;
end;
 
 
procedure ShowOneWordle(Memo: TMemo; Pair: TStringPair);
{Test one wordle pair and display result}
var S: string;
var I: integer;
var WA: TWordleArray;
begin
{Get color pattern}
WA:=TestWordle(Pair.Secret,Pair.Test);
{Generate text for color pattern}
S:='';
for I:=0 to High(WA) do
case WA[I] of
wcGreen: S:=S+' Green';
wcYellow: S:=S+' Yellow';
wcGrey: S:=S+' Gray';
end;
{Display pair and corresponding color pattern}
Memo.Lines.Add(Pair.Secret+' v '+Pair.Test+': '+S);
end;
 
 
procedure ShowWordleColors(Memo: TMemo);
{Show all test pairs}
var I: integer;
begin
for I:=0 to High(Pairs) do
ShowOneWordle(Memo,Pairs[I]);
end;
 
 
 
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY: Yellow Yellow Green Gray Gray
BULLY v LOLLY: Gray Gray Green Green Green
ROBIN v ALERT: Gray Gray Gray Yellow Gray
ROBIN v SONIC: Gray Green Yellow Green Gray
ROBIN v ROBIN: Green Green Green Green Green
 
Elapsed Time: 4.854 ms.
 
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
: color! ( c i -- ) tuck pad + c! here + 0 swap c! ;
 
: wordle ( a1 u1 a2 u2 -- a3 u3 )
2swap here swap move pad over erase dup 0 do
over i + c@ here i + c@ = if 2 i color! then
loop dup 0 do
2dup here swap rot i + 1 search nip nip if 1 i color! then
loop nip pad swap ;
 
:noname
create s" grey" , , s" yellow" , , s" green" , ,
does> swap 2* cells + 2@ type ; execute color.
 
: .wordle ( a1 u1 a2 u2 -- )
2over type ." v " 2dup type ." => " wordle
over + swap do i c@ color. space loop cr ;
 
:noname
0 s" ROBIN" 2dup 2dup s" SONIC" 2over s" ALERT"
s" BULLY" s" LOLLY" s" ALLOW" 2over
begin ?dup while .wordle repeat ; execute
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY => yellow yellow green grey grey
BULLY v LOLLY => grey grey green green green
ROBIN v ALERT => grey grey grey yellow grey
ROBIN v SONIC => grey green yellow green grey
ROBIN v ROBIN => green green green green green
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Function wordle(Byval respuesta As String, Byval supuesto As String) As String
Line 155 ⟶ 534:
BBAABBB: Expected 5 character target.</pre>
 
=={{header|FutureBasic}}==
This compact function returns a byte array (as a pstring) with 2, 1, 0, for matched, mismatched, unmatched. It is useful for games up to 15 chars wide, and is case sensitive as specified.
<syntaxhighlight lang="futurebasic">
short x = 80, y = 20
 
clear local fn colorString( w1 as str15, w2 as str15 ) as str15
str255 n : str15 c : c[0] = w2[0] : short r
for r = 1 to w1[0]
if w2[r] = w1[r] then c[r] = 2 else n[w1[r]]++
next
for r = 1 to w2[0]
if c[r] == 0 then if n[w2[r]] then n[w2[r]]-- : c[r] = 1
next
end fn = c
</syntaxhighlight>
This function uses the array to display output mimicking the appearance of WORDLE.
<syntaxhighlight lang="futurebasic">
mda(0) = {fn ColorDarkGray,fn ColorWithRGB(.7,.6,.3,1),fn ColorWithRGB(.3,.6,.3,1)}
void local fn wordleCompare( wordle as str15, guess as str15 )
str15 color : short r
color = fn colorString( wordle, guess )
text @"menlo bold", 14, fn colorLightGray
print %( 20, y ) wordle : text ,,fn colorWhite
for r = 1 to guess[0]
rect fill ( x, y, 24, 24 ), mda_object( color[r] )
print %( x + 7.5, y + 1 ) chr$( guess[r] ); : x += 28
next
x = 80 : y += 28
end fn
 
window 1, @"FB Wordle Compare", ( 0, 0, 265, 290 )
WindowSetBackgroundColor( 1, fn Colorblack )
fn wordleCompare( "ALLOW", "LOLLY" )
fn wordleCompare( "CHANT", "LATTE" )
fn wordleCompare( "ROBIN", "SONIC" )
fn wordleCompare( "PROUD", "LEAST" )
fn wordleCompare( "STEAL", "LEAST" )
fn wordleCompare( "LEAST", "LEAST" )
fn wordleCompare( "FULLY", "LABEL" )
fn wordleCompare( "We're", "She's" )
fn wordleCompare("LONGER", "STRING")
 
handleevents
</syntaxhighlight>
{{out}}
[[File:Wordle Comparison in FutureBasic.png]]
 
=={{header|Go}}==
Line 349 ⟶ 774:
<syntaxhighlight lang="j"> ('allow' wrdcmp 'lolly')&{&.;: 'gray yellow green'
yellow yellow green gray gray</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public final class WordleComparison {
 
public static void main(String[] args) {
List<TwoWords> pairs = List.of( new TwoWords("ALLOW", "LOLLY"), new TwoWords("ROBIN", "SONIC"),
new TwoWords("CHANT", "LATTE"), new TwoWords("We're", "She's"), new TwoWords("NOMAD", "MAMMA") );
for ( TwoWords pair : pairs ) {
System.out.println(pair.answer + " v " + pair.guess + " -> " + wordle(pair.answer, pair.guess));
}
}
private static List<Colour> wordle(String answer, String guess) {
final int guessLength = guess.length();
if ( answer.length() != guessLength ) {
throw new AssertionError("The two words must be of the same length.");
}
String answerCopy = answer;
List<Colour> result = Stream.generate( () -> Colour.GREY ).limit(guessLength).collect(Collectors.toList());
for ( int i = 0; i < guessLength; i++ ) {
if ( answer.charAt(i) == guess.charAt(i) ) {
answerCopy = answerCopy.substring(0, i) + NULL + answerCopy.substring(i + 1);
result.set(i, Colour.GREEN);
}
}
for ( int i = 0; i < guessLength; i++ ) {
int index = answerCopy.indexOf(guess.charAt(i));
if ( index >= 0 ) {
answerCopy = answerCopy.substring(0, index) + NULL + answerCopy.substring(index + 1);
result.set(i, Colour.YELLOW);
}
}
return result;
}
private enum Colour { GREEN, GREY, YELLOW }
private static record TwoWords(String answer, String guess) {}
private static final char NULL = '\0';
 
}
</syntaxhighlight>
{{ out }}
<pre>
ALLOW v LOLLY -> [YELLOW, YELLOW, GREEN, GREY, GREY]
ROBIN v SONIC -> [GREY, GREEN, YELLOW, GREEN, GREY]
CHANT v LATTE -> [GREY, YELLOW, YELLOW, GREY, GREY]
We're v She's -> [GREY, GREY, YELLOW, YELLOW, GREY]
NOMAD v MAMMA -> [GREY, YELLOW, GREEN, GREY, GREY]
</pre>
 
=={{header|JavaScript}}==
Line 642 ⟶ 1,126:
ROBIN v SONIC => [0, 2, 1, 2, 0] => ["grey", "green", "yellow", "green", "grey"]
ROBIN v ROBIN => [2, 2, 2, 2, 2] => ["green", "green", "green", "green", "green"]
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="Kotlin">
fun main() {
val pairs = listOf(
TwoWords("ALLOW", "LOLLY"),
TwoWords("ROBIN", "SONIC"),
TwoWords("CHANT", "LATTE"),
TwoWords("We're", "She's"),
TwoWords("NOMAD", "MAMMA")
)
 
for (pair in pairs) {
println("${pair.answer} v ${pair.guess} -> ${wordle(pair.answer, pair.guess)}")
}
}
 
private fun wordle(answer: String, guess: String): List<Colour> {
val guessLength = guess.length
require(answer.length == guessLength) { "The two words must be of the same length." }
 
var answerCopy = answer
val result = MutableList(guessLength) { Colour.GREY }
for (i in guess.indices) {
if (answer[i] == guess[i]) {
answerCopy = answerCopy.substring(0, i) + NULL + answerCopy.substring(i + 1)
result[i] = Colour.GREEN
}
}
 
for (i in guess.indices) {
val index = answerCopy.indexOf(guess[i])
if (index >= 0) {
answerCopy = answerCopy.substring(0, index) + NULL + answerCopy.substring(index + 1)
if (result[i] != Colour.GREEN) {
result[i] = Colour.YELLOW
}
}
}
return result
}
 
private enum class Colour { GREEN, GREY, YELLOW }
 
private data class TwoWords(val answer: String, val guess: String)
 
private const val NULL = '\u0000'
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> [YELLOW, YELLOW, GREEN, GREY, GREY]
ROBIN v SONIC -> [GREY, GREEN, YELLOW, GREEN, GREY]
CHANT v LATTE -> [GREY, YELLOW, YELLOW, GREY, GREY]
We're v She's -> [GREY, GREY, YELLOW, YELLOW, GREY]
NOMAD v MAMMA -> [GREY, YELLOW, GREEN, GREY, GREY]
 
</pre>
 
=={{header|Nim}}==
{{trans|Wren}}
<syntaxhighlight lang="Nim">import std/[strformat, strutils]
 
type Color {.pure.} = enum Grey = "grey", Yellow = "yellow", Green = "green"
 
proc wordle(answer, guess: string): seq[Color] =
let n = guess.len
if answer.len != n:
quit "The words must be of the same length.", QuitFailure
var answer = answer
result.setLen(n)
for i in 0..<n:
if guess[i] == answer[i]:
answer[i] = '\0'
result[i] = Green
for i in 0..<n:
let ix = answer.find(guess[i])
if ix >= 0:
answer[ix] = '\0'
result[i] = Yellow
 
const Pairs = [["ALLOW", "LOLLY"],
["BULLY", "LOLLY"],
["ROBIN", "ALERT"],
["ROBIN", "SONIC"],
["ROBIN", "ROBIN"]]
 
for pair in Pairs:
let res = wordle(pair[0], pair[1])
echo &"""{pair[0]} v {pair[1]} → ({res.join(", ")})"""
</syntaxhighlight>
 
{{out}}
<pre>ALLOW v LOLLY → (yellow, yellow, green, grey, grey)
BULLY v LOLLY → (grey, grey, green, green, green)
ROBIN v ALERT → (grey, grey, grey, yellow, grey)
ROBIN v SONIC → (grey, green, yellow, green, grey)
ROBIN v ROBIN → (green, green, green, green, green)</pre>
 
=={{header|PARI/GP}}==
{{trans|Julia}}
<syntaxhighlight lang="PARI/GP">
colors = ["grey", "yellow", "green"];
 
wordle(answer, guess) =
{
n = #guess;
if (#answer != n, error("The words must be of the same length."));
answervector = Vecsmall(answer);
guessvector = Vecsmall(guess); \\ Convert guess to a vector of ASCII values
result = vector(n, i, 0);
for (i = 1, n,
if (guessvector[i] == answervector[i],
answervector[i] = 0;
result[i] = 2;
);
);
for (i = 1, n,
c = guessvector[i];
for (j = 1, n,
if (answervector[j] == c,
answervector[j] = 0;
result[i] = 1;
break;
);
);
);
result;
}
 
{
testpairs = [["ALLOW", "LOLLY"], ["BULLY", "LOLLY"], ["ROBIN", "ALERT"], ["ROBIN", "SONIC"], ["ROBIN", "ROBIN"]];
for (i = 1, #testpairs,
pair = testpairs[i];
res = wordle(pair[1], pair[2]);
res2 = vector(#res, j, colors[res[j] + 1]);
print(pair[1] " v " pair[2] " => " res " => " res2);
)
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY => [1, 1, 2, 0, 0] => ["yellow", "yellow", "green", "grey", "grey"]
BULLY v LOLLY => [0, 0, 2, 2, 2] => ["grey", "grey", "green", "green", "green"]
ROBIN v ALERT => [0, 0, 0, 1, 0] => ["grey", "grey", "grey", "yellow", "grey"]
ROBIN v SONIC => [0, 2, 1, 2, 0] => ["grey", "green", "yellow", "green", "grey"]
ROBIN v ROBIN => [2, 2, 2, 2, 2] => ["green", "green", "green", "green", "green"]
 
</pre>
 
Line 667 ⟶ 1,300:
ROBIN ROBIN => green green green green green
</pre>
 
Explanation (re-written to be more readable):
 
<syntaxhighlight lang="perl">
use strict;
use warnings;
 
sub show {
# print the given string, but convert certain non-printable characters to be visible:
# newline -> \n
# null \0 -> !
# control-A \1 -> ?
# control-B \2 -> _
local $_ = shift;
s/\n/\\n/g;
s/\0/!/g;
s/\01/?/g;
s/\02/_/g;
print "$_\n";
}
 
for my $test ( ["ALLOW", "LOLLY"],
["BULLY", "LOLLY"],
["ROBIN", "ALERT"],
["ROBIN", "SONIC"],
["ROBIN", "ROBIN"] )
{
print "-" x 80, "\n";
 
# @$test is two strings.
# my ($answer, $guess) = @$test
 
print "Start\n";
local $_ = join "\n", @$test;
show " '$_'";
 
show "Same letter, same position -> \0";
# For each letter in $answer that also appears in $guess, change the
# letter to a null character \0.
#
# [ -~] matches any letter (any printable character, not \0 or \n).
# Could also have used [A-Z]
#
# $` the substring before the matched letter
#
# tr!!.!cr
# !! the set of characters to transliterate (i.e., the empty set)
# c - complement the empty set (i.e., all characters)
# r - non-destructive: don't modify $` instead just return the resulting string
# !.! - change every character of $` to a dot '.'
# Could also have used "." x length($`)
#
# (??xxx) - use the result of the Perl expression xxx as a regex pattern,
# xxx will be some number of dots,
# one dot for every character before the matched letter.
# (A dot matches any character except newline \n.)
#
# \1 matches the same letter again.
# Results in something like s/(X)(.*\n...)X/\0$2\0/
#
# i.e., if letter X from $answer appears in the same position in $guess,
# then change X to a null character \0 in both $answer and $guess.
show " '$_'"
while s/([ -~])(.*\n(??{$` =~ tr!!.!cr}))\1/\0$2\0/;
 
show "Same letter, any position -> \1";
# [ -~] matches any remaining letter in $answer (again could have used [A-Z]).
#
# .*\n anything in $answer after the letter.
#
# .*?\1 anything in $guess up to (and including) that same letter.
# \1 matches whatever letter ([ -~]) matched.
# The ? causes us to select the left-most occurrence of the letter in
# $answer (in case there are multiple occurrences).
#
# Change that letter to control-A \01 in both $answer and $guess.
#
# i.e., if letter X from $answer appears anywhere in $guess, then change X
# to control-A in both $answer and $guess.
show " '$_'"
while s/([ -~])(.*\n.*?)\1/\01$2\01/;
 
print "Discard first word\n";
# s/.*\n//r
# r - non-destructive (return the result without modifying $_)
s/.*\n//;
show " '$_'";
 
show "Remaining letters -> \2";
# tr/\0\1/\2/cr
# /\0\1/ - the set of chars to transliterate: \0 null and \1 control-A
# c - complement the set of chars (i.e., any char that's not null or control-A)
# r - non-destructive
tr/\0\1/\2/c;
show " '$_'";
 
# In general: split //, "XYZ" - returns a list ("X", "Y", "Z").
# Here: split // - returns a string of chars all "\0" or "\1" or "\2".
my @chars = split //, $_;
show " @chars";
 
# Change "\0" to integer 0, "\1" to 1, "\2" to 2
my @indexes = map ord, @chars;
show " @indexes";
 
# Convert indexes 0-2 to color names.
my @colors = qw( green yellow grey );
print "@$test => @{ [ @colors[ @indexes ] ] }\n";
#print "@$test => @colors[ @indexes ]\n"; # same
}
</syntaxhighlight>
 
=={{header|Phix}}==
Line 1,032 ⟶ 1,776:
BBAABBB vs BBBBBAA green green yellow yellow green yellow yellow
BBAABBB vs AABBBAA yellow yellow yellow yellow green grey grey
</pre>
 
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="Scala">
object WordleComparison extends App {
 
case class TwoWords(answer: String, guess: String)
enum Colour extends Enum[Colour] {
case GREEN, GREY, YELLOW
}
 
val pairs = List(TwoWords("ALLOW", "LOLLY"), TwoWords("ROBIN", "SONIC"),
TwoWords("CHANT", "LATTE"), TwoWords("We're", "She's"), TwoWords("NOMAD", "MAMMA"))
 
pairs.foreach(pair => println(s"${pair.answer} v ${pair.guess} -> ${wordle(pair.answer, pair.guess)}"))
 
def wordle(answer: String, guess: String): List[Colour] = {
if (answer.length != guess.length) {
throw new AssertionError("The two words must be of the same length.")
}
 
var answerCopy = answer
var result = List.fill(guess.length)(Colour.GREY)
 
for (i <- guess.indices) {
if (answer(i) == guess(i)) {
answerCopy = answerCopy.updated(i, NULL)
result = result.updated(i, Colour.GREEN)
}
}
 
for (i <- guess.indices) {
val index = answerCopy.indexOf(guess(i))
if (index >= 0 && result(i) != Colour.GREEN) {
answerCopy = answerCopy.updated(index, NULL)
result = result.updated(i, Colour.YELLOW)
}
}
result
}
 
val NULL = '\u0000'
}
</syntaxhighlight>
{{out}}
<pre>
ALLOW v LOLLY -> List(YELLOW, YELLOW, GREEN, GREY, GREY)
ROBIN v SONIC -> List(GREY, GREEN, YELLOW, GREEN, GREY)
CHANT v LATTE -> List(GREY, YELLOW, YELLOW, GREY, GREY)
We're v She's -> List(GREY, GREY, YELLOW, YELLOW, GREY)
NOMAD v MAMMA -> List(GREY, YELLOW, GREEN, GREY, GREY)
 
</pre>
 
Line 1,105 ⟶ 1,902:
otherwise $!
\) -> \[i](
when <'.' ?($@wordle <[<=$>]>)> do (yellow:$)! $ -> !removeFirst
when <'.'> do (grey:$)!
otherwise $!
\) !
Line 1,126 ⟶ 1,923:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn wordle(answer string, guess string) []int {
n := guess.len
if n != answer.len {
Line 1,181 ⟶ 1,978:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var colors = ["grey", "yellow", "green"]
 
var wordle = Fn.new { |answer, guess|
9,486

edits