Wednesday, November 25, 2015

Making up Lorem Ipsum

The following javascript function showcases two inner functions that have only scope for the outer function. Not something I use often, but seemed apt for what I was doing here. The output generated looks like this (a cross between Hungarian/Turkish and Indonesian?)
ur tojo imfuw ukba aral inoma bodfuy iknedik ofat aav id evajuragonephu nimemobi umajvamjo lo bijpaulim ugpeibgac depi puisrejnahafi getegvoeysepied hu iclupgak parjonuf bos aivhocu us pokehekgerbak mugu itdaceii ikimhup penka iduab tojeme idmethe nalay ugservanuu atub pavdiv sep cowgimaag gon ipokipaberuvapadaehovcahat lonugirfi acasinal giosug dihocadu vumfilocoy ru benumeohuj rejav puj cidomten rom godioncogal likviu hucous cecioieruhubewuda naivac ive.

function randomClauseMarkup() {

    var initials = "bc df gh jk lm np rs tv"; // chance of an initial is 66%
    var vowels = "aeiou"; // 100%, since all syllables must have vowels
    var finals = "y w b c d f g j k l m n p r s t v"; // change of final is 50%
    var randomsyl=function() {
        var initial = initials.charAt( Math.floor(Math.random()*initials.length));
        var vowel = vowels.charAt( Math.floor(Math.random()*vowels.length));
        var final = finals.charAt( Math.floor(Math.random()*finals.length));
        return (initial+vowel+final).trim()
    }

    var randomword=function() {
        var ns= 1 + Math.floor(Math.random()*4);
        var w = '';
        while (w.length<ns*2) w += randomsyl();
        return ' <span class="word">'+w+'</span>';
    }

    var s = '';
    var numwords = 3 +  Math.floor(Math.random()*30); // these clauses will have [3,33] words
    for (w = 0; w < numwords; w++) {
        s += randomword();
    }
    return ' <span class="clause">'+s+'</span>';
}

To turn the string into html, just use $.parseHTML or load element with .html()
 

Saturday, November 7, 2015

Digrams, or two letter graphs, in any language

Every wonder what the most likely letter is after a given letter in a language. Suppose you needed to know to write an interactive keyboard on a mobile phone to save that precious real estate, instead of taking up half the screen like the iPhone does. That is exactly one of my current projects. So, here is some javascript code to get those frequency graphs, given a list of possible letters (and punctuation) along with a sample test.

Here is a typing program I developed to use timed digrams as a way to improve typing:
TYPOR
Comments?



var letters = "abcdefghijklmnopqrstuvwzyxABCDEFGHIJKLMNOPQRSTUVWXYZ ,;:.";

var sampletext = "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit. Soon Lara spotted other landmarks—an outcropping of limestone beside the path that had a silhouette like a man’s face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised. They were drawing near to the place where there was an island in the river. The island was a good spot to make camp. They would sleep on the island tonight. Lara had been back and forth along the river path many times in her short life. Her people had not created the path—it had always been there, like the river—but their deerskin-shod feet and the wooden wheels of their handcarts kept the path well worn. Lara’s people were salt traders, and their livelihood took them on a continual journey. At the mouth of the river, the little group of half a dozen intermingled families gathered salt from the great salt beds beside the sea. They groomed and sifted the salt and loaded it into handcarts. When the carts were full, most of the group would stay behind, taking shelter amid rocks and simple lean-tos, while a band of fifteen or so of the heartier members set out on the path that ran alongside the river. With their precious cargo of salt, the travelers crossed the coastal lowlands and traveled toward the mountains. But Lara’s people never reached the mountaintops; they traveled only as far as the foothills. Many people lived in the forests and grassy meadows of the foothills, gathered in small villages. In return for salt, these people would give Lara’s people dried meat, animal skins, cloth spun from wool, clay pots, needles and scraping tools carved from bone, and little toys made of wood. Their bartering done, Lara and her people would travel back down the river path to the sea. The cycle would begin again. It had always been like this. Lara knew no other life. She traveled back and forth, up and down the river path. No single place was home. She liked the seaside, where there was always fish to eat, and the gentle lapping of the waves lulled her to sleep at night. She was less fond of the foothills, where the path grew steep, the nights could be cold, and views of great distances made her dizzy. She felt uneasy in the villages, and was often shy around strangers. The path itself was where she felt most at home. She loved the smell of the river on a hot day, and the croaking of frogs at night. Vines grew amid the lush foliage along the river, with berries that were good to eat. Even on the hottest day, sundown brought a cool breeze off the water, which sighed and sang amid the reeds and tall grasses.";

var digrams = new Array(letters.length);
for (var i=0; i<letters.length; i++) {
 digrams[i] = new Array(letters.length);
 for (var j=0; j<letters.length; j++) {
  digrams[i][j] = 0;
 }
}

var nextLets = new Array(letters.length);
for (var i=0; i<letters.length; i++) {
 nextLets[i] = new Array();
}

loadDigrams(sampletext);
document.writeln("<table border='1'><tr><td></td>");
for (var j=0; j<letters.length; j++) {
 document.writeln("<td align='center'>"+letters[j]+"</td>");
}
document.writeln("</tr>");
for (var i=0; i<letters.length; i++) {
 document.write("<tr><td>"+letters[i]+"</td>");
 for (var j=0; j<letters.length; j++) {
  document.writeln("<td align='right'>"+digrams[i][j]+"</td>");
 }
 document.writeln("</tr>");
}
document.writeln("</table>");

loadNextlets();
document.writeln("<div>");
for (var i=0; i<letters.length; i++) {
 document.write("<div><span style='border: 1px solid black;'>"+letters[i].replace(' ','_')+"</span> ");
 for (var j=0; j<nextLets[i].length; j++) {
  if (!nextLets[i][j]) continue;
  document.writeln("&nbsp;<span style='text-align:center;border: 1px solid black;'>"+nextLets[i][j].replace(' ','_')+"</span>");
 }
 document.writeln("</div>");
}
document.writeln("</div>");



function loadDigrams(text) {
 text = text + ' ';
 for (var x=0; x<text.length-1; x++) {
   var i = letters.indexOf(text.charAt(x));
   var j = letters.indexOf(text.charAt(x+1));
   if (i>=0 && j>=0) digrams[i][j]++;
 }
}

function loadNextlets() {
 for (var x=0; x<letters.length; x++) {

  var rowvals = digrams[x].slice()
   .sort(function (a,b) {return b-a;})
   .filter(function(item,ix,ary) {return !ix || item != ary[ix-1];})

  for (var y=0; y<rowvals.length; y++) {
   if (rowvals[y]==0) break;
   nextLets[x][y] = '';
   for (var j=0; j<digrams[x].length; j++) {
    if (digrams[x][j]==rowvals[y]) { nextLets[x][y] += letters[j]; }
   }
  }

 }
}


function getRandomInt(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}