Mccluskey algorithm, javascript - javascript

<html>
<body>
<script type="text/javascript">
start();
function start() {
var val = "0,1";
var n = 5;
var chars = ['a', 'b', 'c', 'd', 'e'];
gVars = chars.slice(0, n);
for (var i = 0; i < gVars.length; i++)
document.write(gVars[i] + "<br />");
var termsStr = val.split(',');
for (var i = 0; i < termsStr.length; i++)
document.write(termsStr[i] + "<br />");
var gOrigTerms = [];
var maxterm = Math.pow(2, termsStr.length) - 1;
document.write("maxterm: " + maxterm + "<br />");
for (var i = 0; i < termsStr.length; i++) {
gOrigTerms[i] = parseInt(termsStr[i]);
document.write(gOrigTerms[i] + "<br />");
if (gOrigTerms[i] > maxterm) document.write("Invalid term in term list." + "<br />");
}
gFormula = new Formula(gVars, gOrigTerms);
document.write(gFormula);
gFormula.toString();
gFormula.reduceToPrimeImplicants(); //here the breakpoint is inserted
}
function Formula(vars, terms)
{
this.vars = vars;
this.termList = [];
for (var i = 0; i < terms.length; i++) {
this.termList[i] = new Term(Dec2Bin(terms[i], vars.length));
document.write("this.termList" + this.termList[i] + "<br />");
}
this.orginalTermList = [];
document.write("this.orginalTermList" + this.orginalTermList + "<br />");
}
function Dec2Bin(dec, size) {
var bits = [];
for (var bit = 0; bit < size; bit++)
{
bits[bit] = 0;
}
var i = 0;
while (dec > 0)
{
if (dec % 2 == 0)
{
bits[i] = 0;
} else
{
bits[i] = 1;
}
i++;
dec = (dec / 2) | 0;
// Or with zero casts result to int (who knows why...)
}
bits.reverse();
return bits;
}
function Term(varVals)
{
this.varVals = varVals;
document.write("this.varVals: " + this.varVals);
}
function reduceToPrimeImplicants() //there is some problem with this function
{
this.originalTermList = this.termList.slice(0);
var numVars = this.termList[0].getNumVars();
var table = [];
for (var dontKnows = 0; dontKnows <= numVars; dontKnows++) {
table[dontKnows] = [];
for (var ones = 0; ones <= numVars; ones++) {
table[dontKnows][ones] = [];
}
table[dontKnows][numVars + 1] = [];
}
table[numVars + 1] = [];
table[numVars + 1][numVars + 1] = [];
for (var i = 0; i < this.termList.length; i++) {
var dontCares = this.termList[i].countValues(DontCare);
var ones = this.termList[i].countValues(1);
var len = table[dontCares][ones].length;
table[dontCares][ones][len] = this.termList[i];
}
for (var dontKnows = 0; dontKnows <= numVars - 1; dontKnows++) {
for (var ones = 0; ones <= numVars - 1; ones++) {
var left = table[dontKnows][ones];
var right = table[dontKnows][ones + 1];
var out = table[dontKnows + 1][ones];
for (var leftIdx = 0; leftIdx < left.length; leftIdx++) {
for (var rightIdx = 0; rightIdx < right.length; rightIdx++) {
var combined = left[leftIdx].combine(right[rightIdx]);
if (combined != null) {
if (out.indexOf(combined) < 0) {
var len = out.length;
out[len] = combined;
}
if (this.termList.indexOf(left[leftIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(left[leftIdx]), 1);
}
if (this.termList.indexOf(right[rightIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(right[rightIdx]), 1);
}
if (this.termList.indexOf(combined) < 0) {
var len = this.termList.length;
this.termList[len] = combined;
}
}
}
}
}
}
}
function getNumVars()
{
return this.varVals.length;
}
function countValues(value)
{
result = 0;
for (var i = 0; i < this.varVals.length; i++) {
if (this.varVals[i] == value) {
result++;
}
}
return result;
}
function combine(term)
{
var diffVarNum = -1; // The position where they differ
for (var i = 0; i < this.varVals.length; i++) {
{
if (this.varVals[i] != term.varVals[i])
if (diffVarNum == -1) {
diffVarNum = i;
} else { // They're different in at least two places return null; }
}
}
if (diffVarNum == -1)
{
// They're identical return null;
}
resultVars = this.varVals.slice(0);
resultVars[diffVarNum] = DontCare;
return new Term(resultVars);
}
</script>
</body>
</html>
In the above code, that is not complete, but which implements quine Mccluskey algorithm. There is a problem while it is debugged.
If a breakpoint is inserted at gFormula.reducetoPrimeImplicants(); the debugger does not go into that function. This is the last function called in the code until now. But, it does go to start(), which is the first function.
There is some problem in reducetoPrimeImplicants(); function because it also gives ERROR in internet explorer.
I am not able to figure out the error. If I remove reducetoPrimeImplicants(); function from the code the works fine.
Please, can somebody tell me why the debugger does not enter reducetoPrimeImplicants();.
I am using the Firebug debugger.
Thanks in advance.

The last function in your page combine() is missing a closing brace.
If you don't mind, a suggestion: Please use http://jsbeautifier.org/ or some similar tool to indent your code better.

Your For loop has two starting braces.
for (var i = 0; i < this.varVals.length; i++) {
{
So remove one. This should solve your problem.

Related

How to change this code to list post titles of all the post on Blogger in format YYYY.MM.DD <title> and chronological order?

I like to show my titles of posts on a specific page. It is more effective to get know what author have written than scroll all pages or navigate using archive widget.
I found code (code is below) for generate list that sort post titles alphabetically but I like to show titles in chronological order. There is lot of code example about this but they are outdated. They doesn’t work anymore after some changes in blogger platform.
How to change code to get post titles in chronological order and in format YYYY.MM.DD ?
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12() {
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root) {
//Sort Alphebetically
allResults.sort(function(a, b)
{
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root) {
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0) {
for (var i = 0; i < feed.entry.length; i++) {
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == "alternate") {
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0) {
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults) {
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>
Code is copied from here: https://dansator.blogspot.fi/2015/10/general-alphabetical-list-of-posts.html
Remove sort method from the code. remove the following :
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
Your code should be
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>

Blogger related post gadget image Resize s72-c [ Need Expert Help ]

I run a Blogger blog and I use follow code JavaScript code (requires no jQuery) to show the related post with labels/categories of the post.
<script type='text/javascript'>
var defaultnoimage="http://1.bp.blogspot.com/-M72rpgunTq0/VUOKijudN_I/AAAAAAAABoI/LQ18scEunSg/w72/favicon-TIK.png";
var maxresults=16;
var splittercolor="#d4eaf2";
var relatedpoststitle="Related Posts";
</script>
<script type='text/javascript'>//<![CDATA[
var relatedTitles = new Array();
var relatedTitlesNum = 0;
var relatedUrls = new Array();
var thumburl = new Array();
function related_results_labels_thumbs(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var entry = json.feed.entry[i];
relatedTitles[relatedTitlesNum] = entry.title.$t;
try {
thumburl[relatedTitlesNum] = entry.media$thumbnail.url
} catch (error) {
s = entry.content.$t;
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) {
thumburl[relatedTitlesNum] = d
} else {
if (typeof(defaultnoimage) !== 'undefined') {
thumburl[relatedTitlesNum] = defaultnoimage
} else {
thumburl[relatedTitlesNum] = "http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png"
}
}
}
if (relatedTitles[relatedTitlesNum].length > 80) {
relatedTitles[relatedTitlesNum] = relatedTitles[relatedTitlesNum].substring(0, 80) + "..."
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
relatedUrls[relatedTitlesNum] = entry.link[k].href;
relatedTitlesNum++
}
}
}
}
function removeRelatedDuplicates_thumbs() {
var tmp = new Array(0);
var tmp2 = new Array(0);
var tmp3 = new Array(0);
for (var i = 0; i < relatedUrls.length; i++) {
if (!contains_thumbs(tmp, relatedUrls[i])) {
tmp.length += 1;
tmp[tmp.length - 1] = relatedUrls[i];
tmp2.length += 1;
tmp3.length += 1;
tmp2[tmp2.length - 1] = relatedTitles[i];
tmp3[tmp3.length - 1] = thumburl[i]
}
}
relatedTitles = tmp2;
relatedUrls = tmp;
thumburl = tmp3
}
function contains_thumbs(a, e) {
for (var j = 0; j < a.length; j++) {
if (a[j] == e) {
return true
}
}
return false
}
function printRelatedLabels_thumbs(current) {
var splitbarcolor;
if (typeof(splittercolor) !== 'undefined') {
splitbarcolor = splittercolor
} else {
splitbarcolor = "#d4eaf2"
}
for (var i = 0; i < relatedUrls.length; i++) {
if ((relatedUrls[i] == current) || (!relatedTitles[i])) {
relatedUrls.splice(i, 1);
relatedTitles.splice(i, 1);
thumburl.splice(i, 1);
i--
}
}
var r = Math.floor((relatedTitles.length - 1) * Math.random());
var i = 0;
if (relatedTitles.length > 0) {
document.write('<div class="title">' + relatedpoststitle + '</div>')
}
document.write('<div style="clear: both;"/>');
while (i < relatedTitles.length && i < 20 && i < maxresults) {
document.write(' <img src="' + thumburl[r] + '"/><br/><div class="relatedpostitle" >' + relatedTitles[r] + '</div>');
i++;
if (r < relatedTitles.length - 1) {
r++
} else {
r = 0
}
}
document.write('</div>');
relatedUrls.splice(0, relatedUrls.length);
thumburl.splice(0, thumburl.length);
relatedTitles.splice(0, relatedTitles.length)
}
//]]></script>
<div id='related-posts'>
<b:loop values='data:post.labels' var='label'>
<b:if cond='data:label.isLast != "true"'/>
<script expr:src='"/feeds/posts/summary/-/" + data:label.name + "?alt=json-in-script&callback=related_results_labels_thumbs&max-results=6"' type='text/javascript'/>
</b:loop>
<script defer='defer' type='text/javascript'>removeRelatedDuplicates_thumbs();printRelatedLabels_thumbs("<data:post.url/>");</script>
</div>
<div style='clear:both'/>
This code works fine except one problem. The code generates small images ( in default blogger thumbnail size which is s72-c) and there is no way to customize the size for (to change s72-c to s200/s200-c/w200).
I have found a image re-sizing solution script for Blogger but they are not helping. Here is it
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s72\-c/g, "\/s" + size + "-c")
}
}
resizeThumb(200);
This is for Popular post widget. And I know if I change the ID in the first line this will replace the image. But this is not solution but a cover up. And this also means the two images are loaded on is s72-c and the replaced one.
I want to integrate it (something like this) in the first related post script. I have tried hard with very very little knowledge of javascript I have but fail. So I signed up to stackoverflow and this is my question post.
Thank you in advance for trying to the help me.
function code for image size s200-c
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s200\-c/g, "\/s" + size + "-c")
}
}
resizeThumb(200);
function code for image size s200
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s200\/g, "\/s" + size + "")
}
}
resizeThumb(200);
first,add
var thumb = 200;
after
var thumburl = new Array();
then
add
thumburl[relatedTitlesNum] = thumburl[relatedTitlesNum].replace("/s72-c/","/s"+thumb+"/");
after
thumburl[relatedTitlesNum] = entry.media$thumbnail.url;
hope you like it

Keep the clicked objects in an array in javascript

I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

Why does my string permutation algorithm only work with 3 or less letters?

The Code:
function recursiveParse(letters, index) {
var i,
index = index || 0;
stringOfLetters = '';
while(index < letters.length) {
stringOfLetters += letters[index] + recursiveParse(letters, ++index);
}
return stringOfLetters;
}
function calcPermutations(letters, index, permutations) {
var head,
index = index || 0,
i,
swapLetters,
permutation,
permutations = permutations || {};
swapLetters = function(letters, index1, index2) {
var tmp = letters[index2];
letters[index2] = letters[index1];
letters[index1] = tmp;
return letters;
}
if(index < letters.length) {
head = letters.splice(index, 1).join('');
for(i = 0; i < letters.length; i++) {
permutation = head + swapLetters(letters.slice(0), index, i).join('');
permutations[permutation] = true;
}
letters.splice(index, 0, head);
calcPermutations(letters, ++index, permutations);
}
return permutations;
}
function testPermutations() {
var expectedPermutations = ['atr', 'rat', 'rta', 'tar', 'tra', 'art'],
actualPermutations = calcPermutations(['a', 'r', 't']);
for(var i = 0; i < expectedPermutations.length - 1; i++) {
if(actualPermutations[expectedPermutations[i]] !== true) {
console.log("You're missing " + expectedPermutations[i]);
} else {
console.log("You've got " + expectedPermutations[i]);
}
}
return actualPermutations;
}
testPermutations();
When I run testPermutations and pass in a 3 letter word, it works fine. However, when I try four, a bunch of permutations are coming up missing. What's the flaw in my logic?

Categories