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 ->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 -> 8 -> 7 -> 17
2 -> 10 -> 6 -> 6 -> 600
2 -> 10 -> 6 -> 6 -> 17
2 -> 10 -> 6 -> 7 -> 600
2 -> 10 -> 6 -> 7 -> 17
2 -> 10 -> 7 -> 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
Related
I would like to ask how to choose increasing subsequence of elements from a list in Haskell. The rule is that in a not empty list the first element is chosen and then every element that is bigger than the previously chosen element. For example in a list [3,1,8,4,6,7,9,2,11,4,3]
would be chosen sublist [3,8,9,11].
My code so far doesn't cover the problem completely:
incrSub :: Ord a => [a] -> [a]
incrSub [] = []
incrSub (x:xs) = if x < head xs then x: incrSub (xs) else incrSub (xs)
Consider the evaluation of your function on the provided sample input:
incrSub [3, 1, 8, 4, 6, 7, 9, 2, 11, 4, 3]
incrSub (3 : 1 : 8 : 4 : 6 : 7 : 9 : 2 : 11 : 4 : 3 : [])
3 < 1 == False → incrSub (1 : 8 : 4 : 6 : 7 : 9 : 2 : 11 : 4 : 3 : [])
1 < 8 == True → 1 : incrSub (8 : 4 : 6 : 7 : 9 : 2 : 11 : 4 : 3 : [])
8 < 4 == False → 1 : incrSub (4 : 6 : 7 : 9 : 2 : 11 : 4 : 3 : [])
4 < 6 == True → 1 : 4 : incrSub (6 : 7 : 9 : 2 : 11 : 4 : 3 : [])
6 < 7 == True → 1 : 4 : 6 : incrSub (7 : 9 : 2 : 11 : 4 : 3 : [])
7 < 9 == True → 1 : 4 : 6 : 7 : incrSub (9 : 2 : 11 : 4 : 3 : [])
9 < 2 == False → 1 : 4 : 6 : 7 : incrSub (2 : 11 : 4 : 3 : [])
2 < 11 == True → 1 : 4 : 6 : 7 : 2 : incrSub (11 : 4 : 3 : [])
11 < 4 == False → 1 : 4 : 6 : 7 : 2 : incrSub (4 : 3 : [])
4 < 3 == False → 1 : 4 : 6 : 7 : 2 : incrSub (3 : [])
3 < undefined == undefined → 1 : 4 : 6 : 7 : 2 : undefined
Notice the relationship between the actual result and the expected result:
input 3 : 1 : 8 : 4 : 6 : 7 : 9 : 2 : 11 : 4 : 3 : []
expected 3 : 8 : 9 : 11 : []
actual 1 : 4 : 6 : 7 : 2 : undefined
So this suggests a few things to look at:
Your condition is filtering the opposite of what you intended.
You are not handling the end of the list correctly. In particular, consider the case of a 1-element list incrSub [42].
Your code is prone to errors because you’re using head, which is a partial function. Preferring pattern-matching may help, especially if you enable warnings (e.g. passing -Wall to GHC or adding {-# GHC_OPTIONS -Wall #-} to your file). Recall that you can use nested patterns like x1 : x2 : xs to match a list of at least 2 elements x1 and x2.
Working through examples like this using equational reasoning is a very powerful debugging technique for Haskell code. You can also use property-based testing libraries like QuickCheck to identify test cases that fail. For example, it quickly identifies the minimal failing test case of singleton lists:
> import Test.QuickCheck (quickCheck)
> resultIsSorted :: [Int] -> Bool; resultIsSorted input = let { result = incrSub input } in result == sort result
> quickCheck resultIsSorted
*** Failed! Exception: 'Prelude.head: empty list' (after 2 tests and 2 shrinks):
[0]
You can write more complex properties to find more interesting edge cases.
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)
I'm new to haskell and I want to sort list of strings. For example I have a list that is in my variable ff that contain three strings ["1 8 8 5 6", "1 4 2 3", "5 4 9 7 9 9"] and I want to sort them so my result should look like ["1 5 6 8 8", "1 2 3 4", "4 5 7 9 9 9"] Here's my code that perfectly works
import System.IO
import Control.Monad
import Data.List
import Data.Function
import Data.Array
import Data.Char
sortNumeric = sortBy (compare `on` (read :: String -> Int))
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
"" -> []
s' -> w : wordsWhen p s''
where (w, s'') = break p s'
main = do
file <- readFile "test.txt"
let ff = map ((!!) (lines file)) [1,3..(length (lines file) - 1)]
let splitString = wordsWhen (==' ') (ff!!0)
let sortedResult = sortNumeric (splitString)
print sortedResult
Problem is with this line let splitString = wordsWhen (==' ') (ff!!0) I always get first element of the list, so only first element is sorted. How can I pass all values of a list? Here's what I tryied to do let splitString = wordsWhen (==' ') (ff!![0..(length(ff)-1)]) unfortunately this doesn't work. Any ideas how to solve this problem?
You can do it easily with map and a niftry trick to use words, sort and then unwords (to restore the whitespace).
Prelude> let ff=["1 8 8 5 6", "1 4 2 3", "5 4 9 7 9 9"]
Prelude> import Data.List
Prelude Data.List> map (unwords . sort . words) ff
["1 5 6 8 8","1 2 3 4","4 5 7 9 9 9"]
Edit: Improvement to correctly sort numeric values:
import Data.List
let ff=["11 8 8 5 6", "11 4 2 3", "5 4 9 7 99 9"]
let sortNumeric = (map show) . sort . (map (read :: String -> Int))
map (unwords . sortNumeric . words) ff
result:
["5 6 8 8 11","2 3 4 11","4 5 7 9 9 99"]
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