Tuesday, December 1, 2015

JavaScript: editing the built-ins

Whilst working on my newest project Jolf, I found the need to “edit” the built-ins of JavaScript. What does that mean? I wanted to edit the alert function so that it would also apply JSON.stringify on the input. How can I do this? Abusing JavaScript closures, of course!

JavaScript is interesting in that it really doesn't care. For the record. JavaScript doesn't care what you do with it. It grumbles only when it cannot possibly complete the action. Other than arguing with you when you use undefined variables (or make a mistake with variables at all) and when you completely garble the text you type, JavaScript rolls with it. That is why the aim of the post is even feasible.

Now, let's do a simple example. Let's fix the abomination of the isNaN function. One would expect that this function would return true if and only the input is NaN; however, this function tries first to evaluate the input as a number, then detecting if the result is NaN. So, isNaN(30) => false, but isNaN("Now in 3d!") => true. We want it so that isNaN(x) iff x is NaN. How? Observe that typeof NaN === "number". So, we check for a number type first, then call the old isNaN function, like so:

(function(oldNaNTest){
  return isNaN = function(inputNum){
    if(typeof inputNum!=="number") return false;  // NaN is a number
    else return oldNaNTest(inputNum);
  }
})(isNaN);

This creates an anonymous function with isNaN as an argument. And, as an argument, oldNaNTest is it's own, “separate” function (i.e. being distinct from `isNaN` and not merely a reference), so it retains `isNaN`s value. We do a type-check on the input, and proceed with returning the correct results.

But why an anonymous function? Well, consider what might happen if it wasn't. We would use something like this:

isNaN = function(inputNum){
  if(typeof inputNum!=="number") return false;
  else return isNaN(inputNum);
}

All would be well with non-numbers, as they return false; however, when given a number, we look to the else statement for our instruction. And what are we pointed to? Yep, isNaN. Is this wrong? Oh good heavens, yes it is! JavaScript looks at this statement and thinks, now, I need to look at the scope for a function named isNaN. Does that exist…yes! I found one! Here, take it! JavaScript hands you the function you just made. Why? Because you overwrote the old one, silly. We could create a reference, say, oldNaNTest, in the global scope, then proceed as normal. Two problems with that: one, you have an extra variable in the global scope. That's dirty! Secondly, if you try to get rid of that variable, you encounter an error, because 'ol JavaScript cannot find the function reference. :( It works, but it is neither elegant nor efficient.

Let's edit the eval command so that it it only evaluates the argument if it is a valid number. We can even use our new, correct isNaN function! We'll assume that is appended in the code snippet below.

(function(oldEval){
  return eval = function(arg){
    // test if valid number
    var testArg = Number(arg);  // will be NaN if invalid
    return isNaN(testArg)?arg:oldEval(arg);
  }
})(eval);

Simplex enough, eh?

Tuesday, November 10, 2015

The Cosmic Number

The Cosmic Problem (JSFiddle)

 ^ Well... what else do you want? Haha, just kidding. Of course I'm going to tell 'ya about it.

Pick a number. Any integer! Because four is the cosmic number.

“Um... 7?”

Seven is five, five is four, four is the cosmic number!

“... 27.”

Twenty-seven is twelve, twelve is six, six is three, three is five, five is four, four is the cosmic number!

What is the trick? (scroll down)


















Give up? Okay, you're going to hit yourself once I tell you: count the lengths of the number. Not the number itself, just the English.

I can just hear you. Don't feel too bad: it's a hard trick; I'm making you think of math when you need to be thinking of words. Now you've learned a neat party trick, but what gives? Of course, I did link to you a working example (that works with any integer between ±undecillion, I think), but that's not what's interesting.

Here's my thought process. First, I wonder if all numbers tend to four. Obviously, four tends to four, it being the only number whose value numbers its letters; thus, it is a natural tendency. Is it, however, a hard-and-fast rule?

I conjecture that this is indeed a rule. Now, a proof is needed. So let us begin!

First, let us describe the process.
  1. Start with a number, call it N0.
  2. Create a marker, call it k. Set k initially to 0.
  3. Let E(x) be the English representation of a number x; for example, E(20) is twenty, E(25) is twenty-five (notice the hyphen), and E(123) is one hundred twenty-three (notice the lack of the improper “and” and punctuation other than the dash).
  4. Let length(S) be the number of characters in string S. For example, length("Hello!") is 6, and length("O'Brien") is 7.
  5. Set Nk+1 = length(E(Nk))
  6. Does Nk+1 = 4?
    1. If so, terminate the process, returning k.
    2. Otherwise, increment k and go to step 5.

Conjecture: All integers, when the above process is repeatedly applied, tend to four, i.e., have “fourness”; equivalently, there is no integer for which the above process does not halt.

My idea at first was to find the name of the longest number within the context (call it M), calculate length(E(M)), and prove that every number from 1 to M tends to four. However, this is [a] a laborious task (also consider that length(E(10M±1)) > length(E(M) ) and [b] is unsatisfactory for all numbers. But what then shall be the argument form?

As it stands, this problem seems to be in, or at the very least related to, a currently unsolvable class of problems. A famous example would be the Collatz Conjecture. As Paul Erdős said,

Mathematics may not be ready for such problems.

So perhaps the proof is unattainable; the Cosmic Problem, like the Collatz Conjecture, involves in a case function's n-ness (i.e. that functions values tending towards n unconditionally). They both have common “seed” strings that are found (e.g. three to five to four). I, however, like to think that, since the Cosmic Problem is different in that it requires a non-mathematical conversion, that a proof can indeed be placed.

As of now, I have not found such a proof. But I'm still looking... ;)

Cheers!

Thursday, October 1, 2015

Esoteric - Simplex

No, no, no, not a simplex. I mean Simplex. Simplex is a single-char programming language, that is, all of its commands are single characters. I'll give a list of commands. Note that there are missing characters. These are either non-serious commands or are unimplemented.
Char Description
A    Adds the current byte to the previous byte and removes the current byte, decrements pointer
B    Converts the byte to binary
C    Asks for input and outputs it
D    Sets the current byte to twice its value
E    Raises the previous byte the (current byte)th power and removes the current byte, decrements pointer
F    Goes back n characters in the source code. Deletes the current byte.
G    Asks for single-char input and Manhattan-adds it to the current byte
I    Increments the byte
J    Binary left-shift
K    Binary right-shift
L    Goes left a byte
M    Decrements the byte
N    Goes (current byte) bytes backwards in the strip.
O    Goes to the (current byte)th position in the source code
R    Goes right a byte
S    Subtracts the current byte from the previous byte and removes the current byte, decrements pointer
T    Multiplies the previous byte by the current byte and removes the current byte, decrements pointer
U    Sets the current byte to half its value
V    Divides the previous byte by the current byte and removes the current byte, decrements pointer
W    Converts character to lower case (ASCII only)
X    Sets the current byte to a random integer from 0 to the current byte
Y    Floors the current value
Z    Converts character to upper case (ASCII only)
0-9  Manhattan-adds the number to the current byte (a+_m b=10a+b).
a    Make the number negative
b    Asks for input that will store each character into a byte on the strip in order.
c    Copies the current byte to the next byte and increments the pointer.
d    Reverses the entire strip/tuple (tuple check first)
e    Manhattan adds e = 2.718281828459045… to the stack.
f    Turns off safety mode.
g    Clears the strip and outputs it as ASCII characters.
 Tuple: deletes the tuple and output its characters as ASCII.
i    Asks for input as a number and stores it.
j    Inserts a new cell at the pointer, pushing everything right.
k    Skips the next command
l    Writes the number of non-empty cells in the strip to the current cell
m    Writes the index of the pointer to the cell
n    Logically negates the current byte
o    Outputs the current byte as a number
p    Silent prime detection
q    Checks for membership in a tuple (tupleByte member <=> member IN tupleByte)
 Like this:
   (t1,…,tN) M → (q) → (t1,…,tN) C
 C is whether (1) or not (0) M in (t1,…,tN)
r    Reverses the current number, removing leading zeroes. (1000→1)d
s    Outputs the current byte as a string character
t    Applies the next character's function (support […]) to every member of the current strip.
u    Increments the strip number
v    Decrements the strip number
x    Proceed (confirms)
y    Takes the current byte n and takes the n previous entries and pushes it into a tuple, then storing the tuple in the byte n bytes away OR if the current byte is a tuple, expands the tuple into n bytes (inclusive of the current byte, going out.)
z    Resets the byte to zero
|    Traverse the stack in the opposite direction
%    Modulo
?    Skips the next command if the byte is zero.
[…]  Block statement. Read by ? as "one character".
{…}  While loop. Execution continues until the current byte is zero.
!…!  Comments.
#    Stops evaluation
;    Pushes the current character to the outer program (ability to compile to itself); if there are characters on the outer program at the end of execution, evaluates the outer program as the inner program.
`    Suppresses evaluation of outer program and instead outputs it.
=    N = current index. S = strip. S[N] = S[N] == S[N-1] (Equality testing)
>    N = current index. S = strip. S[N] = S[N] > S[N-1] (Inequality testing)
<    N = current index. S = strip. S[N] = S[N] < S[N-1] (Inequality testing)
"    Toggle string-parsing mode. In string-parsing mode, char codes are written to the current byte and the pointer incremented. E.g., "Alive" would write values 65, 108, 105, 118, 101 to the current byte, the byte after that, etc.
(…)n Repeats … n times (pre-code compilation). If left off, assumed to be repeated once.
~~   Comment (pre-code, single-line)
Here are some example programs:

BF Interpreter

Since there is a surjection from Simplex to BF, BF can compile to Simplex. The compiler can be written in simplex:

br{j">"=?[v"R";Ru]"<"=?[v"L";Ru]"+"=?[v"I";Ru]"-"=?[v"M";Ru]"."=?[v"s";Ru]","=?[v"G";Ru]"["=?[v"{";Ru]"]"=?[v"}";Ru]LL}

Hello, World!

"Hello, World!"g

What's up? Esoteric! - Cerveau Choix


OK, so I've been really into Esoteric languages. Y'know, those languages that aren't really practical to do real-world-ish stuff in, but are fun to program in. I'm also working on a few (yes, a few!) of my own. I'm not sure which one will be finished first... *OCD FTW*

All notes on these programming schematics are from my notes.

Cerveau Choix

For convenience,there are alternate names by which the language may be named:
  • Cerveau Choix (Pronounced “Sare-voh Schwa”)
  • Cerveau (Pronounced “Sare-voh”)
  • CC (Pronounced “Sea-sea”)
  • Choix (Pronounced “Schwa”)
  • English “Brain Choice”
This is really just a fancy skin for BF (with some extra bonuses), allowing one to golf with certain characters. The concept is that each of the BF characters are mapped to a number, like so:
  1. <
  2. >
  3. +
  4. -
  5. [
  6. ]
  7. ,
  8. .

And then mapping permutations of characters to those symbols.
Outline:
Every program consists of a preamble, consisting of the following:
C1CnD
Where all i, j, CiCj and CiD, also with Ci denoting some arbitrary character. After the preamble follows the code, either on the following lines or on the same line, where a “\n” precedes the code (symbolic of newline). For example, a BF code might be thus:
++++++++[>++++++++<-].
Might print out character 64. Let's say our preamble was thus:
AB.
Then, our dictionary would be this:
<
A
>
B
+
AA
    •  
AB
[
BA
]
BB
,
AAA
.
AAB
And so, the code would be translated as thus:
AB.
AA.AA.AA.AA.AA.AA.AA.AA.BA.B.AA.AA.AA.AA.AA.AA.AA.AA.A.AB.BB.AAB
As one can tell, the trailing delineator is not required.
One is not limited to two symbols in the preamble; one can you anywhere from 1 to 8 (more than 8 is allowed, but is impractical.) Examples of preambles and the respective code and chart:
eFg~!
<
>
+
    •  
[
]
,
.
e
F
g
~
ee
eF
eg
e~
eFg~!
g!g!g!g!g!g!g!g!ee!F!g!g!g!g!g!g!g!g!e!~e!F!e!~

However, I said that this language was not merely a fancy reskin. It also includes a new operator, the stack duplication operator. Here is the syntax:
{operator chain}n
This implies that there are reserved identifiers; these are the numbers 0-9 and the symbol {, }, and |. (The latter I will explain later.) This means that these symbols cannot be used in tandem with the stack duplication operator; that is, if any of the symbols pertinent to said operator are used in the preamble, they cannot be used within the code.
The last symbol is the | or “bar” operator. It can be thought of as the import operator in Python, except it doesn't depend on outside libraries, ergo, it is a self-sufficient program. The bar operator allows one to make certain function accessible and definable. Multiple bar commands should be on the same line. The bar line must precede the preamble, but not necessarily on a line of its own. Here is a list of all valid bar commands:
Command
Description of accessed command
|z
Set current value to zero
|d
Doubles the current value
|h
Halves the current value (floor division of {current} // 2)
|F
Sets the current value to  (fibonacci)
|H
Prints “Hello, world!”
|?
Conditional. Skips the next command if the current stack is zero.
|#
Allows numeric numbers to be set to the next
|c
Sets current value to the number of occupied cells
|C
Sets current value to the number of occupied positive cells
|X
Resets the holder to its original state and resets the IP.
|i
Allows for multi-character input, overriding values to house the string sufficiently, starting at pointer. (I.e., input = "Hello",
|*
Imports all the (non-bolded) commands in linear order.
|~
Imports all the (non-bolded) commands in reverse order.
|T
Imports “true” commands, keeping to the original sense of BF. (Working on specific definition)

When a bar command is used, it adds the function to the end of the list. E.g, if your preamble was hcD;, then the modified table would be like this:
<
h
>
c
+
D
-
hh
[
hc
]
hD
,
ch
.
cc
(sym9)
cD
(sym10)
Dh
Etc.
Dc
So, the Hello, world! program can be written as thus:
|Habc;bc

Friday, January 2, 2015

Math Object Challenge: Update #2.

I have made substantial progress; using Taylor series, I approximated the sin, cos, sec, and csc functions. I also added summation and product and a few others. I now, however, have to lean on the use of ln and exp functions from the math object. I added a new function 'truncIf' that truncates a number if and only if the other parameter is an integer (that is, equal it itself when truncated). It is used to give more accurate results when using the pow command.

Code:
var atan = Math.atan;
var tan = Math.tan;
var pi = Math.PI;
var ln = Math.log;
var exp = Math.exp;

function ceil(x){
return (sgn(x))*(abs(x)+.5+div(atan(-tan(pi*(abs(x)+.5))),pi))+(x<0?1:0);
}

function floor(x){
return -ceil(-x);
}

function abs(x){
return sgn(x)*x;
}

function sgn(x){
return (x<0)?-1:(x>0)?1:0;
}

function div(x,y){
return x/y;
}

function sin(y){
var sign = sgn(y);
var x = abs(y);
while(x>2*pi){
x-=2*pi;
}
return (x - (pow(x,3)/fac(3)) + (pow(x,5)/fac(5)) - (pow(x,7)/fac(7)) + (pow(x,9)/fac(9)) - (pow(x,11)/fac(11)) + (pow(x,13)/fac(13)) - (pow(x,15)/fac(15)) + (pow(x,17)/fac(17)))*sign;
}

function cos(y){
var sign = sgn(y);
var x = abs(y);
while(x>2*pi){
x-=2*pi;
}
return (1 - (pow(x,2)/fac(2)) + (pow(x,4)/fac(4)) - (pow(x,6)/fac(6)) + (pow(x,8)/fac(8)) - (pow(x,10)/fac(10)) + (pow(x,12)/fac(12)) - (pow(x,14)/fac(14)) + (pow(x,16)/fac(16)))*sign;
}

function sec(x){
return 1/cos(x);
}

function csc(x){
return 1/sin(x);
}

function fac(x){
return product(1,x,"#");
}

function product(start,end,transform,inst){
var inst = inst || "#";
var out = 1;
transform = transform.split("");
for(i=0;i<transform.length;i++){
transform[i] = transform[i].replace(inst,"i");
}
transform = transform.join("");
for(i=start;i<=end;i++){
out*=eval(transform);
}
return out;
}

function sum(start,end,transform,inst){
var inst = inst || "#";
var out = 1;
transform = transform.split("");
for(i=0;i<transform.length;i++){
transform[i] = transform[i].replace(inst,"i");
}
transform = transform.join("");
for(i=start;i<=end;i++){
out+=eval(transform);
}
return out;
}

function pow(x,y){
return truncIf(x+y,exp(y*ln(x)));
}

function trunc(x){
return +(x+"").split(".")[0];
}

function truncIf(x,y){
return (trunc(x)==x)?trunc(y):y;
}

Thursday, January 1, 2015

Challenge initiated: Let's re-create the Math object.

First, a public apology: I'm moving away from the syntax highlighter. Sorry, :(, but I don't have the time and energy to use it. So, just a grey-and-white PRE. So, right now, I'm attempting at re-creating all of the functions in the Math object. Typically, this wouldn't be to hard, however; I am trying to define as much of the functions mathematically, that is, with equations, leaning only on the functions I define myself. Currently, I have very few functions covered; I am also currently leaning slightly on the Math object for two functions and a variable: Math.atan, Math.tan, and Math.PI; I can easily define the last one, and possibly the second with a Taylor sequence, but I haven't gotten around to doing this.
var atan  = Math.atan;
var tan   = Math.tan;
var pi    = Math.PI;

function ceil(x){
 return (sgn(x))*(abs(x)+.5+div(atan(-tan(pi*(abs(x)+.5))),pi))+(x<0?1:0);
}
function floor(x){
 return -ceil(-x);
}
function abs(x){
 return sgn(x)*x;
}
function sgn(x){
 return (x<0)?-1:(x>0)?1:0;
}
That's all for now, I hope to have more for you tomorrow.