I've got to create var with few elements:
var arrNum = [4,7,5,3,4,5,6,7,8,10]
I need to find first number that is the same in array using for loop. So it will be "4" and "4"
I need to create var sameIndex and adjust the same number to sameIndex and print after for loop
So I did loop
for(var i = 0; i < arrNum.length; i++){
console.log("")
console.log("Loop number is " + i)
if(arrNum[i] === arrNum[i]{
break
sameIndex = going[i]
}
}
console.log(sameIndex)
It's not working.
One way would be to use Array#indexOf. It returns the first index of the given element in the array:
var arrNum = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10];
var i;
var sameIndex = -1;
for (i = 0; i < arrNum.length; i++) {
if (arrNum.indexOf(arrNum[i]) !== i) {
console.log('This is the second occurrence of', arrNum[i]);
sameIndex = arrNum.indexOf(arrNum[i]);
break;
}
}
console.log('The indices are', sameIndex, 'and', i);
If you're looking to get the first duplicate, then use :
var arrNum = [4,7,5,3,4,5,6,7,8,10];
function firstDuplicate(array){
var history = [];
for(var element of array){
if(history.indexOf(element)<0)
//not in the history yet
history.push(element);
else
return element;
}
return null; //or any distinctive value
}
var fDup = firstDuplicate(arrNum);
You could take a hash table and display the value.
var array = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10],
hash = Object.create(null),
i;
for (i = 0; i < array.length; i++) {
if (hash[array[i]]) {
console.log('first dupe: ' + array[i]);
break;
}
hash[array[i]] = true;
}
A working script:
var arrNum = [4,7,5,3,4,5,6,7,8,10];
var sameIndex = -1, going = new Array();
for(var j = 0; j < arrNum.length; j++) {
for(var i = 1; i < arrNum.length; i++){
console.log("Loop number is " + j + ", " + i)
if(arrNum[i] === arrNum[j]){
sameIndex = i;
break;
}
}
if(sameIndex > 0) {
console.log(j, sameIndex)
break;
}
}
var arrNum = [4,7,5,3,4,5,6,7,8,10];
for(var i = 0; i < arrNum.length; i++){
for(var j = i+1; j < arrNum.length; j++) {
if(arrNum[i] === arrNum[j]) {
console.log('value: '+arrNum[i]+' index1: '+i+' index2: '+j);
}
}
}
Iterate over the original array and if the value is not in a comparison array - push it into a common numbers array. The first item in that common numbers array is the target.
var origArray = [4,7,5,3,4,5,6,7,8,10];
var newArray = [];
var commonNums = [];
origArray.forEach(function(item,i) {
newArray.indexOf(item) == -1
? newArray.push(item)
: commonNums.push({item: item, index:i});
})
if(commonNums.length > 0) {
var firstCommonNum = commonNums[0].item;
var firstCommonNumIndex = commonNums[0].index;
console.log("common number " + firstCommonNum);
console.log("Loop number is " + firstCommonNumIndex);
}
Related
I'm trying to find the number of adjacent element trios with a given sum.
Example:
Inputs arr = [1,2,3,12,1,4,9,6] sum = 6
Output = 2
([1,2,3,12,1,4,1,6])
My Code:
function getCount(arr, sum) {
var count = 0;
var indexes = [];
for (var i = 0; i < arr.length-2; i++) {
for (var j = i + 1; j < arr.length-1; j++) {
for (var k = j + 1; k < arr.length; k++){
if ((arr[i] + arr[j] + arr[k] == sum) && indexes.includes(i) && indexes.includes(j)) {
count++;
}
}
}
}
return count;
}
getCount([1,2,3,12,3,4,9,6],19);
But this is not work for adjacent elements.
I would just use a single loop/pass here:
function getCount(arr, sum) {
if (arr.length < 3) return 0;
var count = 0;
var first = arr[0];
var second = arr[1];
var third;
for (var i=2; i < arr.length; i++) {
third = arr[i];
var currSum = first + second + third;
if (currSum == sum) ++count;
first = second;
second = third;
}
return count;
}
console.log(getCount([], 3));
console.log(getCount([1, 2], 3));
console.log(getCount([1, 2, 3], 3));
console.log(getCount([1, 2, 3], 6));
console.log(getCount([1,2,3,12,3,4,9,6], 19));
The strategy here is to just walk down the input array once, keeping track of the current, previous, and previous previous values at each step. Then, we compute the sum of those three values, and compare against the input target sum.
This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))
Part of my homework I have to write a program that calculates all multiplication tables up to 10 and store the results in an array. The first entry formatting example is "1 x 1 = 1".
I think I have my code written right for the nested for loop but I'm not sure on how to output it properly.
var numOne = [1,2,3,4,5,6,7,8,9,10];
var numTwo = [1,2,3,4,5,6,7,8,9,10];
var multiple = [];
for (var i = 0; i < numOne.length; i++) {
for (var j = 0; j < numTwo.length; j++) {
multiple.push(numOne[i] * numTwo[j]);
console.log(numOne[i] * numTwo[j]);
}
}
You can use a template string, and you can just loop through the numbers in the arrays without using arrays (in the same way you were looping through the indices):
var multiple = [];
var m;
for (var i = 1; i <= 10; i++) {
for (var j = 1; j <= 10; j++) {
m = i * j;
multiple.push(m);
console.log(`${i} * ${j} = ${m}`);
}
}
var multiple = [];
var first = 1;
var last = 10;
for (var i = first; i <= last; i++) {
for (var j = first; j <= last; j++) {
multiple.push(i + " x " + j + " = " + (i*j));
console.log(multiple[multiple.length-1]);
}
}
Not sure if ES6 is part of your curriculum, so here is how to do it with and without template literals
// Create the arrays that you want to multiply
var numOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numTwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Create a function that accepts both arrays as arguments
function multiply(arr1, arr2) {
var products = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
//Here we are using template literals to format the response, so that the program will show you the inputs and calculate the answer
products.push(`${arr1[i]} X ${arr1[j]} = ${arr1[i] * arr2[j]}`);
/* If ES6 is outside of the curriculum, the older method for formatting would be like this:
products.push(arr1[i] + " X " + arr2[j] + " = " + arr1[i]*arr2[j])
*/
}
}
console.log(products);
return products;
}
// Call the second function example
multiply(numOne, numTwo);
I am new to javascript and working with DOM, so please bear with me.
I have an array called num that I want to sort and display. The sort is a selection sort that returns the number of moves it took.
I can display the unsorted array but can't figure out how to call my sort function and then display the sorted array to the screen. My code is below:
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
listlist
list[min] = temp;
count += 3;
}
return count;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
{
var html = "";
html += "Original:" + num + "<br>";
selection(num, fn);
html += "Sorted:" + num + "<br>";
}
demoP.innerHTML = html;
<div id="content"></div>
arr is undefined, you should use list instead. Returning count returns the number of operations (after it's been initialized), return list instead. And as list is local to the function, you need to set num to the return value of the function call.
<span id='content'/>
<script>
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count=0,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
list[min] = temp;
count += 3;
}
return list;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
var html = "";
html += "Original:" + num + "<br>";
num= selection(num, fn);
html += "Sorted:" + num + "<br>";
demoP.innerHTML = html;
</script>
I want to check for the same numbers in "checked" and "numbers". There are six numbers in each array and equal once shuld be outputed in the array "same".
There are 0 elements in "same" even if there are the same numbers in the array. The code to compare the two arrays is right ( I tested it before) but here it wont work.
Please help
Thanks
function getNumbers(){
var boxes = document.forms[0];
var checked = [];
var i;
for (i = 0; i < boxes.length; i++) {
if (boxes[i].checked) {
checked[checked.length] = boxes[i].value;
}
}
if(checked.length != 6){alert("Pick 6");}
else{
document.getElementById("Ausgabe2").innerHTML = "You picked: "+checked;
var numbers = [];
var randomnumber;
while(numbers.length < 6){
randomnumber = Math.ceil(Math.random()*49)
if(numbers.indexOf(randomnumber) > -1) continue;
numbers[numbers.length] = randomnumber;
}
numbers.sort(sortNumber);
document.getElementById("Ausgabe").innerHTML = numbers;
Here the comparing part begins. If I declare 'numbers' and 'checked' here again it works but I dont`t want to do this.
var same = [];
for (i = 0; i < 6; i++) {
if (numbers.indexOf(checked[i]) != -1) {
same.push(checked[i]);
}
}
document.getElementById("Ausgabe3").innerHTML = "You`ve got " + same.length + " right: " + same;
}
}
function sortNumber(a,b) {
return a - b;
}
Is it what you are looking for ?
"use strict"
var numbers = [1, 3, 5, 7, 9, 11];
var checked = [4, 5, 6, 7, 8, 9];
var same = [];
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < checked.length; j++) {
if (numbers[i] === checked[j]) {
same.push(numbers[i]);
}
}
}
alert(same);
It's because each time you enter a value in array same you enter it at a fixed index which is undefined (or 0, depends on how you've initialized the array)
// These declarations are only for this demo
var numbers = [0, 1, 2, 3, 4, 5, 6];
var checked = [3, 4, 5, 6, 7, 8, 9];
var same = [];
// Start of the snippet
// Replace the below part in your code
var len = (numbers.length < checked.legth) ? numbers.length : checked.length;
for (i = 0; i < len; i++) {
if (numbers.includes(checked[i])) {
same.push(checked[i]); // This line is where your code had a error
}
}
// End of snippet
console.log('same array:');
console.log(same);
EDIT:
You are understood JS array wrong. Youv'e used the following loop multiple times in the updated snippet in your question
for (i = 0; i < boxes.length; i++) { // Iterate i from 0 till box.length
if (boxes[i].checked) {
checked[checked.length] = boxes[i].value; // For each value of i, the value of check.length is the same. So every time this condition is executed, you simply overwrite the value.
}
}
Try to update your function wit the one below, I've updated few logical error's...
function getNumbers() {
var boxes = document.forms[0];
var checked = [];
var i;
for (i = 0; i < boxes.length; i++) {
if (boxes[i].checked) {
checked.push(boxes[i].value); // Updated here
}
}
if (checked.length != 6) {
alert("Pick 6");
} else {
document.getElementById("Ausgabe2").innerHTML = "You picked: " + checked;
var numbers = [];
var randomnumber;
while (numbers.length < 6) {
randomnumber = Math.ceil(Math.random() * 49)
if (numbers.indexOf(randomnumber) > -1) continue;
numbers.push(randomnumber); // Updated here
}
numbers.sort(sortNumber);
document.getElementById("Ausgabe").innerHTML = numbers;
var same = [];
for (i = 0; i < 6; i++) {
if (numbers.indexOf(checked[i]) != -1) {
same.push(checked[i]);
}
}
document.getElementById("Ausgabe3").innerHTML = "You`
ve got " + same.length + "
right: " + same;
}
}