I have just started learning haskell and wondering if there is any way we can implement below fibonacci series in C# or java or other non-lazy imperative languages.
In haskell we can succinctly generate fibonacci series with the below one liner
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
Question - I understand that as C#/Java etc eagerly evaluates, the above would probably go to an infinite loop. But what i do not understand is that even if we use a thunk, how can we can create a self referencing data structure which changes as we iterate over it (using recursion).
Appreciate if you could share some snippet
The Scala API docs for Stream contains an example on how to do this in Scala:
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
Edit: To implement memoization in a language which doesn't have it built-in like Haskell, you would obviously need to use mutation (an array or a map). For example:
val fib: Int => Int = {
val m = ArrayBuffer(0, 1)
x => if (x < m.size) m(x) else {
println("Calculating " + x + "...")
val r = fib(x - 2) + fib(x - 1)
m += r
r
}
}
This can still be considered to be a pure function as there are no observable side effects (besides runtime performance) in a single threaded environment.
In C# you can implement this in the next way:
IEnumerable <int> Fibonacci() {
var a = 0;
var b = 1;
while (true) {
var t = b;
yield return b = a + b;
a = t;
}
}
Related
I am working on a Java to WebAssembly compiler (JWebAssembly). I need to replace native code with things that can run in WebAssembly.
For java.lang.Object.hashCode() and java.lang.System.identityHashCode() I use currently the follow JavaScript code:
identityHashCode = (o) => {
var h = o[1];
while( h == 0 ){
o[1] = h = Math.round( ( Math.random() - 0.5 ) * 0xffff );
}
return h;
}
But this required for every new hashCode a round trip to the JavaScript scope which cost performance. With a browserless environment (without JavaScript) like WASI this will not work. That I search for a poor replacement.
I think a hashCode:
does not need be really random
the values must only be well distributed
Is this correct?
The follow Java code should be good enough.
private static int globalHash = (int)System.currentTimeMillis();
private int hashCode;
public int hashCode() {
if( hashCode == 0 ) {
hashCode = globalHash = (globalHash + 1) * 31;
}
return hashCode;
}
Is this good enough for a generic hashCode function? Would there a better implementation?
I am working on a problem that seems to require backtracking of some sort. I have a working recursion method but stackOverFlow happens with larger inputs. Could this be solved with an iterative implementation? I am trying to implement a method that takes in two target values a and b. starting with a = 1 and b = 1, how many "adds" would it take to reach the target a and b values? adds can either make a = a + b or b = b + a, but not both.
for example, if target a = 2 and target b = 1, it takes 1 "add". a=1 & b=1, a = a + b = 2.
public static String answer(String M, String F) {
return answerRecur(new BigInteger(M), new BigInteger(F), 0);
}
public static String answerRecur(BigInteger M, BigInteger F, int its) {
if(M.toString().equals("1") && F.toString().equals("1")) {
return "" + its;
}
else if(M.compareTo(new BigInteger("0")) <=0 || F.compareTo(new BigInteger("0")) <=0) {
return "impossible";
}
String addM = answerRecur(M.subtract(F), F, its +1);
String addF = answerRecur(M, F.subtract(M), its +1);
if(!addM.equals("impossible")) {
return addM;
}
if(!addF.equals("impossible")) {
return addF;
}
return "impossible";
}
Recursive backtracking works by going through all candidate steps, do a step, recurse, undo the step.
This means that if a solution takes N items, ideally the recursion depth will not exceed N.
So: an overflow is not expected, probably too much is tried, or even infinitely recurring.
However in your case a BigInteger might be sufficient large and when using small steps (1) one would have a very recursion depth. And every call creates sufficient much. Better would be int or long instead of BigInteger.
In every call you have two candidates:
M.subtract(F)
F.subtract(M)
You evaluate both, one could stop when a result was found.
Also intelligence (of the math!) is missing: nice would be to prevent too many steps, finding as directed as possible a solution. In general this can be achieved by some way of sorting of the (2) candidates.
How one comes at a smart solution? First the math must be readable, what BigInteger is less. Try some sample solutions by hand, and look for a smart approach to order the attempts.
You can cut the recursion short, assuming keeping M and F positive:
if (M.compareTo(BigInteger.ZERO) <= 0 || F.compareTo(BigInteger.ZERO) <= 0) {
return "impossible";
}
if (M.equals(BigInteger.ONE)) {
return String.valueOf(F.intValue() - 1 + its);
}
if (F.equals(BigInteger.ONE)) {
return String.valueOf(M.intValue() - 1 + its);
}
The same can be done with integer division (and modulo):
if (M.compareTo(F) > 0) {
String addM = answerRecur(M.mod(F), F, its + M.divided(F).intValue());
}
Thinking of an iterative solution actually is possible here despite more than one recursive call, but it would not add to the quality.
Remarks:
by java convention one should use f and m for variable names.
is BigInteger really required? It causes a bit awkward code.
I have been trying to translate a Java for expression into Kotlin which produces this sequence:
1,2,4,8,16,32,64
This is the Java code:
for(int i = 1; i < 100; i = i + i) {
System.out.printf("%d,", i);
}
The only way I have found to translate this into Kotlin is:
var i = 1
while (i < 100) {
print("$i,")
i += i
}
I have tried to use step expressions, but this does not seem to work. Is there any way to express this type of sequence more elegantly in Kotlin?
I know you can have code like this one using Kotlin + Java 9:
Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }
But this relies on Java libraries and I would prefer Kotlin native libraries.
You can use the generateSequence function to create an infinite sequence, then use takeWhile to limit it at a specific value and then use forEach instead of a for-in construct to handle each iteration:
generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }
This question already has answers here:
Non repeating random numbers
(2 answers)
Closed 10 years ago.
I need to randomly sample a subset of n elements from a list in Scala, and I was wondering if there was a convenient way to do so without recourse to manually checking that each of the n elements are unique. At the moment I have something like this:
import util.Random
def sample(itms:List[A], sampleSize:Int) {
var numbersSeen = Set[Int]()
var sampled = List[A]()
val itmLen = itms.size()
var sampleIdex = Random.nextInt(itmLen)
while(sampled < sampleSize) {
if(numbersSeen.contains(sampleIdex)){
sampleIdex = Random.nextInt(itmLen)
} else {
numbersSeen.add(sampleIdex)
sampled.add(itms(sampleIdex))
}
}
sampled
}
I was hoping there was something more elegant that can be done to either generate a non-repeating random list of integers in a range or to randomly sample n elements from a list.
If your list is not too long you could shuffle a list of index numbers and then march through that list.
In Scala that would be something like:
val aList = ('A' to 'Z').toList
val aListIterator = scala.util.Random.shuffle((0 until aList.length).toList).toIterator
and then in your looping structure:
...
if( aListIterator.hasNext ) aList(aListIterator.next)
...
If your list is huge, a function that returns a unique random number in the range of your list size (used as an index) might be a better approach. Jeff Preshing, recently blogged about unique random numbers, http://preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers.
You can pick one randomly, and sample from the list except the one you've just picked, with simpleSize-1 (tail-)recursively:
def sample[A](itms:List[A], sampleSize:Int) = {
def collect(vect: Vector[A], sampleSize: Int, acc : List[A]) : List[A] = {
if (sampleSize == 0) acc
else {
val index = Random.nextInt(vect.size)
collect( vect.updated(index, vect(0)) tail, sampleSize - 1, vect(index) :: acc)
}
}
collect(itms toVector, sampleSize, Nil)
} //> sample: [A](itms: List[A], sampleSize: Int)List[A]
sample(1 to 10 toList, 5) //> res0: List[Int] = List(6, 8, 2, 1, 10)
itms.map(x => (x, util.Random.nextDouble)).sortBy(_._2).take(sampleSize).map(_._1)
as long as you don't care about the inefficiency of sort.
You could take a random sample from the set of subsets, i.e.:
val distinctSubsets = itms.to[Set].subsets(sampleSize)
Then choose one of those randomly.
What about this approach?
trait RandomOrdering[T] extends Ordering[T]
object RandomOrdering {
implicit def defaultOrdering[T] = new RandomOrdering[T] {
def compare(x:T, y:T) = (Random nextInt 3) - 1
}
}
def sample[A](items:List[A], sampleSize:Int)(implicit r:RandomOrdering[A]) =
items.sorted take sampleSize
It might be less performant but it also allows you to inject a different RandomOrdering.
I am trying to learn Scala, so can anyone tell me how to convert the following in scala:
for (int t = 0; true; t++)
Thank you in advance.
With imperative style you can write (as you do in Java):
var t = 0
while(true) {
t+=1
...
}
With lazy functional this could be:
def ints(n: Int = 0): Stream[Int] = Stream.cons(n, ints(n+1))
ints().map(t => ...)
Using built-in functions:
Iterator.from(0).map ( t => .... )
The common use case with such infinite structures, is to take infinite stream or iterator, perform some operations on it, and then take number of results:
Iterator.from(0).filter(t => t % 1 == 0).map(t => t*t).take(10).toList
As I mentioned in the comments, your question does not seem to make much sense - please add more detail.
For now, the closest Scala translation I can come up with would be:
Stream from 0
You can use while or for.
You can use for
for(i<-0 to 100) {
println(i)
}
or you use until when you want to increment by N number
for(i <- 5 until 55 by 5) {
println(i)
}
or you better use while
var i = 0
while(true) {
...
i+=1
}
or also do-while
var i = 0
do {
...
i += 1
} while(true)
Have a look at : http://www.simplyscala.com/
and test it out by yourself
Also, in my blog I did some posts about imperative scala where I used for and while loops you can have a look there.
http://carlosqt.blogspot.com/search/label/Scala
A simple for comprehension in scala looks mostly this way:
for (i <- 0 until 10) {
// do some stuff
}