JMH: Constrain parameter space - jmh

Suppose I have a JMH test with two parameters:
#Param( { "1", "2", 4", "8", "16" } )
int param1;
#Param( { "1", "2", 4", "8", "16" } )
int param2;
Is there an idiomatic way to add a constraint on the parameters, e.g. only to benchmarks for param1 < param2?
Throwing an exception from an #SetUp works, but adds noise to the output.

Nope, not at this point. If you feel the annotations are constraining, you can always fall back to the API. There, you can do something like:
for (int p1 = 1; p1 <= 16; p1 *= 2) {
for (int p2 = 1; p2 <= p1; p2 *= 2) {
Options opt = new OptionsBuilder()
...
.param("param1", p1)
.param("param1", p2)
.build();
RunResult r = new Runner(opt).runSingle();
... put r somewhere to process
}
}
(Maintainer's perspective: it does not seem worthwhile to wind up a full-fledged annotation-based DSL for JMH, it's just simpler to let users code their advanced scenarios in Java).
UPD: Come to think about it, you can probably encode both parameters into a single #Param, if you want to stay with the annotation-only way.

Related

Time complexity for generic algorithms

I was wondering, if my thought process looks odd.
After digging for a bit on time complexity for general code, say:
Alg(x):
statements...
functions...
...
Can we say that T(Alg(x)) = T1(statement) + T2(functions) + T3(...) then break them apart and keep going in depth until we can go no further? This can lead to the Halting Problem which I can see if my previous statement is correct.
From (1) (assuming it holds) then any alg. such that it's non-recursive can we say T(Alg(x)) is:
Alg(x):
block 1 -> {
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
statements
}
}
}
block 2 -> {
for j -> k // T(K)
call_1() // T(N_1)
call_2() // T(N_2)
}
T(Alg(x)) = T1(b1) + T2(b2)
where T1(b1) = T(N) * T2(f2) = T(N) * (T(M) * T3(s3)) as general where N, M are input sizes, and s3 are more breakable parts.
As for T2(b2) we have T(K) + T(N1) + T(N2)

Cannot extropolate encryption techinque from this Hacker Rank challenge on Encryption

I am doing some Hacker Rank problems and I cannot figure out what the encryption method is in the challenge details, here is the challenge.
Excerpt from the challenge:
The encoded message is obtained by displaying the characters in a column, inserting a space, and then displaying the next column and inserting a space, and so on. For example, the encoded message for the above rectangle is:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
There is no mention of how the characters are changed to the output example the challenge provides...
I understand all elements of this question I think. The problem for me is: there is no details in the challenge about, after storing text in a grid, how the letters are encrypted.
Perhaps I am just very unfamiliar with encryption techniques and if I was more versed I could recognize some simple encryption pattern from the example output.
What am I missing here?
Just read it like this (concatenate marked letters):
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
Then go back at the beginning and take the second letter from each word and so on.
IfManWas MeantToS ...
The approach as described in the problem, is to remove spaces and make a hole string. Then calculate the rows and cols and create a matrix multidimensional arre. Go through the string storing the chars in the matrix. Then reverse the matrix and create the final string.
static String encryption(String s) {
String S = s.replace(" ", "");
int L = S.length();
int tryRow = (int) Math.floor(Math.sqrt(L));
int row;
int col = (int) Math.ceil(Math.sqrt(L));
if (tryRow * col < L) {
row = tryRow + 1;
} else {
row = tryRow;
}
char[][] matrix = IntStream.range(0, L).collect(
() -> new char[row][col],
(acc, i) -> {
int r = i / col;
int c = i - (r * col);
acc[r][c] = S.charAt(i);
},
(a, b) -> {
});
char[][] temp = new char[col][row];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
temp[j][i] = matrix[i][j];
}
}
return Arrays.stream(temp)
.map(arr -> String.valueOf(arr).trim())
.collect(Collectors.joining(" "));
}

MVC & Google Line Chart: Data plotted does not start at 0

I have a google line chart and the problem is, it does not start at 0 on the x-axis. I've seen this thread, but the solution seems to work only if x-values are numeric. Mine are not, unfortunatly.
Does anbody know how to resolve this? Maybe it's a problem related to the way I fill the chart with data, this is how I add the columns and rows:
tdata.addColumn('string', data[0][0]);
for (var i = 1; i < cols; i++) {
tdata.addColumn('number', data[0][i]);
}
tdata.addRows(data.length);
for (var i = 1; i < data.length; i++) {
tdata.setCell(i, 0, data[i][0]);
for (var j = 1; j < cols; j++) {
var value = parseInt(data[i][j]);
tdata.setCell(i, j, value);
}
}
And the data I feed to this is in this format:
{ "", "Kasse", "Anleihen", "Fonds", "Futures", "Optionen", "Aktien" } [Column names]
{ "01.02.2012", "10", "12", "23", "10", "12", "23" }

How to eliminate this type of recursion?

This is a bit more intricate than a simple left-recursion or tail-call recursion. So I'm wondering how I can eliminate this kind of recursion. I'm already keeping my own stack as you can see below, so the function needs to no params or return values. However, it's still calling itself up (or down) to a certain level and I want to turn this into a loop, but been scratching my head over this for some time now.
Here's the simplified test case, replacing all "real logic" with printf("dostuff at level #n") messages. This is in Go but the problem is applicable to most languages. Use of loops and goto's would be perfectly acceptable (but I played with this and it gets convoluted, out-of-hand and seemingly unworkable to begin with); however, additional helper functions should be avoided. I guess I should to turn this into some kind of simple state machine, but... which? ;)
As for the practicality, this is to run at about 20 million times per second (stack depth can range from 1 through 25 max later on). This is a case where maintaining my own stack is bound to be more stable / faster than the function call stack. (There are no other function calls in this function, only calculations.) Also, no garbage generated = no garbage collected.
So here goes:
func testRecursion () {
var root *TMyTreeNode = makeSomeDeepTreeStructure()
// rl: current recursion level
// ml: max recursion level
var rl, ml = 0, root.MaxDepth
// node: "the stack"
var node = make([]*TMyTreeNode, ml + 1)
// the recursive and the non-recursive / iterative test functions:
var walkNodeRec, walkNodeIt func ();
walkNodeIt = func () {
log.Panicf("YOUR ITERATIVE / NON-RECURSIVE IDEAS HERE")
}
walkNodeRec = func () {
log.Printf("ENTER LEVEL %v", rl)
if (node[rl].Level == ml) || (node[rl].ChildNodes == nil) {
log.Printf("EXIT LEVEL %v", rl)
return
}
log.Printf("PRE-STUFF LEVEL %v", rl)
for i := 0; i < 3; i++ {
switch i {
case 0:
log.Printf("PRECASE %v.%v", rl, i)
node[rl + 1] = node[rl].ChildNodes[rl + i]; rl++; walkNodeRec(); rl--
log.Printf("POSTCASE %v.%v", rl, i)
case 1:
log.Printf("PRECASE %v.%v", rl, i)
node[rl + 1] = node[rl].ChildNodes[rl + i]; rl++; walkNodeRec(); rl--
log.Printf("POSTCASE %v.%v", rl, i)
case 2:
log.Printf("PRECASE %v.%v", rl, i)
node[rl + 1] = node[rl].ChildNodes[rl + i]; rl++; walkNodeRec(); rl--
log.Printf("POSTCASE %v.%v", rl, i)
}
}
}
// test recursion for reference:
if true {
rl, node[0] = 0, root
log.Printf("\n\n=========>RECURSIVE ML=%v:", ml)
walkNodeRec()
}
// test non-recursion, output should be identical
if true {
rl, node[0] = 0, root
log.Printf("\n\n=========>ITERATIVE ML=%v:", ml)
walkNodeIt()
}
}
UPDATE -- after some discussion here, and further thinking:
I just made up the following pseudo-code which in theory should do what I need:
curLevel = 0
for {
cn = nextsibling(curLevel, coords)
lastnode[curlevel] = cn
if cn < 8 {
if isleaf {
process()
} else {
curLevel++
}
} else if curLevel == 0 {
break
} else {
curLevel--
}
}
Of course the tricky part will be filling out nextsibling() for my custom use-case. But just as a general solution to eliminating inner recursion while maintaining the depth-first traversal order I need, this rough outline should do so in some form or another.
I'm not really sure I understand what it is you want to do since your recursion code looks a little strange. However if I understand the structure of your TMyTreeNode then this is what I would do for a non recursive version.
// root is our root node
q := []*TMyTreeNode{root}
processed := make(map[*TMyTreeNode]bool
for {
l := len(q)
if l < 1 {
break // our queue is empty
}
curr := q[l - 1]
if !processed[curr] && len(curr.childNodes) > 0 {
// do something with curr
processed[curr] = true
q = append(q, curr.childNodes...)
continue // continue on down the tree.
} else {
// do something with curr
processed[curr] = true
q := q[:l-2] // pop current off the queue
}
}
NOTE: This will go arbitrarily deep into the structure. If that's not what you want it will need some modifications.

Regarding IndexOutOfRange error asp.net c#

Hi
i am creating online quiz. For that i am creating arrays of answers selected by user. i used following code for that, it gives correct array but sometimes gives error "Index was outside the range"
//rsel is session values for selected answer
int rsel = Convert.ToInt32(Session["rblsel"]);
// [Convert.ToInt32(Session["Counter"] indicates size of array of no. of questions
int[] ansarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
int[] temp = (int[])Session["arrofans"];
int j,n;
if (temp == null)
n = 0;
else
n = temp.Length;
for (j = 0; j < n; j++)
{
ansarray[j] = temp[j];
}
ansarray[j] = rsel;
Session["arrofans"] = ansarray;
Help me to find out exact error. Asp.net,c#
Thank you.
Why are you reducing the "counter" by one?
int[] ansarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
It looks like that should probably be a + 1... but to be honest it would be simpler to use the size of ansarray - and use Array.Resize to effectively extend it:
int[] ansarray = (int[])Session["arrofans"];
Array.Resize(ref ansarray, ansarray.Length + 1);
ansarray[ansarray.Length - 1] = rsel;
Session["arrofans"] = ansarray;
That way you don't even need the "Counter" part of the session.
One possible OutOfRange could be triggered when
**arrofans.length >= Counter**
temp.Length should not be bigger than ansarray.Length, or precisely from your code it ansarray.Length must be temp.Length+1 or bigger. To avoid your problem you must change it to for (j = 0; j < n && j < (ansarray.Length-1); j++) but i don't know if it will suite your case

Resources