i have some enum class
enum class Foo { A=1, B=18 , Z=42 };
i want to check if some integer can be converted into a Foo.
What would be the ideal way to do this? this is for runtime check (the integer is not known yet at compile-time)
Obviously i can do this the hard way (write a function bool CheckEnum(Foo); with a big-ass switch returning true for all cases except the default one), but i was hoping a more elegant mechanism that avoided so much writing. MPL or Boost.Preprocessor would be a perfectly acceptable solution, but one of which i sadly know very little about
A solution to this problem is to ditch the enums, and replace it with some arrays which are created using XMACROs.
There is no "ideal" way to do it. All ways are going to have to involve some manual work.
You need to create a data structure that contains all of the acceptable values. Then search that data structure with the runtime value you need. A std::set or std::unordered_set would be adequate for this purpose.
Your main difficulty will be in maintaining that list, as it will need to be updated every time you change your enum class.
Ok i'm a little bit fed up with this issue (some of my enums are nearly 100 items)
so i decided to tackle it with code generation, which might not be everyone's cup of tea, but i've realised that is really no such a big deal.
Basically i went for Python Cog, which allows me to embed python snippets inside comments in my .h and .cpp files and auto-generate code. I use it basically like a really smart, imperative macro system:
i added the following to Test.h
/*[[[cog
#----------- definitions
import cog
def createCategoryConstants( enumVar , bitShift ):
categoryIndex = 0
for cat in enumVar:
cog.outl(' const unsigned int %s_op_mask = (%d << %d); ' %(cat[0] , categoryIndex , bitShift))
categoryIndex += 1
cog.outl('\n\n')
def createMultiCategoryEnum( enumVar , enumTypename ):
cog.outl(' enum class %s { ' % enumTypename )
categoryIndex = 0
for i in enumVar:
itemIndex = 0
catName = 'NotExpected'
remainingCategories = len(enumVar)- categoryIndex - 1
for j in i:
if (itemIndex == 0):
catName = j
itemIndex = 1
continue
enumItemIndex = 0
for enumItem in j:
remainingEnums = len(j) - enumItemIndex - 1
currentLine = ' %s = %s_op_mask | %d ' %(enumItem, catName, enumItemIndex)
if (remainingCategories != 0 or remainingEnums != 0):
currentLine += ' , '
cog.outl(currentLine)
enumItemIndex += 1
itemIndex += 1
cog.outl('') #empty line to separate categories
categoryIndex += 1
cog.outl(' };\n\n')
def createIndexFromEnumFunction( enumVar , enumTypename , functionName ):
cog.outl('uint32_t %s(%s a) { \n switch (a)\n {' % (functionName , enumTypename) )
absoluteIndex = 0
for cat in enumVar:
elemInCat = 0
for i in cat:
if elemInCat != 0:
for enumItem in i:
cog.outl('case %s:' % enumItem)
cog.outl(' return %d; \n' % absoluteIndex)
absoluteIndex += 1
elemInCat += 1
cog.outl(' } \n } \n\n ')
def createMultiEnum( enumVar , enumTypename ):
createCategoryConstants( enumVar , 4)
createMultiCategoryEnum( enumVar , enumTypename )
createIndexFromEnumFunction( enumVar , enumTypename , 'FromOpToIndex' )
#------------- generation
multiEnum =[ ['CatA', ['A1', 'A2' , 'A3_foo']] , ['CatSuper8' , ['Z1_bla' , 'Z10' , 'Z11']] ]
createMultiEnum( multiEnum , 'multiFooEnum')
]]]*/
//[[[end]]]
Then i added cog invocation in my Makefile pre-build step:
.build-pre:
# Add your pre 'build' code here...
python /usr/local/bin/cog.py -I../../../tools/cog/ -r *.h
And the results show up just below:
]]]*/
const unsigned int CatA_op_mask = (0 << 4);
const unsigned int CatSuper8_op_mask = (1 << 4);
enum class multiFooEnum {
A1 = CatA_op_mask | 0 ,
A2 = CatA_op_mask | 1 ,
A3_foo = CatA_op_mask | 2 ,
Z1_bla = CatSuper8_op_mask | 0 ,
Z10 = CatSuper8_op_mask | 1 ,
Z11 = CatSuper8_op_mask | 2
};
uint32_t FromOpToIndex(multiFooEnum a) {
switch (a)
{
case A1:
return 0;
case A2:
return 1;
case A3_foo:
return 2;
case Z1_bla:
return 3;
case Z10:
return 4;
case Z11:
return 5;
}
}
//[[[end]]]
So, now my enum validation is about making sure the code generation (invoked at compile time) is done correctly
Related
I try to make an A-star Pathfinding program base on tile-graph (image raster data as graph) where each pixel values represent as cost.. This is my A-star function script so far :
def A_star(h,c,dx,dy,u,s_id,e_id,Op,Cl,Prt,CC,o,ht,w):
Op.append(s_id)
while e_id not in Op :
if Op == [ ] :
break
candidate = { }
for i in Op :
d = {i : CC[i]}
candidate.update(d)
o = min(candidate, key=candidate.get)
Cl.append(o)
Op.remove(o)
adjacent_list = adjacent_cell(o,dx,dy )
for p in adjacent_list :
if p in Cl:
adjacent_list = filter(lambda i: i != p, adjacent_list)
elif p not in Op :
Op.append(p)
d = {p : o }
Prt.update(d)
d = {p : F(p,o,h,u,w,c,dx,e_id,ht,CC)}
CC.update(d)
elif id in Op :
f1 = F(p,o,h,u,w,c,dx,e_id,ht,CC)
f2 = F(p,Prt[p],h,u,w,c,dx,e_id,ht,CC)
if f1 < f2 :
d = {p : o }
Prt.update(d)
d = {id : F(p,o,h,u,w,c,dx,e_id,ht,CC)}
CC.update(d)
return Prt
my sample code and input data can be downloaded here
https://drive.google.com/open?id=0B2zjTfTukbMvaV9BalU4ZGx4MjQ
If i use a small resolution of DEM, 25x29 ( srtm1.tif ), this program goes well. But if i try a large resolution of DEM, for example 1228 x 972 ( dem,asc ). This program took very long time to calculate a whole cell. I guest that the problem is on the looping progress where i try to use loop for iteration (Line 110, A-star function).
while e_id not in Op :
Is there any solution to make my code run faster ?
All kind of help, suggestion, comment, solution will be very appreciate..
some of optimizing will be like this:
def A_star(h,c,dx,dy,u,s_id,e_id,Op,Cl,Prt,CC,o,ht,w):
Op.append(s_id)
continu = e_id not in Op
while continu :
if Op == []:
break
candidate = {i:CC[i] for i in Op } # HERE
o = min(candidate.values()) # HERE
Cl.append(o)
Op.remove(o)
adjacent_list = adjacent_cell(o,dx,dy )
for p in adjacent_list :
if p in Cl:
adjacent_list = filter(lambda i: i != p, adjacent_list)
elif p not in Op :
Op.append(p)
if p==e_id:
continu=False # this will stop while from looping!
Prt[p]=o # HERE
CC[p]=F(p,o,h,u,w,c,dx,e_id,ht,CC) # HERE
elif id in Op :
f1 = F(p,o,h,u,w,c,dx,e_id,ht,CC)
f2 = F(p,Prt[p],h,u,w,c,dx,e_id,ht,CC)
if f1 < f2 :
Prt[p]=o # HERE
CC[id]= F(p,o,h,u,w,c,dx,e_id,ht,CC) # HERE
return Prt
using dict.update is not for setting one item! use dict[key]=value instead.
another help is to check when the p == e_id so if it added to Op the while will stopped!
I have a string with multiple / in it and I am trying to convert this string in to LaTeX code. Basically (a)/(b) becomes \\dfrac{a}{b}.
The difficulty is that (a) and/or (b) could contain other /.
To respect the parentheses balancing, I would like to replace the / from left to right, and replacing them accordingly to what it around. I made a try but I don't know how target a specific / and replace. using position and length parameters seems to be very complicated.
function ToFrac (s)
while s:find ("/") ~= nil
do
-- Replace : \dfrac{}{}/() -> \dfrac{\dfrac...}{}
if ( s:find ( '\\dfrac%b{}%b{}/%b()' , j ) ~= nil )
then
x,y,num,den = s:find( '(\\dfrac%b{}%b{})/(%b())' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(\\dfrac%b{}%b{})/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/\dfrac{}{} -> \dfrac[}]{\dfrac...}
if ( s:find ( '(%b()/\\dfrac%b{}%b{}' ) ~= nil )
then
x,y,num,den = s:find( '((%b())/(\\dfrac%b{}%b{})' )
num = num:gsub( '.(.+).' , '%1' )
s = s:gsub( '((%b())/()\\dfrac%b{}%b{})',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/() -> \dfrac{}{}
if ( s:find ( '%b()/%b()' , 1 ) ~= nil )
then
x,y,num,den = s:find( '(%b())/(%b())' )
num = num:gsub( '.(.+).' , '%1' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(%b())/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
Done = true
end
print ('### -- ', s)
end -- while
return (s)
end
s = "((a)/(b))/(c)"
print (s, ToFrac(s))
s = "(a)/((b)/(c))"
print (s, ToFrac(s))
s = "(a)/(b)/(c)/(d))"
print (s, ToFrac(s))
s = "((a)/(b))/((c)/(d))"
print (s, ToFrac(s))
Amended version of rpattiso's idea:
function to_frac(expr)
local t
return expr == '' and '' or (expr..'()'):gsub('(.-)(%b())',
function(prefix, subexpr)
local replace_with = ''
if not prefix:find'^%s*/%s*$' then
t, replace_with = {}, (not t and ''
or t[2] and '\\dfrac{'..t[1]..'}{'..t[2]..'}'
or '('..t[1]..')')..prefix
elseif t[2] then
t = {'\\dfrac{'..t[1]..'}{'..t[2]..'}'}
end
table.insert(t, to_frac(subexpr:sub(2,-2)))
return replace_with
end
)
end
print(to_frac' (a )/((b) / (c))') --> \dfrac{a }{\dfrac{b}{c}}
print(to_frac'((a)/((b)/(c)))/(e)') --> \dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac'(a)/(b)/(c)/(d)') --> \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}
The 'replace' argument of string.gsub can be a function.
Using that function, you can apply the substitution recursively to the numerator and denominator and build the result that way. string.sub can be used to remove the parentheses from the numerator and denominator.
function to_frac(expr)
return (expr:gsub('%s*(%b())%s*/%s*(%b())%s*',
function(num, denom)
return '\\dfrac{'..to_frac(num:sub(2,-2))..'}{'
..to_frac(denom:sub(2,-2))..'}'
end))
end
expr = ' (a )/((b) / (c))' -- \dfrac{a }{\dfrac{b}{c}}
print(to_frac(expr))
expr = '((a)/((b)/(c)))/(e)' -->\dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac(expr))
If you want to go beyond using parentheses for delimiting arguments and obey precedence rules, then look into LPeg.
I have a list of items and for each item I am computing a value. Computing this value is a bit computationally intensive so I want to minimise it as much as possible.
The algorithm I need to implement is this:
I have a value X
For each item
a. compute the value for it, if it is < 0 ignore it completely
b. if (value > 0) && (value < X)
return pair (item, value)
Return all (item, value) pairs in a List (that have the value > 0), ideally sorted by value
To make it a bit clearer, step 3 only happens if none of the items have a value less than X. In step 2, when we encounter the first item that is less than X we should not compute the rest and just return that item (we can obviously return it in a Set() by itself to match the return type).
The code I have at the moment is as follows:
val itemValMap = items.foldLeft(Map[Item, Int)]()) {
(map : Map[Item, Int], key : Item) =>
val value = computeValue(item)
if ( value >= 0 ) //we filter out negative ones
map + (key -> value)
else
map
}
val bestItem = itemValMap.minBy(_._2)
if (bestItem._2 < bestX)
{
List(bestItem)
}
else
{
itemValMap.toList.sortBy(_._2)
}
However, what this code is doing is computing all the values in the list and choosing the best one, rather than stopping as a 'better' one is found. I suspect I have to use Streams in some way to achieve this?
OK, I'm not sure how your whole setup looks like, but I tried to prepare a minimal example that would mirror your situation.
Here it is then:
object StreamTest {
case class Item(value : Int)
def createItems() = List(Item(0),Item(3),Item(30),Item(8),Item(8),Item(4),Item(54),Item(-1),Item(23),Item(131))
def computeValue(i : Item) = { Thread.sleep(3000); i.value * 2 - 2 }
def process(minValue : Int)(items : Seq[Item]) = {
val stream = Stream(items: _*).map(item => item -> computeValue(item)).filter(tuple => tuple._2 >= 0)
stream.find(tuple => tuple._2 < minValue).map(List(_)).getOrElse(stream.sortBy(_._2).toList)
}
}
Each calculation takes 3 seconds. Now let's see how it works:
val items = StreamTest.createItems()
val result = StreamTest.process(2)(items)
result.foreach(r => println("Original: " + r._1 + " , calculated: " + r._2))
Gives:
[info] Running Main
Original: Item(3) , calculated: 4
Original: Item(4) , calculated: 6
Original: Item(8) , calculated: 14
Original: Item(8) , calculated: 14
Original: Item(23) , calculated: 44
Original: Item(30) , calculated: 58
Original: Item(54) , calculated: 106
Original: Item(131) , calculated: 260
[success] Total time: 31 s, completed 2013-11-21 15:57:54
Since there's no value smaller than 2, we got a list ordered by the calculated value. Notice that two pairs are missing, because calculated values are smaller than 0 and got filtered out.
OK, now let's try with a different minimum cut-off point:
val result = StreamTest.process(5)(items)
Which gives:
[info] Running Main
Original: Item(3) , calculated: 4
[success] Total time: 7 s, completed 2013-11-21 15:55:20
Good, it returned a list with only one item, the first value (second item in the original list) that was smaller than 'minimal' value and was not smaller than 0.
I hope that the example above is easily adaptable to your needs...
A simple way to avoid the computation of unneeded values is to make your collection lazy by using the view method:
val weigthedItems = items.view.map{ i => i -> computeValue(i) }.filter(_._2 >= 0 )
weigthedItems.find(_._2 < X).map(List(_)).getOrElse(weigthedItems.sortBy(_._2))
By example here is a test in the REPL:
scala> :paste
// Entering paste mode (ctrl-D to finish)
type Item = String
def computeValue( item: Item ): Int = {
println("Computing " + item)
item.toInt
}
val items = List[Item]("13", "1", "5", "-7", "12", "3", "-1", "15")
val X = 10
val weigthedItems = items.view.map{ i => i -> computeValue(i) }.filter(_._2 >= 0 )
weigthedItems.find(_._2 < X).map(List(_)).getOrElse(weigthedItems.sortBy(_._2))
// Exiting paste mode, now interpreting.
Computing 13
Computing 1
defined type alias Item
computeValue: (item: Item)Int
items: List[String] = List(13, 1, 5, -7, 12, 3, -1, 15)
X: Int = 10
weigthedItems: scala.collection.SeqView[(String, Int),Seq[_]] = SeqViewM(...)
res27: Seq[(String, Int)] = List((1,1))
As you can see computeValue was only called up to the first value < X (that is, up to 1)
I ve got the following class and I want to write some Spec test cases, but I am really new to it and I don't know how to start. My class do loke like this:
class Board{
val array = Array.fill(7)(Array.fill(6)(None:Option[Coin]))
def move(x:Int, coin:Coin) {
val y = array(x).indexOf(None)
require(y >= 0)
array(x)(y) = Some(coin)
}
def apply(x: Int, y: Int):Option[Coin] =
if (0 <= x && x < 7 && 0 <= y && y < 6) array(x)(y)
else None
def winner: Option[Coin] = winner(Cross).orElse(winner(Naught))
private def winner(coin:Coin):Option[Coin] = {
val rows = (0 until 6).map(y => (0 until 7).map( x => apply(x,y)))
val cols = (0 until 7).map(x => (0 until 6).map( y => apply(x,y)))
val dia1 = (0 until 4).map(x => (0 until 6).map( y => apply(x+y,y)))
val dia2 = (3 until 7).map(x => (0 until 6).map( y => apply(x-y,y)))
val slice = List.fill(4)(Some(coin))
if((rows ++ cols ++ dia1 ++ dia2).exists(_.containsSlice(slice)))
Some(coin)
else None
}
override def toString = {
val string = new StringBuilder
for(y <- 5 to 0 by -1; x <- 0 to 6){
string.append(apply(x, y).getOrElse("_"))
if (x == 6) string.append ("\n")
else string.append("|")
}
string.append("0 1 2 3 4 5 6\n").toString
}
}
Thank you!
I can only second Daniel's suggestion, because you'll end up with a more practical API by using TDD.
I also think that your application could be nicely tested with a mix of specs2 and ScalaCheck. Here the draft of a Specification to get you started:
import org.specs2._
import org.scalacheck.{Arbitrary, Gen}
class TestSpec extends Specification with ScalaCheck { def is =
"moving a coin in a column moves the coin to the nearest empty slot" ! e1^
"a coin wins if" ^
"a row contains 4 consecutive coins" ! e2^
"a column contains 4 consecutive coins" ! e3^
"a diagonal contains 4 consecutive coins" ! e4^
end
def e1 = check { (b: Board, x: Int, c: Coin) =>
try { b.move(x, c) } catch { case e => () }
// either there was a coin before somewhere in that column
// or there is now after the move
(0 until 6).exists(y => b(x, y).isDefined)
}
def e2 = pending
def e3 = pending
def e4 = pending
/**
* Random data for Coins, x position and Board
*/
implicit def arbitraryCoin: Arbitrary[Coin] = Arbitrary { Gen.oneOf(Cross, Naught) }
implicit def arbitraryXPosition: Arbitrary[Int] = Arbitrary { Gen.choose(0, 6) }
implicit def arbitraryBoardMove: Arbitrary[(Int, Coin)] = Arbitrary {
for {
coin <- arbitraryCoin.arbitrary
x <- arbitraryXPosition.arbitrary
} yield (x, coin)
}
implicit def arbitraryBoard: Arbitrary[Board] = Arbitrary {
for {
moves <- Gen.listOf1(arbitraryBoardMove.arbitrary)
} yield {
val board = new Board
moves.foreach { case (x, coin) =>
try { board.move(x, coin) } catch { case e => () }}
board
}
}
}
object Cross extends Coin {
override def toString = "x"
}
object Naught extends Coin {
override def toString = "o"
}
sealed trait Coin
The e1 property I've implemented is not the real thing because it doesn't really check that we moved the coin to the nearest empty slot, which is what your code and your API suggests. You will also want to change the generated data so that the Boards are generated with an alternation of x and o. That should be a great way to learn how to use ScalaCheck!
I suggest you throw all that code out -- well, save it somewhere, but start from zero using TDD.
The Specs2 site has plenty examples of how to write tests, but use TDD -- test driven design -- to do it. Adding tests after the fact is suboptimal, to say the least.
So, think of the most simple case you want to handle of the most simple feature, write a test for that, see it fail, write the code to fix it. Refactor if necessary, and repeat for the next most simple case.
If you want help with how to do TDD in general, I heartily endorse the videos about TDD available on Clean Coders. At the very least, watch the second part where Bob Martin writes a whole class TDD-style, from design to end.
If you know how to do testing in general but are confused about Scala or Specs, please be much more specific about what your questions are.
Using Groovy, I wish to grab two parts of a tab-separated line. Take the example line:
one fish two fish red fish blue fish ----(each character tab /t separated)
Suppose I want to print one and then I want to print red fish blue
How can I do this?
Alternatively, suppose I want to print one and then a count of the number of characters (words) following red? Or between two and blue?
A previous question yielded this response for printing everything following a certain part of the line:
c = ~/.*red(.*)/
m = line =~ c
if (m) {
println m[0][1]
}
to yield fish blue fish but I'm not comptetent enough with regex's to modify this appropriately. I've tried a few iterations, inserting /t in there and modifying my capturing expression but I've not figured it out. This is three or four questions in one, any help is appreciated. Thanks!!
def a = [:].withDefault{[]}
def b = [:].withDefault{[]}
def c = 0
def d = 0
def e = 0
def f = 0
seuss = "one\tfish\ttwo\tfish\tred\tfish\tblue\tfish"
a = seuss.split (/\t/)
for (i =0; i<a.size(); i++) {
if (d != 0) {
c = c + 1
}
if ( a[i] == "red") {
d = i
}
}
println a[4] + '\t' + c
for (i =0; i<a.size(); i++) {
if ( a[i] == "blue") {
e = 0
}
if (e != 0) {
f = f + 1
}
if ( a[i] == "two") {
e = i
}
}
println a[0] + '\t' + f