I'm trying to solve the Project Euler Problem on the largest palindrome product in Javascript and I don't understand why the program doesn't enter the IF statement if (number.toString() == number.toString().split('').reverse().join('')):
(function palyndrom(max, min) {
top:
for (i = max; i > min; i--) {
for (c = max; c > min; c--) {
if(i*c == c*i) {
alert('same was before');
}
else {
var number = i*c;
console.log('i*c = ' + i + '*' + c + ' = ' + number);
//this if not entered, alert doesn't work
if (number.toString() == number.toString().split('').reverse().join('')) {
alert('PALYNDROM FOUND: i*c = ' + i + '*' + c + ' = ' + number);
break top;
}
}
}
}
})(999, 900);
i*c == c*i
will always result in true. The function will never reach the else part. I think what you wanted to do is
i === c
instead:
(function palyndrom(max, min) {
top:
for (var i = max; i > min; i--) {
for (var c = max; c > min; c--) {
if (i === c) {
alert('same was before');
} else {
var number = i * c;
console.log('i*c = ' + i + '*' + c + ' = ' + number);
if (number.toString() == number.toString().split('').reverse().join('')) {
alert('PALYNDROM FOUND: i*c = ' + i + '*' + c + ' = ' + number);
break top;
}
}
}
}
} )(999, 900);
You are missing a "}" which results in an error.
Aside from that, i * c is always equal to c * i.
I modified the snippet so that it returns the first palindrome. The second function returns an array of all of the palindromes.
You don't need to verify that i !== c.
(function palindrome(max, min) {
for (var i = max; i > min; i--) {
for (var c = max; c > min; c--) {
var number = i * c;
if (number.toString() == number.toString().split('').reverse().join('')) {
console.log('PALINDROME FOUND: i*c = ' + i + '*' + c + ' = ' + number);
return number;
}
}
}
})(999, 900);
//PALINDROME FOUND: i*c = 993*913 = 906609
(function palindrome(max, min) {
var palindromes = {};
for (var i = max; i > min; i--) {
for (var c = max; c > min; c--) {
var number = i * c;
if (!(number in palindromes) && number.toString() == number.toString().split('').reverse().join('')) {
palindromes[number] = 1;
}
}
}
return Object.keys(palindromes);
})(999, 900);
//["819918", "824428", "861168", "886688", "888888", "906609"]
Related
In my research, I need to generate Fricke Polynomials. Luckily the job has been done for me on a website. However, it is in javascript+html+css so I am not sure how it works as I only use Mathematica. I was wondering if anyone could explain how I could make all of this work on a single javascript code with a single input (and where to put the input). My plan is then to just take the code and embed it in Mathematica as I have seen this is possible. The input is a word say made up of a's and b's say aabbbaa and an output is a polynomial. I do not need to understand the code really.
Thank you
function Polynomial(){
this.data = "";
this.setData = function(str){
this.data = str;
}
this.toString = function(){
var s = this.data;
if (this.data.startsWith("x0y0z0"))
s = s.replace("x0y0z0", "1");
s = s.replace(/x0y0z0/g, "")
.replace(/\s\+\s-/g, "</sup> - ").replace(/\s\+/g, "</sup> +")
.replace(/x/g, "x<sup>").replace(/y/g, "</sup>y<sup>")
.replace(/z/g, "</sup>z<sup>")
.replace(/\s1x/g, " x").replace(/\s1y/g, " y").replace(/\s1z/g, " z");
s += "</sup>";
s = s.replace(/x<sup>0<\/sup>/g, "").replace(/y<sup>0<\/sup>/g, "")
.replace(/z<sup>0<\/sup>/g, "")
.replace(/x<sup>1<\/sup>/g, "x").replace(/y<sup>1<\/sup>/g, "y")
.replace(/z<sup>1<\/sup>/g, "z");
if (s.startsWith("1x"))
s = s.replace("1x", "x");
if (s.startsWith("1y"))
s = s.replace("1y", "y");
if (s.startsWith("1z"))
s = s.replace("1z", "z");
return s;
}
}
function compareMonomial(m1, m2){
m1s = m1.split(/[x|y|z]/g);
m2s = m2.split(/[x|y|z]/g);
if (m1s[3]< m2s[3]) return -1;
else if (m1s[3] > m2s[3]) return 1;
else if (m1s[2]< m2s[2]) return -1;
else if (m1s[2] > m2s[2]) return 1;
else if (m1s[1]< m2s[1]) return -1;
else if (m1s[1] > m2s[1]) return 1;
else return 0;
}
function addMonomial(m1, m2){
m1s = m1.split(/[x|y|z]/g);
m2s = m2.split(/[x|y|z]/g);
coef = parseInt(m1s[0]) + parseInt(m2s[0]);
if (coef == 0)
return "ZERO"
else
return coef + "x" + m1s[1] + "y" + m1s[2] + "z" + m1s[3];
}
function subMonomial(m1, m2){
m1s = m1.split(/[x|y|z]/g);
m2s = m2.split(/[x|y|z]/g);
coef = parseInt(m1s[0]) - parseInt(m2s[0]);
if (coef == 0)
return "ZERO";
else
return coef + "x" + m1s[1] + "y" + m1s[2] + "z" + m1s[3];
}
function mulMonomial(m1, m2){
m1s = m1.split(/[x|y|z]/g);
m2s = m2.split(/[x|y|z]/g);
coef = parseInt(m1s[0]) * parseInt(m2s[0]);
coefx = parseInt(m1s[1]) + parseInt(m2s[1]);
coefy = parseInt(m1s[2]) + parseInt(m2s[2]);
coefz = parseInt(m1s[3]) + parseInt(m2s[3]);
if (coef == 0)
return "ZERO";
else
return coef + "x" + coefx + "y" + coefy + "z" + coefz;
}
function add(p1, p2){
if (p1.data == "")
return p2;
if (p2.data == "")
return p1;
var r = new Polynomial();
p1Mos = p1.data.split(" + ");
p2Mos = p2.data.split(" + ");
var data = "";
var k = 0; var current = p1Mos[0];
for (var i = 0; i < p2Mos.length; i++){
if (k >= p1Mos.length)
data += " + " + p2Mos[i];
else {
while (k < p1Mos.length && compareMonomial(current, p2Mos[i]) < 0){
data += " + " + p1Mos[k]; k++; current = p1Mos[k];
}
if (current == undefined)
data += " + " + p2Mos[i];
else if (compareMonomial(current, p2Mos[i]) == 0){
if (addMonomial(current, p2Mos[i]) != "ZERO")
data += " + " + addMonomial(current, p2Mos[i]);
k++; current = p1Mos[k];
}
else{
data += " + " + p2Mos[i];
}
}
}
while (k < p1Mos.length){
data += " + " + p1Mos[k]; k++
}
r.setData(data.substring(3));
return r;
}
function sub(p1, p2){
if (p2.data == "")
return p1;
if (p1.data == ""){
//need to update here
return p2;
}
var r = new Polynomial();
p1Mos = p1.data.split(" + ");
p2Mos = p2.data.split(" + ");
var data = "";
var k = 0; var current = p1Mos[0];
for (var i = 0; i < p2Mos.length; i++){
p2coef = p2Mos[i].split(/[x|y|z]g/)[0];
if (parseInt(p2coef) < 0)
p2MoNeg = p2Mos[i].substring(1);
else
p2MoNeg = "-" + p2Mos[i];
if (k >= p1Mos.length)
data += " + " + p2MoNeg;
else {
while (k < p1Mos.length && compareMonomial(current, p2Mos[i])< 0){
data += " + " + p1Mos[k]; k++; current = p1Mos[k];
}
if (current == undefined)
data += " + " + p2MoNeg;
else if (compareMonomial(current, p2Mos[i]) == 0){
if (subMonomial(current, p2Mos[i]) != "ZERO")
data += " + " + subMonomial(current, p2Mos[i]);
k++; current = p1Mos[k];
}
else{
data += " + " + p2MoNeg;
}
}
}
while (k < p1Mos.length){
data += " + " + p1Mos[k]; k++
}
r.setData(data.substring(3));
return r;
}
// multiply polynomial p1 (with array of monomials p1Mos) with a monomial m2
function mulPM(p1Mos, m2){
r = new Polynomial();
var data = "";
for (var i = 0; i < p1Mos.length; i++){
if (mulMonomial(p1Mos[i], m2) != "ZERO")
data += " + " + mulMonomial(p1Mos[i], m2);
}
r.setData(data.substring(3)); return r;
}
// multiply polynomial p1 with polynomial p2
function mul(p1, p2){
p1s = p1.data.split(" + ");
p2s = p2.data.split(" + ");
r = new Polynomial();
for (var i = 0; i < p2s.length; i++){
r = add(r, mulPM(p1s, p2s[i]));
}
return r;
}
function Fricke(s){
var w = new Word();
w.setWordString(s);
w.reduce(); s = w.toString();
var r = new Polynomial();
var l = s.length;
// Trivial case or case where 2 consecutive letters among last 4 letter
// are the same
if (l == 0){
r.setData("2x0y0z0");
return r;
}
if (l == 1){
if (s == "a" || s == "A")
r.setData("1x1y0z0");
else
r.setData("1x0y1z0");
return r;
}
if (s.charAt(l-1) == s.charAt(l-2)){
var c = s.charAt(l-1);
var s1 = s.substring(0, l-2);
r = sub(mul(Fricke(s1 + c), Fricke(c + "")), Fricke(s1));
return r;
}
if (l == 2){
if (s == "ab" || s == "ba" || s == "AB" || s == "BA"){
r.setData("1x0y0z1");
return r;
}
else if (s == "aB" || s == "Ba" || s == "Ab" || s == "bA"){
r.setData("1x1y1z0 + -1x0y0z1");
return r;
}
}
if (s.charAt(l-2) == s.charAt(l-3)){
s = s.charAt(l-1) + s.substring(0, l-1);
r = Fricke(s);
return r;
}
if (l == 3){
s = s.charAt(l-1) + s.substring(0, l-1);
r = Fricke(s);
return r;
}
if (s.charAt(l-3) == s.charAt(l-4)){
s = s.substring(l-2, l) + s.substring(0, l-2);
r = Fricke(s);
return r;
}
// Case 2: w = x1Yx2y
var t = s.charCodeAt(l-1) - s.charCodeAt(l-3);
if ( t == 32 || t == -32){
var w1 = new Word();
w1.setWordString(s.substring(l-2, l));
var s2 = s.substring(0, l-2) + w1.bar().toString();
r = sub(mul(Fricke(s.substring(0, l-2)), Fricke(s.substring(l-2, l))),
Fricke(s2));
return r;
}
// Case 3: w = ...Xyxy
t = s.charCodeAt(l-2) - s.charCodeAt(l-4);
if ( t == 32 || t == -32){
r = Fricke(s.charAt(l-1) + s.substring(0, l-1));
return r;
}
// Last case 4: w = ...xyxy
r = sub(mul(Fricke(s.substring(0, l-2)), Fricke(s.substring(l-4, l-2))),
Fricke(s.substring(0, l-4)));
return r;
}
// Helper methods:
function cancel2Char(src, i){
dest = [];
for (var j = 0; j < i; j++)
dest[j] = src[j];
for (var j = i; j < src.length - 2; j++)
dest[j] = src[j+2];
return dest;
}
function trim2Ends(src){
dest = [];
for (var j = 1; j < src.length - 1; j++)
dest[j - 1] = src[j];
return dest;
}
// Function to find the minimum equivalent class of a reduced cyclic word rc.
function minReduceCyclic(rc){
var min = rc.clone();
var W = new Word();
for (var i = 0; i < rc.word.length; i++){
W = rc.permute(i);
if (min.compareTo(W) > 0)
min = W;
}
return min;
}
function canonical(W){
W.reduce();
W.toReduceCyclic();
W = minReduceCyclic(W);
return W;
}
// CLASS Word
function Word(){
this.word = [];
this.setWord = function(w){
this.word = w;
}
this.setWordString = function(s){
// a-z = 1-26 && A-Z = -1 - -26;
for (var i = 0; i < s.length; i++){
var c = s.charCodeAt(i);
if (c >= 65 && c <= 90 )
this.word[i] = -(c - 64);
else if (c >= 97 && c < 122)
this.word[i] = c - 96;
else {
this.word = []; return;
}
}
}
this.length = function(){ return this.word.length; }
}
Word.prototype.isReduce = function(){
for(var i = 0; i < this.word.length - 1; i++)
if (this.word[i] == -this.word[i+1])
return false;
return true;
}
Word.prototype.reduce = function(){
var i = -2;
while(i != this.word.length - 1){
if (this.word.length == 0)
return;
for(i = 0; i < this.word.length - 1; i++)
if (this.word[i] == -this.word[i+1]){
this.word = cancel2Char(this.word, i);
break;
}
}
return;
}
Word.prototype.toReduceCyclic = function(){
this.reduce();
while(this.word[0] == -this.word[this.word.length - 1])
this.word = trim2Ends(this.word);
return;
}
Word.prototype.toString = function(){
var s = "";
for (var i = 0; i < this.word.length; i++){
if (this.word[i] < 0)
s = s + String.fromCharCode(-this.word[i] + 64);
else
s = s + String.fromCharCode(this.word[i] + 96);
}
return s;
}
Word.prototype.bar = function(){
var r = new Word();
var w = r.word;
for (var j = 0; j < this.word.length; j++)
w[j] = - this.word[this.word.length - 1 - j];
return r;
}
Word.prototype.permute = function(i){
var r = new Word();
var w = r.word;
for (var j = 0; j < this.word.length; j++)
w[j] = this.word[(j + i) % this.word.length];
return r;
}
Word.prototype.isEqual = function(W2){
var w1 = this.word;
var w2 = W2.word;
if (w1.length != w2.length)
return false;
for (var i = 0; i < w1.length; i++)
if (w1[i] != w2[i])
return false;
return true;
}
Word.prototype.compareTo = function(W2){
var w1 = this.word;
var w2 = W2.word;
var l = Math.min(w1.length, w2.length);
for (var i = 0; i < l; i++){
if (w1[i] < w2[i])
return -1;
if (w1[i] > w2[i])
return 1;
}
if (w1.length > w2.length)
return 1;
if (w1.length < w2.length)
return -1;
return 0;
}
Word.prototype.clone = function(){
var r = new Word();
w = r.word;
for (var i = 0; i < this.word.length; i++)
w[i] = this.word[i];
return r;
}
Word.prototype.primitiveExp = function(){
w = this.word; l = w.length;
for(var i = 1; i <= l/2; i++){
if (l % i == 0){
found = true;
test:
for (var j = 0; j < l/i; j++)
for (var t = 0; t < i; t++)
if (w[t] != w[t + j * i]){
found = false;
break test;
}
}
if (found)
return l/i;
}
return 1;
}
// Need to debug
function concat(W1, W2){
r = new Word();
var w1 = W1.word;
var w2 = W2.word;
var w = []
for (var i = 0; i < w1.length; i++)
w[i] = w1[i];
for (var i = 0; i < w2.length; i++)
w[i + w1.length] = w2[i];
r.setWord(w);
return r;
}
// These are supposed to be surface word methods
// sw is a word and the order is a map, which
// maps characters in a word (1-k or (-1)-(-k)) to its order in the alphabet
function order(sw){
var w = sw.word;
var o = new Map();
for (var i = 0; i < w.length; i++)
o.set(w[i], i);
return o;
}
function findCharPos(sw, c){
for (var i = 0; i < sw.word.length; i++)
if (sw.word[i] == c)
return i;
}
var time;
$(document).ready(function(){
$("#compute").click(function(){
$("#note").text("Note: Computing.....");
time = new Date().getTime();
setTimeout(function(){
new Promise(compute).then(doneCompute("Note: Done! The computation time is about "));
}, 50);
});
$("#reset").click(function(){
$("#note").text("Note:");
$("#word").val("");
$("#fpOutput").text("");
});
});
function compute(value){
$("#fpOutput").html(Fricke($("#word").val()).toString());
$("#fpOutput").slideDown("slow");
}
function doneCompute(value){
$("#note").text(value + (new Date().getTime() - time - 50) + " milliseconds.");
}
<!DOCTYPE html>
<html>
<head>
<link href="fricke.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="Word.js"></script>
<script type="text/javascript" src="Polynomial.js"></script>
<script type="text/javascript" src="gui.js"></script>
</head>
<body>
<h2>Computing Fricke Polynomial for word with 2 generators a and b</h2>
<br>
<b>Word: </b>
<input type="text" class="inputText" id="word"></input><br><br>
<br><br>
<button class="button" id="compute">Compute</button>
<button class="button" id="reset">Reset</button>
<br><br>
<div id="note">Note:</div>
<br><br>
<div class="slide">Fricke Polynomial</div>
<div class="output" id="fpOutput"></div>
</body>
</html>
--SOLVED--
I was just forgetting to reset the number of flags after each game.
I'm having issues with the number of flags in my minesweeper game. For some reason, sometimes when I flag a tile the number of flags increases by more than 1. Sometimes it increases by 3, sometimes 4, sometimes 7. I can't find the issue in my logic, so I was hoping to get another set of eyes on it.
The only sort of pattern I can see when it adds more flags than it should, i.e. the flags variable is incremented more than once, is when I flag a tile that is mostly surrounded by revealed tiles.
Javascript:
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50);
if (0 <= q && q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function(e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
My guess is that there's something wrong with my revealNeighbors() function or it's some scope issue, but I can't for the life of me figure out what it is.
Hi I change a litle and works fine
<html>
<head>
<style>
.tile{padding:5px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Width : <input type="text" id="width" value="15" /> Height :<input type="text" id="height" value="15" /><input type="button" onclick="newGame()" id="btnstart" value="start" />
<br />
<div>
<div id="board" >
</div>
</div>
<script>
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50) + 1;
if (q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function (e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
</script>
</body>
</html>
I am using tafgeet javascript function to convert numbers into Arabic words, but the problem is that it supports only 2 decimal places, how can I modify the function to make it read 3 decimal places:
It actually translates upto a million on the left hand side, so it would be possible to apply the same methodology on the right side.
I tried to fiddle with it, but it doesn't work. I am posting the original javascript.
/**
* TafgeetJS module.
* #module TafgeetJS
* #description Converts currency digits into written Arabic words
* #author Mohammed Mahgoub <mmahgoub#gmail.com>
*/
function Tafgeet(digit) {
var currency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "SDG";
//Split fractions
var splitted = digit.toString().split(".");
this.fraction = 0;
if (splitted.length > 1) {
var fraction = parseInt(splitted[1]);
if (fraction >= 1 && fraction <= 99) {
this.fraction = splitted[1].length === 1 ? fraction * 10 : fraction;
} else {
//trim it
var trimmed = Array.from(splitted[1]);
this.fraction = "" + trimmed[0] + trimmed[1];
}
}
this.digit = splitted[0];
this.currency = currency;
}
Tafgeet.prototype.parse = function () {
var serialized = [];
var tmp = [];
var inc = 1;
var count = this.length();
var column = this.getColumnIndex();
if (count >= 16) {
console.error("Number out of range!");
return;
}
//Sperate the number into columns
Array.from(this.digit.toString()).reverse().forEach(function (d, i) {
tmp.push(d);
if (inc == 3) {
serialized.unshift(tmp);
tmp = [];
inc = 0;
}
if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
serialized.unshift(tmp);
}
inc++;
});
// Generate concatenation array
var concats = []
for (i = this.getColumnIndex(); i < this.columns.length; i++) {
concats[i] = " و";
}
//We do not need some "و"s check last column if 000 drill down until otherwise
if (this.digit > 999) {
if (parseInt(Array.from(serialized[serialized.length - 1]).join("")) == 0) {
concats[parseInt(concats.length - 1)] = ""
for (i = serialized.length - 1; i >= 1; i--) {
if (parseInt(Array.from(serialized[i]).join("")) == 0) {
concats[i] = ""
} else {
break;
}
}
}
}
var str = "";
str += "فقط ";
if (this.length() >= 1 && this.length() <= 3) {
str += this.read(this.digit);
} else {
for (i = 0; i < serialized.length; i++) {
var joinedNumber = parseInt(serialized[i].reverse().join(""));
if (joinedNumber == 0) {
column++;
continue;
}
if (column == null || column + 1 > this.columns.length) {
str += this.read(joinedNumber);
} else {
str += this.addSuffixPrefix(serialized[i], column) + concats[column];
}
column++;
}
}
if (this.currency != "") {
if (this.digit >= 3 && this.digit <= 10) {
str += " " + this.currencies[this.currency].plural;
} else {
str += " " + this.currencies[this.currency].singular;
}
if (this.fraction != 0) {
if (this.digit >= 3 && this.digit <= 10) {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fractions;
} else {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fraction;
}
}
}
str += " لا غير";
return str;
};
Tafgeet.prototype.addSuffixPrefix = function (arr, column) {
if (arr.length == 1) {
if (parseInt(arr[0]) == 1) {
return this[this.columns[column]].singular;
}
if (parseInt(arr[0]) == 2) {
return this[this.columns[column]].binary;
}
if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
return (
this.readOnes(parseInt(arr[0])) +
" " +
this[this.columns[column]].plural
);
}
} else {
var joinedNumber = parseInt(arr.join(""));
if (joinedNumber > 1) {
return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
} else {
return this[this.columns[column]].singular;
}
}
};
Tafgeet.prototype.read = function (d) {
var str = "";
var len = Array.from(d.toString()).length;
if (len == 1) {
str += this.readOnes(d);
} else if (len == 2) {
str += this.readTens(d);
} else if (len == 3) {
str += this.readHundreds(d);
}
return str;
};
Tafgeet.prototype.readOnes = function (d) {
if (d == 0) return;
return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function (d) {
if (Array.from(d.toString())[1] === "0") {
return this.tens["_" + d.toString()];
}
if (d > 10 && d < 20) {
return this.teens["_" + d.toString()];
}
if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
return (
this.readOnes(Array.from(d.toString())[1]) +
" و" +
this.tens["_" + Array.from(d.toString())[0] + "0"]
);
}
};
Tafgeet.prototype.readHundreds = function (d) {
var str = "";
str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];
if (
Array.from(d.toString())[1] === "0" &&
Array.from(d.toString())[2] !== "0"
) {
str += " و" + this.readOnes(Array.from(d.toString())[2]);
}
if (Array.from(d.toString())[1] !== "0") {
str +=
" و" +
this.readTens(
(Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
);
}
return str;
};
Tafgeet.prototype.length = function () {
return Array.from(this.digit.toString()).length;
};
Tafgeet.prototype.getColumnIndex = function () {
var column = null;
if (this.length() > 12) {
column = 0;
} else if (this.length() <= 12 && this.length() > 9) {
column = 1;
} else if (this.length() <= 9 && this.length() > 6) {
column = 2;
} else if (this.length() <= 6 && this.length() >= 4) {
column = 3;
}
return column;
};
Tafgeet.prototype.ones = {
_1: "واحد",
_2: "ٱثنين",
_3: "ثلاثة",
_4: "أربعة",
_5: "خمسة",
_6: "ستة",
_7: "سبعة",
_8: "ثمانية",
_9: "تسعة"
};
Tafgeet.prototype.teens = {
_11: "أحد عشر",
_12: "أثني عشر",
_13: "ثلاثة عشر",
_14: "أربعة عشر",
_15: "خمسة عشر",
_16: "ستة عشر",
_17: "سبعة عشر",
_18: "ثمانية عشر",
_19: "تسعة عشر"
};
Tafgeet.prototype.tens = {
_10: "عشرة",
_20: "عشرون",
_30: "ثلاثون",
_40: "أربعون",
_50: "خمسون",
_60: "ستون",
_70: "سبعون",
_80: "ثمانون",
_90: "تسعون"
};
Tafgeet.prototype.hundreds = {
_100: "مائة",
_200: "مائتين",
_300: "ثلاثمائة",
_400: "أربعمائة",
_500: "خمسمائة",
_600: "ستمائة",
_700: "سبعمائة",
_800: "ثمانمائة",
_900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
singular: "ألف",
binary: "ألفين",
plural: "ألآف"
};
Tafgeet.prototype.milions = {
singular: "مليون",
binary: "مليونين",
plural: "ملايين"
};
Tafgeet.prototype.bilions = {
singular: "مليار",
binary: "مليارين",
plural: "مليارات"
};
Tafgeet.prototype.trilions = {
singular: "ترليون",
binary: "ترليونين",
plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];
Tafgeet.prototype.currencies = {
SDG: {
singular: "جنيه سوداني",
plural: "جنيهات سودانية",
fraction: "قرش",
fractions: "قروش"
},
SAR: {
singular: "ريال سعودي",
plural: "ريالات سعودية",
fraction: "هللة",
fractions: "هللات"
},
QAR: {
singular: "ريال قطري",
plural: "ريالات قطرية",
fraction: "درهم",
fractions: "دراهم"
},
AED: {
singular: "درهم أماراتي",
plural: "دراهم أماراتية",
fraction: "فلس",
fractions: "فلوس"
},
EGP: {
singular: "جنيه مصري",
plural: "جنيهات مصرية",
fraction: "قرش",
fractions: "قروش"
},
USD: {
singular: "دولار أمريكي",
plural: "دولارات أمريكية",
fraction: "سنت",
fractions: "سنتات"
},
AUD: {
singular: "دولار أسترالي",
plural: "دولارات أسترالية",
fraction: "سنت",
fractions: "سنتات"
},
TND: {
singular: "دينار تونسي",
plural: "دنانير تونسية",
fraction: "مليم",
fractions: "مليمات"
}
};
module.exports = Tafgeet;
Thanks.
Change this:
this.fraction = "" + trimmed[0] + trimmed[1];
To this:
this.fraction = "" + trimmed[0] + trimmed[1] + trimmed[2];
But this is a crude solution you need to do some validations and checks before you deploy this to production
I'm writing a math problem generator, but when I run it only equations with 2 numbers are displayed, anything more and it says "undefined" and refuses to show the answer. Here is the entire code(please note it is incomplete right now)
var type = 0;
var ans = 0;
function generatenumeral() {
var num = (Math.round(1000 * Math.random())) / 100;
var abs = Math.random();
if (abs < .4) {
num = num * -1;
}
console.log(num);
return (num);
}
function generatelength() {
var num = (Math.ceil(3 * Math.random()));
console.log(num);
return (num);
}
function generateSymbol() {
var sign = 0;
var num = (Math.round(12 * Math.random()));
console.log(num);
if (num === 0 || num == 1 || num == 9) {
sign = "+";
};
if (num === 2 || num == 3 || num == 10) {
sign = "-";
};
if (num === 4 || num == 5 || num == 11) {
sign = "/";
};
if (num === 6 || num == 7 || num == 12) {
sign = "*";
};
if (num == 8) {
sign = "+";
};
return (sign);
}
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
function twoNumb() {
var sign = 0;
var equation = 0;
var a = generatenumeral();
var b = generatenumeral();
var siggn = generateSymbol();
equation = a + " " + siggn + " " + b;
if (siggn == "+") {
ans = a + b;
}
if (siggn == "-") {
ans = a - b;
}
if (siggn == "/") {
ans = a / b;
}
if (siggn == "*") {
ans = a * b;
}
return (equation);
}
function threNumb() {
var sign = 0;
var a = generatenumeral();
var b = generatenumeral();
var c = generatenumeral();
var siggn = generateSymbol();
var siggnA = generateSymbol();
var equation = a + " " + siggn + " " + b +" "+ siggnA +" "+ c;
if (siggn.equals("+")) {
if (siggna.equals("+")) {
ans = a + b + c;
}
if (siggna.equals("-")) {
ans = (a + b) - c;
}
if (siggna.equals("/")) {
ans = a + (b / c);
}
if (siggna.equals("*")) {
ans = a + (b * c);
}
}
if (siggn.equals("-")) {
if (siggna.equals("+")) {
ans = a - b + c;
}
if (siggna.equals("-")) {
ans = (a - b) - c;
}
if (siggna == "/") {
ans = a - (b / c);
}
if (siggna.equals("*")) {
ans = a - (b * c);
}
}
if (siggn.equals("/")) {
if (siggna.equals("+")) {
ans = (a / b) + c;
}
if (siggna.equals("-")) {
ans = (a / b) - c;
}
if (siggna.equals("/")) {
ans = (a / b) / c;
}
if (siggna.equals("*")) {
ans = (a / b) * c;
}
}
if (siggn.equals("*")) {
if (siggna.equals("+")) {
ans = (a * b) + c;
}
if (siggna.equals("-")) {
ans = (a * b) - c;
}
if (siggna.equals("/")) {
ans = (a * b) / c;
}
if (siggna.equals("*")) {
ans = (a * b) * c;
}
}
// if (siggn == "^") {
// var ba = Math.round(b);
// var count = 0;
// for (count = 0; count < ba; count += 1) {
// var ab = ab * a;
// }
// ans = ab;
return (equation);
}
document.getElementById("ans").innerHTML = "not yet";
function arithmetic() {
type = 1;
document.getElementById("demo").innerHTML = WarmUpAr();
}
function preAlg() {
type = 2;
document.getElementById("demo").innerHTML = "hello";
}
function Alg() {
type = 3;
document.getElementById("demo").innerHTML = "This is cool";
}
function theAns() {
document.getElementById("ans").innerHTML = ans;
}
<p> "your warm up is....." </p>
<button onclick="arithmetic()">Arithmetic Warm Up </button>
<button onclick="preAlg()">PreAlg Warm Up </button>
<button onclick="Alg()">Algerbra Warm Up </button>
<p id="demo"></p>
<p>the answer is ....</p>
<button onclick="theAns()">answer</button>
<p id="ans"></p>
You forgot to close the WarmUpAr funtion,that's why you are getting undefined error
close this function WarmUpAr();
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
}
The reason threNumb() is failing is because your calling siggna.equals() in all your if statements. twoNumb() works because your using == instead of equals().
Also, in terms of calculating the answer to the equation, your doing it the hard way. In twoNumb() and threNumb() everything between where you set the 'equation' variable and where you return the 'equation' can be replaced with:
ans = eval(equation);
I want my HTML page to show me the events/ in this case birthday(s) of this day.
But my Code doesn't work.
function birthday() {
var event = [];
var temp = [];
event[0] = ["31.10.1991", "test1"];
event[1] = ["11.12.2015", "TestToday"];
var datum = new Date();
var today = today.getDate();
var month = today.getMonth() + 1;
for (i = 0; i < event.length; i++) {
if (event[i]) {
if (event[i][0] == today && event[i][0] == month) {
event[i][0] = temp[i];
}
}
else {
break;
}
}
if (temp.length == 0) {
document.write("Today nobody has a birthday");
}
else {
var x2 = "Today " + ((temp.length == 1) ? "has" : "have");
for (i = 0; i < temp.length; i++) {
x2 += ((temp[i] > 0) ? ((temp[i] == (temp.length - 1)) ? " and " : ", ") : " ") + temp[event[1]][3] + "(" + temp[event[i]][2] + ")";
}
document.write(x2 + " birthday");
}
}
Question1: Where are my mistakes and how can I make it work?
Question2: How can the program take the dates out of a excel sheet?
In JavaScript you define arrays using [];
I don't speak German so i don't know what you need to print
function birthday() {
var Geb = [];
var ausgabe = [];
Geb[0] = ["31.10.1991", "Test1"];
Geb[1] = ["23.11.2000", "Testheute"];
var datum = new Date(); //Datums Objekt
var heute = datum.getDate(); //Tage 1-31
var monat = datum.getMonth() + 1; //Monate von 0-11
for (i = 0; i < Geb.length; i++) {
if (Geb[i]) {
if (Geb[i][0] == heute && Geb[i][0] == monat) {
Geb[i][0] = ausgabe[i];
}
}
else {
break;
}
}
if (ausgabe.length == 0) {
document.write("Heute hat niemand Geburtstag");
}
else {
var x2 = "Heute " + ((ausgabe.length == 1) ? "hat" : "haben");
for (i = 0; i < ausgabe.length; i++) {
x2 += ((ausgabe[i] > 0) ? ((ausgabe[i] == (ausgabe.length - 1)) ? " und " : ", ") : " ") + ausgabe[Geb[i1]][3] + "(" + ausgabe[Geb[i]][2] + ")";
}
document.write(x2 + " Geburtstag");
}
}
birthday();