How to test if Qore object is inherited from a specific class - qore

When I have more classes, how can I test if instance is derived from a class?
class a {
};
class b inherits a {
};
class c inherits b {
};
a B = new b();
a C = new c();
assert ((B is instance_of b) == (C is instance_of b))
Ugly hack is testing B.className == 'b' but it is wrong for 'C'. I cannot find an operator.

use the instanceof operator:
class A {
}
class B inherits A {
}
class C inherits B {
}
A a();
B b();
C c();
printf("%y %y %y\n", a instanceof B, b instanceof B, c instanceof C);
prints: False True True
(the code above is based on your code but follows Qore's standard naming conventions and was also corrected for syntax errors)

Related

Return the path between two nodes in a minimum spanning tree

I have a minimum spanning tree created using Kruskal's algorithmstored in a map of key:string and data:set(string)
mst = { "A" : ["B"]
"B" : ["A", "C", "D"]
"C" : ["B"]
"D" : ["B", "E"]
"E" : ["D", "F"] }
I am trying to write an algorithm that will return the path between a specified start and end node
$ findPath A F
> A B D E F
$ findPath F C
> F E D B C
I think I should use some kind of modified depth first search but I am not sure how to implement the algorithm or how to store the nodes that form the path. I don't believe I have to worry about marking nodes as "visited" since there are no cycles in a MST.
There are some similar questions but I haven't been able to find any that can be applied to my specific scenario, they seem to only deal with a non-MST and only return if a path can be found between two nodes, which in my case I already know that there is a path between every node and I also require a list of nodes on the path.
EDIT
The answer converted to c++, probably not the cleanest code but it works
vector<string> findPath(map<string, set<string>> mst, string src, string dest, vector<string> path) {
if(src == dest) {
return path;
}
set<string> possible = mst[src];
for(vector<string>::iterator it = path.begin(); it != path.end(); it++) {
if(possible.find(*it) != possible.end())
possible.erase(*it);
}
for(set<string>::iterator it = possible.begin(); it != possible.end(); it++) {
vector<string> a = path;
if(find(a.begin(), a.end(), src) == a.end())
a.push_back(src);
vector<string> p = findPath(mst, *it, dest, a);
if(p[0] != "FALSEBEGINNING") {
return p;
}
}
vector<string> p = path;
p[0] = "FALSEBEGINNING";
return p;
}
const mst = {
A: ['B'],
B: ['A', 'C', 'D'],
C: ['B'],
D: ['B', 'E'],
E: ['D', 'F']
}
const findPathTraversal = (mst, src, dest, path) => {
const findPath = (mst, src, dest, path) => {
if (src === dest) return path
let possible = mst[src]
possible = possible.filter(v => !path.includes(v))
for (let i = 0; i < possible.length; i++) {
let a = path
if (!a.includes(src)) a.push(src)
let p = findPath(mst, possible[i], dest, a)
if (p != -1) return path
}
return -1
}
let ans = findPath(mst, src, dest, path)
ans.push(dest)
return ans
}
console.log(findPathTraversal(mst, 'A', 'F', []))

How to reverse a Map in Kotlin?

I am trying to reverse a Map in Kotlin. So far, I have come up with:
mapOf("foo" to 42)
.toList()
.map { (k, v) -> v to k }
.toMap()
Is there any better way of doing this without using a middleman(middlelist)?
Since the Map consists of Entrys and it is not Iterable you can use Map#entries instead. It will be mapped to Map#entrySet to create a backed view of Set<Entry>, for example:
val reversed = map.entries.associateBy({ it.value }) { it.key }
OR use Iterable#associate, which will create additional Pairs.
val reversed = map.entries.associate{(k,v)-> v to k}
OR using Map#forEach:
val reversed = mutableMapOf<Int, String>().also {
// v-- use `forEach` here
map.forEach { (k, v) -> it.put(v, k) }
}.toMap()
// ^--- you can add `toMap()` to create an immutable Map.
Here is a simple extension function that reverse a map - without generating unneeded garbage (like pairs, intermediate data structures and unnecessary closures )
fun <K, V> Map<K, V>.reversed() = HashMap<V, K>().also { newMap ->
entries.forEach { newMap.put(it.value, it.key) }
}
note that apply is inlined, and entries.forEach is also inlined (which is not the same for Map::forEach)
In case your map is not a 1-1 mapping and you want the inversion to be a list of values:
mapOf(1 to "AAA", 2 to "BBB", 3 to "BBB").toList()
.groupBy { pair -> pair.second } // Pair<Int, String>
.mapValues { entry ->
entry.value.map { it.first } // Entry<String, List<Pair<Int, String>>
}
If you need to reverse a multimap like m: Map<K, List<V>> to a Map<V, List<K>> you can do
m
.flatMap { it.value.map { oneValue -> oneValue to it.key } }
.groupBy({ it.first }, { it.second })
.toMap()
In sequence,
mapOf('a' to listOf('b', 'c'), 'd' to listOf('b'))
gets flat mapped to a sequence like
listOf('b' to 'a', 'c' to 'a', 'b' to 'd') which gets grouped to
listOf('b' to listOf('a', 'd'), 'c' to listOf('a')) which then gets converted to a map.
This probably creates intermediate objects.
I'm still learning the ins and outs of Kotlin, but I had the same requirement and as of Kotlin 1.2 it appears that you can iterate over a Map and so map() it directly like this:
#Test
fun testThatReverseIsInverseOfMap() {
val intMap = mapOf(1 to "one", 2 to "two", 3 to "three")
val revMap = intMap.map{(k,v) -> v to k}.toMap()
assertTrue(intMap.keys.toTypedArray() contentEquals revMap.values.toTypedArray())
assertTrue(intMap.values.toTypedArray() contentEquals revMap.keys.toTypedArray())
}
This is my take on a 1:1 map
private fun <K, V> Map<K, V>.reverseOneToOneMap(): Map<V, K> {
val result = this.entries.associateBy({ it.value }) { it.key }
if (result.size != this.size) {
throw RuntimeException("Map must be 1:1")
}
return result
}

How to use a map to fire async request but get an aggregated result?

I have the Code:
import 'dart:async';
Future<int> expensiveCallFromALib(int value) async {
print('expensiveCall($value)');
return value + 1;
}
test() {
Map<String, int>input = {"one":1, "two":2};
Map result = {};
print("A");
input.forEach((String key, int value) {
expensiveCallFromALib(value).then((int value) {
result[key] = value;
});
print("B");
});
print("C");
print(result);
}
main() {
test();
}
... with the output
A
B
B
C
{}
expensiveCall(1)
expensiveCall(2)
... but I want
A
B
expensiveCall(1)
B
expensiveCall(2)
C
{one: 2, two: 3}
The Point is, that I cant change the expensiveCallFromALib method.
test() async {
Map<String, int>input = {"one":1, "two":2};
Map result = {};
print("A");
for(final key in input.keys) {
int value = await expensiveCallFromALib(input[key]);
result[key] = value;
print("B");
}
print("C");
print('result: $result');
}
The output is not exactly how you want it but I guess it's close enough ;-)
HTML OUTPUT
CONSOLE
A
expensiveCall(1)
B
expensiveCall(2)
B
C
result: {one: 2, two: 3}
Plunker example

Quadratic Formula Program Java?

Im writing a program, that takes the a, b, and c from an equation, and uses them to find x using the formula:
http://www.purplemath.com/modules/quads/qform01.gif.
The problem im getting, is that when I plugin the equation 1x^2 +3x +4 I get x = -Infinity and x = infinity instead of x = 1 and x = -4.
Heres my code:
Class 1:
public class quadratictest
{
public static void main(String args[])
{
DecimalFormat df = new DecimalFormat("#.###");
System.out.println("--------------------------------------------------");
System.out.println(" ~Quadratic Formula~");
System.out.println("--------------------------------------------------");
System.out.println("in a polynomial, there are 3 important numbers used");
System.out.println("to figure out x. they are a, b, and c, shown below.\n");
System.out.println("\t\t1x^2 +3x +4");
System.out.println("\t\t^ ^ ^");
System.out.println("\t\ta b c");
Scanner input = new Scanner(System.in);
System.out.print("\nPlease type a, b, and c here[a b c]: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
mathey quad = new quadsong(a,b,c);
System.out.println("------------");
System.out.println(quad.solveb());
System.out.println(quad.solvea());
//System.out.println("x =" +df.format(quad.solvea()));
//System.out.println("x =" +df.format(quad.solveb()));
System.out.println("------------");
}
}
Class 2:
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
/**
* Write a description of class quadsong here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class mathey
{
int a;int b;int c;
double solution1;
double solution2;
public mathey(int aN, int bN, int cN)
{
int a = aN;
int b = bN;
int c = cN;
solvea();
solveb();
}
public double solvea()
{
solution1 = ( (b*-1) + Math.sqrt((b^2)-(4*a*c)))/(a+a);
if (solution1 == Math.floor(solution1))
{
return solution1;
}
else
{
return 0;
}
}
public double solveb()
{
solution2 = ( (b*-1) - Math.sqrt((b^2)-(4*a*c)))/(2*a);
if (solution2 == Math.floor(solution2))
{
return solution2;
}
else
{
return 0;
}
}
}
heres my output:
--------------------------------------------------
~Quadratic Formula~
--------------------------------------------------
in a polynomial, there are 3 important numbers used
to figure out x. they are a, b, and c, shown below.
1x^2 +3x +4
^ ^ ^
a b c
Please type a, b, and c here[a b c]: 1 3 4
------------
x =Infinity
x =-Infinity
------------
Whats going wrong? Thanks in advance!
P.S Sorry for the code formatting, idk why its not working like I want on here haha
The problem that you're having here is that: 1x^2 + 3x + 4 has no roots. It's more of a math error than anything else.

What are the performance side effects of defining functions inside a recursive function vs outside in F#

If you have a recursive function that relies on some other function what is the preferred way to implement that?
1) outside the recursive function
let doSomething n = ...
let rec doSomethingElse x =
match x with
| yourDone -> ...
| yourNotDone -> doSomethingElse (doSomething x)
2) inside the recursive function
let rec doSomethingElse x =
let doSomething n = ...
match x with
| yourDone -> ...
| yourNotDone -> doSomethingElse (doSomething x)
3) encapsulate both inside the a third function
let doSomethingElse x =
let doSomething n = ...
let innerDoSomethingElse =
match x with
| yourDone -> ...
| yourNotDone -> innerDoSomethingElse (doSomething x)
4) something even better?
module Test =
let f x =
let add a b = a + b //inner function
add x 1
let f2 x =
let add a = a + x //inner function with capture, i.e., closure
add x
let outerAdd a b = a + b
let f3 x =
outerAdd x 1
Translates to:
[CompilationMapping(SourceConstructFlags.Module)]
public static class Test {
public static int f(int x) {
FSharpFunc<int, FSharpFunc<int, int>> add = new add#4();
return FSharpFunc<int, int>.InvokeFast<int>(add, x, 1);
}
public static int f2(int x) {
FSharpFunc<int, int> add = new add#8-1(x);
return add.Invoke(x);
}
public static int f3(int x) {
return outerAdd(x, 1);
}
[CompilationArgumentCounts(new int[] { 1, 1 })]
public static int outerAdd(int a, int b) {
return (a + b);
}
[Serializable]
internal class add#4 : OptimizedClosures.FSharpFunc<int, int, int> {
internal add#4() { }
public override int Invoke(int a, int b) {
return (a + b);
}
}
[Serializable]
internal class add#8-1 : FSharpFunc<int, int> {
public int x;
internal add#8-1(int x) {
this.x = x;
}
public override int Invoke(int a) {
return (a + this.x);
}
}
}
The only additional cost for an inner function is new'ing up an instance of FSharpFunc--seems negligible.
Unless you're very performance sensitive, I would go with the scope that makes the most sense, that is, the narrowest scope possible.

Resources