How do I generate and print Fibonacci numbers in X10? - x10-language

I would like to generate and print the first 10 Fibonacci numbers. I don't want to be efficient, but I want to see some (working) X10 code that is easy to understand.
My try
// file Fibonacci.x10
public class Fibonacci {
public static def fib(n:Int): Int {
if (n < 2) {
return n;
}
val f1:Int;
val f2:Int;
finish {
async f1 = fib(n-1);
async f2 = fib(n-2);
}
return f1 + f2;
}
public static def main(args:Rail[String]) {
x10.io.Console.OUT.println("This is fibonacci in X10.");
for (var i:Int=0; i < 10; ++i) {
x10.io.Console.OUT.println(i + ": " + fib(i));
fib(i);
}
}
}
When I compile this, I get:
/home/moose/Fibonacci.x10:11: No valid method call found for call in given type.
Call: fib(x10.lang.Long)
Type: Fibonacci
/home/moose/Fibonacci.x10:12: No valid method call found for call in given type.
Call: fib(x10.lang.Long)
Type: Fibonacci
/home/moose/Fibonacci.x10:19: Cannot assign expression to target; base types are incompatible.
Expression: 0L
Expected base type: x10.lang.Int
Found base type: x10.lang.Long
3 errors.
I use X10 release 2.4.2.

The following version works as expected:
// file Fibonacci.x10
public class Fibonacci {
public static def fib(n:Long): Long {
if (n < 2) {
return n;
}
val f1:Long;
val f2:Long;
finish {
async f1 = fib(n-1);
async f2 = fib(n-2);
}
return f1 + f2;
}
public static def main(args:Rail[String]) {
x10.io.Console.OUT.println("This is fibonacci in X10.");
for (var i:Long=0; i < 10; ++i) {
x10.io.Console.OUT.println(i + ": " + fib(i));
}
}
}
It seems as if number are Long per standard.

Related

How to sort List in dart based on value returned by a function

I have to show a list of stores in a sorted order by nearest location
and I have a unsorted list of stores and a function to calculate
distance of each store from my current location but I don't know how
to sort List in dart based on value returned by a function.
I am getting the unsorted List of stores data from an api.
I need logic for this question for sorting the _kikkleStores List
class KikkleStoresBloc extends BlocBase {
List<KikkleStoreInfo> _kikkleStores = [];
//for distance sorting
List<KikkleStoreInfo> _kikkleStoresSorted = [];
List<double> distanceFromCurrentLocation;//already got
value in it
bool hasReachedEndOfList = false;
Coordinate _currentLocation;
KikkleStoresBloc();
final _kikkleStoreSubject =
BehaviorSubject<List<KikkleStoreInfo>>
();
// Getter Stream
Stream<List<KikkleStoreInfo>> get kikkleStores =>
_kikkleStoreSubject.stream;`enter code here`
// Getter Sink
Function(List<KikkleStoreInfo>) get _fetchedkikkleStores =>
_kikkleStoreSubject.sink.add;
getKikkleStores() async {
try {
if (_currentPage <= _totalPages) {
final response = await
ApiController.getKikkleStores(_currentPage);
_kikkleStores.addAll(response.item1);
//here how to sort _kikkleStores by using
getStoreDistance function
_totalPages = response.item3;
_fetchedkikkleStores(_kikkleStores);
if (_currentPage == _totalPages) {
hasReachedEndOfList = true;
} else if (_currentPage < _totalPages &&
_kikkleStores.length
< 10) {
}
}
}
}
// this function returns distance
getStoreDistance(Coordinate currentLocation, KikkleStoreInfo
store)
async {
if (currentLocation == null) return 0.0;
try {
double distanceInMeter = await
LocationUtils.getDistanceInMeters(
currentLocation, Coordinate(store.latitude,
store.longitude));
// final miles = (distanceInMeter / 1609.344).round();
return distanceInMeter;
} catch (e) {
return 0.0;
}
}
void getCurrentLocation() async {
try {
final isAllowed = await
PermissionsUtils.isLocationAccessAllowed();
if (isAllowed) {
final coordinates = await
LocationUtils.getCurrentLocation();
if (coordinates != null) {
_currentLocation = coordinates;
}
}
}
catch (e) {
print(e);
}
}
}
Take the reference of below code
void main(){
List<POJO> pojo = [POJO(5), POJO(3),POJO(7),POJO(1)];
// fill list
pojo..sort((a, b) => a.id.compareTo(b.id));
for(var i in pojo){
print(i.id); // prints list in sorted order i.e 1 3 5 7
}
}
class POJO {
int id;
POJO(this.id);
}
void sortfun() async {
for (int c = 0; c < (_kikkleStores.length - 1); c++) {
for (int d = 0; d < _kikkleStores.length - c - 1; d++) {
if (await getStoreDistance(_currentLocation, _kikkleStores[d]) >
await getStoreDistance(_currentLocation,
_kikkleStores[d + 1])) /* For descending order use < */
{
swap = _kikkleStores[d];
_kikkleStores[d] = _kikkleStores[d + 1];
_kikkleStores[d + 1] = swap;
}
}
}
}

Repeated overriding of functional interface's abstract method?

I have a functional interface in Java 8:
public interface IFuncLambda1 {
public int someInt();
}
in main:
IFuncLambda1 iFuncL1 = () -> 5;
System.out.println("\niFuncL1.someInt: " + iFuncL1.someInt());
iFuncL1 = () -> 1;
System.out.println("iFuncL1.someInt: " + iFuncL1.someInt());
Running this will yield:
iFuncL1.someInt: 5
iFuncL1.someInt: 1
Is this functionality OK as it is? Is it intended?
If the overriding would be done in an implementing class, and the implementation would change at some point, then in every place that that method is called, the behaviour would be the same, we would have consistency. But if I change the behaviour/implementation through lambda expressions like in the example, the behaviour will only be valid til the next change, later on in the flow. This feels unreliable and hard to follow.
EDIT:
#assylias I don't see how someInt() has its behaviour changed...
What if I added a param to someInt and have this code:
IFuncLambda1 iFuncL1 = (x) -> x - 1;
System.out.println("\niFuncL1.someInt: " + iFuncL1.someInt(var));
iFuncL1 = (x) -> x + 1;
System.out.println("iFuncL1.someInt: " + iFuncL1.someInt(var));
with var being a final even, how would you re-write that with classes?
In your example, () -> 5 is one object and () -> 1 is another object. You happen to use the same variable to refer to them but that is just how references work in Java.
By the way it behaves exactly the same way as if you had used anonymous classes:
IFuncLambda1 iFuncL1 = new IFuncLambda1() { public int someInt() { return 5; } };
System.out.println("\niFuncL1.someInt: " + iFuncL1.someInt());
iFuncL1 = new IFuncLambda1() { public int someInt() { return 1; } };
System.out.println("iFuncL1.someInt: " + iFuncL1.someInt());
Or using "normal" classes:
public static class A implements IFuncLambda1 {
private final int i;
public A(int i) { this.i = i; }
public int someInt() { return i; }
}
IFuncLambda1 iFuncL1 = new A(5);
System.out.println("\niFuncL1.someInt: " + iFuncL1.someInt());
iFuncL1 = new A(1);
System.out.println("iFuncL1.someInt: " + iFuncL1.someInt());
There again there are two instances of A but you lose the reference to the first instance when you reassign iFuncL1.

Find anagram of input on set of strings..?

Given a set of strings (large set), and an input string, you need to find all the anagrams of the input string efficiently. What data structure will you use. And using that, how will you find the anagrams?
Things that I have thought of are these:
Using maps
a) eliminate all words with more/less letters than the input.
b) put the input characters in map
c) Traverse the map for each string and see if all letters are present with their count.
Using Tries
a) Put all strings which have the right number of characters into a trie.
b) traverse each branch and go deeper if the letter is contained in the input.
c) if leaf reached the word is an anagram
Can anyone find a better solution?
Are there any problems that you find in the above approaches?
Build a frequency-map from each word and compare these maps.
Pseudo code:
class Word
string word
map<char, int> frequency
Word(string w)
word = w
for char in word
int count = frequency.get(char)
if count == null
count = 0
count++
frequency.put(char, count)
boolean is_anagram_of(that)
return this.frequency == that.frequency
You could build an hashmap where the key is sorted(word), and the value is a list of all the words that, sorted, give the corresponding key:
private Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
void buildIndex(){
for(String word : words){
String sortedWord = sortWord(word);
if(!anagrams.containsKey(sortedWord)){
anagrams.put(sortedWord, new ArrayList<String>());
}
anagrams.get(sortedWord).add(word);
}
}
Then you just do a lookup for the sorted word in the hashmap you just built, and you'll have the list of all the anagrams.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/*
*Program for Find Anagrams from Given A string of Arrays.
*
*Program's Maximum Time Complexity is O(n) + O(klogk), here k is the length of word.
*
* By removal of Sorting, Program's Complexity is O(n)
* **/
public class FindAnagramsOptimized {
public static void main(String[] args) {
String[] words = { "gOd", "doG", "doll", "llod", "lold", "life",
"sandesh", "101", "011", "110" };
System.out.println(getAnaGram(words));
}
// Space Complexity O(n)
// Time Complexity O(nLogn)
static Set<String> getAnaGram(String[] allWords) {
// Internal Data Structure for Keeping the Values
class OriginalOccurence {
int occurence;
int index;
}
Map<String, OriginalOccurence> mapOfOccurence = new HashMap<>();
int count = 0;
// Loop Time Complexity is O(n)
// Space Complexity O(K+2K), here K is unique words after sorting on a
for (String word : allWords) {
String key = sortedWord(word);
if (key == null) {
continue;
}
if (!mapOfOccurence.containsKey(key)) {
OriginalOccurence original = new OriginalOccurence();
original.index = count;
original.occurence = 1;
mapOfOccurence.put(key, original);
} else {
OriginalOccurence tempVar = mapOfOccurence.get(key);
tempVar.occurence += 1;
mapOfOccurence.put(key, tempVar);
}
count++;
}
Set<String> finalAnagrams = new HashSet<>();
// Loop works in O(K), here K is unique words after sorting on
// characters
for (Map.Entry<String, OriginalOccurence> anaGramedWordList : mapOfOccurence.entrySet()) {
if (anaGramedWordList.getValue().occurence > 1) {
finalAnagrams.add(allWords[anaGramedWordList.getValue().index]);
}
}
return finalAnagrams;
}
// Array Sort works in O(nLogn)
// Customized Sorting for only chracter's works in O(n) time.
private static String sortedWord(String word) {
// int[] asciiArray = new int[word.length()];
int[] asciiArrayOf26 = new int[26];
// char[] lowerCaseCharacterArray = new char[word.length()];
// int characterSequence = 0;
// Ignore Case Logic written in lower level
for (char character : word.toCharArray()) {
if (character >= 97 && character <= 122) {
// asciiArray[characterSequence] = character;
if (asciiArrayOf26[character - 97] != 0) {
asciiArrayOf26[character - 97] += 1;
} else {
asciiArrayOf26[character - 97] = 1;
}
} else if (character >= 65 && character <= 90) {
// asciiArray[characterSequence] = character + 32;
if (asciiArrayOf26[character + 32 - 97] != 0) {
asciiArrayOf26[character + 32 - 97] += 1;
} else {
asciiArrayOf26[character + 32 - 97] = 1;
}
} else {
return null;
}
// lowerCaseCharacterArray[characterSequence] = (char)
// asciiArray[characterSequence];
// characterSequence++;
}
// Arrays.sort(lowerCaseCharacterArray);
StringBuilder sortedWord = new StringBuilder();
int asciiToIndex = 0;
// This Logic uses for reading the occurrences from array and copying
// back into the character array
for (int asciiValueOfCharacter : asciiArrayOf26) {
if (asciiValueOfCharacter != 0) {
if (asciiValueOfCharacter == 1) {
sortedWord.append((char) (asciiToIndex + 97));
} else {
for (int i = 0; i < asciiValueOfCharacter; i++) {
sortedWord.append((char) (asciiToIndex + 97));
}
}
}
asciiToIndex++;
}
// return new String(lowerCaseCharacterArray);
return sortedWord.toString();
}
}

How to find a word from arrays of characters?

What is the best way to solve this:
I have a group of arrays with 3-4 characters inside each like so:
{p, {a, {t, {m,
q, b, u, n,
r, c v o
s } } }
}
I also have an array of dictionary words.
What is the best/fastest way to find if the array of characters can combine to form one of the dictionary words? For example, the above arrays could make the words:
"pat","rat","at","to","bum"(lol)but not "nub" or "mat"Should i loop through the dictionary to see if words can be made or get all the combinations from the letters then compare those to the dictionary
I had some Scrabble code laying around, so I was able to throw this together. The dictionary I used is sowpods (267751 words). The code below reads the dictionary as a text file with one uppercase word on each line.
The code is C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace SO_6022848
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Trie
{
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
}
class Program
{
static void GenWords(Trie.Node n, HashSet<Letter>[] sets, int currentArrayIndex, List<string> wordsFound)
{
if (currentArrayIndex < sets.Length)
{
foreach (var edge in n.Edges)
{
if (sets[currentArrayIndex].Contains(edge.Key))
{
if (edge.Value.IsTerminal)
{
wordsFound.Add(edge.Value.Word);
}
GenWords(edge.Value, sets, currentArrayIndex + 1, wordsFound);
}
}
}
}
static void Main(string[] args)
{
const int minArraySize = 3;
const int maxArraySize = 4;
const int setCount = 10;
const bool generateRandomInput = true;
var trie = new Trie(File.ReadAllLines("sowpods.txt"));
var watch = new Stopwatch();
var trials = 10000;
var wordCountSum = 0;
var rand = new Random(37);
for (int t = 0; t < trials; t++)
{
HashSet<Letter>[] sets;
if (generateRandomInput)
{
sets = new HashSet<Letter>[setCount];
for (int i = 0; i < setCount; i++)
{
sets[i] = new HashSet<Letter>();
var size = minArraySize + rand.Next(maxArraySize - minArraySize + 1);
while (sets[i].Count < size)
{
sets[i].Add(Letter.Chars[rand.Next(Letter.Chars.Length)]);
}
}
}
else
{
sets = new HashSet<Letter>[] {
new HashSet<Letter>(new Letter[] { 'P', 'Q', 'R', 'S' }),
new HashSet<Letter>(new Letter[] { 'A', 'B', 'C' }),
new HashSet<Letter>(new Letter[] { 'T', 'U', 'V' }),
new HashSet<Letter>(new Letter[] { 'M', 'N', 'O' }) };
}
watch.Start();
var wordsFound = new List<string>();
for (int i = 0; i < sets.Length - 1; i++)
{
GenWords(trie.Root, sets, i, wordsFound);
}
watch.Stop();
wordCountSum += wordsFound.Count;
if (!generateRandomInput && t == 0)
{
foreach (var word in wordsFound)
{
Console.WriteLine(word);
}
}
}
Console.WriteLine("Elapsed per trial = {0}", new TimeSpan(watch.Elapsed.Ticks / trials));
Console.WriteLine("Average word count per trial = {0:0.0}", (float)wordCountSum / trials);
}
}
}
Here is the output when using your test data:
PA
PAT
PAV
QAT
RAT
RATO
RAUN
SAT
SAU
SAV
SCUM
AT
AVO
BUM
BUN
CUM
TO
UM
UN
Elapsed per trial = 00:00:00.0000725
Average word count per trial = 19.0
And the output when using random data (does not print each word):
Elapsed per trial = 00:00:00.0002910
Average word count per trial = 62.2
EDIT: I made it much faster with two changes: Storing the word at each terminal node of the trie, so that it doesn't have to be rebuilt. And storing the input letters as an array of hash sets instead of an array of arrays, so that the Contains() call is fast.
There are probably many way of solving this.
What you are interested in is the number of each character you have available to form a word, and how many of each character is required for each dictionary word. The trick is how to efficiently look up this information in the dictionary.
Perhaps you can use a prefix tree (a trie), some kind of smart hash table, or similar.
Anyway, you will probably have to try out all your possibilities and check them against the dictionary. I.e., if you have three arrays of three values each, there will be 3^3+3^2+3^1=39 combinations to check out. If this process is too slow, then perhaps you could stick a Bloom filter in front of the dictionary, to quickly check if a word is definitely not in the dictionary.
EDIT: Anyway, isn't this essentially the same as Scrabble? Perhaps try Googling for "scrabble algorithm" will give you some good clues.
The reformulated question can be answered just by generating and testing. Since you have 4 letters and 10 arrays, you've only got about 1 million possible combinations (10 million if you allow a blank character). You'll need an efficient way to look them up, use a BDB or some sort of disk based hash.
The trie solution previously posted should work as well, you are just restricted more by what characters you can choose at each step of the search. It should be faster as well.
I just made a very large nested for loop like this:
for(NSString*s1 in [letterList objectAtIndex:0]{
for(NSString*s2 in [letterList objectAtIndex:1]{
8 more times...
}
}
Then I do a binary search on the combination to see if it is in the dictionary and add it to an array if it is

Task Parallel Library - How do you get a Continuation with TaskContinuationOptions.OnlyOnCanceled to Fire?

I'm experimenting with the Task support in .NET 4.0 - specifically with the continuation support. What I'm perplexed about is that I can't figure out how to get a continuation with the TaskContinuationOptions.OnlyOnCanceled flag set to execute. If I do a ThrowIfCancellationRequested in my worker routine, it only seems to propagate out of the continuation as a fault instead of a cancel operation. For instance, given this code:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskExp1
{
class Program
{
static void Main()
{
var n = 10000;
DumpThreadId("main method");
var cts = new CancellationTokenSource();
var task = Task.Factory.StartNew<int>(_ => Sum(cts.Token, n),
cts.Token);
task.ContinueWith(t =>
{
DumpThreadId("ContinueWith Completed, ", newline:false);
Console.WriteLine("The result is " + t.Result);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(t =>
{
DumpThreadId("ContinueWith Faulted, ", newline: false);
Console.WriteLine(t.Exception.InnerExceptions[0].Message);
}, TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(_ =>
{
DumpThreadId("ContinueWith Cancelled, ");
}, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Computing sum of " + n + " ...");
Thread.SpinWait(100000);
cts.Cancel();
Console.WriteLine("Done.");
Console.ReadLine();
}
static int Sum(CancellationToken cancelToken, int n)
{
DumpThreadId("from Sum method");
int sum = 0;
for (; n > 0; n--)
{
Thread.SpinWait(500000);
if (n == 10000) cancelToken.ThrowIfCancellationRequested();
checked { sum += n; }
}
return sum;
}
static void DumpThreadId(string msg = "", bool newline = true)
{
var formattedMsg = String.Format("ThreadId: {0} {1}",
Thread.CurrentThread.ManagedThreadId, msg);
if (newline) formattedMsg += "\n";
Console.Write(formattedMsg);
}
}
}
This outputs:
ThreadId: 9 main method
Computing sum of 10000 ...
Done.
ThreadId: 10 from Sum method
ThreadId: 10 ContinueWith Faulted, The operation was canceled.
How do I exit my worker (Sum) method such that the OnlyOnCanceled continuation gets fired?
When you are using the _ => lambda expression you are using the
Func<Object, TResult> function, Object state
overload. If you change the Factory.StartNew to
Task.Factory.StartNew<int>(() => Sum(cts.Token, n), cts.Token);
it will call the "ContinueWith Cancelled".

Resources