Des lignes directrices
Scénario
John a un nombre important et il ne veut pas que les autres le voient.
Il a décidé de chiffrer le numéro en procédant comme suit:
Son numéro est toujours une séquence non décroissante (ie. "1123"
)
Il convertit chaque chiffre en mots anglais. (ie. "123" -> "ONETWOTHREE"
)
Et puis, réorganisez les lettres au hasard. (ie. "ONETWOTHREE" -> "ENOWTOHEETR"
)
John sentait que son numéro était en sécurité. En fait, un tel cryptage peut être facilement décrypté :(
Tâche
Étant donné la chaîne cryptée s, votre tâche consiste à la déchiffrer et à renvoyer le numéro d'origine.
Règles
- C'est le code de golf, donc la réponse la plus courte en octets gagne
- Vous pouvez supposer que la chaîne d'entrée est toujours valide
- La chaîne d'entrée ne contient que des lettres majuscules
- Les numéros d'origine sont toujours classés par ordre croissant
- Vous pouvez retourner le nombre au format chaîne ou entier
- Les lettres ne seront mélangées qu'entre un mot, pas entre la chaîne entière.
- Les chiffres ne seront de 1 à 9 inclus (
ONE
àNINE
)
Chaîne non brouillée possible
Voici une liste des chaînes juste après leur conversion en chaînes des nombres:
1 -> ONE
2 -> TWO
3 -> THREE
4 -> FOUR
5 -> FIVE
6 -> SIX
7 -> SEVEN
8 -> EIGHT
9 -> NINE
Exemples
"NEO" -> 1
"ENOWOT" -> 12
"EONOTWHTERE" -> 123
"SNVEEGHEITNEIN" -> 789
"ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN" -> 123456789
"NOEWOTTOWHEERT" -> 1223
la source
Réponses:
Jelly,
3837 bytesA monadic link taking a list of characters (the string) and returning an integer.
Try it online!
Uses a very different method to Pietu1998's Jelly answer,
yet has the same byte count(I really thought it mightit did end up as less)!Does not rely on the monotonicity of the original number (so an input of
HTREEWTONOE
would work for example).How?
Tout d’abord, notez que les mots eux-mêmes (et donc leurs anagrammes) peuvent tous être remplacés par des mots de longueur 4 en supprimant tous les Rs, G et S et en remplaçant les Os par deux caractères (par exemple, "12") et les X par trois ( dites "345").
Nous pouvons ensuite mapper le produit des ordinaux de ces caractères sur les nombres de 1 à 9 en utilisant une arithmétique modulo, selon notre choix (le "12345"), puis les rechercher dans une liste de chiffres réordonnée. Le code convertit en fait d’abord les caractères puis remplace les ordinaux, mais il est également possible de créer 37 octets avec des caractères, par exemple "DIAAE" ( essayez-le ).
la source
NINEONENIENOENNNIENOENNEINEONEINEONNENIENOINNEINENINNEINENIENNIENNNNIENNEININENIENNENINEINENINENNIEINNEINNENNIENIN
.Python 2,
121117115 bytes-4 bytes: After all that golfing I forgot to inline a single-use variable. Brain fart.
-2 bytes: Double-spaced indent → single tab indent (thanks to Coty Johnathan Saxman); note that this does not display correctly in the answer.
Ungolfed (compatible with python 3):
Magic number finder:
Explanation:
I had a feeling that I could smash the ASCII bits together and sum them up somehow to determine when I had a full word. Originally I tried messing with
3**ord(letter)
and comparing to expected results, but it resulted in some very large numbers. I though it would be appropriate to brute-force some parameters a little, namely modulus (to ensure the numbers are small) and a multiplier to disperse the numbers differently around the range of the modulus.I ended up changing the multiplier variable into a variable affecting the power itself because (from trial and error) that somehow managed to give me a slightly shorter golfed answer.
And above you see the results of that brute-forcing and a little manual golfing.
The reason for choosing
3**x
originally is because I knew you could represent every number there. The most repeated digits any number had is two (thrEE, sEvEn, NiNe, etc), so I decided to think of every input as a base-3 number. That way I could (mentally) represent them as something like10100000000010020000
(three; a 1 in thet
slot, a 1 in ther
slot, a 1 in theh
slot, and a 2 in thee
slot). Each number this way gets a unique representation which can be easily pieced together by iterating the string and summing some numbers, and it ends up independent of the actual order of the letters. Of course, this didn't turn out to be the ideal solution, but the current solution is still written with this idea in mind.la source
\x83
,\x8e
, and\x92
in the string.SyntaxError: Non-ASCII character '\xc2' in file <stdin> on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
. It works if I put thecoding
comment up there, but that gains 15 extra bytes.Python 2,
131127 bytesTry it online!
Based on a corrected version of the JavaScript Draco18s solution.
la source
vars
!PHP, 164 bytes
Try it online!
PHP, 179 bytes
based on the previous approach check first the even numbers and then the odd numbers in increasing order
Try it online!
PHP, 201 bytes
Try it online!
la source
ENOOWTWTOWOT
$i++<9
and$i
instead of$i<10
and++$i
(-1 byte);_405162738[$i]
instead of$i%2?$i/2+4:$i/2-1
(-4 bytes) ($i/2+~($i%2*-5)
would work too, but that´s one byte longer.)Javascript (ES6),
288150144 bytesLonger than
the other twoone of the other JS entries, but I thought I'd drop an interesting approach that might work for someone in another language.Essentially we can determine the following:
Any occurrence of these letters implies that that digit exists in the original number. From here we can deduce the rest of the digits:
Including the two complicated cases:
Both
1
and9
area Hard comparatively. For ONE,E
shows up more than once in some words (SEVEN
has two) as doesN
(NINE
), so we're stuck with checking forO
which occurs in two other places, fortunately both are simple.For NINE, nine is hard no matter how you slice it.
Thus we end up with this map:
9 is able to back-reference siX, eiGht, and Five (with 5 back-referencing foUr) with the variable assignments, saving bytes. Thanks to Neil for this, it uses several features of JS I am very unfamiliar with (the back-ticks for stripping
('
in half, for instance) and actually comes much closer to the idea I'd doodled out on paper before attempting to code it (I'd left 9 as "what's left over", thinking about it as "if I see anX
I can remove it and anS
andI
from the string, then..." so that after the four simple cases the next 3 would become simple).The reason this entry is interesting is because it can handle any shuffled string as input. i.e. rather than the individual words being shuffled, we can shuffle the whole string, which is what I thought John was doing originally:
la source
s.split(t).length-1
, 2 bytes usings.repeat(n>0&&n)
(why is n less than zero anyway? saves 7 bytes). Save a bunch of bytes by declaringg
in the scope ofs
so that you don't have to keep passing it all the time, and better still you can make it a tagged template, which saves 55 bytes in total (before 9 correction). Save more bytes by saving repeated values in temporaries, and I shaved a few more off usingmap
:s=>[,(l=t=>s.split(t).length-1)`O`-l`W`-l`U`,w=l`W`,l`R`-w,u=l`U`,l`F`-u,x=l`X`,l`S`-x,g=l`G`,l`I`-x-g].map((n,i)=>`${i}`.repeat(n)).join``
.Mathematica, 133 bytes
input
output
la source
c@#[[i]]
instead ofc[#[[i]]]
? You might be able to save another byte by using infix syntax~
on theTable
.C#, 218 bytes
Short Version:
Expanded version:
Try ONLINE!
Being my first entry, I'm uncertain about the rules... I'm only counting the size of the class used to de-crypt, not the code that tests it, right?
Edit
And for the fun of it - here's what I started doing, not reading the complete rules :S - See it at IdeOne. It de-crypts even when characters from one digit can be scrambled to any place in the string.
Edit 2
Shortened according to tips by TheLethalCoder. Thanks!
Edit 3
And now Titus shaved of a few more bytes. Thanks!
la source
public static
from it to. You can convert to an anonymous method likes=>{<do stuff>return"";}
. You can usevar
a few times, declaring variables together saves bytes i.e.int i=1,j;
. Creating an array from a string and splitting on it is usually shorter (though I haven't checked in this case) i.e."ONE|TWO".Split('|')
. You can use<0
instead of==-1
s=>{var n="ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE".Split('|');for(int i=0,j;++i<= 9;)for(j=0;n[i-1].IndexOf(s[j])<0;){if(++j==n[i-1].Length){var r=i+"";while(j<s.Length){j+=n[i].Length;r+=++i;}return r;}}return "";}
JavaScript (ES6),
142139 BytesSaved 3 Bytes thanks to Neil.
Doesn't currently take advantage of numbers are always arranged in ascending order
la source
"axbxc".split`x`.join``
. How is this called? Can't seem to find anything on google.split
andjoin
x=`foo${5+5}bar`
), they're tagged when you call a function using them without parens:foo`foo${5+5}bar`
which is the same asfoo(['foo','bar'], 10)
f(s.slice(y))
is always a string so you don't need the''+
before it.Jelly, 38 bytes
Try it online!
Explanation
la source
"EIGHTNINE"
into it :)3
with2.2
to use a smaller upper bound, which allows you to easily calculate 789 without changing the working principle.2
would be nice, but it would barely fail for certain inputs with lots of sixes.Javascript (ES6), 221 bytes
Example code snippet:
la source
Retina, 160 bytes
Try it online! Loosely based on @TessellatingHeckler's PowerShell answer.
la source
Retina, 88 bytes
Try it online!
Explanation
la source
PowerShell, 182 bytes
Try it online!
Ungolfed but not working code:
e.g.
(?<3>[THRE]{5})
matches the character classTHRE
, so it can match them out of order, and has to match any of these characters five times next to each other, and the capture group is named '3' to map names with numbers.Rudimentary compression by swapping the repeating text
})|(?<
for az
.la source
C++,
296, 288 bytesShort Version:
Full Version:
Try ONLINE!
Edit:
1) 200->296 bytes, for including namespace and definition of N in the count, as suggested by orlp 2) 296->288, for using macro, thanks to Zacharý
la source
N
andusing namespace std;
into your byte count.Q
right after it without any other additions.Ruby,
138114110 bytesByte count includes 1 byte for the
-p
option.What?
This:
is a regex literal which, through string interpolation, evaluates to:
If we assign that to
regex
, the rest of the code is somewhat easy to grasp: Each match in the input is substituted with the number of the capturing group, extracted from the magical variable$~
which contains the current match data:Try it online!
la source
Java 8,
198256 bytes+58 bytes.. due to regex of the previous version not working properly (it was also matching "EEE";"EEN";etc.)
Explanation:
Try it here.
la source
"ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN"
:([ONE]{3}
is that it also matchesEEN
at the end of that test case with parts of EIGHT and NINE.. And I doubt there is a regex to match all these:ENO|EON|NEO|NOE|OEN|ONE
without also matchingEEE;EEN;EEO;...
for all numbers that is shorter than 40 bytes.. Maybe I can do something usingsubstring
and reverse checking the numbers, but I don't really have the time to figure it out now..Java (OpenJDK 8), 181 bytes
Try it online!
I took the liberty to reuse Kevin Cruyssen's TIO template. Hope you don't mind ;)
la source
s.substring
. The worst part is, is that I am usings.substring
in my current answer, lol.. Ah well, +1 from me. Glad it's almost weekend..05AB1E,
3631 bytesTry it online!
View it ran with debug: TIO With Debug
la source
FURONESEV
returnsFUR1SEV
:(Perl 5, 102 + 1 (-n) = 103 bytes
Try it online!
la source
map{...}
can often be replaced withmap...,
,length
andy///c
are usually interchangeable too (not always smaller when not working on$_
though!), instead of thewhile
,++$,x s/^$i//
is shorter, and if you change-n
to-p
you can append to ` $\ ` instead of callingprint
! Try it online!Python 3,
238236 bytesTry it online!
Brute-force solution, doesn't take advantage non-decreasingness of digits.
Thanks to @Mr. Xcoder for saving 2 bytes!
la source
def f(s):
in your byte count, this is not an anonymouos functionwhile len(s)>0
withwhile len(s)
e
into the function header for -1 byte. Also,exec
and list comprehensions might save bytes on indentation.PHP, 141 bytes
older version, 151 bytes:
loops through the digits from 1 to 9, counting unique characters in the word and subtracting non-unique characters´ counts, printing the digit on the go.
Although it is printing on the go, the digit counts must be stored for the
9
case to work.Run as pipe with
-nR
or try it online.It would save 4 more bytes to store the digit counts in
$a[$i]
instead of$a[$i+48]
and use ASCII1
and7
(in quotes) instead of the digit characters themselves.breakdown
ONE
is not the only word with anO
, so it needs to subtract the counts forW
(only appearing inTWO
) andU
(only appearing inFOUR
) and so on.NINE
is special, because there is no way to just subtract if I used the letters (that would requireI-X-G-F+U
orN-O-S+W+U+X
), so I use the digit counts instead.PHP, 160 bytes
assumes all upper case input; characters may be scrambled all over.
Run as pipe with
-nR
or try it online.explanation
loops through the digit words, counting their unique characters´ occurences in the input and in the process reducing the count of other characters. "Other characters" could mean all other characters in the word; but only considering those that will be needed later saved 19 bytes.
Transforming the
str_repeat
loop to a combined loop saved 5 bytes.And using variable variables for the digit count saved another 8.
breakdown
la source