So, I stumbled upon this problem recently. I can't figure out what is happening in this code. I used a compiler to create and linked list and inserted the values in it to get the answer
check this code first the question is as follows what will happen to the linklist after it is passed in this function.
front -> 25 -> 40 -> 50 -> 20 -> 50 -> 10 -> 8 -> 60 -> 60 -> 37 /
what will be its state after it the function is called
The function is given below
void linklink(node*& front) {
node* curr = front;
while (curr->next != NULL) {
node* temp = curr->next;
if (curr->data >= curr->next->data) {
curr->next = temp->next;
if (curr->data == temp->data) {
curr->next = temp->next;
delete temp;
} else {
temp->next = front;
front = temp;
}
} else {
curr = curr->next;
}
}
}
I am a novice, just started to learn pointers and linked lists , Can anyone explain how we are getting this answer (front -> 37 -> 8 -> 10 -> 20 -> 25 -> 40 -> 50 -> 60 -> ) The more the detailed explaining the better it is gonna be for me to understand . Thanks in advance.
When curr has smaller data than its next, it just moves the point to the next node.
When curr has bigger data than curr->next, it moves the node curr->next to the first of the link.
When curr is same with curr->next, it deletes the next node.
It would work like this.
curr25 -> 40 -> 50 -> 20 -> 50 -> 10 -> 8 -> 60 -> 60 -> 37 (1st while)
25 -> curr40 -> 50 -> 20 -> 50 -> 10 -> 8 -> 60 -> 60 -> 37 (2nd while)
25 -> 40 -> curr50 -> 20 -> 50 -> 10 -> 8 -> 60 -> 60 -> 37 (3rd while)
20 -> 25 -> 40 -> curr50 -> 50 -> 10 -> 8 -> 60 -> 60 -> 37 (4th while)
20 -> 25 -> 40 -> curr50 -> 10 -> 8 -> 60 -> 60 -> 37 (5th while)
10 -> 20 -> 25 -> 40 -> curr50 -> 8 -> 60 -> 60 -> 37 (6th while)
8 -> 10 -> 20 -> 25 -> 40 -> curr50 -> 60 -> 60 -> 37 (7th while)
8 -> 10 -> 20 -> 25 -> 40 -> 50 -> curr60 -> 60 -> 37 (8th while)
8 -> 10 -> 20 -> 25 -> 40 -> 50 -> curr60 -> 37 (9th while)
37 -> 8 -> 10 -> 20 -> 25 -> 40 -> 50 -> curr60 (10th while)
Related
The command
ogr2ogr -f GeoJSON out.json BGRI2021_0706.gpkg
returns
ERROR 1: database disk image is malformed
FAILURE:
Unable to open datasource `BGRI2021_0706.gpkg' with the following drivers.
-> `FITS'
-> `PCIDSK'
-> `netCDF'
-> `PDS4'
-> `VICAR'
-> `JP2OpenJPEG'
-> `PDF'
-> `MBTiles'
-> `BAG'
-> `EEDA'
-> `OGCAPI'
-> `ESRI Shapefile'
-> `MapInfo File'
-> `UK .NTF'
-> `LVBAG'
-> `OGR_SDTS'
-> `S57'
-> `DGN'
-> `OGR_VRT'
-> `REC'
-> `Memory'
-> `CSV'
-> `NAS'
-> `GML'
-> `GPX'
-> `LIBKML'
-> `KML'
-> `GeoJSON'
-> `GeoJSONSeq'
-> `ESRIJSON'
-> `TopoJSON'
-> `Interlis 1'
-> `Interlis 2'
-> `OGR_GMT'
-> `GPKG'
-> `SQLite'
-> `ODBC'
-> `WAsP'
-> `PGeo'
-> `MSSQLSpatial'
-> `OGR_OGDI'
-> `PostgreSQL'
-> `MySQL'
-> `OpenFileGDB'
-> `DXF'
-> `CAD'
-> `FlatGeobuf'
-> `Geoconcept'
-> `GeoRSS'
-> `GPSTrackMaker'
-> `VFK'
-> `PGDUMP'
-> `OSM'
-> `GPSBabel'
-> `OGR_PDS'
-> `WFS'
-> `OAPIF'
-> `SOSI'
-> `Geomedia'
-> `EDIGEO'
-> `SVG'
-> `CouchDB'
-> `Cloudant'
-> `Idrisi'
-> `ARCGEN'
-> `XLS'
-> `ODS'
-> `XLSX'
-> `Elasticsearch'
-> `Walk'
-> `Carto'
-> `AmigoCloud'
-> `SXF'
-> `Selafin'
-> `JML'
-> `PLSCENES'
-> `CSW'
-> `VDV'
-> `GMLAS'
-> `MVT'
-> `NGW'
-> `MapML'
-> `TIGER'
-> `AVCBin'
-> `AVCE00'
-> `HTTP'
I am in the correct directory and the file exists
ll BGRI2021_0706.gpkg -h
-rw-r--r-- 1 joao joao 1,1M nov 28 18:07 BGRI2021_0706.gpkg
ogr2ogr support the format:
$ ogrinfo --formats | grep GPKG
GPKG -raster,vector- (rw+vs): GeoPackage
I am using v3.3.2
$ ogr2ogr --version
GDAL 3.3.2, released 2021/09/01
this is my code
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode* odd=head;
ListNode* even=odd->next;
ListNode* evenStart = even;
while(odd->next!=NULL && even->next!=NULL)
{
odd->next = even->next;
odd=odd->next;
even=odd->next;
even=even->next;
}
odd->next=evenStart;
return head;
}
};
and is showing error
Line 18: Char 41: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:27:41
Take a look at this screen shot
Your first few lines are assuming that the list has at least two elements.
This is your first problem.
If you fix that, note that all you know when you enter the loop body is that odd->next!=NULL && even->next!=NULL.
On the first iteration, this means that the list has at least three elements.
Let's draw a list and see what happens.
"o" and "e" are odd and even, and the curly brace is the boundary to the unknown part of the list, which might not exist:
1 -> 2 -> 3 -> { 4 -> 5 -> 6 ...
o e
odd->next = even->next
+---------+
| V
1 2 -> 3 -> { 4 -> 5 -> 6 ...
o e
odd = odd->next
+---------+
| V
1 2 -> 3 -> { 4 -> 5 -> 6 ...
e o
even = odd->next
+---------+
| V
1 2 -> 3 -> { 4 -> 5 -> 6 ...
o e
Oops...
even = even->next
+---------+
| V
1 2 -> 3 -> { 4 -> 5 -> 6 ...
o e
Double oops.
Work out the solution using pen(cil) and paper first.
It's by far the best method to solve (and debug) pointer manipulation problems.
I won't give you a solution, because how much fun would that be?
Error: You are trying to access the 'next' data member of a NULL pointer of type ListNode.
Solution: You should check if(even!=NULL) then condition(even->next)
take example 1,2,3,4
Iterations:
odd -> 1, odd->next -> 2, even -> 2, even->next -> 3
odd -> 3, odd->next -> 4, even -> NULL
now if you check odd->next!=NULL is true but even->next will throw the error.
I have stored a directed graph in a 2D vector and I want to iterate through all the possible path from any directed graph going from left to right via groups in a recursive manner. I have given an example below and want to iterate through all the paths from the first group (in this example G1) to any last group (in this example G3). I have been trying a lot but I'm not able to build a recursive to iterate through all the paths with any amount of groups. So I need help with building a manual iteration system/algorithm of loops without recursion function calls. For the iteration part, if I can get an algorithm which can print all the possible paths, it will be more than helpful. So, any source, tips and tricks will be useful. Thanks.
graph:
script.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> map = {
{ 1, 2 },
{ 3, 4, 5 },
{ 6, 7 }
};
// Print all paths
// Note :- every array in the map is a group
return 0;
}
output:
1 -> 3 -> 6
1 -> 3 -> 7
1 -> 4 -> 6
1 -> 4 -> 7
1 -> 5 -> 6
1 -> 5 -> 7
2 -> 3 -> 6
2 -> 3 -> 7
2 -> 4 -> 6
2 -> 4 -> 7
2 -> 5 -> 6
2 -> 5 -> 7
#Compile using g++ -std=c++11 code.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int> > map = {
{ 1, 2 },
{ 3, 4, 5 },
{ 6, 7 }
};
vector<int> sizes(map.size());
vector<int> indexes(map.size());
int combinations = 1;
for(int i=0; i<map.size();i++){
sizes[i]=map[i].size();
}
for(int i=0; i<map.size();i++){
combinations*=map[i].size();
}
for(int combination=1; combination <= combinations; combination++){
int multiple = 1;
for(int ind=0; ind<indexes.size(); ind++){
cout << map[ind][indexes[ind]];
if(ind < indexes.size()-1)
cout << " -> ";
}
cout << endl;
for(int j=map.size()-1;j>=0;j--){
multiple*=map[j].size();
indexes[map.size()-1]=combination % map[map.size()-1].size();
if(combination % multiple == 0 && j>0){
//cout << "*";
indexes[j-1] = (indexes[j-1]+1)%map[j-1].size();
}
}
}
return 0;
}
vector<vector<int> > map = {
{ 1, 2 },
{ 3, 4, 5, 10, 100 },
{ 6, 7, 8 },
{ 6, 7 },
{ 600, 17 }
};
1 -> 3 -> 6 -> 6 -> 600
1 -> 3 -> 6 -> 6 -> 17
1 -> 3 -> 6 -> 7 -> 600
1 -> 3 -> 6 -> 7 -> 17
1 -> 3 -> 7 -> 6 -> 600
1 -> 3 -> 7 -> 6 -> 17
1 -> 3 -> 7 -> 7 -> 600
1 -> 3 -> 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-> 6 -> 600
2 -> 10 -> 7 -> 6 -> 17
2 -> 10 -> 7 -> 7 -> 600
2 -> 10 -> 7 -> 7 -> 17
2 -> 10 -> 8 -> 6 -> 600
2 -> 10 -> 8 -> 6 -> 17
2 -> 10 -> 8 -> 7 -> 600
2 -> 10 -> 8 -> 7 -> 17
2 -> 100 -> 6 -> 6 -> 600
2 -> 100 -> 6 -> 6 -> 17
2 -> 100 -> 6 -> 7 -> 600
2 -> 100 -> 6 -> 7 -> 17
2 -> 100 -> 7 -> 6 -> 600
2 -> 100 -> 7 -> 6 -> 17
2 -> 100 -> 7 -> 7 -> 600
2 -> 100 -> 7 -> 7 -> 17
2 -> 100 -> 8 -> 6 -> 600
2 -> 100 -> 8 -> 6 -> 17
2 -> 100 -> 8 -> 7 -> 600
2 -> 100 -> 8 -> 7 -> 17
Here is the solution in recursive way:
#include <iostream>
#include <vector>
using namespace std;
void solve(vector < vector<int> >map, vector<int>ans, int pos) {
if(pos == map.size()) {
for(int i = 0; i < ans.size(); i++) {
cout<<ans[i];
if(i != ans.size() - 1) {
cout<<"->";
}
else {
cout<<endl;
}
}
return;
}
for(int i = 0; i < map[pos].size(); i++) {
ans.push_back(map[pos][i]);
solve(map, ans, pos+1);
ans.pop_back();
}
}
int main() {
vector<vector<int> > map = {
{ 1, 2 },
{ 3, 4, 5 },
{ 6, 7 }
};
vector<int>empty;
solve(map, empty, 0);
}
Output:
1->3->6
1->3->7
1->4->6
1->4->7
1->5->6
1->5->7
2->3->6
2->3->7
2->4->6
2->4->7
2->5->6
2->5->7
Problem Statement:
On a positive integer, you can perform any one of the following 3 steps.
Subtract 1 from it. ( n = n - 1 )
If its divisible by 2, divide by 2. ( if n % 2 == 0 , then n = n / 2 )
If its divisible by 3, divide by 3. ( if n % 3 == 0 , then n = n / 3 )
Given a positive integer n and you task is find the minimum number of steps that takes n to one .
My Recursive Solution (in C++) compares all the 3 cases when N is divisible by 3, while the general solution compares only 2, but still gives the correct solution.
int min_steps(int N){
if(N==1) return 0;
else{
if(N%3==0){
if(N%2==0)
return (1+min(min_steps(N/3),min_steps(N/2),min_steps(N-1)));
else
return(1+min(min_steps(N/3),min_steps(N-1)));
}
else if(N%2==0){
return(1+min(min_steps(N/2),min_steps(N-1)));
}
else
return(1+min_steps(N-1));
}
}
But the general solution is,
int min_steps(int N){
if(N==1) return 0;
else{
if(N%3==0){
return(1+min(min_steps(N/3),min_steps(N-1)));
}
else if(N%2==0){
return(1+min(min_steps(N/2),min_steps(N-1)));
}
else
return(1+min_steps(N-1));
}
}
My question is, how come we don't compare all the 3 cases but still derive at the correct solution. I cannot follow the general solution's algorithm. Any help for letting me understand would be appreciated hugely.
The "general solution" is incorrect. Sometime's it's optimal to divide by 2 and then subtract 1, and the general solution code doesn't allow for that.
The "general solution" produces incorrect results for 642.
642 -> 214 -> 107 -> 106 -> 53 -> 52 -> 26 -> 13 -> 12 -> 4 -> 2 -> 1
However, this is optimal, being one shorter:
642 -> 321 -> 320 -> 160 -> 80 -> 40 -> 20 -> 10 -> 9 -> 3 -> 1
You can see the general solution starts by dividing by 3, and the optimal solution starts by dividing by 2 and then subtracting 1... which is exactly the case that's been removed.
While it's not directly relevant to your question, here's the code I used to find the counter-example (albeit greatly tidied up since I wrote it). It uses the two algorithms you gave, but memoizes them for an exponential speed increase. It also uses a trick of returning two results from min_steps: not only the length of the shortest path, but also the first step in that path. This makes it extremely convenient to reconstruct the path without writing much extra code.
def memoize(f):
"""Simple memoization decorator"""
def mf(n, div2, cache={}):
if (n, div2) not in cache:
cache[n, div2] = f(n, div2)
return cache[(n, div2)]
return mf
#memoize
def min_steps(n, div2):
"""Returns the number of steps and the next number in the solution.
If div2 is false, the function doesn't consider solutions
which involve dividing n by 2 if n is divisible by 3.
"""
if n == 1:
return 0, None
best = min_steps(n - 1, div2)[0] + 1, n-1
if n % 3 == 0:
best = min(best, (min_steps(n // 3, div2)[0] + 1, n//3))
if n % 2 == 0 and (div2 or n%3):
best = min(best, (min_steps(n // 2, div2)[0] + 1, n//2))
return best
def path(n, div2):
"""Generates an optimal path starting from n.
The argument div2 has the same meaning as in min_steps.
"""
while n:
yield n
_, n = min_steps(n, div2)
# Search for values of n for which the two methods of finding
# an optimal path give different results.
for i in xrange(1, 1000):
ms1, _ = min_steps(i, True)
ms2, _ = min_steps(i, False)
if ms1 != ms2:
print i, ms1, ms2
print ' -> '.join(map(str, path(i, True)))
print ' -> '.join(map(str, path(i, False)))
Here's the output, including run-times:
$ time python minsteps.py
642 10 11
642 -> 321 -> 320 -> 160 -> 80 -> 40 -> 20 -> 10 -> 9 -> 3 -> 1
642 -> 214 -> 107 -> 106 -> 53 -> 52 -> 26 -> 13 -> 12 -> 4 -> 2 -> 1
643 11 12
643 -> 642 -> 321 -> 320 -> 160 -> 80 -> 40 -> 20 -> 10 -> 9 -> 3 -> 1
643 -> 642 -> 214 -> 107 -> 106 -> 53 -> 52 -> 26 -> 13 -> 12 -> 4 -> 2 -> 1
real 0m0.009s
user 0m0.009s
sys 0m0.000s
If n is divisible by 3 and divisible by 2, then it does not matter if you divide by 3 first and then by 2 in the next step, or by 2 first and then by 3 in the next step.
Example: 18 = 3*3*2
a) 18/3 = 6, 6/3 = 2, 2/2 = 1, or
b) 18/2 = 9, 9/2 = #!?#, 9/3 = 3, 3/3 = 1, or ...
I have datatype:
data SidesType = Sides Int Int Int deriving (Show)
And I need a function which get a list of SidesType and remove duplicates from it.
*Main> let a = [Sides 3 4 5,Sides 3 4 5,Sides 5 12 13,Sides 6 8 10,Sides 6 8 10,Sides 8 15 17,Sides 9 12 15,Sides 5 12 13,Sides 9 12 15,Sides 12 16 20,Sides 8 15 17,Sides 15 20 25,Sides 12 16 20,Sides 15 20 25]
*Main> removeDuplicateFromList [] a
[Sides 3 4 5,Sides 5 12 13,Sides 6 8 10,Sides 6 8 10,Sides 8 15 17,Sides 9 12 15,Sides 5 12 13,Sides 9 12 15,Sides 12 16 20,Sides 8 15 17,Sides 15 20 25,Sides 12 16 20,Sides 15 20 25]
Here is my solution:
removeElementFromList :: [SidesType] -> SidesType -> [SidesType]
removeElementFromList lst element =
let (Sides a b c) = element
in [(Sides x y z) | (Sides x y z) <- lst, (x /= a) || (y /= b)]
removeDuplicateFromList :: [SidesType] -> [SidesType] -> [SidesType]
removeDuplicateFromList inlist outlist
| (length outlist) == 0 = inlist
| otherwise =
let element = head outlist
b = tail outlist
filtered = removeElementFromList b element
in removeDuplicateFromList (inlist ++ [element]) filtered
I am just wondering if there is any other way to write this code in more haskell-way ?
As usual there is "By" function which adds flexibility:
nubBy :: (a -> a -> Bool) -> [a] -> [a]
PS Although it's O(n^2)
You're already deriving Show for your datatype. If you also derive Eq, you can use nub from module Data.List.
Use Data.List.nub
First derive the order class also:
data XYZ = XYZ .... deriving (Show, Eq, Ord)
Or write your on Eq instance:
instance Eq XYZ where
a == b = ...
Then be intelligent and use a Tree! [Computer Science Trees grow from top to bottom!][1]
import qualified Data.Map.Strict as Map
removeDuplicates ::[a] -> [a]
removeDuplicates list = map fst $ Map.toList $ Map.fromList $ map (\a -> (a,a)) list
Complexity (from right to left) for list with length N:
map of the list: O(N)
Map.fromList: O(N*log N)
Map.toList: O(log N)
map over list with list length smaller or equal to N: O(N)
They are called consecutively, this means, there are pluses between the complexities of the parts => O(2 * N + N * log N + log N) = O(N * log N)
This is way better than traversing N^2 times over the list!
See: wolframAlpha plots. I included 2*N also for comparison reasons.
2+3: http://hackage.haskell.org/package/containers-0.5.4.0/docs/Data-Map-Strict.html
[1]: Search wikipedia for Computer Science Tree