I want to map array element and return true or false if for example there is the summation of two numbers in my array equal 8.
bad way
function showNumbered(arr) {
for(let i = 0; i < arr.length; i++) {
for(let x = 0; x < arr.length; x++) {
if( arr[i] + arr[x] == 8 ) {
console.log(true);
}else{
console.log(false);
}
}
}
}
Make sum of each with each number value in array.
If there is a sum that is equal to 8 returns true else return false
var array = [3, 6, 2, 8, 4, 7];
function arrSum(arr) {
var ret = true;
for (var i = 0; i < arr.length; i++) {
for (var ii = i+1; ii < arr.length; ii++) {
if (arr[i] + arr[ii] === 8) {
console.log(arr[i], '+', arr[ii], '=', true);
ret = false;
}
}
}
if(ret) { console.log(false); }
}
arrSum(array);
"how to pass array to function as argument"
function showNumbered(arr) {
for(let i = 0; i < arr.length; i++) {
for(let x = 0; x < arr.length; x++) {
if( arr[i] + arr[x] == 8 ) {
console.log(true);
}else{
console.log(false);
}
}
}
}
const arr = [1,2,3,4,5,6]
showNumbered(arr)
you can do it in linary way. O(n)
function showNumbered(arr, target) {
const complementary = new Map();
for(let i = 0; i < arr.length; i++) {
if(complementary.has(arr[i])){
console.log(complementary.get(arr[i]), i)
}
complementary.set(target - arr[i], i)
}
}
showNumbered([1,3,5,6,8,3,4], 4)
Related
const N = 4;
const fourbyfour = [
[1, 0, 0, 4],
[3, 4, 1, 2],
[2, 1, 4, 3],
[4, 3, 2, 1],
];
function solve(board) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (board[i][j] === 0) {
for (let k = 1; k < N + 1; k++) {
board[i][j] = k;
if (isValidBoard(board)) {
if (isSolved(board)) return board;
else solve(board);
}
}
}
}
}
return;
}
function isSolved(board) {
let cells = [];
for (let row of board) {
cells.push(...row);
}
return !cells.includes(0);
}
function isValidBoard(board) {
// Check rows are valid
for (let i = 0; i < N; i++) {
const row = board[i].filter((cell) => cell !== 0);
if (new Set(row).size !== row.length) {
return false;
}
}
// Check columns are valid
for (let i = 0; i < N; i++) {
let column = [];
for (let j = 0; j < N; j++) {
if (board[j][i] !== 0) column.push(board[j][i]);
}
if (new Set(column).size !== column.length) {
return false;
}
}
const root = Math.sqrt(N);
// Check each grid
for (let i = 0; i < N; i += root) {
for (let j = 0; j < N; j += root) {
const square = [];
for (let k = i; k < i + root; k++) {
for (let l = j; l < j + root; l++) {
if (board[k][l] !== 0) {
square.push(board[k][l]);
}
}
}
if (new Set(square).size !== square.length) {
return false;
}
}
}
return true;
}
console.table(solve(fourbyfour));
solve() keeps on returning undefined.
I'm fairly certain the issue is in the solve function, and not related to isSolved() and isValidBoard(). The solve function is getting the correct board, if I console.log the board instead of returning it, the correct board gets printed, but for some reason it isn't getting returned.
You are never returning the value of your recursion. You need to return from the second time you enter solve.
Also, console.table does not seams to be working in the snippet
const N = 4;
const fourbyfour = [
[1, 0, 0, 4],
[3, 4, 1, 2],
[2, 1, 4, 3],
[4, 3, 2, 1],
];
function solve(board) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (board[i][j] === 0) {
for (let k = 1; k < N + 1; k++) {
board[i][j] = k;
if (isValidBoard(board)) {
if (isSolved(board)) {
return board;
} else {
return solve(board);
}
}
}
}
}
}
return 'test';
}
function isSolved(board) {
let cells = [];
for (let row of board) {
cells.push(...row);
}
return !cells.includes(0);
}
function isValidBoard(board) {
// Check rows are valid
for (let i = 0; i < N; i++) {
const row = board[i].filter((cell) => cell !== 0);
if (new Set(row).size !== row.length) {
return false;
}
}
// Check columns are valid
for (let i = 0; i < N; i++) {
let column = [];
for (let j = 0; j < N; j++) {
if (board[j][i] !== 0) column.push(board[j][i]);
}
if (new Set(column).size !== column.length) {
return false;
}
}
const root = Math.sqrt(N);
// Check each grid
for (let i = 0; i < N; i += root) {
for (let j = 0; j < N; j += root) {
const square = [];
for (let k = i; k < i + root; k++) {
for (let l = j; l < j + root; l++) {
if (board[k][l] !== 0) {
square.push(board[k][l]);
}
}
}
if (new Set(square).size !== square.length) {
return false;
}
}
}
return true;
}
console.log(solve(fourbyfour));
Trying to count possible combinations to get a targetTotal. Using powerSet returns the sum without adding itself. E.g [1,2,3,5] returns [3+1] for a targetSum of 4, whereas I expect to get [1+1+1+1], [2+2], [3+1].
Do you have any ideas how I could make it count itself first as a case?
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
findSums([1,2,3,4,5],6); [[2,3], [1,4], [5], [1,1,1,1,1,1], [2,2,2], [3,3]]
I have this function which returns an array of prime numbers:
function getPrimeFactors(n) {
var factors = [];
for (i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
var numbers = [2, 3, 4, 5];
var array = [];
I want to get prime factors of all the numbers in the numbers array and push it into a new array (array)
for(i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
What am i doing wrong?
As mentioned by Damien Gold in the answer that was deleted, use var in your for-loops to make the variables local and to prevent your 2 functions from interfering with each other.
function getPrimeFactors(n) {
var factors = [];
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (var j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
And:
var numbers = [2, 3, 4, 5];
var array = [];
for(var i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
As a sidenote,
you are pushing arrays into your array instead of adding the values contained in your getPrimeFactors-array. If you instead want to push the resulting numbers into one array, try this:
for(var i=0; i<numbers.length; i++) {
array = array.concat(getPrimeFactors(numbers[i]));
}
The aim of the bellow function is to output only the non-unique items from an array that is passed as an argument:
"use strict";
function nonUnique(data){
var tab = [];
for(var d = 0; d < data.length; d++) {
if(typeof(data[d]) == "string"){
tab[d] = data[d].toUpperCase();
}
else{
tab[d] = data[d];
}
}
var count = 0;
var tab_non_unique = [];
var tab_unique = [];
for(var i = 0; i < tab.length; i++){
for(var j = 0; j < tab.length; j++){
if(tab[i] == tab[j]){
count ++;
}
if(count > 1){
tab_non_unique.push(tab[i]);
count = 0;
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}
return tab_non_unique;
}
I have tested the function by calling it on different arrays but somehow on
nonUnique([1, 2, 3, 4, 5]);
it fails by returning:
=> [ 2, 4 ]
I don't understand what in my code causes 2 and 4 to raise the counter higher than 1 and thus end up in the tab_non_unique array. Any help would be greatly appreciated, thanks.
The problem is that you reset count only if a non-unique is found. But it should be reset always when starting with a new number.
So put the count=0 at the top of the loop.
for (var i = 0; i < tab.length; i++) {
count = 0;
for (var j = 0; j < tab.length; j++) {
if (tab[i] == tab[j]) {
count++;
}
if (count > 1) {
tab_non_unique.push(tab[i]);
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}
I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';
Something that doesn't work:
function replaceAt(str, i, char) {
return str.substr(0,i) + char + str.substr(i + 1)
}
function swap(str, i1, i2) {
return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}
function sort(str) {
var sorted = str;
for (var i = 0; i < str.length; i++) {
if (str[i] > str[i + 1]) {
str = swap(str, i, i+1)
}
}
return str;
}
Pseudo-code or books, courses recommendations on programming are welcome!
Your code is not applying any sort algorithm logic, I recommend you to read atleast 1 to solve your problem.
Below is the program, which produces the expected output from your program using selection sort.
swap and replace functions works fine.
function sort(str) {
var sorted = str;
//Selection sort
for (var i = 0; i < str.length; i++) {
for(var j = i + 1; j < str.length - 1; j++) {
if (str[i] < str[j]) {
str = swap(str, i, j)
}
}
}
return str;
}
console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
Note: no need of using temp variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
var count = array.length - 1,
temp,
j,
i;
for (j = 0; j < count; j++)
{
for (i = 0; i < count; i++)
{
if (array[i] > array[i + 1])
{
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
document.write(array[k]+ "<br>");
}
document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){
document.write(array[k]+ "<br>");
}
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){
if((array[k])>array[k-1]){
document.write(array[k]+"<br>")
break;
}
}
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){
if((array[k])<array[k+1]){
document.write(array[k]+"<br>")
break;
}
}
}
</script>
<title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>
//generic sort function to sort a word
function sortArray(str){
let strr = str.split('');
for(var index = 0 ;index <strr.length ;index ++ ){
for(var index1 = 0;index1<(strr.length-index) ;index1++){
let temp;
if( strr[index1] > strr[index1+1] ){
temp = strr[index1] ;
strr[index1] = strr[index1 +1];
strr[index1+1] =temp;
}
}
}
return(strr.join(''));
}
//data set to sort
let data = "Hey Goodmorning How are you";
let result;
let data1 =data.split(' ');
data1.forEach(value => {
value = sortArray(value.toLowerCase());
if(result){
result += " ";
result += value;
}
else {result = value;}
});
console.log(result);