My prettier is adding extra empty lines after blocks in JavaScript. It is OK after first save and empty line is just one, but after second save it add another line, and after third save it add one more. It not adds more with further saves.
Example:
function calcTempAmplitude(array1, array2) {
for (temp of array2)
array1.push(temp);
let max = array1[0];
let min = array1[0];
for (temp of array1) {
if (typeof temp !== 'number')
continue;
if (temp > max)
max = temp;
if (temp < min)
min = temp;
}
// return(min <= 0) ? max + min : max - min;
return max - min;
}
console.log(calcTempAmplitude(tempetures1, tempetures2));
how to solve this buggy behavior?
It fixed through reinstalling the Prettier extension!
Related
I've just learned how a binary search works and I need to find the min and max index in a vector. I tried multiple things, but every time my function avoids a part of my code... I have no more ideas, it doesn't seem that difficult but still... I'm struggling a lot with this concept.
EDIT: I realise my explanation were non existant. So what i want to do is, for a given note, i want to find the lowest index of it into a members vector of Song.
heres my closest try :
int Song::binarySearchMin(const Note& note)
{
int Min = 0, Max = notes.size() ,ind=0;
while (Min <= Max)
{
int middle = (Min + Max) / 2;
if (note == notes[middle])
{
ind = middle;
Max = middle;
while (Min <= Max)
{
middle = (Min + Max) / 2;
if ((note == notes[middle]) && (middle <= ind))
{
ind = middle;
}
Max = middle - 1;
}
return ind;
}
else if (note < notes[middle])
{
Max = middle-1;
}
else
{
Min = middle +1;
}
}
return -1;
}
I can't figured out why it's not covering every situation. Right now it work when my index is in the middle. But, it c'ant process multiple index.
as far as I know a binary search works on sorted data so I think it's not a good idea to use it on unsorted data , finding min and max in unsorted vector requires a linear search . and a binary search is efficient in finding an element in a sorted array or vector.
I have to make a program in C++ what can manage a sequence optionally with from 2 to 1000 element. At the end the program has to cout the longest increasing or decreasing sequence's numbers of element.
Examples:
6;1;2;3;2;4;1; output: 3; (because: 1;2;3 is the longest with 3 elements)
6;4;3;1;5;2;1; output: 4; (because: 6;4;3;1 is the longest with 4 elements)
I tired the following code and kind of working. The problem is that it cant give the longest one it gives the number of last sequence every time.
Unfortunately i cant find the bug or problem. Could anyone help please?
int counting = 1;
int counting_max = 0, counting_min = 0;
for (int i = 1; i < n; ++i) {
if(block[i] < block[i+1]) {
if(block[i]-block[i-1]>0) {
counting++;
if(counting>counting_max) {
counting_max = counting;
}}
else {
counting = 1;
}
}
if(block[i] > block[i+1]) {
if(block[i]-block[i-1]<0) {
counting++;
if(counting>counting_min) {
counting_min = counting;
}}
else {
counting = 1;
}
}
}
if(counting_max >= counting_min) {
cout<< counting_max;
}
else {
cout<< counting_min;
}
return 0;}
In my code I didn't share the first part because i guess it works properly.
The first is just a while and for function to call for the elements number and after the exact numbers in a block.
So in my code the block contains the numbers.
In the code you have posted your outer loop creates an out-of-bounds access of the block array, since you're accessing block[i+1] in the loop. That's likely the reason that your code is producing correct answers in one direction and not in the other.
Beyond that there are some other problems you might come across with this approach:
You probably don't need to keep track of two separate counters if in the end you take the largest. You could just keep track of the largest sequence regardless of if it increases or decreases.
Since you test the relationships between three elements in the array to see if the sequence is increasing/decreasing, you will have to add extra logic to handle when the list has fewer than three elements.
You need to be careful of when the same number repeats, as this probably does not count as increasing or decreasing.
Here's a revised version that covers these points:
int counting = std::min(n, 1);
int counting_max = counting;
for (int i = 0; i < n - 1; ++i) {
if (
block[i] < block[i + 1] &&
(counting < 2 || block[i] > block[i - 1])
) {
counting++;
} else if (
block[i] > block[i + 1] &&
(counting < 2 || block[i] < block[i - 1])
) {
counting++;
} else if (block[i] == block[i + 1]) {
counting = 1;
} else {
counting = 2;
}
if (counting > counting_max) {
counting_max = counting;
}
}
cout << counting_max << "\n";
Try this alternate code: counting_max is finding longest ascending sequence and counting_min is finding longest descending sequence(by decrementing its loop counter) and at the end, we compare them to find the ultimate longest(supposing we have n-1 elements, if not change it accordingly)
for (int i=1,j=n-2; i<n && j>=0; ++i,--j) {
if (block[i] - block[i - 1]>0) {
counting++;
if (counting>counting_max)
counting_max = counting;
}
else
counting = 1;
if (block[j] - block[j + 1]>0) {
counting_back++;
if (counting_back>counting_min)
counting_min = counting_back;
}
else
counting_back = 1;
}
if (counting_max >= counting_min)
cout << counting_max;
else
cout << counting_min;
I wrote a code which has to take two string as input. It has to output number of steps(adjacent letter flips or flipping first and last letter) it takes one word to convert to another. It gives correct values till the size of string is 8. If the size of string is more than 8, it gives segmentation fault. I could not find any mistake. Can anyone please help me out. Thanks in advance. This is the code:
map<string,int>imap;
int easyStrings(string a, string b) {
//cout<<a<<endl;
if(a.compare(b) == 0)
return 0;
map<string,int>::iterator it = imap.find(a);
if(it != imap.end())
return it->second;
imap.insert(pair<string,int>(a,-2));
int min = -2;
string str = a;
str[0] = a[a.length()-1];
str[a.length()-1] = a[0];
it = imap.find(str);
if(it == imap.end() || it->second != -2)
min = 1 + easyStrings(str,b);
for(int i = 0 ; i < a.length()-1; i++)
{
string check = a;
check[i] = a[i+1];
check[i+1] = a[i];
int steps = 0;
it = imap.find(check);
if(it == imap.end() || it->second != -2)
{
steps = 1 + easyStrings(check,b);
if(steps < min || min ==-2)
if(steps > 0)
min = steps;
}
}
imap[a] = min;
return min;
}
I tried using debugger. I shows error in imap.insert(pair(a,-2));. It also gives a huge trace showing problems mainly with malloc.
It does not go into infinite recursion. There are factorial of length of input string at maximum and I only insert a string when it is not found in map.
A cursory glance at this function with gdb reveals that this function is recursive, and that strings over a certain length trigger it to enter infinite-depth recursion (or at least a depth that 4 gigs of RAM can't handle). I would look at your recursion conditionals and double check that there is an exit case that will be met for all of them.
I am attempting to make a maze-solver using a Breadth-first search, and mark the shortest path using a character '*'
The maze is actually just a bunch of text. The maze consists of an n x n grid, consisting of "#" symbols that are walls, and periods "." representing the walkable area/paths. An 'S' denotes start, 'F' is finish. Right now, this function does not seem to be finding the solution (it thinks it has the solution even when one is impossible). I am checking the four neighbors, and if they are 'unfound' (-1) they are added to the queue to be processed.
The maze works on several mazes, but not on this one:
...###.#....
##.#...####.
...#.#.#....
#.####.####.
#F..#..#.##.
###.#....#S.
#.#.####.##.
....#.#...#.
.####.#.#.#.
........#...
What could be missing in my logic?
int mazeSolver(char *maze, int rows, int cols)
{
int start = 0;
int finish = 0;
for (int i=0;i<rows*cols;i++) {
if (maze[i] == 'S') { start=i; }
if (maze[i] == 'F') { finish=i; }
}
if (finish==0 || start==0) { return -1; }
char* bfsq;
bfsq = new char[rows*cols]; //initialize queue array
int head = 0;
int tail = 0;
bool solved = false;
char* prd;
prd = new char[rows*cols]; //initialize predecessor array
for (int i=0;i<rows*cols;i++) {
prd[i] = -1;
}
prd[start] = -2; //set the start location
bfsq[tail] = start;
tail++;
int delta[] = {-cols,-1,cols,+1}; // North, West, South, East neighbors
while(tail>head) {
int front = bfsq[head];
head++;
for (int i=0; i<4; i++) {
int neighbor = front+delta[i];
if (neighbor/cols < 0 || neighbor/cols >= rows || neighbor%cols < 0 || neighbor%cols >= cols) {
continue;
}
if (prd[neighbor] == -1 && maze[neighbor]!='#') {
prd[neighbor] = front;
bfsq[tail] = neighbor;
tail++;
if (maze[neighbor] == 'F') { solved = true; }
}
}
}
if (solved == true) {
int previous = finish;
while (previous != start) {
maze[previous] = '*';
previous = prd[previous];
}
maze[finish] = 'F';
return 1;
}
else { return 0; }
delete [] prd;
delete [] bfsq;
}
Iterating through neighbours can be significantly simplified(I know this is somewhat similar to what kobra suggests but it can be improved further). I use a moves array defining the x and y delta of the given move like so:
int moves[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
Please note that not only tis lists all the possible moves from a given cell but it also lists them in clockwise direction which is useful for some problems.
Now to traverse the array I use a std::queue<pair<int,int> > This way the current position is defined by the pair of coordinates corresponding to it. Here is how I cycle through the neighbours of a gien cell c:
pair<int,int> c;
for (int l = 0;l < 4/*size of moves*/;++l){
int ti = c.first + moves[l][0];
int tj = c.second + moves[l][1];
if (ti < 0 || ti >= n || tj < 0 || tj >= m) {
// This move goes out of the field
continue;
}
// Do something.
}
I know this code is not really related to your code, but as I am teaching this kind of problems trust me a lot of students were really thankful when I showed them this approach.
Now back to your question - you need to start from the end position and use prd array to find its parent, then find its parent's parent and so on until you reach a cell with negative parent. What you do instead considers all the visited cells and some of them are not on the shortest path from S to F.
You can break once you set solved = true this will optimize the algorithm a bit.
I personally think you always find a solution because you have no checks for falling off the field. (the if (ti < 0 || ti >= n || tj < 0 || tj >= m) bit in my code).
Hope this helps you and gives you some tips how to improve your coding.
A few comments:
You can use queue container in c++, its much more easier in use
In this task you can write something like that:
int delta[] = {-1, cols, 1 -cols};
And then you simple can iterate through all four sides, you shouldn't copy-paste the same code.
You will have problems with boundaries of your array. Because you are not checking it.
When you have founded finish you should break from cycle
And in last cycle you have an error. It will print * in all cells in which you have been (not only in the optimal way). It should look:
while (finish != start)
{
maze[finish] = '*';
finish = prd[finish];
}
maze[start] = '*';
And of course this cycle should in the last if, because you don't know at that moment have you reach end or not
PS And its better to clear memory which you have allocate in function
I'm trying to get quicksort working to sort an array of 7000 strings into alphabetical order, but all i'm getting is a blank output file. It works fine with my bubblesort method, but not with this. I'm sure it's an obvious mistake, but i can't pin-point it.
void ArrayStorage::quicksort(int first, int last, string list[])
{
int middle, p, index;
string temp, partition;
if (first < last)
{
middle = int(first + last)/2;
temp = list[middle];
list[middle] = list[first];
list[first] = temp;
partition = list[first];
p = first;
for (index = first + 1; index <= last; index++)
{
if(list[index] < partition)
{
p = p + 1;
temp = list[index];
list[index] = list[p];
list[p] = temp;
}
}
temp = list[first];
list[first] = list[p];
list[p] = temp;
quicksort(first, p - 1, list);
quicksort(p + 1, last, list);
}
}
I call the method like this:
quicksort(0,GetSize() -1,namesArray);
How about using the built in quicksort?:
std::sort(&namesArray[0], &namesArray[GetSize()]);
Well as the principle in each loop of quick sort is to make the temp variable in the position that all elements less than it are put left to temp and greater ones on the right. So that must be a loop contains both rightwards iteration to search if there's any number greater than temp and leftwards vice versa. If there is, put the current content to the other side then iterating from the other side until the overall iteration of the list. After the loop all elements less than temp should be on the left while greater ones on right.
temp = list[first];
int f = first, l = last;
while (f < l)
{
while ((f <= l) && (list[l] < temp)) l--;
if (f <= l)
{
list[f] = list[l];
f++;
}
while ((f <= l) && (list[f] > temp)) f++;
if (f <= l)
{
list[l] = list[f];
l--;
}
}
This piece of code should work.(I don't have the compiler on this computer) If it does, try to invoke the function itself recursively.
In addition there's an advice. As many people's recommended you, trying debug and solve the problem yourself.
Hope it helps