The following code should convert a string into an array of numbers and sort them in descending order. The purpose is to find a substitution for the sort() method.
Something is wrong. If 7 is placed in the first half of the array (like in the example), the code does not work properly. If you swap 7 for a number bigger than the last one (22 in the example), the code will work fine.
I'm looking to get it to work right regardless of the positioning of the numbers.
var row = '92 43 7 119 51 22';
var row = row.split(' ');
var column = row.map(Number);
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = column.length - i; j >= 0; j--) {
if (column[j] > column[j - 1]) {
var temp = column[j];
column[j] = column[j - 1];
column[j - 1] = temp;
}
}
}
return column;
}
console.log(arrangeNum(column));
Something is wrong. If 7 is placed in the first half of the array
(like in the example), the code does not work properly.
It is because of your second-for-loop's initialization of j
Replace
for (var j = column.length - i; j >= 0; j--) {
with
for (var j = column.length - 1; j >= i; j--) {
Notice that j is initialized to column.length - 1, but is only allowed to go as low as i
Demo
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = column.length - 1; j >= i; j--) {
if (column[j] > column[j - 1]) {
[column[j], column[j - 1]] = [column[j - 1], column[j]];
}
}
}
return column;
}
console.log( arrangeNum( '92 43 7 119 51 22'.split( /\s+/ ).map( Number ) ) );
The problem you are having is that you implemented the bubble sort wrong.
See this line var j = column.length - i; j >= 0; j--, will cause you to ignore the elements of the array starting from the right-side. Since this is a descending order algo, you need to ignore the elements from the left-side, so this: var j = column.length - 1; j >= i; j--.
I added some console logs to show this below:
See in yellow your algo ignores the first element on the next loop.
Below I added my full correction (you had some other minor issues):
for (var i = 1; i <= column.length; i++) {
for (var j = column.length - i; j >= 0; j--) {
console.log({i,j}, column.map((v,idx) => (idx===j) || (idx===j-1) ? `[${v}]` : v ).join(' '))
if (column[j] > column[j - 1]) {
var temp = column[j];
column[j] = column[j - 1];
column[j - 1] = temp;
console.log({i,j}, ' ',column.map((v,idx) => (idx===j) || (idx===j-1) ? `[[${v}]]` : v ).join(' '))
}
}
}
Here you go, you just needed to reverse the order of execution of the j loop, starting from 0 till column.length - 1
var row = '92 43 7 119 51 22';
var row = row.split(' ')
var column = row.map(Number);
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = 0; j <= column.length - i; j++) { // SEE THIS
console.log(column)
if (column[j] > column[j - 1]) {
var temp = column[j];
column[j] = column[j - 1];
column[j - 1] = temp;
}
}
}
return column;
}
console.log(arrangeNum(column))
Pls make change in a code as below.
It will work
var row = '92 43 7 119 51 22';
var row = row.split(' ');
var column = row.map(Number);
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = column.length - 1; j >= i; j--) {// see this change
if (column[j] > column[j - 1]) {
var temp = column[j];
column[j] = column[j - 1];
column[j - 1] = temp;
}
}
}
return column;
}
console.log(arrangeNum(column));
Related
function LCSubStr(X, Y) {
let m = X.length;
let n = Y.length;
let result = 0;
let end;
let len = new Array(4);
for (let i = 0; i < len.length; i++) {
len[i] = new Array(n);
for (let j = 0; j < n; j++) {
len[i][j] = 0;
}
}
let currRow = 0;
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
len[currRow][j] = 0;
}
else if (X[i - 1] == Y[j - 1]) {
len[currRow][j] = len[1 - currRow][j - 1] + 1;
if (len[currRow][j] > result) {
result = len[currRow][j];
end = i - 1;
}
}
else {
len[currRow][j] = 0;
}
}
currRow = 1 - currRow;
}
if (result == 0) {
return "-1";
}
return X.substr(end - result + 1, result);
}
// Driver Code
let X = "GeeksforGeeks";
let Y = "GeeksQuiz";
// function call
document.write(LCSubStr(X, Y));
How can I convert this code for multiple input?
I checked many lcs code but no one works with
ABCQEFDEFGHIJ BCXEFGYZBCDEWEFGHU > EFGH
This one just works good without any problem. I should convert this one for multiple input in Javascript.
Now we have X,Y but it shoulde be with multiple inputs.
This question already has answers here:
Print an output in one line using console.log()
(13 answers)
Closed last year.
Instead of 1 index on each row, I want horizontal not vertical returns.
let n = [6];
function staircase() {
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
console.log("0");
}
for (let k = 1; k <= i; k++) {
console.log('#');
}
}
}
staircase();
But I need it to render like this. (This works using Java; it's the same logic, but renders differently.)
#
##
###
####
#####
######
console.log prints one line each therefore i put 2 variables to keep the empty string and hash string and after the loops logged the concatenation of the strings
let n = 6
function staircase() {
for (let i = 1; i <= n; i++) {
let emptyString = '';
let hashString = '';
for (let j = 1; j <= n - i; j++) {
emptyString += " ";
}
for (let k = 1; k <= i; k++) {
hashString += '#'
}
console.log(emptyString + hashString)
}
}
staircase();
const n = [6]
for (let i = 1; i <= n; i++) {
//
// this array stores the results;
//
const array = [];
//
for (let j = 1; j <= n - i; j++) {
array.push("0");
}
for (let k = 1; k <= i; k++) {
array.push('#');
}
// adding `toString`, does the magic
console.log(array.toString())
}
I am currently trying to solve the xmas tree problem, with internal tree-like shape.
issue is with internal spacing, it supposed to be like: 1, 5, 7, 9. Instead it is 1, 3, 4, 5. I do not know, how to increment s loop by 2 in each loop turn.
/*
*********
**** ****
*** ***
** **
* *
*********
*/
function drawTree(h) {
let n = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= n; j++) {
temp = temp + "*";
}
console.log(temp);
}
for (var i = 0; i < h - 2; i++) {
var tree = '';
console.log("\n");
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
tree += "s";
for (var k = 1; k <= i; k++) {
for (var k = 1; k <= i; k++) {
tree += "s";
};
tree += "s";
};
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
console.log(tree);
};
console.log("\n");
let g = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= g; j++) {
temp = temp + "*";
}
console.log(temp);
}
};
drawTree(6);
function drawTree(stars, rowLength) {
for (let row = 0; row < rowLength; row++) {
if (row === 0) {
console.log("*".repeat(stars));
} else if(row === rowLength - 1) {
console.log("*".repeat(stars));
} else {
let spaces = 2 * row - 1;
if (spaces > stars) {
spaces = stars;
}
let numStarsInRow = "*".repeat((stars - spaces) / 2);
console.log(numStarsInRow + " ".repeat(spaces) + numStarsInRow);
}
}
}
drawTree(9, 5)
You can implement this by nesting loops over the height and the width of the tree, noting that the output is a * whenever:
it's the first or last row; or
the current x position is less than or equal to the halfway point minus the row number; or
the current x position is greater than or equal to the halfway point plus the row number
For all other cases the output is a space. For example:
function drawTree(height) {
// compute the width of the tree from the height
let width = height % 2 ? height + 2 : height + 3;
// find the halfway point
let half = (width - 1) / 2;
for (let i = 0; i < height; i++) {
let l = '';
for (let j = 0; j < width; j++) {
if (i == 0 || // first row
i == height - 1 || // last row
j <= (half - i) || // left side
j >= (half + i) // right side
) {
l += '*';
}
else {
l += ' ';
}
}
console.log(l);
}
}
drawTree(6);
drawTree(5);
am trying to solve this problem.
You are working at the cash counter at a fun-fair, and you have different types of coins available to you in infinite quantities. The value of each coin is already given. Can you determine the number of ways of making change for a particular number of units using the given types of coins?
Sample Input 1
10 4
2 5 3 6
Sample Output 1
5
Explanation 1
There are five ways to make change for n = 10 units using coins with values given by C= [2,5,3,6]:
1) {2,2,2,2,2}
2) {2,2,3,3}
3) {2,2,6}
4) {2,3,5}
5) {5,5}
The code I've written:
const getWays = (n, c) => {
let m = c.length
let matrix = Array.from(new Array(m + 1), () => Array(n + 1).fill(0))
console.log(matrix);
for (let i = 0; i <= m; i++) {
matrix[i][0] = 1
}
for (let j = 1; j <= n; j++) {
matrix[0][j] = 0
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (c[i] > j) matrix[i][j] = matrix[i - 1][j]
else {
matrix[i][j] = matrix[i - 1][j] + matrix[i][j - c[i]]
}
}
}
}
console.log(getWays(10, [2, 5, 3, 6])) //5
I can't figure out where my logic is breaking in the assignment of values to the matrix. What am I doing wrong?
Check this recursive algorithm.
function getWays(n, c) {
const len = c.length
if (n < 0 || len < 1) return 0
if (len == 1) {
if (n % c[0] == 0) return 1
return 0
}
let cnt = 0
for (let i = 0; i < len - 1; i++) {
for (let j = c[i]; j <= n; j += c[i]) {
cnt += getWays(n - j, c.slice(i + 1))
}
}
if (n % c[len - 1] == 0) cnt++
return cnt
}
console.log(getWays(10, [2, 5, 3, 6])) //5
Here I have two array,but they are not the simple array.See below:
var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]
for (var i = a.length - 1; i >= 0; i--) {
for (var j =b.length - 1; j >= 0; j--) {
if( a[i]['id'] == b[j]['id']){
a[i]['rest'] = a[i]['num'] - b[j]['num']
}
}
}
console.log(a)
but I cannot get the id 3, because id 3 was not in b array. Please help.
here is the answer i want
a = [
{"id":1,"in":1,"num":3000,"rest":2000},
{"id":2,"in":1,"num":1500,"rest":500},
{"id":3,"in":1,"num":1000,"rest":1000}
]
thk
So you want to substract the 'num' in b from the corresponding 'num' in a for every element of a? Than just iterate over a and check if it is contained also in b:
var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]
for (var i = a.length - 1; i >= 0; i--) {
a[i]['rest'] = a[i]['num'];
for (var j =b.length - 1; j >= 0; j--) {
if( a[i]['id'] == b[j]['id']){
a[i]['rest'] = a[i]['num'] - b[j]['num'];
break;
}
}
}
you can add some variable for flag to know whether you have a same id or not, here's an example with your code
var flag;
var a = [{"id":1,"in":1,"num":3000},{"id":2,"in":1,"num":1500},{"id":3,"in":1,"num":1000}]
var b = [{"id":1,"in":0,"num":1000},{"id":2,"in":0,"num":1000}]
for (var i = a.length - 1; i >= 0; i--)
flag = false;
for (var j =b.length - 1; j >= 0; j--) {
if( a[i]['id'] == b[j]['id']){
a[i]['rest'] = a[i]['num'] - b[j]['num']
flag = true;
}
}
if(!flag) {
a[i]['rest'] = a[i]['num']
}
}