the following code is supposed to count the number of heads vs tails. The code below was given to me but I was tasked with counting heads vs tails, I tried with the function function countHeadsAndTails(flips) and below but running into a small issue. I have triple asterisked the line that is giving me an error: arr is not defined (under the function countHeadsAndTails(flips)) I'm sure this is just a silly mistake and I'd hate to waste your time with such an easy fix but I've been banging my head against the wall for the past 30 mins trying to solve it, thanks :)
var NUM_FLIPS = 100;
var headCount = 0, tailCount = 0;
function start(){
var flips = flipCoins();
printArray(flips);
}
// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
var flips = [];
for(var i = 0; i < NUM_FLIPS; i++){
if(Randomizer.nextBoolean()){
flips.push("Heads");
}else{
flips.push("Tails");
}
}
return flips;
}
function printArray(arr){
for(var i = 0; i < arr.length; i++){
println(i + ": " + arr[i]);
}
countHeadsAndTails();
}
function countHeadsAndTails(flips) {
for (var i = 0; i < NUM_FLIPS; i++) {
***if (arr["flips"] === "heads")***
headCount += arr[i];
else
tailCount += arr[i];
}
print("Heads: " + headCount + " " + "Tails: " + tailCount);
}
You have not declared the arr array as global, therefore you have to pass it to functions that are supposed to use it. The arr array is actually flips. I changed your code below to pass the array to the countHeadsAndTails() function and also added a couple other small changes to the same function (see arrows below).
Run and test:
var NUM_FLIPS = 100;
var headCount = 0, tailCount = 0;
function start(){
var flips = flipCoins();
printArray(flips);
}
// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
var flips = [];
for(var i = 0; i < NUM_FLIPS; i++){
if( Math.round(Math.random()) ){ // <- To mimic Randomizer
flips.push("Heads");
} else {
flips.push("Tails");
}
}
return flips;
}
function printArray(arr){
for(var i = 0; i < arr.length; i++){
console.log(i + ": " + arr[i]);
}
countHeadsAndTails(arr); // <- passing array to function
}
function countHeadsAndTails(flips) { // <- array is now called flips again
for (var i = 0; i < NUM_FLIPS; i++) {
if (flips[i] === "Heads") // <- check the ith element, and capital H
headCount++; // <- increment headCount
else
tailCount++; // <- increment tailCount
}
console.log("Heads: " + headCount + " " + "Tails: " + tailCount);
}
start();
Note: I also changed print() and println() to console.log() in order to be consistent with correct JavaScript output syntax.
Related
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
I need to count numbers upward and have it print out with a string "then" in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function name when you return. My code is below.. but could someone help with this?
function countUp(start) {
start +=
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
}
return start;
}
I would do something like this:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.
If you did want to build up a string and then have your function return it though, you could do something like this instead:
function countSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).
We can use JavaScript join function as well to achieve this
Code
function getCountStr(count) {
var str =[];
for (var i = 1; i <= count; i++) {
str.push(i);
}
console.log(str.join(' then '));
}
There are few issues with your code
function countUp(start) {
start += // <<<<< what's this? It's an incomplete (and useless) statement
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
// ^^^^^^^^ why are doing this? you should only write i
}
return start; // you don't need to return anything
}
A cleaned and working version from your code
function countUp(start) {
for(var i = start; i < start + 10; i++) {
console.log(i + " then ");
}
}
But this code will have an extra 'then' at the end like 1 then 2 then, so here's a code that will handle this
function countUp(start) {
// a temporary array to store your numbers
var tmpArr = [];
for (var i = start; i < start + 10; i++) {
// store the count into the array
tmpArr.push(i);
}
// display the count by putting ' then ' between each number
var stringToDisplay = tmpArr.join(' then ');
console.log(stringToDisplay);
document.write(stringToDisplay);
}
countUp(1);
Following were an output from an array returned by following function:
$scope.variantOptions = $scope.variantLists.join(", ");
medium,small,medium,small,small
How can I sort the result, so it represent the output as:
medium x 2,small x 3
EDIT
addCount function:
$scope.addCount = function($index){
$scope.counter = 1;
if($scope.activity['variant'][$index]['count'] != undefined ){
$scope.counter = parseInt($scope.activity['variant'][$index]["count"]) +1;
$scope.variantLists.push($scope.activity['variant'][$index]['variant_dtl_name']);
}
$scope.activity['variant'][$index]["count"] = $scope.counter;
console.log(arraySimplify($scope.variantLists));
};
Thanks!
pass your '$scope.variantLists' arry into this function it will give you the expected result.
function arraySimplify(arr){
arr.sort();
var rslt = [], element =arr[0] ,count = 0 ;
if(arr.length === 0) return; //exit for empty array
for(var i = 0; i < arr.length; i++){
//count the occurences
if(element !== arr[i]){
rslt.push(element + ' x ' + count);
count =1;
element = arr[i];
}
else{
count++;
}
}
rslt.push(element + ' x ' + count);
return rslt.join(', ');
}
Your code is working:
for (var i = 0;i < $scope.variantLists.length;i++) {
obj[arr[i]] = (obj[arr[i]] || 0) + 1;
}
Gives you an object:
obj = {medium: 2, small: 3}
To see it without having to go into the console, you can just alert the object after the 'for' loop:
alert(obj);
To get the EXACT string you want:
var string = "";
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var count = validation_messages[key];
string += key + " x " + count;
}
}
Although it may look like an entry in Code Golf but this is one of the rare times when Array.reduce makes sense.
var r = a.sort().reduce(
function(A,i){
A.set(i, (!A.get(i))?1:A.get(i)+1);
return A;
},new Map());
Which makes basically what Jon Stevens proposed but in a more modern and highly illegible way. I used a Map because the order in a normal Object dictionary is not guaranteed in a forEach loop. Here r.forEach(function(v,k,m){console.log(k + ":" + v);}) gets printed in the order of insertion.
Okay, trying to put together a numeric array and arrange it in ascending order. The more I look, the more I confuse myself. The alerts come up as "undefined." What am I overlooking?
var random = new Array();
function main() {
generate();
original();
ascending(random);
}
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = document.write(Math.floor(Math.random() * 100) + ", ");
}
}
function original() {
var storage = "";
for (var i = 0; i < 25; i++) {
storage += random[i] + ", ";
}
alert(storage);
}
function ascending(random) {
var tempArray = random;
var storage = "";
random.sort(function (a, b) {
return a - b
});
for (i = 0; i < 25; i++) {
storage += tempArray[i] + ", ";
}
alert("ASCENDING- " + storage);
}
No need for document.write (not sure what were you trying to achieve with it), this is enough:
random[i] = Math.floor(Math.random() * 100);
Afterwards, if you need to convert it to a string for output, just join it:
random.join(",");
Here is your generate function:
var random = [];
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = Math.floor(Math.random() * 100);
}
}
generate();
var str = random.join(', ');
document.write(str);
Note: try to avoid using document.write whenever you can.
Take out your document.write() call in generate(), that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.
Beginner here, eagerly trying to get my code to work.
I need to ask the user how many lines of "lottery coupons" they want. After the prompt the code outputs seven randomly generated numbers, line by line, as I wanted. But after each line, I get "undefined".
Why is this? I know I'm not too far off...
var ask = prompt("How many lines?");
function numbers() {
for(var i=0; i<7; i++) {
var line = Math.floor(Math.random()*39)+1;
document.write(line + ' ');
}
}
for(var x=0; x<ask; x++) {
document.write(numbers() + '<br>');
}
numbers() returns undefined, so you don't want to output it. Try:
var ask = prompt("How many lines?");
function numbers() {
for(var i=0; i<7; i++) {
var line = Math.floor(Math.random()*39)+1;
document.write(line + ' ');
}
}
for(var x=0; x<ask; x++) {
numbers();
document.write('<br>');
}
It because your numbers(); function doesn't have any defined return.
You can return an empty string. return "";
var ask = prompt("How many lines?");
function numbers() {
for (var i = 0; i < 7; i++) {
var line = Math.floor(Math.random() * 39) + 1;
document.write(line + ' ');
}
return "";
}
for (var x = 0; x < ask; x++) {
document.write(numbers() + '<br>');
}
You are writing the return value of calling numbers and then a line break element.
document.write(numbers() + '<br>');
The numbers function doesn't have a returnstatement , so it returns undefined.
You want:
numbers();
document.write('<br');
Because your numbers function isn't returning anything.
Here's an example with putting the numbers into an array and then joining them:
var ask = prompt("How many lines?");
function numbers() {
var nums = [];
for(var i=0; i<7; i++) {
nums.push(Math.floor(Math.random()*39)+1);
}
return nums.join(' ');
}
for(var x=0; x<ask; x++) {
document.write(numbers() + '<br>');
}
See a working example here: http://jsfiddle.net/6SHJE/1/