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]);
}
}
}
Related
I am trying to understand what this mean?
What I am thinking is that phrase will pass a part of array, so this in this case eve to phrase.palindrome method. That method will take and run it through. First var len takes eve and remove 1 from it using length -1. This results in var len being assigned number two as the length of eve is 3. Now for is in use, so var i = 0; i <= len/2; i++.
now becomes var i = 1;1 <= 1; i++."is this correct"
I don't understand what going on here:
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
Here is all of the the code:
String.prototype.palindrome = function() {
var len = this.length-1;
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
}
}
return true;
};
var phrases = ["eve", "kayak", "mom", "wow", "Not a palindrome"];
for (var i = 0; i < phrases.length; i++) {
var phrase = phrases[i];
if (phrase.palindrome()) {
console.log("'" + phrase + "' is a palindrome");
} else {
console.log("'" + phrase + "' is NOT a palindrome");
}
}
The code is essentially iterating through the string from both directions, comparing the first and last characters (indexes 0 and len) then the second from first and second from last and so forth until you reach the middle. A word is a palindrome if and only if the first and last characters are the same and the second and second to last characters are the same and so forth.
Note, there is something very wrong with this code. While it is technically possible to mutate the prototypes of built-in types in Javascript you should never, ever, ever do it. You gain no functionality you wouldn't from a normal function, while badly violating the principle of least surprise. Treat all types from other libraries, including built ins as if they are closed for modification and open for extension.
I think this line has error:
for (var i = 0; i <= len/2; i++) {
Beacuse somethimes length can be 3,5,7... and that can be problem.
I added some using examples:
for (var i = 0; i <= Math.floor(len / 2); i++) {
// That same thing with floor in positive numbers, but in negative numbers that works like ceil.
for (var i = 0; i <= ~~(len / 2); i++) {
// That same thing with floor, we can think like this pollyfill of floor.
for (var i = 0; i <= ~~(len / 2) + (Math.abs(len)>len?-1:0); i++) {
I'm learning to analyze space complexity, but I'm confused of analyzing an array vs an object in JS. So I'd like to get some help here.
ex1. array []
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
}
ex1. is from an example online, and it says the space complexity is O(1) because the table's size stays constant.
ex2. object {}
let nums[0,1,2,3,4,5], map = {};
for (let i = 0; i < nums.length; i++) {
map[ nums[i] ] = i;
}
I think ex2. uses O(n) because the map object is accessed 6 times. However, if I use the concept learned from ex1., the space complexity should be O(1)? Any ideas where I went wrong?
From the complexity analysis point of view, in ex 1, the complexity is O(1) because the array size doesn't increase. Because you are initializing the table to a fixed size of 26 (Looks like you are counting the characters in a string?).
See the below example that keeps track of counts of a alphabets in a string (Only small letters for clarity). In this case the length of array which tracks the count of alphabets never change even if the string changes its length.
function getCharacterCount(s){
const array = new Int8Array(26);
for (let i = 0; i < s.length; i++) {
array[s.charCodeAt(i) - 97]++;
}
return array;
}
Now let's change the implementation to map instead. Here the size of the map increases as and when a new character is encountered in the string.So
Theoretically speaking, the space complexity is O(n).
But in reality, we started with map with length 0 (0 keys) and it doesn't go beyond 26. If the string doesn't contain all the characters, the space taken would be much lesser than an array as in previous implementation.
function getCharacterCountMap(s){
const map = {};
for (let i = 0; i < s.length; i++) {
const charCode = s.charCodeAt(i) - 97;
if(map[charCode]){
map[charCode] = map[charCode] + 1
}else{
map[charCode] = 0;
}
}
return map;
}
function getCharacterCount(s){
const array = new Int8Array(26);
for (let i = 0; i < s.length; i++) {
array[s.charCodeAt(i) - 97]++;
}
return array;
}
function getCharacterCountMap(s){
const map = {};
for (let i = 0; i < s.length; i++) {
const charCode = s.charCodeAt(i) - 97;
if(map[charCode]){
map[charCode] = map[charCode] + 1
}else{
map[charCode] = 1;
}
}
return map;
}
console.log(getCharacterCount("abcdefabcedef"));
console.log(getCharacterCountMap("abcdefabcdef"));
I am trying to write a function which should calculate all prime numbers up to an input parameter and return it. I am doing this for practice.
I wrote this function in a few ways but I was trying to find new ways to do this for more practice and better performance. The last thing I tried was the code below:
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1, 0);
}
j+=s[i];
}
}
s = s.filter(a => a != 0);
return s;
}
console.log(primes(10));
The problem is that when I run this in a browser it keeps calculating and won't stop and I don't know why.
Note: when I comment out the splice and uncomment console.log(j); everything works as expected and logs are the things they should be but with splice, the browser keep calculating and won't stop.
I am using the latest version of Chrome but I don't think that can have anything to do with the problem.
Your problem lies in this line:
s.splice(s.indexOf(j), 1, 0);
Splice function third argument contains elements to be added in place of the removed elements. Which means that instead of removing elements, you are swapping their values with 0's, which then freezes your j-loop.
To fix it, simply omit third parameter.
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1);
}
j+=s[i];
}
}
return s;
}
console.log(primes(10));
Your problem is in this loop:
for(let j = s[i]*s[i]; j <= num;)
This for loop is looping forever because j is always less than or equal to num in whatever case you're testing. It is very difficult to determine exactly when this code will start looping infinitely because you are modifying the list as you loop.
In effect though, the splice command will be called setting some portion of the indexes in s to 0 which means that j+=s[i] will no longer get you out of the loop.
I have been stumped on this problem for a few hours now and am making no progress. I feel like this should be simple. I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
var newString = string.split("");
var finalArrayWithNoDuplicates = []
for (var i = 0; i < newString.length; i++){
for (var=0; j < newString.length; i++){
while(newString[i])
if (newString[i] !== newString[j]){
}
}
}
return finalArrayWithNoDuplicates.join("");
};
I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding. Is there a way to do this with only using a a for and while loops?
There are several things wrong with the proposed code:
It has serious errors (the inner loop is written all wrong)
You don't need to involve arrays at all, strings will do just fine
The "if char !== other char" check will never provide enough information to act on
Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
var result = "";
for (var i = 0; i < str.length; ++i) {
var found = false;
for (var j = 0; j < i; ++j) {
if (str[i] == str[j]) {
found = true;
break;
}
}
if (!found) result += str[i];
}
return result;
}
Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".
Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
var finalArrayWithNoDuplicates = [];
var seen = {};
for (var i = 0; i < string.length; i++) {
if (!seen[string[i]]) {
finalArrayWithNoDuplicates.push(string[i]);
seen[string[i]] = 1;
}
}
return finalArrayWithNoDuplicates.join("");
};
No need for two nested for-loops
No need for "while" loop as well
in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j
It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {
var finalArrayWithNoDuplicates = []
var x = 0;
for (var i = 0; i < newString.length; i++){
// if the char appears in another index
// or if it's already in the result - don't add it
if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
continue;
}
else{
finalArrayWithNoDuplicates[x++] = newString[i];
}
}
return finalArrayWithNoDuplicates.join("");
};
var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));
OUTPUT:
1234567
I have an array
var aos = ["a","a","a","b","b","c","d","d"];
I want to know if I can remove just 1 item if it finds 2 or more of the same value in the array. So for instance if it finds
"a", "a"
it will remove one of those "a"
This is my current code:
var intDennis = 1;
for (var i = 0; i < aos.length; i++) {
while (aos[i] == aos[intDennis]) {
aos.splice(i, 1);
intDennis++;
console.log(aos[intDennis], aos[i]);
}
intDennis = 1;
}
NOTE: My array is sorted.
Edited after better understanding of OP use-case.
Updated solution and fiddle test to incorporate suggestion from pst in comments.
(Not for nothing, but this method does not require the original array be sorted.)
Try this...
var elements = [];
var temp = {};
for (i=0; i<aos.length; i++) {
temp[aos[i]] = (temp[aos[i]] || 0) + 1;
}
for (var x in temp) {
elements.push(x);
for (i=0; i<temp[x]-2; i++) {
elements.push(x);
}
}
Fiddle Test
Because you said you have a sorted array, you only need to remove the second time a element is found. You only need one for.
The splice() function returns the removed element so, just use it to not remove more elements of that kind.
This solution is more clean and efficient.
var aos = ["a","a","a","b","b","c","d","d"];
var lastRemoved = "";
for (var i = 1; i < aos.length; i++) {
if (aos[(i-1)] == aos[i] && lastRemoved != aos[i]) {
lastRemoved = aos.splice(i, 1);
}
}
Code tested and working. Result: ["a", "a", "b", "c", "d"]
I don't believe there's any better way to do this on an unsorted array than an approach with O(n^2) behaviour. Given ES5 array-builtins (supported in all modern browsers, though not in IE prior to IE9), the following works:
aos.filter(function(value, index, obj) { return obj.indexOf(value) === index; })
UPDATED ANSWER TO REMOVE ONLY 1 DUPLICATE:
Assuming that each object will resolve to a unique String, here's a potential solution. The first time the object is detected, it sets a counter for that object to one. If it finds that object again, it splices that element out and increments the associated counter. If it finds that element more times, it will leave it alone.
var elements = {};
for (var i = 0; i < aos.length; i++) {
if(elements[aos[i]]){
if(elements[aos[i]] == 1){
aos.splice(i,1);//splice the element out of the array
i--;//Decrement the counter to account for the reduced array
elements[aos[i]]++;//Increment the count for the object
}
} else {
elements[aos[i]] = 1;//Initialize the count for this object to 1;
}
}
Here's the test fiddle for this.
I would not mutate the input -- that is, don't use splice. This will simplify the problem a good deal. Using a new array object here may actually be more efficient. This approach utilizes the fact that the input array is sorted.
Consider: (jsfiddle demo)
var input = ["a","a","a","b","b","c","d","d"]
var result = []
for (var i = 0; i < input.length; i++) {
var elm = input[i]
if (input[i+1] === elm) {
// skip first element (we know next is dup.)
var j = i + 1
for (; input[j] === elm && j < input.length; j++) {
result.push(input[j])
}
i = j - 1
} else {
result.push(elm)
}
}
alert(result) // a,a,b,c,d
Happy coding.
Replace === with a custom equality, as desired. Note that it is the first item is omitted from the output, which may not always be "correct".
REVISED EXAMPLE
function removeDuplicate(arr) {
var i = 1;
while(i < arr.length) {
if(arr[i] == arr[i - 1]) {
arr.splice(i, 1);
}
while(arr[i] == arr[i - 1] && i < arr.length) {
i += 1;
}
i += 1;
}
return arr;
}
alert(removeDuplicate(["a","a","a","b","b","c","d","d"]));