Écrivez une fonction mathématique dont le résultat est «bonjour le monde» [fermé]


9

Écrivez une fonction mathématique qui donne une représentation entière de "bonjour le monde"

Par exemple, "bonjour le monde" en hexadécimal est 68656c6c6f20776f726c64donc le but sera d'écrire un programme mathématique qui donne un nombre représentant "bonjour le monde".

Voici un exemple d'une solution possible utilisant python:

print(2*2*3*59*61*97*416510539*72330832279)==int("68656c6c6f20776f726c64", 16)

N'importe quel type d'équations mathématiques pourrait être utilisé, telles que: puissances, séries, factorielles et autres opérations mathématiques.

Les règles:

  • Vous pouvez sélectionner votre propre méthode pour encoder / représenter "hello world" sous forme d'entier. Les fonctions de hachage sont également autorisées

  • Les bibliothèques mathématiques (par exemple numpy, GMP) sont autorisées.

  • L'intention est de se concentrer sur la partie mathématique


1
La créativité n'est pas objective. Pensez-vous à un concours de popularité ?
Kendall Frey

4
Tout entier peut représenter "bonjour le monde" si vous êtes autorisé à décider de l'encodage. par exemple -1 = "hello worlc", 0 = "hello world", 1 = "hello worle", etc.
Kendall Frey

1
@kylek Puisque vous n'avez pas spécifié les critères de gain exacts au-delà de "le plus créatif / ingénieux", j'ai pris la liberté d'ajouter le concours de popularité comme critère de gain.
Victor Stafusa

2
(dans le contexte de ce site Web) toutes les données et tous les programmes informatiques peuvent être trivialement représentés sous forme de nombres - parce que c'est le modèle utilisé par les inventeurs (Babbage, et al). Permettre également tout encodage en fait vraiment un concours pour savoir qui peut écrire le programme le plus créatif qui donne un nombre. Il y a une implication que le code source doit utiliser des "opérations mathématiques", mais tout ce qu'un programme fait peut être modélisé comme une opération mathématique. Suggérez que vous ayez besoin d'un codage ASCII, puis lancez le concours pour le représenter comme un "numéro spécial" Voir: www2.stetson.edu/~efriedma/numbers.html
user2460798

1
Vous jouez extrêmement rapidement et librement avec votre terminologie mathématique. Vous utilisez "équation" et "fonction" apparemment de façon interchangeable. Je pense que le mot que vous cherchiez est "expression". Mais même alors, la question n'est pas bien posée. L'encodage mathématique pour "hello world" que je choisis pour le mien est le code source original de K&R hello world. Oh, hé, ça marche!
Tim Seguine

Réponses:


14

Python 2.7

Certains abus du générateur de nombres aléatoires, fonctionnent sur Python 2.7 mais pas sur Python 3.x car le générateur semble avoir changé l'algorithme d'ensemencement;

>>> import random
>>> n=[(15,30,15,25,15,0,-15,-25,-15,-30,-15),(107,35,34,26,22,0,71,188,94,64,81)]
>>> random.seed(4711)
>>> m = zip("MERRY CHRISTMAS",*n)
>>> print(''.join(map(lambda x:chr(ord(x[0])+random.randint(x[1],x[2])),m)))

hello world

Cela m'a fait rire à haute voix à mon bureau. Les gens me regardent en ce moment: - /
jmiserez

25

Je ferai mieux que de simplement l'imprimer, je l'imprimerai infiniment de fois!

Le nombre rationnel

1767707668033969 / 3656158440062975

renvoie l'expansion de base 36 suivante:

0.helloworldhelloworldhelloworldhelloworldhelloworld...

Essaye le! (Wolfram Alpha)

Ou, si vous voulez un message plus subliminal, essayez:

2399843759207982499621172523113947162810942763812298565948669
/ 1357602166130257152481187563160405662935023615

Ce qui revient (encore en base 36):

helloworld.helpimtrappedinanumberfactoryhelpimtrappedinanumberfactoryhelpimtrappedinanumberfactory...

Si votre programme ne fonctionnait qu'avec des entiers, vous ne verriez jamais la partie fractionnaire.


12

Python (pas fini ... encore!) Terminé! :RÉ

number = ((sum(b'This text will end up converting to the text "hello world" by a bunch of math.') *
sum(b'For example, multiplication will be used to increase the number so that it may reach the required result.') *
sum(b'Wow, double multiplication! The required result number is extremely big so I have to use lots of math to get there.') *
sum(b'TRIPLE multiplication?!?!?! Wow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Did I put too many exclamation points?') *
sum(b'I think maybe I might have put too many exclamation points, oops. :(') *
sum(b'This is taking a long time...') *
sum(b'A very, very, very long time...')) // 2)

number -= (sum(b'Okay, the number is a bit too high. Blah. This is extremely hard.') *
sum(b'I need to reduce it. I will just keep multiplying again! Yay! That seems effective!') *
sum(b'I don\'t know what to write now... I used up all my creativity in the previous number.') *
sum(b'So. Uhhh, how has your day been? Was it good? I wonder how many people are still reading.') *
sum(b'Gah! There is nothing to type about anymore! I will just type randomness then.') *
sum(b'Do you like pie? I like pie. Refrigerator. The chicken ate the potato. Llamas are not tasty.'))

number -= (sum(b'Blah, I am still a tiny bit too high!') *
sum(b'This is very frustrating!') * sum(b'Argh!!!!!!!') *
sum(b'I have even less creative ideas now since I have written two paragraphs already.') *
sum(b'Well, I suppose they\'re not paragraphs. They\'re just blocks of code.') *
sum(b'The only reason I made that remark was to increase this number to subtract, so that I reach my target.'))

number -= (sum(b'I am an extremely miniscule amount over the target!!!') *
sum(b'I am so close!!! So close!!') *
sum(b'I must make it!!! I will!!!') *
sum(b'I shall NEVER give up!!!') *
sum(b'Okay, ummm... maybe not exactly "never"...') *
sum(b'I mean, this is REALLY hard...'))

number -= (sum(b'I am so close. This is just ridiculous.') *
sum(b'Just ridiculous. And that\'s awesome :D') *
sum(b'Why am I doing this?!?') *
sum(b'The answer\'s probably "becase I can."') *
sum(b'Notice how most of the text in this program is meaningless.'))

number -= (sum(b'How have I been above my target this whole time? That is very odd.') *
sum(b'I wonder how much time I could have saved if I removed a few characters in the first block.') *
sum(b'I wish I did that. That would have made it so much easier.... But oh well.') *
sum(b'Well, I am really really really really really really close now!'))

number -= (sum(b'I am so close!') *
sum(b'I will never give up now! Not after all this!') *
sum(b'I wonder if I will ever get exactly on the target. What if I do, and then discover a typo? :O') *
sum(b'So close!'))

number -= (sum(b'Wow; this is the eighth block. That\'s a lot of blocks!') *
sum(b'I only have a little more to go! I must finish! I will!') *
sum(b'It is starting to get harder thinking of things to type than it is getting to the target...'))

number -= (sum(b'These strings are short') *
sum(b'So the number to subtract is less') *
sum(b'Hi'))

number += (sum(b'Finally adding') *
sum(b'That\'s new') *
sum(b':D'))

number -= (sum(b'I am back to subtraction, and also longer strings.') *
sum(b'But this time I only get two strings!'))

number -= (sum(b'I have switched over to adding the strings, not multiplying them!') +
sum(b'I am really really close! So close that I can\'t even multiply two strings to subtract anymore!') +
sum(b'This is very exciting; I\'ve nearly made it! Only a few more strings to add...') +
sum(b'I ran out of ideas for what to type again... I will just type exactly what I am thinking, which is what I am doing now actually.') +
sum(b'But now the only thing I am thinking about is getting to the target, and there is not much about that to type...') +
sum(b'I am only a few thousand away!!!!!!!!!!!!'))

number += 8 # NOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

print(number)

Sorties 126207244316550804821666916(équivalentes à votre exemple 0x68656c6c6f20776f726c64)


Vous comprenez bien ce que je demande.
kyle k

1
"Les lamas ne sont pas savoureux " haha ​​+1
assylias

2
Cela devrait gagner.
tomsmeding

8

Vous pouvez sélectionner votre propre méthode pour encoder / représenter "hello world" sous forme d'entier.

Eh bien...

PHP

<?=1?>

où 1 représente "bonjour le monde" parce que je l'ai dit.


14
10dans la base - "bonjour le monde"
Emil Vikström

7

Police de calculatrice / FreePascal

Je peux avoir des ennuis pour poster ça, mais je le ferai quand même :-)

  1. Calculez 7734/100000. Remplacez le premier zéro par le bleu et les autres chiffres par la police de la calculatrice. Tournez-le à l'envers. Le O bleu représente le monde:

entrez la description de l'image ici

Si c'est trop paresseux, pourquoi pas:

uses graph;
var gd, gm : integer;
var n,m:integer;

begin
  gd := D4bit;
  gm := m640x480;
  initgraph(gd,gm,'');
  setcolor(black);

  For n:=0 to 5  do for m:=0 to 3 do begin;
    setfillstyle(solidfill,(abs(n*2-1)));

    if(($967EEF shr (20-n*4+m)) and 1) = 1
      then sector(50+n*80,100,90*m,90*(m+1),40,60);

    if(($EDF7E9 shr (20-n*4+m)) and 1) = 1
      then sector(50+n*80,300,90*m,90*(m+1),40,60);
    end;

  readln;
  closegraph;
end.

entrez la description de l'image ici

cercles numérotés 0-5, couleur déterminée par abs (2n-1). Un chiffre hexadécimal par cercle, quadrants colorés du bit le plus significatif vers le bas, dans le sens des aiguilles d'une montre en bas à droite. Par les constantes mystiques 967EEF et EDF7E9 hex.

Un merci spécial à la primitive suivante et à Borland pour l'avoir mis dans TurboPascal afin que FreePascal puisse le cloner.

procédure Sector (x: SmallInt; y: SmallInt; StAngle: Word; EndAngle: Word; XRadius: Word; YRadius: Word); Le secteur dessine et remplit un secteur d'une ellipse avec le centre (X, Y) et les rayons XRadius et YRadius, commençant à l'angle Start et se terminant à l'angle Stop.


Je n'ai jamais pensé à cette méthode auparavant, bonne réflexion hors de la boîte!
kyle k

3

Rubis et Python

En utilisant les mathématiques de base 36, nous arrivons assez facilement à une représentation entière en Ruby et Python:


Rubis

%w(hello world).map{|n|n.to_i(36)}

résultat:

[29234652, 54903217]

ou, exprimé en fonction générale:

def f(words); words.split.map{|n|n.to_i(36)}; end

exemple:

f("hello world")
=> [29234652, 54903217]

Python

def f(words): return map(lambda n: int(n,36), words.split())

exemple:

>>> f("hello world")
[29234652, 54903217]

3

Certains PHP soigneusement conçus:

$x=18306744;
$w=($z=($y=30)/3)/2;
echo base_convert($x, $z, $y+$z/$w),chr($y+$z/$w).base_convert($x*($y/$z)-$w*41*83,$z,$y+$y/$w);

C'est une bonne réponse, c'est le genre de réponse que je cherchais.
kyle k

1

Schéma R6RS

#!r6rs
(import (rnrs))
(define (hello-world)
  (bitwise-xor (fold-left (lambda (acc d) 
                        (+ (* acc 256) 
                           (+ (bitwise-and 255 acc) d)))
                      104
                      '(-3 7 0 3 8 0 -8 3 -6 -8))
               (bitwise-arithmetic-shift 87 40)))

Sorties # x68656c6c6f20776f726c64 (en décemale):

126207244316550804821666916

Mon implémentation d'origine était:

Raquette (Schéma dialectal)

(define (hello-world)
  (bitwise-xor (foldl (lambda (d acc) 
                        (+ (* acc 256) 
                           (+ (bitwise-and 255 acc) d)))
                      104
                      '(-3 7 0 3 8 0 -8 3 -6 -8))
               (arithmetic-shift 87 40)))

1

Javascript

function stringTheory(theory) {
  var proof = 0;
  var principles = theory.split(/[ ,.'-]/);
  for (var i = 0; i < principles.length; i++) {
      var formula = '';
      for (var j = 0; j < principles[i].length; j++) {
        formula += principles[i].charCodeAt(j).toString(10);
      }
      proof += +formula;
  }
  return proof;
}

console.log(
/* \2 and \3 are start of text and end of text characters */ 
stringTheory('\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home.  And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3') + 42
);

Que se passe-t-il?

On prend cette chaîne et on l'applique un peu stringTheory()(c'est en fait une transmission du futur):

'\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home. And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3'

Nous l'avons d'abord divisé à sa ponctuation pour former des mots. Nous créons ensuite un ensemble de nombres en convertissant les caractères en leur code ASCII décimal. Les lettres jointes deviennent des nombres joints (par exemple aadevient 9797).

Les nombres sont ensuite additionnés. Ce que nous récupérons est 191212222216169un nombre totalement inutile, il n'a pas de sens, tout comme les quadrillions de roches qui flottent paresseusement dans l'espace. Qu'est-ce qui rend ce monde spécial? Pourquoi c'est la vie. Donc, en donnant à ce nombre le sens de la vie, +=42 nous obtenons 191212222216211;

Mais pourquoi?

Qu'est-ce que ça veut dire? Pourquoi cela signifie stringTheory("Hello world")bien sûr.


1

Python

from math import fsum
c=[104.,-4412.705557362921,12008.518259002305,-13041.051140948179,7566.060243625142,-2619.91695720304,567.427662301322,-77.52280096313,6.48776455347,-0.303552138602,0.006079144624]
def f(x):
    return fsum([c[i]*x**i for i in range(len(c))])
s=""
for i in range(11):
    s+=chr(int(round(f(i))))
print s

0

Rubis

Toute chaîne est mappée sur un entier.

# encode string to integer
def str_to_int(s)
  i = 0
  s.chars.each do |c|
    i = i << 7 | c.ord
  end
  i
end

La fonction inverse:

# decode integer to string
def int_to_str(i)
  s = ''
  while i > 0 do 
    s = (i & 0x7f).chr + s
    i = i >> 7
  end
  s
end

Exemples:

str_to_int("ABC")
=> 1073475
int_to_str(1073475)
=> "ABC"

str_to_int("hello world")
=> 123720932638399026476644
int_to_str(123720932638399026476644)
=> "hello world"

0

C #

Une méthode pour convertir n'importe quelle chaîne (bonjour le monde ou autre) en chaîne hexadécimale

string Encode(string text)
{
   string hexValue = String.Empty;
   foreach(char c in text)
      hexValue += String.Format("{0:X}", (int)c);
   return hexValue;
}

Une méthode pour convertir une chaîne hexadécimale en chaîne

string Decode(string hexValue)
{
   string text = String.Empty;
   for (int i = 0; i < hexValue.Length; i += 2)
   {
     int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
     text += (char)value;
   }
   return text;
}

Voici le programme C # complet

using System;

namespace ConsoleApplication1
{
    class Program
    {       

        static string Encode(string text)
        {
            string hexValue = String.Empty;
            foreach(char c in text)
                hexValue += String.Format("{0:X}", (int)c);
            return hexValue;
        }

        static string Decode(string hexValue)
        {
            string text = String.Empty;

            for (int i = 0; i < hexValue.Length; i += 2)
            {
                int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
                text += (char)value;
            }

            return text;
        }

        static void Main(string[] args)
        {  
            string Text1 = "Hello World!";
            Console.WriteLine("Before Encoding: " + Text1 + "\n");

            string Hex = Encode(Text1);
            Console.WriteLine("After endoding: " + Hex + "\n");

            string Text2 = Decode(Hex);
            Console.WriteLine("After decoding: " + Text2 + "\n");
        }
    }
}

Et voici la sortie.

entrez la description de l'image ici


0

Python

def D(A):
    try:
        return sum(D(x)**2 for x in A)
    except TypeError:
        return A
print hex(D([[[[33,22,3,1],[20,13,2],5],[[31,19,1],[11,5,3],1]],[[[26,13],[18,14,6,4],1],[[12,10],[10,3,1],2],4],28]))

Décompose récursivement le nombre cible en sommes de quatre carrés au maximum. Mon cas de base est <100. J'ai utilisé http://www.alpertron.com.ar/FSQUARES.HTM pour calculer les décompositions.

(Peut-être qu'un cas de base de <= 1 aurait été intéressant ...)


0

Python

def church(i):
    if i > 0:
        return 'f(' + church(i-1) + ')'
    else:
        return 'x'

def church_string(bs):
    import base64
    return church(int(base64.b16encode(bs), 16))

print(church_string(b'hello world'))

Le résultat est vraiment un chiffre, je le jure!


0

Juste un petit C amusant avec les chiffres, rien de spécial.

int main()
{
    int a , b, c;
    double i = 0, f = 0;

    for (; i < 1; i += .00000012785666)
        f += cos(i);
    c = f;
    a = f * 276.393089;
    b = a + f * 7.4358109;

    printf("%.4s%.4s%.4s\n", &a, &b, &c);
}

démo


En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.