OCAML counting frequency of char using switches - switch-statement

I am trying to count the amount of time each char appears in a string, I'm using switches and a for loop, however, they are not being incremented properly. Here is my code
let countChar x =
match x with
'A'-> countA := !countA +1;
|'C'-> countC := !countC +1;
|'T'-> countT := !countT +1;
|'G'-> countG := !countG +1;
;;
let demoStri = "ACGTACGT" in
for j = 0 to 7 do
countChar demoStri.[j];
let tempA = !countA in
print_int tempA;
print_string "\n";
let tempC = !countC in
print_int tempC;
print_string "\n";
let tempG = !countG in
print_int tempG;
print_string "\n";
let tempT = !countT in
print_int tempT;
print_string "\n";
done
But for some reason it's only incrementing 1, and it returns 1 0 0 0, 2 0 0 0, 3 0 0 0 and so on..... I was wondering if something went wrong in the process?

I see no problem with this code in its current form, it works for me. You don't show your initializations of countA, countC, countT, and countG, but if I initialize as follows:
let countA = ref 0
let countC = ref 0
let countT = ref 0
let countG = ref 0
Then run your code I get this series of numbers (collapsed four to a line to save space):
1 0 0 0
1 1 0 0
1 1 1 0
1 1 1 1
2 1 1 1
2 2 1 1
2 2 2 1
2 2 2 2

The biggest problem here is that you are using the tempH variable to index the string instead of the j you should have been using.
let () =
let demoStri = "ACGTACGT" in
let countA = ref 0 in
let countC = ref 0 in
let countT = ref 0 in
let countG = ref 0 in
for j = 0 to String.length demoStri - 1 do
match demoStri.[j] with
| 'A'-> countA := !countA +1
| 'C'-> countC := !countC +1
| 'T'-> countT := !countT +1
| 'G'-> countG := !countG +1
| _ -> assert false
done;
print_int !countA; print_string "\n";
print_int !countC; print_string "\n";
print_int !countT; print_string "\n";
print_int !countG; print_string "\n"

Related

Dynamic programming table for number of steps problem

There is a well known problem called "Triple Step" that states:
"A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs"
The algorithm below is a version without memoization:
int countWays(int n) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
} else {
return countWays(n-1) + countWays(n-2) + countWays(n-3);
}
}
I know that its runtime can be improved from the exponential time complexity.
But I really would like to know how to build a dynamic programming table over this problem,
for example I tried the table below for n being 4 steps:
0 | 1 | 2 | 3 | 4 <= staircase size
1 1 | 1 | 1 | 1 | 1
2 1 | 1 | 2 | 2 | 3
3 1 | 1 | 2 | 3 | 4 <=** There's something wrong because for n=4 the output should be 7
Could someone give me a hint about how this table could be built for the problem above? (or maybe the table is fine and I'm not able to interpret it right)
Thanks!
As you mentioned that countWays(N) can be solved by taking sum of countWays(N-1), countWays(N-2) and countWays(N-3).
Since we know the answer for n<=0, we can start constructing our solution from n=0 to n=N and at any point of time we will always have N-1, N-2 and N-3 values ready to be used.
In the process of constructing solution from n=0 to n=N at any point of time we should have results of our earlier calculations stored somewhere.
you can take 3 variables to store these values and keep updating these 3 variables at each iteration to store the last 3 calculations.
int countWays(int n) {
int last = 1; // for n = 0
int secondLast = 0; // for n = -1
int thridLast = 0; // for n = -2
for(int i = 1 ; i <= n ; i++) {
int current = last + secondLast + thirdLast;
thirdLast = secondLast;
secondLast = last;
last = current;
}
return last;
}
instead of taking 3 variables you can store all the earlier calculations in an array and the code will look like this,
int countWays(int n) {
if(n<0) return 0;
int[] a = new int[n+3];
a[0] = 0;
a[1] = 0;
a[2] = 1; // stores the result for N=0
for(int i = 3 ; i < n+3 ; i++) {
a[i] = a[i-1] + a[i-2] + a[i-3];
}
return a[n+2];
}
and array will look like,
Answer -> [0, 0, 1, 1, 2, 4, 7]
Value Of N -> -2, -1,0 ,1, 2, 3, 4
Array created in this solutions is known is dynamic programming table also known as memoization or bottom up approach to DP
Run time complexity of above solution is O(N)
There is another way to solve these type of problems in O(Log N) time complexity, where solution can be described in terms of a linear recurrence relation.
The solution is known as Matrix Exponentiation, follow this link for more explanation - https://discuss.codechef.com/t/building-up-the-recurrence-matrix-to-compute-recurrences-in-o-logn-time/570
The table for this is 1d which is the staircase size, on every step x you add x-1, x-2, and x-3 if possible, for example:
0 | 1 | 2 | 3 | 4 <= staircase size
1st step 1 | 1 | 0 | 0 | 0 only x-1 is possible
2nd step 1 | 1 | 2 | 0 | 0 x-1 + x-2 are possible
3rd step 1 | 1 | 2 | 4 | 0 x-1 + x-2 + x-3 are possible
4th step 1 | 1 | 2 | 4 | 7 x-1 + x-2 + x-3 are possible
More explanation:
Step 1:
only reachable by 1-step
Step 2:
1-step + 1-step
2-steps
Step 3:
1-step + 1-step + 1-step
1-step + 2-steps
2-steps + 1-step
3-steps
Step 4:
1-step + 1-step + 1-step + 1-step
2-steps + 1-step + 1-step
1-step + 2-steps + 1-step
1-step + 1-step + 2-steps
1-step + 3-steps
3-steps + 1-step
2-steps + 2-steps
Assume that you are using dynamic programming to solve the problem.
Let a be the name of the variable of your table.
The formulae for a[n] with n = 0, 1, 2, .... are as you mentioned:
a[0] = 1
a[n] = a[n-1] + a[n-2] + a[n-3]
Be sure that a[n] for n < 0 is 0 always.
The answer for staircase size = 4 can be solved only if all the answers for 0 <= staircase size < 4 are given. i.e., a[4] can be calculated only if a[0], a[1], ..., a[3] are calculated.
The answer for staircase size = 3 can be solved only if all the answers for 0 <= staircase size < 3 are given. i.e., a[3] can be calculated only if a[0], ..., a[2] are calculated.
The answer for staircase size = 2 can be solved only if all the answers for 0 <= staircase size < 2 are given. i.e., a[2] can be calculated only if a[0], a[1] are calculated.
The answer for staircase size = 1 can be solved only if all the answers for 0 <= staircase size < 1 are given. i.e., a[1] can be calculated only if a[0] is calculated.
a[0] is the first formula.
Here, you can start.
a[0] = 1 // Initialization
a[1] = a[0] + a[-1] + a[-2] = a[0] + 0 + 0 // calculated at 1st loop (a[1] = 1)
a[2] = a[1] + a[0] + a[-1] = a[1] + a[0] + 0 // calculated at 2nd loop (a[2] = 1 + 1)
a[3] = a[2] + a[1] + a[0] // calculated at 3rd loop (a[3] = 2 + 1 + 1)
a[4] = a[3] + a[2] + a[1] // calculated at 4th loop (a[4] = 4 + 2 + 1)
...
a[n] = a[n-1] + a[n-2] + a[n-3] // calculated at nth loop

How to do a string match on a set of digits?

I have the following data set:
Word-1-random
Word-2-random
Word-3-random
Word-4-random
upto
Word-19-random
Other-Word-1-random
Other-Word-2-random
Other-Word-3-random
Other-Word-4-random
upto
Other-Word-19-random
Now i want to do a match on a group of date, digits 1 - 5, 6-10, 11-15 etc.
I thought it was the following:
match("^Word%-d[1-5]%-",string)
match("%-Word%-d[1-5]%-",string)
Acording to you example, the idea could be something like this:
<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">
local text = [[
Word-1-random
Word-2-random
Word-3-random
Word-4-random
upto
Word-19-random
Other-Word-1-random
Other-Word-2-random
Other-Word-3-random
Other-Word-4-random
Other-Word-5-random
Other-Word-6-random
Other-Word-7-random
Other-Word-8-random
Other-Word-9-random
Other-Word-10-random
Other-Word-11-random
]]
local s1,s2
local grp,cnt = 0,0
text:gsub('(%S+%-)(%d+)(%-%S+)', function(p1,n,p2)
if s1 ~= p1 or s2 ~= p2 or cnt == 5 then
print('Group'..grp)
s1,s2 = p1,p2
cnt = 0
grp = grp + 1
end
print(p1..n..p2)
cnt = cnt + 1
end)
</script>

Coin Chane - Dynamic Programming - How read all solutions from the DP table

I have seen different solutions to the same problem, but none of them seem to use the approach I used. So here I'm trying to solve the classical coin-change problem in a bottom up dynamic programming approach using a DP table.
int[][] dp = new int[nums.length+1][target+1];
for (int i = 0; i <= nums.length; ++i)
dp[i][0] = 1;
for (int i = 1; i < dp.length; ++i) {
for (int j = 1; j < dp[i].length; ++j) {
if (nums[i-1] <= j)
dp[i][j] = dp[i-1][j] + dp[i][j-nums[i-1]];
else
dp[i][j] = dp[i-1][j];
}
}
The above code generates the table. For fun if I have: {2,3,5} coins, and want to exchange 8, the table would look like:
1 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1
1 0 1 1 1 1 2 1 2
1 0 1 1 1 2 2 2 3
For the above the following method seem to be working well:
current <- 4
while (current > 0) do
i <- current
j <- 8
while (j > 0) do
if (dp[i][j] != dp[i-1][j]) then
nums[i-1] is part of the current solution
j <- j-1
else
i <- i-1
end
end
current <- current-1
end
Walking through for the above example, we get the following solutions:
1) [5,3]
2) [3,3,2]
3) [2,2,2,2]
Which is great! At least I thought, until I tried: {1,2} with a T=4. For this the table looks like:
1 0 0 0 0
1 1 1 1 1
1 1 2 2 3
With the above algorithm to print all solutions, I only get:
[2,2]
[1,1,1,1]
Which means I won't recover [2,1,1]. So this question is not about the generic how to print the solutions for different approaches to this problem, but how can I read the above DP table to find all solutions.
Well I have one solution but sure... I can see why the other similar answers are using different approaches for this problem. So the algorithm to generate all the possible answers from the above table looks like:
private List<List<Integer>> readSolutions(int[] nums, int[][] dp, int currentRow, int currentColumn, List<Integer> partialSolution) {
if (currentRow == 0) {
return new ArrayList<>();
}
if (currentColumn == 0) {
return new ArrayList<List<Integer>>(Collections.singleton(partialSolution));
}
List<List<Integer>> solutions = new ArrayList<>();
if (dp[currentRow][currentColumn] != dp[currentRow-1][currentColumn]) {
List<Integer> newSolution = new ArrayList<>(partialSolution);
newSolution.add(nums[currentRow-1]);
solutions.addAll(readSolutions(nums, dp, currentRow, currentColumn-nums[currentRow-1], newSolution));
solutions.addAll(readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution));
return solutions;
}
return readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution);
}
The logic on the other hand is simple. Take the above table for example:
0 1 2 3 4
0 1 0 0 0 0
1 1 1 1 1 1
2 1 1 2 2 3
To get a single solution we start from the bottom right corner. If the value does match with the value directly above us, we move up. If it doesn't we move left by the amount corresponding to the row we're in. To generate all answers on on the other hand from the above table...
we're at some position (i,j)
if the value at (i-1,j) is the same as (i,j) we make a recursive call to (i-1,j)
if the values do not match, we have 2 choices...
we can use the number corresponding to the current row, and recurse into (i,j-n)
we can skip the number and check if we can create (i,j) instead by using a recursive call to (i-1,j) instead.
if we reach the first row, we return an empty list
if we reach the first column, we return what we have already found, which will have the sum of target.
Looks awful right, but works as expected.

OCaml counter does not terminate without using threads

I have the following code:
let counter n =
let rec count i =
if i > n
then ()
else
print_int i;
count (i+1)
in count 0
It should simply output all numbers from 0 to n. To clarify, I know there are easier ways to achieve the same result but I want to know why it is not working in this specific case.
When I run this code with some parameter eg. counter 5 it does not terminate.
Instead when I change the last line of my code in count 0 to in Thread.create count 0 it outputs 012345
Can someone explain this behaviour?
EDIT
Also found that if you modify the code to this:
let counter n =
let rec count i =
if i > n
then ()
else
let i = i
in print_int i;
count (i+1)
in count 0
it works fine. Why is this?
Your indentation is misleading; your code does
if i > n then () else print_int i;
first and then
count (i+1)
Of course it doesn't terminate! What you want is
else begin
print_int i;
count (i+1)
end
(or else ( ... )). See e.g. "Using begin ... end" in https://ocaml.org/learn/tutorials/if_statements_loops_and_recursion.html.

MDP Policy Plot for a Maze

I have a 5x-5 maze specified as follows.
r = [1 0 1 1 1
1 1 1 0 1
0 1 0 0 1
1 1 1 0 1
1 0 1 0 1];
Where 1's are the paths and 0's are the walls.
Assume I have a function foo(policy_vector, r) that maps the elements of the policy vector to the elements in r. For example 1=UP, 2=Right, 3=Down, 4=Left. The MDP is set up such that the wall states are never realized so policies for those states are ignored in the plot.
policy_vector' = [3 2 2 2 3 2 2 1 2 3 1 1 1 2 3 2 1 4 2 3 1 1 1 2 2]
symbols' = [v > > > v > > ^ > v ^ ^ ^ > v > ^ < > v ^ ^ ^ > >]
I am trying to display my policy decision for a Markov Decision Process in the context of solving a maze. How would I plot something that looks like this? Matlab is preferable but Python is fine.
Even if some body could show me how to make a plot like this I would be able to figure it out from there.
function[] = policy_plot(policy,r)
[row,col] = size(r);
symbols = {'^', '>', 'v', '<'};
policy_symbolic = get_policy_symbols(policy, symbols);
figure()
hold on
axis([0, row, 0, col])
grid on
cnt = 1;
fill([0,0,col,col],[row,0,0,row],'k')
for rr = row:-1:1
for cc = 1:col
if r(row+1 - rr,cc) ~= 0 && ~(row == row+1 - rr && col == cc)
fill([cc-1,cc-1,cc,cc],[rr,rr-1,rr-1,rr],'g')
text(cc - 0.55,rr - 0.5,policy_symbolic{cnt})
end
cnt = cnt + 1;
end
end
fill([cc-1,cc-1,cc,cc],[rr,rr-1,rr-1,rr],'b')
text(cc - 0.70,rr - 0.5,'Goal')
function [policy_symbolic] = get_policy_symbols(policy, symbols)
policy_symbolic = cell(size(policy));
for ii = 1:length(policy)
policy_symbolic{ii} = symbols{policy(ii)};
end

Resources