I tried to make a code that returns many "9" characters to a string according to an int value.
Ej.: If "y" is equal to 5, "w" should return "99999".
I used the "for" instruction, but it makes the tab freeze.
The code:
var w = "";
var y = "";
function Calc()
{
x = document.getElementById("inputX").value;
y = document.getElementById("inputY").value;
for (var i; i = y.length; i++)
{
w += 9;
}
}
Thanks! (and sorry for my bad english).
I have updated your code. I have changed the condition in the for loop and and initialized i variable.
function Calc()
{
var w = "";
var y = "";
x = document.getElementById("inputX").value;
y = document.getElementById("inputY").value;
for (var i = 0; i < y.length; i++)
{
w += 9;
}
console.log(w);
}
X : <input type="text" id="inputX"><br>
Y : <input type="text" id="inputY"><br>
<button type="button" onclick="Calc()">Calculate</button>
Related
I am making tetris in JS. When making a block fall, it makes the block reach the bottom of the screen in one draw instead of slowly approaching the bottom. I tried creating a variable that stores the changes to be made so that it only looks at the current board, but no luck. After checking whether the output variable is == to the board, it seems like the board is changing after all, as it returns true. What's going on?
EDIT: I have successfully made a shallow copy of the array. It still falls to the bottom immediately, though. What's going on?
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x-1; i++) {y.push(text);}
return y;
}
for (var i=0; i<20; i++){data.push(array(10, "b"));}
function draw(){
var j;
var i;
var dataOut = [...data];
for (i = 0; i < data.length - 1; i++){
for (j = 0; j < data[i].length; j++){
if (data[i][j] == "a" && data[i + 1][j] == "b" && i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
data = dataOut;
}
data[0][4] = 'a';
draw();
console.log(data);
In JavaScript, Arrays and Objects are passed by reference. So when you do this:
var dataOut = data;
Both of these references point to the same Array. You could clone the Array every time:
var dataOut = JSON.parse(JSON.stringify(data));
Or simply revert your loop, to go from the bottom to the top. I took the liberty of renaming the variables to make this more clear. Try it below:
var chars = {empty: '.', block: '#'},
grid = createEmptyGrid(10, 20);
function createEmptyGrid(width, height) {
var result = [], x, y;
for (y = 0; y < height; y++) {
var row = [];
for (x = 0; x < width; x++) {
row.push(chars.empty);
}
result.push(row);
}
return result;
}
function draw() {
var x, y;
for (y = grid.length - 1; y > 0; y--) {
for (x = 0; x < grid[y].length; x++) {
if (grid[y][x] === chars.empty && grid[y - 1][x] === chars.block) {
grid[y][x] = chars.block;
grid[y - 1][x] = chars.empty;
}
}
}
}
// Just for the demo
var t = 0, loop = setInterval(function () {
draw();
if (grid[0].includes(chars.block)) {
clearInterval(loop);
grid[9] = 'GAME OVER!'.split('');
}
document.body.innerHTML = '<pre style="font-size:.6em">'
+ grid.map(row => row.join(' ')).join('\n')
+ '</pre>';
if (t % 20 === 0) {
grid[0][Math.floor(Math.random() * 10)] = chars.block;
}
t++;
}, 20);
I tried to code a Ceasar Cipher coder as an exercise in school.
I have encountered a problem where the letters x, y, and z come out as undefined.
function txtcipher() {
var txt = document.getElementById("txt").value;
var txtlen = txt.length;
var txtciphered = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (x = 0; x < txtlen; x++) {
for (y = 0; y < alphabet.length; y++) {
if (txt[x] === alphabet[y]) {
txtciphered += alphabet[y + 3];
}
}
}
document.getElementById("cpher").value = txtciphered;
console.log(txtciphered);
}
<input id="txt" />
<button onclick="txtcipher()">Check</button><br />
<input type="text" id="cpher" readonly></input>
How do I fix this?
You need to stay in the bounds of array length of alphabet array
Instead of
y + 3
use
(y + 3) % alphabet.length
function txtcipher() {
var txt = document.getElementById("txt").value;
var txtlen = txt.length;
var txtciphered = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (x = 0; x < txtlen; x++) {
for (y = 0; y < alphabet.length; y++) {
if (txt[x] === alphabet[y]) {
txtciphered += alphabet[(y + 3) % alphabet.length];
}
}
}
document.getElementById("cpher").value = txtciphered;
console.log(txtciphered);
}
<input id="txt" value="xyzabc"/>
<button onclick="txtcipher()">Check</button><br />
<input type="text" id="cpher" readonly placeholder="abcdef <-- xyzabc"></input>
You are just going out of array bounds - here:
txtciphered += alphabet[y + 3];
when y is bigger than alphabet.length - 3
I tried making mean deviation calculator using javascript but when I try to output the summation of |x-x̅|, It always returns 0;
var frequencies = []
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = scoreMinusMean
}
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
In your last loop, the condition you have is k < scoreMinusMean, you forgot to add .length there. It should be
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
Also, you should use let before declaring the variables or else they will be made global.
var frequencies = [];
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = summation
}
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
THe last four lines of your code should be:
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML =summation/frequencies.length
}
As you forgot the .length on the array, and for a standard deviation, you need to average the deviation again (ie. divide the total of deviations from the mean, by the number of elements).
I have learned in class how to make a function that generates all combinations of an inputted word. However, how to make it so that instead of a windowed prompt or alert popping up to enter the word and shows all combination on the prompt box, I want to display the result on the screen itself. How would i do that through the code i have already written?
This is my complete code:
<!DOCTYPE html>
<html>
<title>Combinations of a Word</title>
<body>
<script>
function combinations(str){
var substr = [];
for (var x = 0; x < str.length; x++)
{
for (var y = x + 1; y <= str.length; y++)
{
substr.push(str.substring(x,y));
}
}
return substr;
}
document.write(combinations(window.prompt("Please enter a word")));
</script>
</body>
</html>
Simply
<input type="text" id="word"/>
<div id="comb"></div>
JavaScript
function combinations(str) {
var substr = [];
for (var x = 0; x < str.length; x++) {
for (var y = x + 1; y <= str.length; y++) {
substr.push(str.substring(x, y));
}
}
return substr;
}
var input = document.getElementById('word');
var out = document.getElementById('comb');
input.addEventListener('keyup', function(e){
out.innerHTML = combinations(this.value).join(',');
});
FIDDLE
PS - your combinations code is wrong
For some odd reason that I can't figure out, the code won't work when I have these if/else statements inside it, it works fine when they aren't there. I assume it's something to do with the condition I've attached to the if/else statements, as when simpler conditions are used it seems all right. Can someone please tell me what I'm doing wrong?
function wordSplit(){
var sentence = document.getElementById("two").value;
var userWords=sentence.split(" ");
while(t<userWords.length){
alert(userWords[t]);
t++
};
x = 0;
for (var x = 0; x < userWords.length; x++){
y = 0;
for (var y = 0; y < vocab.length; y++){
if (y<vocab.length) {
y++
};
else if (vocab[y] == userWords[x]){
y = 0;
x++
};
else if(y<vocab.length) {
y++
};
else if (y == vocab.length){
y = 0;
};
else if (y == 0)
{
vocab.push(userWords[x]);
x++
};
};
};
};
To reiterate, as far as I can tell the problem is definitely in that if else section, as when it is removed or altered to be a lot simpler, it suddenly works.
#DCoder is correct, you need to drop the extra ;
HTML:
<input type="text" id="two" value="What the hell is wrong here??" />
JavaScript:
wordSplit();
function wordSplit() {
var vocab = [];
var sentence = document.getElementById("two").value;
var userWords = sentence.split(" ");
var t = 0;
while (t < userWords.length) {
alert(userWords[t]);
t++
};
x = 0;
for (var x = 0; x < userWords.length; x++) {
y = 0;
for (var y = 0; y < vocab.length; y++) {
if (y < vocab.length) {
y++
} else if (vocab[y] == userWords[x]) {
y = 0;
x++
} else if (y < vocab.length) {
y++
} else if (y == vocab.length) {
y = 0;
} else if (y == 0) {
vocab.push(userWords[x]);
x++
}
}
}
}
Fixed Live Demo