I have this sequence:
let wheel235 = [4; 2; 4; 2; 4; 6; 2; 6]
let wheel = seq { while true yield! wheel235 }
I'd like to build a second sequence that starts on a particular number, and each following number in that sequence is the previous number with the next item in the wheel sequence added to it. So if I started the sequence at 5, I would have 5, 9, 11, 15, 17, 21, 27, etc...
I can't quite wrap my head around how to do it.
For those familiar with it, it's obviously a number wheel for prime number generation, but I don't think knowing that would matter much for the answer. :)
You can do it with Seq.scan:
let wheel235 = [4; 2; 4; 2; 4; 6; 2; 6]
let wheel = seq { while true do yield! wheel235 }
let result = wheel |> Seq.scan (+) 5
# result will be 5, 9, 11, 15, 17, 21, 27, etc
I think that if you want to do this just using a sequence expression, you would need to use a mutable ref cell:
let wheel = seq {
let result = ref 5
yield !result
while true do
for x in wheel235 do
result := !result + x
yield !result
}
But I think a better way would be to combine your code to repeat wheel235 inifitely (after fixing the syntax error) with Seq.scan (as suggested bu LukeH):
let wheel = seq { while true do yield! wheel235 } |> Seq.scan (+) 5
Related
I need to print the second largest number on the list, the output from the below code is all elements in the list except the first and the last one.
What is the mistake?
void main () {
List a = [9,6,4,10,13,2,3,5];
a.sort;
for(int x in a){
for (int max in a){
for (int second_last in a){
if (x > max) {
second_last = max;
max = x;
} else if (x > second_last && x != max) {
second_last = x;
print(second_last);
}
}
}
}
}
There are a few things wrong with your code:
You're not actually sorting the list. The sort method returns a new sorted list, it doesn't sort the existing list. So you need to do:
a = a.sort;
You're iterating over the list 3 times when you only need to iterate over it once.
You're not keeping track of the second largest number, you're just printing it out as you find it.
You're not checking for duplicates. If there are duplicate numbers in the list, your code will print them out multiple times.
Here's a corrected pseudo-code
void main() {
List a = [9, 6, 4, 10, 13, 2, 3, 5];
a.sort;
int max = a[0];
int second_last = a[0];
for (int x in a) {
if (x > max) {
second_last = max;
max = x;
} else if (x > second_last && x != max) {
second_last = x;
}
}
print(second_last);
}
I need to print the second largest number on the list
Sort the array (desc).
Access the second element.
List a = [9, 6, 4, 10, 13, 2, 3, 5];
a.sort((a, z) => z - a);
// final b = a.toList()..sort(...); if you do not want to modify the original array.
print(a.take(2)); // [13, 10]
print(a.take(2)[1]); // [10]
print(a.take(2).skip(1)); // [10]
print(a.skip(1).first); // [10]
You are missing () on sort. You can do
void main() {
List a = [9, 6, 4, 10, 13, 2, 3, 5];
a.sort();
print(a[a.length - 2]); //get second large item
List b = [9, 6, 4, 10, 13, 2, 3, 5];
//or like revese sort
b.sort((a, b) => b.compareTo(a));
print(b[1]);
}
If you find a solution that is without using the sort function, and also works with all possible conditions,
so you can use this solution as well,
void main(){
var list =[9,6,4,10,13,2,3,5,13];
var secondLargest = findSecLargest(list);
print(secondLargest);
}
findSecLargest(List<int> list) {
var secLargest =-1;
var largest=list[0];
for(int i = 1 ; i < list.length ; i ++){
if(largest<list[i]){
secLargest = largest;
largest = list[i];
}else if(secLargest<list[i] && list[i]!=largest){
secLargest = list[i];
}
}
return secLargest;
}
Say, I have an array
a = { 1, 2, 10, 15 }
I would like to divide each element by 3 and store the result in a new array. Is there a more efficient / elegant way of doing that than this:
b = { }
for i,x in pairs(a) do
b[i] = x / 3
end
In R, I would simply do b <- a/3. Is there anything like that in lua, or maybe a way of applying a function to each element of a table?
Lua is lightweight, so there is no ready-made functions, but you can create a similar function with metatable.
local mt_vectorization = {
__div = function (dividend, divisor)
local b = {}
for i,x in pairs(dividend) do
b[i] = x / divisor
end
return b
end
}
a = setmetatable({ 1, 2, 10, 15 }, mt_vectorization)
b = a / 3
In addition to the answer by shingo, I found in the meanwhile that writing an R-style mapping function is very easy in lua:
function map(x, f)
local ret = { }
for k, v in pairs(x) do
ret[k] = f(v)
end
return ret
end
This makes some operations easy, for example
a = { 1, 2, 3, 5, 10 }
map(a, function(x) return x * 2 end)
def getNeighbors(v, adjacency_list):
return adjacency_list[v]
import random
def h(n):
H = {
'A': 14,
'B': 12,
'C': 11,
'D': 6,
'E': 4,
'F': 11,
'Z':random.randint(0,22),
Error message shows in this line saying invalid syntax.
h('Z')=='Z',
}
return H[n]
def A_star(start_node, stop_node,adjacency_list):
open_list = set([start_node])
closed_list = set([])
g = {}
g[start_node] = 0
parents = {}
parents[start_node] = start_node
while len(open_list) > 0:
n = None
for v in open_list:
if n == None or g[v] + h(v) < g[n] + h(n):
n = v;
if n == None:
print('Path does not exist!')
return None
if n == stop_node:
reconst_path = []
while parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
for (m, weight) in getNeighbors(n,adjacency_list):
if m not in open_list and m not in closed_list:
open_list.add(m)
parents[m] = n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
open_list.remove(n)
closed_list.add(n)
print('Path does not exist!')
return None
adjacency_list = {
'A': [('B', 4), ('C', 3)],
'B': [('E', 12),('F',5)],
'C': [('D', 7),('E',10)],
'D': [('E',2)],
'E': [('Z',5)],
'F': [('Z',16)]
}
A_star('A', 'Z',adjacency_list)
I would like to know if there is anything wrong with my code. Here I am trying to implement the A star algorithm while giving heuristics randomly, Are there any mistakes that I have done. I know there might be a very silly one. If you find anything please correct me.
I have an array of number which can be varied in length
let arrayNum = [1 ,5, 3, 12] // could also be [1, 5] or [1, 3, 5, 3, 1]
let sum = arrayNum.reduce(0, +)
To calculate percentage of each element and display on a label, I use this method
for value in arrayNum {
percentageLabel.text = "\(value * 100 / sum) %"
}
However, the percentage doesnt add up to 100%
1 has 4%
5 has 23%
3 has 14%
12 has 57%
total % is 99%
Does anyone have a better solution in this case? Thanks.
P.S I don't want them to have fraction values like 99.2% or 40.56%. I only want them to be 99% or 40%.
You are deliberately introducing a rounding error and then trying to pretend you didn't. That's never going to work.
It happens that for the particular cases you gave, you can solve the problem by rounding:
let arrayNum = [1 ,5, 3, 12] // could also be [1, 5] or [1, 3, 5, 3, 1]
let sum = arrayNum.reduce(0, +)
for value in arrayNum {
let d = (Double(value) * 100 / Double(sum)).rounded()
let s = "\(Int(d))%"
percentageLabel.text = s
}
5%
24%
14%
57%
[total is 100%]
But you cannot expect that approach to work universally; numbers just don't work that way. You have to be arithmetically honest.
I'm trying to parallelize the element by element multiplication of two matrices in F#. I can't quite figure it out thought. I keep trying to create tasks but it never wants to compile. My non-working messy code is the following:
let myBigElemMultiply (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
for i in 0 .. destination.NumCols
destination.[row, i] <- source1.[row,i] + source2.[row,i]
destination
let result = Matrix.zero(m.NumRows)
let operations = [ for i in 0 .. m.NumRows -> AddTwoRows i result m n ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks
result
You have made several small mistakes, e.g., you haven't figured how to do matrix multiplication.
let myBigElemMultiply (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
for col=0 to destination.NumCols-1 do
let mutable sum = 0.0
for k=0 to m.NumCols-1 do
sum <- sum + source1.[row,k] * source2.[k,col]
destination.[row,col] <- sum
let result = Matrix.zero m.NumRows n.NumCols
let operations = [ for i=0 to m.NumRows-1 do yield async { AddTwoRows i result m n} ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks |> ignore
result
One thing to notice is that this code would perform very badly because m.[i,j] is an inefficient way to access elements in a matrix. You'd better use a 2D array:
let myBigElemMultiply2 (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
let destination = destination.InternalDenseValues
let source1 = source1.InternalDenseValues
let source2 = source2.InternalDenseValues
for col=0 to Array2D.length2 destination - 1 do
let mutable sum = 0.0
for k=0 to Array2D.length1 source2 - 1 do
sum <- sum + source1.[row,k] * source2.[k,col]
destination.[row,col] <- sum
let result = Matrix.zero m.NumRows n.NumCols
let operations = [ for i=0 to m.NumRows-1 do yield async { AddTwoRows i result m n} ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks |> ignore
result
testing:
let r = new Random()
let A = Matrix.init 280 10340 (fun i j -> r.NextDouble() )
let B = A.Transpose
some timing:
> myBigElemMultiply A B;;
Real: 00:00:22.111, CPU: 00:00:41.777, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
> myBigElemMultiply2 A B;;
Real: 00:00:08.736, CPU: 00:00:15.303, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
> A*B;;
Real: 00:00:13.635, CPU: 00:00:13.166, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
>
Check here by using ParallelFor, which should have a better performance than async.
Here's at least some code that compiles, perhaps this will get you headed in the right direction?
let myBigElemMultiply (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
async {
for i in 0 .. destination.NumCols do
destination.[row, i] <- source1.[row,i] + source2.[row,i]
}
let result = Matrix.zero m.NumRows m.NumCols
let operations = [ for i in 0 .. m.NumRows -> AddTwoRows i result m n ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks |> ignore
result
There's no point. Out-of-place element-wise multiplication of a pair of matrices is little more that copying at which point a single core will happily max out the entire memory bandwidth of your machine and adding more cores will not improve performance. So it is almost certainly a waste of time.