Hello I need to write a pair of loops that would go through numbers in specific way. I'll try to show on example.
lets say I have loops like this.
for(let i = 0; let i <4; i++){
for (let j = ?; condition;? ){
console.log(j)
}
and from this I would want result in console like this: 12345 2345 345 45 (but numbers printed in console indivudally not as string)
If it was i < 3 result should be 1234 234 34 etc.
How would you write the conditions or what would you do to get the result?
Thank you for any help.
Edit: I need the numbers to be printed by console.log as individual number and not a s string, sorry for bad description, same way this code would
(let i =0; i<4; i++ )
{
console.log(i)
}
here you go:
for(let i = 1; i <= 4; i++){
if(i!=4){
for (let j = i; j<=4;j++){
console.log(j)
}
}
}
A general solution using for-loop.
function ReturnNumberList(n){
let arrayList=[], base= "";
//loop to build the base number
for(let i=1;i<n+1;i++){
base= base + (i).toString();
}
//loop to print the list
for(let i=0;i<n-1;i++){
let temp = base.substr(i,base.length);
console.log(temp)
arrayList.push(temp);
}
return arrayList.join(",").replace(/,/g,"");
}
Related
For example I have this string "()[]|}" and I want to compare each characters with eachother, but first I can't get the loop to work correctly. For the first log it works correctly, but after instead of going +1 it should go +2 I believe so it doesn't start from ). How do can I do this properly?
function isValid(s) {
let temp = s.split("");
for (let i = 0; i < s.length/2; i++) {
console.log(temp[i], temp[i+1]);
}
};
isValid("()[]|}");
I want to log this
( )
[ ]
| }
not
( )
) [
[ ]
Your code is correct but your for loop is slightly off:
for (let i = 0; i < s.length; i += 2) {
Loop while i is less than the length, but add 2 instead of 1.
function isValid(s) {
let temp = s.split("");
for (let i = 0; i < s.length; i += 2) {
console.log(temp[i], temp[i+1]);
}
};
isValid("()[]|}");
If the question is 'how do I increment by two instead of by 1', use i += 2 instead of i++ (since the increment operator only increments by 1)
I'm trying to solve this problem where I initialize an array of 5 elements and print the sum of the elements. I can't wrap my head around the logic behind the solution. Please review my code.
Another problem with reading an array of 5 integers and printing the smallest element. I keep getting the wrong answer...
This's a script embedded inside an HTML file.
Problem 1
var num= [1,1,1,1];
var total=num[0];
for( var i=0 ; i < num.length ; i++)
{
total =+num[i];
}
window.alert("The total is "+ total);
I expected the answer to be 4, but all I get is 1.
Problem 2
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small= [0];
for(var j=0; j< len ; j++)
{
if(r[i] < small )
small = r[i];
}
window.alert("The smallest element is the array is "+small);
I get the last element in my array as the smallest element which's obviously isn't right.
In problem 1) you just need to change =+ to +=
In problem 2) you need to start in the first element of r and in the for loop you need index the r array by the variable j instead of i variable
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small = r[0];
for( var j=0; j< len ; j++)
{
if(r[j] < small )
small = r[j];
}
window.alert("The smallest element is the array is "+small);
But you could just do:
const min = Math.min(...r)
window.alert("The smallest element is the array is "+ min);
There are a couple things here.
For problem 1:
Since you initialize the total to the first item I think you end up counting it 2 times. Likely you'd want to initialize to 0. var total = 0.
You will also want to use += instead of =+ the latter sets the value instead of adding it.
For Problem 2:
new Array(5) creates a new sparse array. It's kinda weird. It's like it's full of undefined values. So when you assign small you'll want to access the first element of r, var small = r[0] but that will be undefined due to r being a sparse array. So you'll want var r = new Array(5).fill().map((x,i) => i) to set values in that array. You will also want to use j instead of i in the body of the second loop.
That should do it ;).
Hi The problem 1 could be tackled with reduce method check the Docs here:
The problem 2 could be solved with Math.min method:
var num= [1,1,1,1];
var numMin= [100,1121,1212,122, 12];
//Problem1
let totalSum = num.reduce( ( accumulator, currentItem ) => {
return accumulator = accumulator += currentItem;
} , 0 );
console.log(totalSum)
//Problem 2
console.log( 'Min',Math.min( ...numMin ) );
Here is a replit so you can play with the code
// Find array elements sum
let total = 0;
let arr = [1,2,3,4];
arr.map(el => total+=el);
console.log(total); // 10
// Find array smallest element
let arr = [1,-2,13,-4,7];
let smlEl = arr[0]
arr.map(el => {
if(el < smlEl) {
smlEl = el;
}
})
console.log(smlEl); // -4
(I know there is easier way to convert to binary but I didn't know that before I was almost finished with this. So I am just gonna try to finish this. I coded this just to learn) :)
I am trying to create a function that converts binary to ASCII code. Here is how I am converting from binary to number:
function fromBinaryToNumber(num) {
let numbers = num.split('') //turns the binary into an array
let firstIndexWith1;
let numbersToAdd = [];
let result;
//Delete 0's at start of array
for (i = 0; i < numbers.length; i++) {
numbers[i] = parseInt(numbers[i], 10);
}
firstIndexWith1 = numbers.indexOf(1);
numbers.splice(0, firstIndexWith1);
//Convert
let checkAgainstThese = [128, 64, 32, 16, 8, 4, 2, 1];
checkAgainstThese = checkAgainstThese.slice(checkAgainstThese.length - numbers.length, checkAgainstThese.length);
//put numbers to add in array
for (i = 0; i < numbers.length; i++) {
if (numbers[i] === 1) {
numbersToAdd.push(checkAgainstThese[i]);
}
}
//add numbers
result = numbersToAdd.reduce((a, b) => a + b, 0);
return result;
}
It works. But I want to be able to convert more than one byte at a time. This is how I am trying to do that:
function fromBinaryToASCII(sentence) {
let convertThis = sentence.split(' ');
let result = [];
for (i = 0; i < convertThis.length; i++) {
result.push(fromBinaryToNumber(convertThis[i]));
}
return result;
}
I have already made a function that successfully converts from a sentence to binary and for some reason that one works but not this one, even though they both look very similar.
So I was trying to find out what the problem was and I tried putting a console.log inside the for loop and printing out the i. Like this:
for (i = 0; i < convertThis.length; i++) {
result.push(fromBinaryToNumber(convertThis[i]));
console.log(i);
}
And for some reason it outputted only the number 6. When I remove the result.push code it outputs correctly. I am very confused. Can someone help me?
-Thanks
(sorry for bad title or if i explained badly)
for(i=0; i<convertThis.length; i++) { <-- global i
for(i=0; i<numbers.length; i++) { <-- global i
When the one runs, it will change the number for the other.... This is why var is not optional. So either use let or var
for(let i=0; i<convertThis.length; i++) {
for(let i=0; i<numbers.length; i++) {
Good day fellow Stack-ers,
I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).
I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.
Here is my answer:
var array = [3,8,5,6,5,7,1,9];
var outputArray = [];
function arrayTrim() {
var sortedArray = array.sort();
outputArray.push(sortedArray[1],array[array.length-2]);
return outputArray;
}
arrayTrim();
and here is the answer that they have provided:
function Second_Greatest_Lowest(arr_num) {
arr_num.sort(function(x,y) {
return x-y;
});
var uniqa = [arr_num[0]];
var result = [];
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
result.push(uniqa[1],uniqa[uniqa.length-2]);
return result.join(',');
}
alert(Second_Greatest_Lowest([1,2,3,4,5]));
I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.
Thank you!
Your answer does not perform correct for input such as f.e. [3,8,5,6,5,7,1,1,9]. Your proposed solution returns 1 as the second lowest number here – whereas it should actually be 3.
The solution suggested by the site takes that into account – that is what the if inside the loop is for, it checks if the current number is the same as the previous one. If that’s the case, it gets ignored. That way, every number will occur once, and that in turn allows to blindly pick the second element out of that sorted array and actually have it be the second lowest number.
It seems like a long way around to the solution
You took a short cut, that does not handle all edge cases correctly ;-)
The loop in question:
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
Provides some clue as to what it's doing by using a (reasonably) descriptive variable name: uniqa - or "unique array". The if statement is checking that the current element is not the same as the previous element - having sorted the array initially this works to give you a unique array - by only filling a new array if the element is indeed unique.
Thereafter the logic is the same as yours.
import java.util.Arrays;
public class BubbleWithMax_N_Min
{
public static void main(String[] agrs)
{
int temp;
int[] array = new int[5];
array[0] = 3;
array[1] = 99;
array[2] = 55;
array[3] = 2;
array[4] = 1;
System.out.println("the given array is:" + Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] + "");
}
for (int i = 0; i < array.length; i++)
{
for (int j = 1; j < array.length - i; j++)
{
if (array[j - 1] > array[j])
{
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(" 2nd Min and 2nd Highest:");
for (int i = 0; i < 1; i++)
{
System.out.println(array[i+1]);
}
for (int i = 0; i < 1; i++)
{
int a= array.length-2;
System.out.println(array[a]);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
var points = new Array(100);
var label = points.length;
for (var i = 0; i < label; i++) {
console.log(points[i]);
}
</script>
</body>
</html>
This is my First question in Stackoverflow. As i am an beginner, Please bare me and i need alot of support from you people. I m trying to print 1 to 100 numbers using arrays in javascript only. I'm Facing some errors in the above code. Please correct my mistakes to get the output..Thankyou in advance.
This will print 1-100 without any loops
Array.from({length: 100},(_,x) => console.log(x+1))
he said he wants to print 1-100 from an ARRAY...So the array needs to be populated, first. THEN, you can loop through the array.
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1; //This populates the array. +1 is necessary because arrays are 0 index based and you want to store 1-100 in it, NOT 0-99.
}
for (var i = 0; i < points.length; i++) {
console.log(points[i]); //This prints the values that you stored in the array
}
The array values are uninitialized. I'm assuming that you want to print the values 1 to 100 using arrays where the values 1 to 100 are inside the array.
First initialize the array.
var oneToHundredArray = [];
Now populate it with values 1 to 100.
for(var value = 1; value <= 100; value++) {
oneToHundredArray.push(value);
}
Now the contains the values you want. Just loop and print over it now.
for(var index = 0; index < oneToHundredArray.length; index++) {
console.log(oneToHundredArray[index]);
}
Done :)
Array.from(Array(100), (_,i) => console.log(i+1));
The second parameter acts as mapping callback, so you also do this...
const arr = Array.from(Array(100), (_,i) => i+1);
for(num of arr) {
console.log(num);
}
Reference: Array.from
You should start off with an empty array, then run a loop for 1-101, I logged the iterator so you can see the values populate, you then need a binding agent to hold the value of the iteration, then you would need to push those values to your empty array.
var numbersArray = [];
for( var i = 1; i <101; i++){
console.log(i);
var numbers = i;
numbersArray.push(numbers);
}
After that, you then need to run a loop for the length of the numbersArray to output the individual results.
for(var m=0; m<= numbersArray.length -1; m++){
console.log(numbersArray[m]);
}
output console.log logs numbers 1-100 respectively.
var label = new Array(100);
for (var i = 0; i < 100; i++) {
label[i] = i + 1;
}
for (var i = 0; i < label.length; i++) {
console.log(label[i]);
}
It's much more easier with "while"
var i = 1;
while (i < 100) {
document.write(i + "<br/>");
i++;
}
Using a for loop:
function get_array() {
var arr = [];
for(var i=1; i<=100; i++) {
arr.push(i);
}
console.log(arr);
}
get_array()