Javascript- randomize 8 groups of 4 - javascript

This is my code for my final, objective is to create 8 groups of 4 in each group and than, ask what country are you looking for, than tell person which group they are in.
/*This program will create the 2026 world cup groups (8 groups 0f 4) with the countries for each group
being randomly seleceted from the list of countries*/
println("2026 World Cup Groups");
println(" 🏆🏆🏆");
println(" ");
var countries = ["Mexico🇲🇽", "Brazil🇧🇷", "Poland🇵🇱", "Argentina🇦🇷", "Uruguay🇺🇾",
"England🏴󠁧󠁢󠁥󠁮󠁧󠁿", "Spain🇪🇸", "Germany🇩🇪", "Portugal🇵🇹", "Morocco🇲🇦",
"Croatia🇭🇷", "Cameroon🇨🇲", "USA🇺🇸", "Ecuador🇪🇨", "Japan🇯🇵", "Saudi Arabia🇸🇦",
"Canada🇨🇦", "Senegal🇸🇳", "Netherlands🇳🇱", "Costa Rica🇨🇷", "Colombia🇨🇴",
"Wales🏴󠁧󠁢󠁷󠁬󠁳󠁿", "Belgium🇧🇪", "Serbia🇷🇸", "Italy🇮🇹" , "France🇫🇷", "Australia🇦🇺",
"Denmark🇩🇰", "Tunisia🇹🇳", "Ghana🇬🇭", "Korea Republic🇰🇷", "Qatar🇶🇦"];
function start(){
var groupA = [];
var groupB = [];
var groupC = [];
var groupD = [];
var groupE = [];
var groupF = [];
var groupG = [];
var groupH = [];
for(let i = 0; i < 4; i++){
groupA.push(groupRandomizer(countries));
groupB.push(groupRandomizer(countries));
groupC.push(groupRandomizer(countries));
groupD.push(groupRandomizer(countries));
groupE.push(groupRandomizer(countries));
groupF.push(groupRandomizer(countries));
groupG.push(groupRandomizer(countries));
groupH.push(groupRandomizer(countries));
}
println("Group A:");
println(groupA);
println(" ");
println("Group B:");
println(groupB);
println(" ");
println("Group C:");
println(groupC);
println(" ");
println("Group D");
println(groupD);
println(" ");
println("Group E:");
println(groupE);
println(" ");
println("Group F:");
println(groupF);
println(" ");
println("Group G:");
println(groupG);
println(" ");
println("Group H:");
println(groupH);
println(" ");
var lookForCountry = readLine("What country are you looking for? " );
/*this if function will take the country that you inputed in lookForCountry and
return a line telling you what group that country is located in*/
if(lookForCountry == groupA){
println(lookForCountry + "is in group A");
}
}
function groupRandomizer(arr){
var randomizer = Randomizer.nextInt(countries.indexOf[0],
countries.indexOf[31]);
return arr[randomizer];
}
this is the code, this is the error
if you guys know what I am doing wrong please let me know. I would appreciate it.
Again
the objective of this code is to randomize 8 groups, each group containing 4 countrys
than ask which country are they looking for
than display where that country is.

If you can change everything in the code, this version seems simple
let countries = ["Mexico🇲🇽", "Brazil🇧🇷", "Poland🇵🇱", "Argentina🇦🇷", "Uruguay🇺🇾",
"England🏴󠁧󠁢󠁥󠁮󠁧󠁿", "Spain🇪🇸", "Germany🇩🇪", "Portugal🇵🇹", "Morocco🇲🇦",
"Croatia🇭🇷", "Cameroon🇨🇲", "USA🇺🇸", "Ecuador🇪🇨", "Japan🇯🇵", "Saudi Arabia🇸🇦",
"Canada🇨🇦", "Senegal🇸🇳", "Netherlands🇳🇱", "Costa Rica🇨🇷", "Colombia🇨🇴",
"Wales🏴󠁧󠁢󠁷󠁬󠁳󠁿", "Belgium🇧🇪", "Serbia🇷🇸", "Italy🇮🇹" , "France🇫🇷", "Australia🇦🇺",
"Denmark🇩🇰", "Tunisia🇹🇳", "Ghana🇬🇭", "Korea Republic🇰🇷", "Qatar🇶🇦"];
countries = countries.map( name => ({name, group: null}) );
const order = new Array(countries.length).fill().map( (_, i) => i);
const groups = [[]];
for( let i of order ) {
let currentGroup = groups[groups.length-1];
if( currentGroup.length === 4 ) {
currentGroup = [];
groups.push(currentGroup);
}
countries[i].group = groups.length;
currentGroup.push(countries[i]);
}
function findInGroup(name) {
const found = countries.find( c => c.name.toLowerCase().startsWith(name.toLowerCase() ) );
if( !found ) {
console.log('Cannot found');
return;
}
console.log(found);
}
console.log(groups);
findInGroup('Mexi');

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

alert 2 arrays in same line javascript

I have a problem alerting out 2 arrays on same line in Javascript. The user should write Movie name and movie rating(1-5) 5 times, and printMovies() function should print out users (movie)name and (movie)rating in a single line something like this:
Movie Rating
Star Wars 5
Lord of the Rings 4
Casino 4
Movie4 3
Movie5 2
How do I alert out all of five inputs in a single line (movie + rating) per line, AFTER they have got input from user?
//CODE
var title;
var rating;
var a = [];
var movies = [];
var ratings = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
}
function addMovie(title, rating) {
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title);//Pushing title to movies
a.push(movies);//Pushing movies to a array
ratings.push(rating);//Pushing rating to ratings
a.push(ratings);//Pushing ratings to a array
printMovies()
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[0][0] + " " + a[0][1]);//Here is my biggest problem!
}
}
You problem is in the addMovie function your push the array to array. that means structure of the a is
a = [['title'] , ['rating'] , ['title','title1'],['rating',ratting1],......]
Try this with json object.
var movies = [];
function addMovie(title, rating) {
var movie = {};
do {
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movie.title = title;
movie.ratings = rating; movies.push(movie);
}
function printMovies() {
for (var i = 0; i < movies.length; i++) {
alert(movies[i].title + " " + movies[i].ratings);
}
}
function buttonAddMovie()//Button onclick
{
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
printMovies();
}
<html>
<head>
<script>
var arr = [{
"Movie": "Movie1",
"Rating": 1
}, {
"Movie": "Movie2",
"Rating": 2
}, {
"Movie": "Movie3",
"Rating": 2
}, {
"Movie": "Movie5",
"Rating": 4
}, {
"Movie": "Movie4",
"Rating": 5
}, ];
var str = "";
for (var i = 0; i < arr.length; i++) {
str += "Movie Name: " + arr[i].Movie + " || Rating: " + arr[i].Rating + "\n";
}
alert( "Json Iterated Output \n" + str);
</script>
</head>
</html>
The reason it wasn't working was you had an array, a.
You pushed the movie name to 'a'
a = ['Movie name'];
But then you pushed the rating to 'a' separately
a = ['Rating'];
So the movie's name was replaced with rating, hence the alerts saying '(movie's name) undefined', then '(movie's rating) undefined'.
What I've done is removed the rating array and pushed the movie name and rating at the same time.
Also, I've changed the for loop to display the current movie by changing
alert(a[0][0] + " " + a[0][1]);
to
alert(a[i][0] + " " + a[i][1]);
otherwise it will always display the first movie rating.
var title;
var rating;
var a = [];
var movies = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating, document.getElementById('quantity').value)
}
function addMovie(title, rating, amount) {
for(var count = 0; count < amount; count++){
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title,rating);//Pushing title to movies
a.push(movies);//Pushing movies to a array
movies = [];
}
printMovies();
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[i][0] + " " + a[i][1]);
document.getElementById('movielist').innerHTML+= "<li>"+a[i][0]+" - "+a[i][1]+"</li>"; // Adds movies to the <ul>
}
}
<h2>Add</h2>
<input id='quantity' placeholder='Amount of movies you want to add' /><br>
<button onclick='buttonAddMovie();'>Add Movies</button>
<h2>Movie list</h2>
<ul id='movielist'></ul>
Now you can stack as many as you want by writing the number in the input tag.
The movies are then displayed at the end in an unformatted list.
Very basic code, but I hope it helps.

How to sort the string based on numbers present in it, separated by (.)

Hi I want to sort the string based on numbers present in it
e.g
1.1.act2
13.1.2.1.act3
2.1.4.act56
1.3.actorg
3.1.3.args
13.1.3.4.acr
I want to this in a manner
1.1.act2
1.3.actorg
2.1.4.act56
3.1.3.args
13.1.2.1.act3
13.1.3.4.acry
How do I achieve it in javascript?
You can use the Arrays sort method with a custom iterator function. e.g:
mylist = ["1.1.act2", "13.1.2.1.act3", "2.1.4.act56", "1.3.actorg", "3.1.3.args", "13.1.3.4.acr"];
mylist.sort(function(a, b) {
a = a.split("."); b = b.split(".");
var parts = Math.min(a.length, b.length);
for(var i = 0; i < parts; ++i) {
var numA = parseInt(a[i]); var numB = parseInt(b[i]);
if (numA != numB)
return numA > numB;
}
});
This is a stub and untested, but I guess you see where I'm heading
Try this. This code is not optimized but it works
<script type="text/javascript">
function fnc()
{
var arr=new Array();
arr[0]="1.1.act2";
arr[1]="13.1.2.1.act3";
arr[2]="2.1.4.act56";
arr[3]="1.3.actorg";
arr[4]="3.1.3.args";
arr[5]="13.1.3.4.acr";
var it0=arr[0].split(".");
var it1=arr[1].split(".");
var it2=arr[2].split(".");
var it3=arr[3].split(".");
var it4=arr[4].split(".");
var it5=arr[5].split(".");
var newarr=new Array();
newarr[0]=parseInt(it0[0],10);
newarr[1]=parseInt(it1[0],10);
newarr[2]=parseInt(it2[0],10);
newarr[3]=parseInt(it3[0],10);
newarr[4]=parseInt(it4[0],10);
newarr[5]=parseInt(it5[0],10);
newarr.sort(function(a,b){return a-b});
alert(newarr);
for(i=0;i<arr.length;i++)
{
if(newarr[i]==it0[0])
{console.log(arr[0]);}
else if(newarr[i]==it1[0])
{console.log(arr[1]);}
else if(newarr[i]==it2[0])
{console.log(arr[2]);}
else if(newarr[i]==it3[0])
{console.log(arr[3]);}
else if(newarr[i]==it4[0])
{console.log(arr[4]);}
else if(newarr[i]==it5[0])
{console.log(arr[5]);}
else if(newarr[i]==it6[0])
{console.log(arr[6]);}
}
}
<input type="button" onclick="fnc()" value="click" />

Check if Number entered is correct By ID - JavaScript

Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}

Javascript String issue

i am trying to concat a query value into a link
wwww.test/video (query value) ".flv"
altought i think i did something wrong.
function doSomething() {
var test = new StringBuilderEx();
var a = querySt("number");
test.append("<h1>test</h1> ");
test.append("<a ");
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
test.append("Style =\"display:block;width:425px;height:300px;\" ");
test.append("id=\"player\" ");
test.append("</a> ");
test.append("<script language=\"JavaScript\" ");
test.append("> ");
test.append("flowplayer(\"player\" ");
test.append(", \"flowplayer-3.2.2.swf\" ");
test.append("); <\/script>");
return test.toString()
}
at the end all i get is a link with test.com/video and the the passed value. The StringBuilderEx is a JS script and queryST is
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
So it would be awesome if i get to know what am i not getting
where 1 is the query number.
href="http://test.com/video1.flv"
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
You have an extraneous \" there.
test.append("href=\"http://test.com/video" + a + ".flv\" ");
Also a missing >
test.append("id=\"player\" ");
should be
test.append("id=\"player\">");
Also, your link has no content to click on
test.append("</a> ");
should be
test.append("Click me!</a> ");

Categories