JavaScript, JSON : how can I run a foor loop a specific amount of time? - javascript

I have this code - its a bit tricky:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++;
output.current = input;
return JSON.stringify(output);
}
The output looks like this:
{"current":605,"sum":0}
{"current":708}
{"current":456}
{"current":1838,"sum":1769}
{"current":1619}
{"current":1404}
{"current":1068,"sum":6630}
{"current":1178}
{"current":989}
{"current":1280,"sum":9865}
But I want it to look like this:
{"current": 605}
{"current": 708}
{"current": 456}
{"current": 1838,"sum":1769}
{"current": 1619}
{"current": 1404}
{"current": 1068,"sum":6630}
{"current": 1178}
{"current": 989}
{"current": 1280,"sum":9865}
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {
"current": "0"
};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++;
output.current = input;
return JSON.stringify(output);
}
I don't want to show the sum the first time but later show it every 3 times
Got any ideas? :D
PS. I prefer staying basic and only use a for loop
Have a nice evening

Could you just check if the i is not zero when you assign the value of output.sum?
Something like the following:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
if (i !== 0) output.sum = sum; // HERE
}
i++;
output.current = input;
return JSON.stringify(output);
}

I found this out, yours is obviously shorter but here was my Idea :D
let i = 0;
const inputBuffer = [];
let db = false;
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (db && i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++
db = true;
output.current = input;
return JSON.stringify(output);
}

Related

How to push both sum of even and odd result from for loop into an array?

Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. Print sum of evens and sum of odds as array
Output: [2550, 2500]
let sumOfEven = 0;
let EvenOddArr = [];
for (let i = 0; i <= 100; i += 2) {
sumOfEven += i;
}
console.log(sumOfEven);
let sumOfOdd = 0;
for (let i = 1; i <= 100; i += 2) {
sumOfOdd += i;
}
console.log(sumOfOdd);
console.log(EvenOddArr);
You could take the remainder of two as index for the array.
const evenOddArr = [0, 0];
for (let i = 0; i <= 100; i++) evenOddArr[i % 2] += i;
console.log(evenOddArr);
You're nearly there - all you need is a couple of pushes
let sumOfEven = 0;
let EvenOddArr = [];
for (let i = 0; i <= 100; i += 2) {
sumOfEven += i;
}
EvenOddArr.push(sumOfEven)
let sumOfOdd = 0;
for (let i = 1; i <= 100; i += 2) {
sumOfOdd += i;
}
EvenOddArr.push(sumOfOdd)
console.log(EvenOddArr);
console.log(Array(101).fill().reduce((a,_,i)=>(a[i%2]+=i,a),[0,0]))
Here is an alternative for when you have studied JS a bit more
let sumArr = Array.from({ length: 101 })
.reduce((acc,_,i) => (acc[i % 2] += i, acc), [0, 0]);
console.log(sumArr);
An easy-to-understand version:
let sumOfEven = 0;
let sumOfOdd = 0;
for (let i = 0; i <= 100; i++) {
if (i % 2 === 0) {
sumOfEven += i;
} else {
sumOfOdd += i;
}
}
let evenOddArr = [sumOfEven, sumOfOdd];
console.log(evenOddArr);

How do I fix this cocktail shaker sort code to work?

I'm trying to write a code that sorts random numbers with different sorting alrorithms. I have 5 algorithms so far, including bubble sort, javascript built in sort, insertion sort, selection sort, and cocktail sort. I am also writing how many swaps and how much time each sort takes. Other sorts are working just fine( I think), but it seems like cocktail sort is not working.
I tried to modify that part of the code, but none of them worked. Here is the code below. I want it to work properly while displays how many swaps and how much time it took at the console. Thank you.
NUM_ELEMENTS = 500;
numbers = [];
function setup() {
createCanvas(400, 300);
for(i=0;i<=NUM_ELEMENTS;i++) {
numbers.push(round(random(1,NUM_ELEMENTS)));
}
para1 = createElement("p","");
tempString = "";
for(i=0;i<=NUM_ELEMENTS;i++) {
console.log(numbers[i]);
tempString = tempString + numbers[i] + ",";
}
para1.html(tempString);
button1 = createButton("Bubble Sort");
button1.mousePressed(bubbleSort);
button2 = createButton("Seclection Sort");
button2.mousePressed(selectionSort);
button3 = createButton("Insertion Sort");
button3.mousePressed(insertionSort);
button4 = createButton("Javascript Bulit-in Sort");
button4.mousePressed(bSort);
}
function bubbleSort() {
total = 0
swaps = 0
t1 = millis();
console.log("sorting")
let n = numbers.length;
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
if(numbers[j] > numbers[j+1]){
let t = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = t;
swaps = swaps + 1;
}
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :",swaps);
}
function selectionSort() {
let n = numbers.length;
console.log("Sorting...")
total = 0
t1 = millis();
swaps = 0
for(let i = 0; i < n; i++) {
let min = i;
for(let j = i+1; j < n; j++){
if(numbers[j] < numbers[min]) {
min=j;
swaps = swaps + 1;
}
}
if (min != i) {
let tmp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = tmp;
swaps = swaps + 1;
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :", swaps);
}
function insertionSort() {
console.log("sorting");
t1 = millis();
swaps = 0;
total = 0
let n = numbers.length;
for (let i = 1; i < n; i++) {
let current = numbers[i];
let j = i-1;
while ((j > -1) && (current < numbers[j])) {
numbers[j+1] = numbers[j];
swaps = swaps + 1;
j--;
}
numbers[j+1] = current;
}
t2 = millis();
console.log(t2-t1);
console.log("swaps : ", swaps);
}
function bSort() {
console.log("Sorting...")
total = 0
t1 = millis();
sort(numbers);
t2 = millis();
console.log(t2-t1);
console.log("swaps : unknown");
}
function cocktailSort() {
console.log("sorting...")
total = 0
swaps = 0
t1 = millis();
let n = numbers.length;
let sorted = false;
while (!sorted) {
sorted = true;
for (let i = 0; i < n - 1; i++) {
if (numbers[i] > numbers[i + 1]){
let tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = tmp;
sorted = false;
}
}
if (sorted)
break;
sorted = true;
for (let j = n - 1; j > 0; j--) {
if (numbers[j-1] > numbers[j]) {
let tmp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j+1] = tmp;
sorted = false;
}
}
}
t2 = millis();
console.log(t2-t1);
}
function draw() {
background(220);
textSize(13);
column = 10;
row = 0;
for (i=0;i<NUM_ELEMENTS;i++) {
if (i%18==0) {
column = column + 18;
row = 0;
}
text(numbers[i],column,row*15+15);
row++;
}
}

CodeWars sorting numbers and letters

I am currently doing a codewars problem, and I think I almost got it however, I ran across a problem when sorting index values with the same letter. link to problem is here. https://www.codewars.com/kata/5782dd86202c0e43410001f6
function doMath(s) {
let strSplit = s.split(' ');
let clonedArr = strSplit.slice();
for (let i = 0; i < strSplit.length; i++) {
for (let j = 0; j < strSplit[i].length; j++) {
let current = strSplit[i][j];
if (isNaN(current)) {
let letter = current;
strSplit[i] = strSplit[i].replace(letter, '');
strSplit[i] = letter + strSplit[i];
}
}
}
let sortedArr = strSplit.sort();
console.log(sortedArr);
// ["b900", "y369", "z123", "z246", "z89"]
let noLetterArr = sortedArr.map(x => {
return x.slice(1);
});
let numberArr = noLetterArr.map(y => {
return +y;
})
let firstEl = numberArr[0];
for (let i = 1; i < numberArr.length; i++) {
if (numberArr.indexOf(numberArr[i]) % 4 == 1) {
firstEl += numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 2) {
firstEl -= numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 3) {
firstEl *= numberArr[i];
}
}
return firstEl;
}
console.log(doMath('24z6 1z23 y369 89z 900b'));
I would like to sort the sortedArr the ones with the same letter by how they first appeared in string. So since "z246" appeared first in the original string. I would like to have that before "1z23". I had a hard time creating a function for that.
var al = [];
function doMath(s) {
var ar = s.split(" ");
for (let i = 0; i < ar.length; i++) {
for (let char of ar[i]) {
let temp = char.match(/[a-z]/i);
if (temp) {
al[i] = char;
ar[i] = ar[i].replace(char, '');
ar[i] = char + ar[i];
}
}
}
al = al.sort();
//New Sort Logic to pass above test case and others too
var n = [];
for (let i = 0; i < al.length; i++) {
for (let j = 0; j < ar.length; j++) {
if (ar[j].startsWith(al[i]) && !n.includes(ar[j])) {
n.push(ar[j]);
}
}
}
var result = parseInt(n[0].substr(1)),
count = 1;
for (let i = 1; i < n.length; i++) {
if (count == 1) {
result = result + parseInt(n[i].substr(1));
count++;
} else if (count == 2) {
result = result - parseInt(n[i].substr(1));
count++;
} else if (count == 3) {
result = result * parseInt(n[i].substr(1));
count++;
} else if (count == 4) {
result = result / parseInt(n[i].substr(1));
count = 1;
}
}
return Math.round(result);
}

Generate arrays with random numbers in javascript

I need to create an array (observations) which contains arrays of eight numbers (named observation). These numbers should be in range between 0 and 9.
let observations = [];
let observation = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
for (let j = 0; j < 8; j++) {
observation[j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
observations.push(observation);
}
Problem: The numbers are pseudo random and I get the same result 20 000 times.
Is there a possibility to fix this issue in JavaScript?
You're reusing the same observation array each time, but simply overwriting it in the inner loop. So all the references to it contain the results from the last iteration.
You need to create a new observation array each time through the outer loop.
let observations = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
let observation = [];
for (let j = 0; j < 8; j++) {
observation.push(Math.floor(Math.random() * (max - min + 1)) + min);
}
observations.push(observation);
}
You could move the empty array inside of the first level, because you keep the same object reference.
let observations = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
let observation = [];
for (let j = 0; j < 8; j++) {
observation[j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
observations.push(observation);
}
Math.seed = function(s) {
return function() {
s = Math.sin(s) * 10000; return s - Math.floor(s);
};
};
let observations = [];
let observation = [];
let min = 0;
let max = 9;
for (let i = 0; i < 20000; i++) {
var d = new Date();
var n = d.getMilliseconds();
for (let j = 0; j < 8; j++) {
observation[j] = Math.floor(Math.seed(i+j+n)() * (max - min + 1)) + min;
}
observations.push(observation);
observation = [];
}
JSON.stringify(observations);
A functional solution:
const observations = Array.from({length: 20000}, () =>
Array.from({length: 10}, () => (Math.random() * 10 | 0)))

Need help sorting array and displaying it on the HTML page

My HW assignment requires me to have a user enter integers and for it to come out on the HTML in sorted array without the sort method. I have this code and it asks the users input but the integers do not come up on page.
<script type="text/javascript">
var arr = [];
function addNum() {
var n = prompt("How many integrs?", "0");
var num = parseInt(n);
for (var i = 0; i < num; i++) {
arr[i] = parseInt(prompt("Enter next integer: ","0"));
}
var outputSorted = document.getElementById('outputSorted');
outputSorted = "";
outputSorted.append("Input array : ");
for (var i = 0; i < num; i++) {
outputSorted.append(arr[i]+" ");
}
bubbleSort(arr);
outputSorted.append("Sorted array : ");
for (var i = 0; i < num; i++) {
outputSorted.append(arr[i]+" ");
}
}
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i=0; i < a.length - 1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
function searchNum() {
var m = parseInt(prompt("Enter num to be searched: ","0"));
var found = binarySearch(arr, m);
var outputSearch = document.getElementById('outputSearch');
if (found == -1) {
outputSearch.append("Number not found");
} else {
outputSearch.append("Number found at index : " + (found + 1));
}
}
function binarySearch(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;
}
</script>
outputSorted is a DOM element, and append() is not a function of that element. Rather than that, use innerHTML += for each bit you want to add. See below. And note, those are the ONLY changes I made. So your ugly rendered HTML is what it is.
var arr = [];
addNum = function addNum() {
var n = prompt("How many integrs?", "0");
var num = parseInt(n);
for (var i = 0; i < num; i++) {
arr[i] = parseInt(prompt("Enter next integer: ", "0"));
}
var outputSorted = document.getElementById('outputSorted');
outputSorted.innerHTML += "Input array : "
for (var i = 0; i < num; i++) {
outputSorted.innerHTML += arr[i] + " ";
}
bubbleSort(arr);
outputSorted.innerHTML += "Sorted array : ";
for (var i = 0; i < num; i++) {
outputSorted.innerHTML += arr[i] + " ";
}
}
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
var temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
function searchNum() {
var m = parseInt(prompt("Enter num to be searched: ", "0"));
var found = binarySearch(arr, m);
var outputSearch = document.getElementById('outputSearch');
if (found == -1) {
outputSearch.innerHTML += ("Number not found");
} else {
outputSearch.innerHTML += ("Number found at index : " + (found + 1));
}
}
function binarySearch(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
} else if (array[guess] < targetValue) {
min = guess + 1;
} else {
max = guess - 1;
}
}
return -1;
}
<button onclick="addNum()">
Add some!
</button>
<div id="outputSorted">
</div>
<div id="outputSearch">
</div>

Categories

Resources