Anagrams/Deranged anagrams: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 22:
=={{header|11l}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=11l>F is_not_deranged(s1, s2)
L(i) 0 .< s1.len
I s1[i] == s2[i]
Line 44:
L(ana) anagram.values()
I ana.len > 1 & ana[0].len == count
print(ana)</langsyntaxhighlight>
{{out}}
<pre>[excitation, intoxicate]</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program anaderan64.s */
Line 518:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
<pre>
Program 64 bits start.
Line 525:
=={{header|Ada}}==
{{Works with|Ada 2005}}
<langsyntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Containers.Indefinite_Vectors;
Line 569:
Close (File);
Put_Line (Vect.Element (p1) & " " & Vect.Element (p2));
end Danagrams;</langsyntaxhighlight>
{{out}}
<pre>intoxicate excitation</pre>
Line 575:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} Uses the "read" PRAGMA of Algol 68 G to include the associative array code from the [[Associative_array/Iteration]] task.
<langsyntaxhighlight lang=algol68># find the largest deranged anagrams in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
Line 698:
)
)
FI</langsyntaxhighlight>
{{out}}
<pre>
Line 708:
This can now return all the co-longest deranged anagrams when there are more than one. However it turns out that unixdict.txt only contains one. :)
 
<langsyntaxhighlight lang=applescript>use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands!
-- Uses the customisable AppleScript-coded sort shown at <https://macscripter.net/viewtopic.php?pid=194430#p194430>.
-- It's assumed scripters will know how and where to install it as a library.
Line 797:
set wordFile to ((path to desktop as text) & "unixdict.txt") as «class furl»
set wordList to paragraphs of (read wordFile as «class utf8»)
return longestDerangedAnagrams(wordList)</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang=applescript>{{"excitation", "intoxicate"}}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<langsyntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* program anaderan.s */
Line 1,229:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
Program 32 bits start.
Line 1,236:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang=rebol>isDeranged?: function [p][
[a,b]: p
loop 0..dec size a 'i [
Line 1,269:
]
 
print maxDeranged</langsyntaxhighlight>
 
{{out}}
Line 1,276:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=Autohotkey>Time := A_TickCount
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetBatchLines -1
Line 1,331:
}
old1 := no_let1, old2 := A_Loopfield
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,339:
{{works with|GNU awk (gawk) 3.1.5}}
 
<langsyntaxhighlight lang=awk>#!/bin/gawk -f
BEGIN{
FS=""
Line 1,397:
if (length(found) > 0) exit
}
}</langsyntaxhighlight>
On my system, this awk-file is located at /usr/local/bin/deranged,
so it can be invoked with:
Line 1,405:
 
Regular invocation would be:
<langsyntaxhighlight lang=sh>gawk -f deranged.awk /tmp/unixdict.txt</langsyntaxhighlight>
{{out}}
<pre>
Line 1,412:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang=freebasic>DECLARE idx$ ASSOC STRING
 
FUNCTION Deranged(a$, b$)
Line 1,440:
PRINT "Maximum deranged anagrams: ", an1$, " and ", an2$
 
PRINT NL$, "Total time: ", TIMER, " msecs.", NL$</langsyntaxhighlight>
{{out}}
<pre>
Line 1,450:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang=bbcbasic> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Line 1,502:
$$^a&(0) = A$
CALL Sort%, a&(0)
= $$^a&(0)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,528:
Bracmat shuffles each new factor into place to keep the growing product normalized before continuing with the next word from the list.
The result is exactly the same, but the running time becomes much longer.
<langsyntaxhighlight lang=bracmat> get$("unixdict.txt",STR):?wordList
& 1:?product
& :?unsorted
Line 1,590:
* ?
| out$!derangedAnagrams
);</langsyntaxhighlight>
{{out}}
<pre>excitation.intoxicate</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang=C>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,704:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,716:
{{libheader|System.IO}}
{{works with|C sharp|6}}
<langsyntaxhighlight lang=csharp>public static void Main()
{
var lookupTable = File.ReadLines("unixdict.txt").ToLookup(line => AnagramKey(line));
Line 1,735:
&& Enumerable.Range(0, first.Length).All(i => first[i] != second[i])
select new [] { first, second })
.FirstOrDefault();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,742:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <algorithm>
#include <fstream>
#include <functional>
Line 1,791:
std::cout << result.first << ' ' << result.second << '\n';
return EXIT_SUCCESS;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,798:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=Clojure>(->> (slurp "unixdict.txt") ; words
(re-seq #"\w+") ; |
(group-by sort) ; anagrams
Line 1,806:
(sort-by #(count (first %)))
last
prn)</langsyntaxhighlight>
{{out}}
<pre>$ lein exec deranged.clj
Line 1,812:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang=cobol>
******************************************************************
* COBOL solution to Anagrams Deranged challange
Line 1,994:
*> BUBBLE SORT REFERENCE:
*> https://mainframegeek.wordpress.com/tag/bubble-sort-in-cobol
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
This example was tested with node.js.
<langsyntaxhighlight lang=coffeescript>http = require 'http'
 
is_derangement = (word1, word2) ->
Line 2,036:
req.end()
get_word_list show_longest_derangement</langsyntaxhighlight>
{{out}}
<pre>
Line 2,044:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(defun read-words (file)
(with-open-file (stream file)
(loop with w = "" while w collect (setf w (read-line stream nil)))))
Line 2,063:
(setf (gethash ws h) (cons w l))))))
 
(format t "~{~A~%~^~}" (longest-deranged "unixdict.txt"))</langsyntaxhighlight>
{{out}}
<pre>intoxicate
Line 2,070:
=={{header|D}}==
===Short Version===
<langsyntaxhighlight lang=d>void main() {
import std.stdio, std.file, std.algorithm, std.string, std.array;
 
Line 2,084:
.minPos!q{ a[0].length > b[0].length }[0]
.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>Tuple!(string, string)("intoxicate", "excitation")</pre>
Line 2,090:
 
Using const(ubytes)[] instead of dstrings gives a runtime of about 0.07 seconds:
<langsyntaxhighlight lang=d> string[][ubyte[]] anags;
foreach (const w; "unixdict.txt".readText.split)
anags[w.dup.representation.sort().release.assumeUnique] ~= w;</langsyntaxhighlight>
 
===Faster Version===
<langsyntaxhighlight lang=d>import std.stdio, std.file, std.algorithm, std.string, std.array,
std.functional, std.exception;
 
Line 2,124:
return writefln("Longest deranged: %-(%s %)", pairs.front);
}
}</langsyntaxhighlight>
{{out}}
<pre>Longest deranged: excitation intoxicate</pre>
Line 2,132:
{{libheader| System.Classes}}
{{libheader| System.Diagnostics}}
<langsyntaxhighlight lang=Delphi>program Anagrams_Deranged;
 
{$APPTYPE CONSOLE}
Line 2,236:
Dict.Free;
Readln;
end.</langsyntaxhighlight>
 
{{out}}
Line 2,249:
=={{header|EchoLisp}}==
For a change, we use the french dictionary included in EchoLisp package.
<langsyntaxhighlight lang=scheme>(lib 'hash)
(lib 'struct)
(lib 'sql)
Line 2,280:
(write lmin) (for-each write lw)
(writeln)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang=scheme>
(lib 'dico.fr.no-accent) ;; 209315 words into *words* table
(task)
Line 2,304:
14 charlatanistic antarchistical
15 megachiropteran cinematographer
17 misconstitutional constitutionalism</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang=Eiffel>class
ANAGRAMS_DERANGED
 
Line 2,430:
words: HASH_TABLE [LINKED_LIST [STRING], STRING]
 
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,439:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=elixir>defmodule Anagrams do
def deranged(fname) do
File.read!(fname)
Line 2,468:
{_, words} -> IO.puts "Longest derangement anagram: #{inspect words}"
_ -> IO.puts "derangement anagram: nothing"
end</langsyntaxhighlight>
 
{{out}}
Line 2,477:
=={{header|Erlang}}==
Using anagrams:fetch/2 from [[Anagrams]] and init_http/0 from [[Rosetta_Code/Find_unimplemented_tasks]]. Exporting words_from_url/1 to [[Ordered_words]].
<langsyntaxhighlight lang=Erlang>-module( anagrams_deranged ).
-export( [task/0, words_from_url/1] ).
 
Line 2,516:
lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ).
 
is_deranged_char( {One, Two} ) -> One =/= Two.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,524:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>open System;
 
let keyIsSortedWord = Seq.sort >> Seq.toArray >> String
Line 2,549:
|> snd
|> printfn "%A"
0</langsyntaxhighlight>
{{out}}
<pre>[("excitation", "intoxicate")]</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: assocs fry io.encodings.utf8 io.files kernel math
math.combinatorics sequences sorting strings ;
IN: rosettacode.deranged-anagrams
Line 2,577:
 
: longest-deranged-anagrams ( path -- anagrams )
deranged-anagrams [ first length ] sort-with last ;</langsyntaxhighlight>
 
"unixdict.txt" longest-deranged-anagrams .
Line 2,583:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>' FB 1.05.0 Win64
 
Type IndexedWord
Line 2,717:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,731:
=={{header|GAP}}==
Using function [[Anagrams#GAP|Anagrams]].
<langsyntaxhighlight lang=gap>IsDeranged := function(a, b)
local i, n;
for i in [1 .. Size(a)] do
Line 2,760:
n := Maximum(List(a, x -> Size(x[1])));
Filtered(a, x -> Size(x[1]) = n);
# [ [ "excitation", "intoxicate" ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
import (
"fmt"
Line 2,814:
 
fmt.Println(w1, w2, ": Length", best_len)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,822:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang=groovy>def map = new TreeMap<Integer,Map<String,List<String>>>()
 
new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').eachLine { word ->
Line 2,850:
} else {
println 'Deranged anagrams are a MYTH!'
}</langsyntaxhighlight>
 
{{out}}
Line 2,857:
=={{header|Haskell}}==
If the longest deranged anagram includes three or more words we'll only print two of them. We also correctly handle duplicate words in the input.
<langsyntaxhighlight lang=haskell>{-# LANGUAGE TupleSections #-}
 
import Data.List (maximumBy, sort, unfoldr)
Line 2,900:
case maxDerangedAnagram $ words input of
Nothing -> putStrLn "No deranged anagrams were found."
Just (a, b) -> putStrLn $ "Longest deranged anagrams: " <> a <> " and " <> b</langsyntaxhighlight>
{{out}}
<pre>Longest deranged anagrams: excitation and intoxicate</pre>
Line 2,906:
=={{header|Icon}} and {{header|Unicon}}==
This solution (which works in both languages) does a strict interpretation of the problem and ignores the fact that there may be multiple derangements that are the same length (including ignoring multiple derangements arising from the same set of words that are all anagrams).
<langsyntaxhighlight lang=unicon>link strings # for csort() procedure
 
procedure main()
Line 2,931:
every i := 1 to *s1 do if s1[i] == s2[i] then fail
return [s1,s2]
end</langsyntaxhighlight>
{{out|Sample run}}
<pre>->dra <unixdict.txt
Line 2,939:
=={{header|J}}==
This assumes that [http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt] has been saved in the current directory.
<langsyntaxhighlight lang=j> #words=: 'b' freads 'unixdict.txt'
25104
#anagrams=: (#~ 1 < #@>) (</.~ /:~&>) words
Line 2,952:
││excitation│intoxicate││
│└──────────┴──────────┘│
└───────────────────────┘</langsyntaxhighlight>
Note that anagram sets with more than two members might, hypothetically, have made things more complicated. By lucky coincidence, this was not an issue. We could have taken advantage of that coincidence to achieve slight further simplifications. Perhaps <code>maybederanged=: (#~ (-: ~."1)@|:@:>&>) anagrams</code>
 
Line 2,959:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang=java>import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
Line 3,005:
return true;
}
}</langsyntaxhighlight>
{{out}}
<pre>excitation intoxicate</pre>
Line 3,017:
brevity.
 
<langsyntaxhighlight lang=JavaScript>#!/usr/bin/env js
 
function main() {
Line 3,091:
}
 
main();</langsyntaxhighlight>
 
{{out}}
Line 3,098:
=== Gecko ===
Word file is saved locally because browser won't fetch it cross-site. Tested on Gecko.
<langsyntaxhighlight lang=javascript><html><head><title>Intoxication</title></head>
<body><pre id='x'></pre>
<script type="application/javascript">
Line 3,142:
 
show(best_pair);
</script></body></html></langsyntaxhighlight>
 
{{Out|Output (in a browser window)}}
Line 3,152:
This solution allows for the possibility of more than one answer.
 
<langsyntaxhighlight lang=jq># Input: an array of strings
# Output: a stream of arrays
def anagrams:
Line 3,183:
else .
end) ) )
| unique</langsyntaxhighlight>
 
'''Invocation and output'''
Line 3,191:
=={{header|Julia}}==
 
<langsyntaxhighlight lang=julia>using Base.isless
# Let's define the less than operator for any two vectors that have the same type:
# This does lexicographic comparison, we use it on vectors of chars in this task.
Line 3,233:
break
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,239:
 
=={{header|K}}==
<langsyntaxhighlight lang=K> / anagram clusters
a:{x g@&1<#:'g:={x@<x}'x}@0:"unixdict.txt";
Line 3,245:
b@&c=|/c:{#x[0]}'b:a@&{0=+//{x=y}':x}'a
("excitation"
"intoxicate")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.0.6
 
import java.io.BufferedReader
Line 3,286:
.filter { it.size > 1 && it[0].length == count }
.forEach { println(it) }
}</langsyntaxhighlight>
 
{{out}}
Line 3,294:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=Lasso>local(
anagrams = map,
words = include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt') -> split('\n'),
Line 3,346:
}
 
#findings -> join('<br />\n')</langsyntaxhighlight>
 
Result -> excitation, intoxicate
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang=lb>print "Loading dictionary file."
open "unixdict.txt" for input as #1
a$=input$(#1,lof(#1))
Line 3,402:
 
print theWord$(maxPtrI);" => ";theWord$(maxPtrJ)
end</langsyntaxhighlight>
{{out}}
excitation => intoxicate
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>string.tacnoc = function(str) -- 'inverse' of table.concat
local arr={}
for ch in str:gmatch(".") do arr[#arr+1]=ch end
Line 3,442:
end
end
print(answer.word, answer.anag, answer.len)</langsyntaxhighlight>
{{out}}
<pre>excitation intoxicate 10</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight lang=Maple>with(StringTools):
dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]):
L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]:
len:=length(ListTools:-FindMaximalElement(L,(a,b)->length(a)<length(b))):
select(w->length(w)=len,L)[];</langsyntaxhighlight>
{{out}}
<pre>
Line 3,458:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>words=First/@Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Table"];
anagramDegrangement=Function[{w1,w2},
Module[{c1=ToCharacterCode@w1,c2=ToCharacterCode@w2},
Sort@c1==Sort@c2&&Select[c1-c2,#==0&,1]==={}]];
gs=Select[GatherBy[words,{StringLength@#,Union@ToCharacterCode@#}&],Length@#>=2&];
First@Flatten[Function[ws,Select[Join@@Outer[List,ws,ws,1],anagramDegrangement@@#&]]/@SortBy[gs,-StringLength@First@#&],1]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,470:
 
A similar approach using Mathematica 10:
<langsyntaxhighlight lang=Mathematica>list = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Lines"];
MaximalBy[
Select[GatherBy[list, Sort@*Characters],
Length@# > 1 && And @@ MapThread[UnsameQ, Characters /@ #] &],
StringLength@*First]</langsyntaxhighlight>
 
{{out}}
Line 3,482:
 
=={{header|Nim}}==
<langsyntaxhighlight lang=Nim>import algorithm
import tables
import times
Line 3,522:
 
echo "Longest deranged anagram pair: ", best1, " ", best2
echo "Processing time: ", (getTime() - t0).inMilliseconds, " ms."</langsyntaxhighlight>
 
{{out}}
Line 3,529:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>let sort_chars s =
let r = String.copy s in
for i = 0 to (String.length r) - 2 do
Line 3,593:
) ([], 0) lst
in
List.iter (fun (w1, w2) -> Printf.printf "%s, %s\n" w1 w2) res</langsyntaxhighlight>
{{out}}
<pre>$ ocaml deranged_anagram.ml
Line 3,599:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang=ooRexx>-- This assumes you've already downloaded the following file and placed it
-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt
 
Line 3,661:
loop pair over pairs
say pair[1] pair[2]
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,669:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang=parigp>dict=readstr("unixdict.txt");
len=apply(s->#s, dict);
getLen(L)=my(v=List()); for(i=1,#dict, if(len[i]==L, listput(v, dict[i]))); Vec(v);
Line 3,677:
getDeranged(v)=my(u=List(),w); for(i=1,#v-1, for(j=i+1,#v, if(deranged(v[i], v[j]), listput(u, [v[i], v[j]])))); Vec(u);
f(n)=my(t=getAnagrams(getLen(n))); if(#t, concat(apply(getDeranged, t)), []);
forstep(n=vecmax(len),1,-1, t=f(n); if(#t, return(t)))</langsyntaxhighlight>
{{out}}
<pre>%1 = [["excitation", "intoxicate"]]</pre>
Line 3,684:
Using extra Stringlist for sorted by character words and insertion sort.<BR>
Runtime 153 ms -> 35 ms (Free Pascal Compiler version 3.3.1-r20:47268 [2020/11/02] for x86_64)
<langsyntaxhighlight lang=pascal>program Anagrams_Deranged;
{$IFDEF FPC}
{$MODE Delphi}
Line 3,800:
Dict.Free;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,810:
 
=={{header|Perl}}==
<langsyntaxhighlight lang=Perl>sub deranged { # only anagrams ever get here
my @a = split('', shift); # split word into letters
my @b = split('', shift);
Line 3,846:
# if we find a pair, they are the longested due to the sort before
last if find_deranged(@{ $letter_list{$_} });
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,852:
</pre>
===Alternate===
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Line 3,865:
($_ ^ $word) =~ /\0/ or exit !print "$_ $word\n" for @{ $anagrams{$key} };
push @{ $anagrams{$key} }, $word;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,872:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>-->
<span style="color: #008080;">function</span> <span style="color: #000000;">deranged</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">word1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">word2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word2</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">0</span>
Line 3,918:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,926:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
by Galileo, 06/2022 #/
 
Line 3,973:
 
candidate print
</syntaxhighlight>
</lang>
{{out}}
<pre>["excitation", "intoxicate"]
Line 3,979:
 
=={{header|PHP}}==
<langsyntaxhighlight lang=PHP><?php
$words = file(
'http://www.puzzlers.org/pub/wordlists/unixdict.txt',
Line 4,029:
echo implode(" ", $final_word), "\n";
}
?></langsyntaxhighlight>
{{out}}
<pre>
Line 4,036:
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat>go =>
M = [W:W in read_file_lines("unixdict.txt")].group(sort),
Deranged = [Value : _Key=Value in M, Value.length > 1, allderanged(Value)],
Line 4,066:
V = apply(F,E),
P.put(V, P.get(V,[]) ++ [E])
end.</langsyntaxhighlight>
 
{{out}}
Line 4,072:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(let Words NIL
(in "unixdict.txt"
(while (line)
Line 4,090:
(cons (pack @) (pack Lst)) ) )
(val Key) ) )
(idx 'Words) ) ) )</langsyntaxhighlight>
{{out}}
<pre>-> ("excitation" . "intoxicate")</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang=PowerShell>function Test-Deranged ([string[]]$Strings)
{
$array1 = $Strings[0].ToCharArray()
Line 4,127:
Length = $deranged[0].Length
Words = $deranged
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 4,137:
=={{header|Prolog}}==
{{Works with|SWI Prolog}}
<langsyntaxhighlight lang=Prolog>longest_deranged_anagram :-
http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt',In,[]),
read_file(In, [], Out),
Line 4,194:
msort(W, W1),
atom_codes(A, W1),
read_file(In, [A-W | L], L1)).</langsyntaxhighlight>
{{out}}
<pre> ?- longest_deranged_anagram.
Line 4,202:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>Structure anagram
word.s
letters.s
Line 4,336:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Largest 'Deranged' anagrams found are of length 10:
Line 4,344:
 
=={{header|Python}}==
<langsyntaxhighlight lang=python>import urllib.request
from collections import defaultdict
from itertools import combinations
Line 4,382:
print("Longest anagrams with no characters in the same position:")
print(' ' + '\n '.join(', '.join(pairs)
for pairs in largest_deranged_ana(anagrams)))</langsyntaxhighlight>
{{out}}
<pre>Word count: 25104
Line 4,394:
 
Append the following to the previous code:
<langsyntaxhighlight lang=python>def most_deranged_ana(anagrams):
ordered_anagrams = sorted(anagrams.items(),
key=lambda x:(-len(x[0]), x[0]))
Line 4,411:
for pairs in most:
print()
print(' ' + '\n '.join(', '.join(p) for p in pairs))</langsyntaxhighlight>
 
{{out}}
Line 4,443:
 
===Python: Faster Version===
<langsyntaxhighlight lang=python>from collections import defaultdict
from itertools import combinations
from pathlib import Path
Line 4,529:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{out}}
<pre>The longest anagram is: excitation, intoxicate</pre>
Line 4,535:
=={{header|Quackery}}==
 
<langsyntaxhighlight lang=Quackery> [ over size over size != iff
[ 2drop false ] done
over sort over sort != iff
Line 4,557:
temp take
sortwith [ 0 peek size swap 0 peek size > ]
0 peek witheach [ echo$ sp ]</langsyntaxhighlight>
 
{{out}}
Line 4,564:
 
=={{header|R}}==
<langsyntaxhighlight lang=R>puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
 
longest.deranged.anagram <- function(dict=puzzlers.dict) {
Line 4,588:
}
}
}</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang=R>> longest.deranged.anagram()
a b
3 excitation intoxicate</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>#lang racket
(define word-list-file "data/unixdict.txt")
 
Line 4,638:
(daps (in-value (deranged-anagram-pairs anagrams)))
#:unless (null? daps))
daps)</langsyntaxhighlight>
{{out}}
<pre>'(("intoxicate" "excitation"))</pre>
Line 4,647:
{{works with|Rakudo|2016.08}}
 
<langsyntaxhighlight lang=perl6>my @anagrams = 'unixdict.txt'.IO.words
.map(*.comb.cache) # explode words into lists of characters
.classify(*.sort.join).values # group words with the same characters
Line 4,661:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,667:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>/*REXX program finds the largest deranged word (within an identified dictionary). */
iFID= 'unixdict.txt'; words=0 /*input file ID; number of words so far*/
wL.=0 /*number of words of length L. so far*/
Line 4,708:
do while h>1; h=h % 2; do i=1 for ho-h; j= i; k= h+i
do while !.k<!.j; t=!.j; !.j=!.k; !.k=t; if h>=j then leave; j=j-h; k=k-h
end /*while !.k···*/; end /*i*/; end /*while h>1*/; return</langsyntaxhighlight>
{{out|output|text= &nbsp; when using the default dictionary:}}
<pre>
Line 4,716:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring># Project : Anagrams/Deranged anagrams
 
load "stdlib.ring"
Line 4,794:
astring = substr(astring,substr(astring,bstring)+len(string(sum)))
end
return cnt</langsyntaxhighlight>
{{out}}
<pre>
Line 4,801:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang=ruby>def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}
end
Line 4,822:
break
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 4,829:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
dim theWord$(30000)
dim ssWord$(30000)
Line 4,875:
 
print maxLen;" ";theWord$(maxPtrI);" => ";theWord$(maxPtrJ)
end</langsyntaxhighlight>
{{out}}
<pre>10 excitation => intoxicate</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang=rust>//! Deranged anagrams
use std::cmp::Ordering;
use std::collections::HashMap;
Line 4,954:
Err(e) => panic!("Could not read words: {}",e)
}
}</langsyntaxhighlight>
{{out}}
<pre>excitation intoxicate</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>object DerangedAnagrams {
 
/** Returns a map of anagrams keyed by the sorted characters */
Line 4,992:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>Longest deranged pair: excitation and intoxicate</pre>
Line 4,998:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang=scheme>(import (scheme base)
(scheme char)
(scheme cxr)
Line 5,046:
(cdr rem))))))))
 
(display (find-deranged-words (read-ordered-words))) (newline)</langsyntaxhighlight>
 
{{out}}
Line 5,054:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>func find_deranged(Array a) {
for i in (^a) {
for j in (i+1 .. a.end) {
Line 5,088:
}
 
main(%f'/tmp/unixdict.txt')</langsyntaxhighlight>
{{out}}
<pre>length 10: excitation => intoxicate</pre>
 
=={{header|Simula}}==
<langsyntaxhighlight lang=simula>! cim --memory-pool-size=512 deranged-anagrams.sim;
BEGIN
 
Line 5,224:
OUTTEXT(VECT.ELEMENT(P1) & " " & VECT.ELEMENT(P2));
OUTIMAGE;
END</langsyntaxhighlight>
{{out}}
<pre>intoxicate excitation
Line 5,232:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang=tcl>package require Tcl 8.5
package require http
 
Line 5,284:
puts "considered candidate pairing: $pair"
}
puts "MAXIMAL DERANGED ANAGRAM: LENGTH $max\n\t[lindex $candidates end]"</langsyntaxhighlight>
{{out}}
<pre>
Line 5,303:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang=tuscript>$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
 
Line 5,347:
ENDLOOP
ENDLOOP
ENDCOMPILE</langsyntaxhighlight>
{{out}}
<pre>
Line 5,356:
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<langsyntaxhighlight lang=bash>function get_words {
typeset host=www.puzzlers.org
typeset page=/pub/wordlists/unixdict.txt
Line 5,402:
fi
done <word.list
echo $max - ${max_deranged[@]} </langsyntaxhighlight>
{{out}}
<pre>10 - excitation intoxicate</pre>
Line 5,408:
=={{header|Ursala}}==
This solution assumes the file <code>unixdict.txt</code> is passed to the compiler as a command line parameter.
<langsyntaxhighlight lang=Ursala>#import std
 
anagrams = |=tK33lrDSL2SL ~=&& ==+ ~~ -<&
Line 5,416:
#cast %sW
 
main = leql$^&l deranged anagrams unixdict_dot_txt</langsyntaxhighlight>
The <code>anagrams</code> function is a little slow as defined above, but can be sped up by at least two orders of magnitude by grouping the words into classes of equal length, and sorting each word once in advance instead of each time a comparison is made as shown below.
<langsyntaxhighlight lang=Ursala>anagrams = @NSiXSlK2rSS *= ^(-<&,~&)*; |=rSStFtK33lrDSL2SL ~=@br&& ==@bl</langsyntaxhighlight>
We can speed it up by about another factor of 5 by starting from the group of longest words and stopping as soon as a deranged anagram is found instead of generating all anagrams.
<langsyntaxhighlight lang=Ursala>#import std
 
longest_deranged_anagram =
Line 5,430:
#cast %sW
 
main = longest_deranged_anagram unixdict_dot_txt</langsyntaxhighlight>
{{out}}
<pre>
Line 5,437:
 
=={{header|VBA}}==
<langsyntaxhighlight lang=vb>Sub Main_DerangedAnagrams()
Dim ListeWords() As String, Book As String, i As Long, j As Long, tempLen As Integer, MaxLen As Integer, tempStr As String, IsDeranged As Boolean, count As Integer, bAnag As Boolean
Dim t As Single
Line 5,486:
DerangedAnagram = True
Lenght = Len(str1)
End Function</langsyntaxhighlight>
 
{{out}}
Line 5,496:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang=vlang>import os
 
fn deranged(a string, b string) bool {
Line 5,538:
println('$w1 $w2: Length $best_len')
}</langsyntaxhighlight>
 
{{out}}
Line 5,547:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight lang=ecmascript>import "io" for File
import "/sort" for Sort
 
Line 5,587:
for (words in deranged) {
if (words[0].count == most) System.print([words[0], words[1]])
}</langsyntaxhighlight>
 
{{out}}
Line 5,595:
 
=={{header|zkl}}==
<langsyntaxhighlight lang=zkl>words:=Dictionary(25000); //-->Dictionary(sorted word:all anagrams, ...)
File("unixdict.txt").read().pump(Void,'wrap(w){
w=w.strip(); key:=w.sort(); words[key]=words.find(key,T).append(w);
Line 5,616:
nws.filter(fcn(nws,max){ nws[0]==max },
nws.reduce(fcn(p,nws){ p.max(nws[0]) },0) )
.println();</langsyntaxhighlight>
{{out}}
<pre>
Line 5,622:
</pre>
Replace the center section with the following for smaller code (3 lines shorter!) that is twice as slow:
<langsyntaxhighlight lang=zkl>nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...)
if(ws.len()>1){ // two or more anagrams
n:=ws[0].len(); // length of these anagrams
Line 5,631:
}
Void.Skip
});</langsyntaxhighlight>
10,327

edits