Javascript - write duplicates in array to html - javascript

I need to write a function that creates an array of random numbers between 1 and 20 and prints each number in a table. If it's a duplicate of a number that has already been generated, it needs to be highlighted in red.
My issue is that after the first duplicate has been printed in red, if there is another, it would not be printed in red. I can't get it to work for more than one time.
Here's the output:
Here's my code:
function randomNumberTable(){
// create array with random numbers
var nums = new Array();
for(var i = 0; i < 10; i++){
nums[i] = randomNumber();
}
// create header row
document.writeln("<table border = \"1\">");
document.writeln("<th>Index</th>");
document.writeln("<th>Number</th>");
// if duplicate, print in red, else, black
for(var j = 0; j <= nums.length-1; j++){
var isExist = numberExists(nums[j], nums, j);
if (isExist){
document.writeln("<tr>");
document.writeln("<td>" + j + "</td>");
document.writeln("<td><font color=\"red\">" + nums[j] + "</font></td>");
document.writeln("</tr>");
}
else{
document.writeln("<tr>");
document.writeln("<td>" + j + "</td>");
document.writeln("<td>" + nums[j] + "</td>");
document.writeln("</tr>");
}
}
}
// generate a random number between 1 and 20
function randomNumber(){
var randomNum = Math.floor(Math.random()*20) + 1;
return randomNum;
}
// checking if the number exists
function numberExists(num, myArray, myIndex){
for(var k = 0; k < myIndex; k++){
if(num == myArray[k])
return true;
else
return false;
}
}

change your numberExists function like this.
function numberExists(num, myArray, myIndex){
for(var k = 0; k < myIndex; k++){
if(num == myArray[k])
return true;
}
return false;
}

Related

Simple Javascript Christmas Tree

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("&nbsp&nbsp");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write("&nbsp");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>

Exercise with a loop in javascript

I need for an university exercise to display onscreen with a document.write the tree below using a kind of loop:
I used at the beginning a for loop but i printed only the first row... someone can help me?
This is what I tried:
var numbers = [0, 1, 2, 3, 4]
for (var i = 0; i <= numbers.length; i++) {
if (numbers [i] == 0) {
document.write(" * </br>");
}
if (numbers [i] == 1) {
document.write(" *** </br>");
}
if (numbers [i] == 2) {
document.write(" ****** </br>");
}
if (numbers [i] == 3) {
document.write(" ******* </br>"); }
if (numbers [i] == 4) {
document.write("********* </br>");
}
return
}
Thank You!
I'm going to give you a "golfed-ish" (goldfish? should this be a thing?) version of the code. In other words, the smallest, most obscure code I can think of to accomplish the task. You should not use this, because your teacher will undoubtedly ask you what it means and you won't know, but I'm bored XD
var size = 5;
document.write("<center>"+Array.apply(0,new Array(size)).map(function(_,i) {return new Array((i+1)*2).join(" * ");}).join("<br>")+"</center>");
Demo
As I said, don't use this :p
Here is my code for you ...
<html>
<head>
<script type="text/javascript" language="javascript">
document.write("<center>"); //write a center tag to make sure the pyramid displays correctly(try it without this step to see what happens)
for(var i = 0; i <= 10; i++) //a loop, this counts from 0 to 10 (how many rows of stars)
{
for(var x = 0; x <= i; x++)// a loop, counting from 0 to whatever value i is currently on
{
document.write("*");//write a * character
}
document.write("<br/>"); //write a br tag, meaning new line, after every star in the row has been created
}
document.write("</center>"); //close the center tag, opened at the beginning
</script>
</head>
<body>
</body>
</html>
Adds spaces and fully extendable
function pyramid(lines, char) {
var start = 2,html = '<pre>';
for (var i=lines; i--;) {
html += new Array(Math.floor(i+1)).join(' ') + new Array((start=start+2)-2).join(char) + '<br />';
}
return html + '</pre>';
}
document.write( pyramid(5, '*') );
FIDDLE
function pyramidStar(n) {
var str = "";
for(var i=1; i<=n; i++) {
for(var j=1; j<=n-i; j++) {
str += " ";
}
for(var k=n-i+1; k<n+i; k++) {
str += "* ";
}
for(var m=n+i; m<=2*n-1; m++) {
str += " ";
}
str += "\n";
}
return str;
}
document.getElementById("result").innerHTML = pyramidStar(9);
<pre id="result"></pre>
Another way of printing pyramid of stars.
<pre><script>
for (var i = 0; i < 5; i++) {
for (var c = 0; c < 9; c++) {
if (Math.abs(4 - c) <= i)
document.write("*");
else
document.write(" ");
}
document.write("<br />");
}
</script></pre>
It is a simple version with document.write(). The only complicated thing is Math.abs which gives the distance from the middle.
PS: watch out for magic numbers
function star(n) {
for (var i = 1; i <= n; i++) {
for (var j = i; j < n; j++) {
document.write("-");
}
for (var k = 1; k <= (2 * i) - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
}
//function calling
star(9);

Javascript Loto Game

How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();

changing 2 random numbers in 30 times in number table using java script

In this code each time you open the html page two random numbers are generated and thier location in the matrix will be changed.
for example the random numbers are 2,8
in the main table 2 is in the matrix[0][1],matrix[1][7],matrix[2][4],matrix[3][0],matrix[4][6],matrix[5][3],matrix[6][8],matrix[3][0],matrix[7][5]
,matrix[8][2] .in the result table 8 is set in these location and 2 is set in the current locations of 8.
I want to repeat this, 30 times.
so far I have :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
document.writeln('<table border="1">');
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
document.writeln("The result table is:");
for(i=0; i<9; i++)
{
document.writeln('<tr>');
for(j=0; j<9; j++)
{
if(matrix[i][j]==r1)
{
matrix[i][j]=r2;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
else if(matrix[i][j]!=r1 && matrix[i][j]!=r2)
document.writeln('<td>' + matrix[i][j] + '</td>');
else if(matrix[i][j]==r2)
{
matrix[i][j]=r1;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
</script>
</body>
</html>
I would change your code slightly.
First, I'd make a method to print the table:
function printMatrix(var matrix)
{
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
}
Then, I'd make a method for the swapping:
function sawpTwoNumbers(matrix)
{
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
// This is new code:
for(int i=0; i< matrix.length; i++){
var r1Index = matrix[i].indexOf(r1);
var r2Index = matrix[i].indexOf(r2);
matrix[i][r1Index] = r2;
matrix[i][r2Index] = r1;
}
}
Next, I'd put your code in the pageLoad method:
function pageLoad()
{
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
printMatrix(matrix);
// This is new code:
// It will call the swap method and the print method 30 times.
for(int i = 0; i < 30; i++)
{
swapTwoNumbers(matrix);
printMatrix(matrix);
}
}
Please Note: I haven't tested this code. I don't guarantee that it works. I hope it'll give you a push in the right direction though.

Javascript: getting rid of nested loop

It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});

Categories

Resources