Conditional If not returning as expected - visual-studio-2013

for (int i = 0; i < iMatrix1.Count(); i++)
{
if (Math.Abs(iMatrix1[i]) > 1E-20 & Math.Abs(iMatrix1[i]) < 0.0001) { oArrayList.Add(0); }
else { oArrayList.Add(iMatrix1[i]); }
}
Maybe it's just tired eyes... But I'm not getting my expected result, here. I'm attempting to eliminate erroneous numbers that are outside the lower bound for a given tolerance. (meaning, if they are outside of the range I'm trying to define, they need to be handled as zero)
For some reason, it's also changing numbers that are outside of this lower bound.
I'm sure this is just a silly mistake. Please set me straight.
My return value for iMatrix[i] = -0.000000000000000055
And clearly, 0.00000000000000000001 < |-0.000000000000000055| < .00001
Again, I'm sure that this is just a silly oversight... But it's killing me, at the moment.

Mhan7, if I get you correctly, you are trying to do this?
var a = 0.00000000000000000001;
var b = -0.000000000000000055;
var c = .00001;
Console.WriteLine($"a={c},b={b},c={c} | a < b = { a < Math.Abs(b)} | c > b = { c > Math.Abs(b)}");
if (Math.Abs(b) > a & Math.Abs(b) < c)
{
Console.WriteLine("Hello, World!");
}
Does that work on your computer - I used the same conditional as you. It appears that the above verifies that your code is correct, aka returns "Hello, World", because - as you said above:
a < Math.Abs(b) < c, or AKA 0.00000000000000000001 < |-0.000000000000000055| < .00001

Related

Loops and iterations

Is there a way that a function has 2 options of return and the option of return is chosen after a certain interval of iterations?
example:
a function that swaps from "a" to "b" and "b" to "a" after 4 iterations returns:
a
a
a
a
b
b
b
b
a
a
a
a
b
b
b
b
.
.
.
Edit I did something like this to solve the problem:
var counter = 0;
var state = true;
var changeState = function(){
var x = 0
while(x != 12){
if(counter == 4){
counter = 0;
state = !state;
}
if (state){
console.log("a");
} else {
console.log("b")
}
counter += 1;
x += 1
}
}
changeState();
You will need to have a stateful function, as it needs to somehow remember something from previous call(s) that were made to it. This is a so-called side effect, and means that the function is not pure.
For the example you have given, the function would need to know (i.e. have a state with) the number of previous calls (modulo 8), or the previous four returned values, or some mix of this information.
How such a function is implemented, depends on the programming language.
In object oriented programming languages you would create a class with the function as method, and a property reflecting that state. When the function is called, it also updates the state. For instance, in Java:
class MyClass {
int callCount = 0;
char myFunction() {
return "aaaabbbb".charAt(this.callCount++ % 8);
}
}
You would call the function repeatedly like so:
MyClass obj = new MyClass();
for (int i = 0; i < 10; i++) {
System.out.println(obj.myFunction());
}
In JavaScript you could do the same, or you could create a closure:
function createFunction() {
let callCount = 0;
return function myFunction() {
return "aaaabbbb"[callCount++ % 8];
}
}
let myFunction = createFunction();
for (let i = 0; i < 10; i++) {
console.log(myFunction());
}
In Python you can do the same, but it allows also to use default arguments (which are only initialised at function definition time), and so you could define an argument that is an object holding a counter:
def myFunction(counter=[0]):
counter[0] += 1
return "aaaabbbb"[counter[0] % 8]
for _ in range(10):
print(myFunction())
This is of course not an exhaustive list of possibilities, but the essence is that programming languages offer their own ways to construct such stateful functions.
Iterators
Some languages offer a different approach: iterators. This means the function produces a stream of return values. The function can run to produce the first value after which the running state is saved until a new value is requested from it. The function's execution context is then restored to run until it can produce the next value, ...etc.
Here is how that design would look in JavaScript:
function * myIterator() {
let callCount = 0;
while (true) {
yield "aaaabbbb"[callCount++ % 8];
// ^^^^^ a language construct for yielding back to the caller
}
}
let iter = myIterator();
for (let i = 0; i < 10; i++) {
console.log(iter.next().value);
}
When a programming language offers this possibility, it is often preferred over the other alternatives listed earlier.

Is there any language that allows a break through multiple loops?

break interrupts a for-loop in most languages, but in the case of nested loops I have never encountered an n-th order break.
1. Is there such a thing in any language?
2. If so what is the correct name for it?
3. If not, why?
NB. I am not looking for workarounds.
Regarding point 3. The closest thing I know is goto, which should not be used as it leads to spaghetti code (Python has it only in a joke module), but this seems like a different problem as a boolean variable to mark an inner break, catching a raised a custom error or moving the block to a function in order to break with return are a lot more convoluted (in terms of line numbers and variables in the code).
(This is a curiosity question from a theoretical point of view, but if it helps, I code primarily in Python, Matlab and JS. I have know Perl, Pascal and Basic, but I know only the basics of C++ and know shamefully little of machine code.)
Java has a labeled break statement that lets you break out of any number of loops:
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search; // <<=== This statement breaks both nested loops
}
}
}
I don't know of any language that lets you do this (apart from #dasblinkenlight example - and not saying there aren't any) but you can easily emulate it in any language that has the break statement.
I.e. conditionnaly break on a boolean exit loop var.
var exitLoops = false;
for (var i = 0; i < x; i++) {
for (var j = 0; j < y; j++) {
for (var k = 0; k < z; k++) {
if (something) {
exitLoops = true;
break;
}
}
if (exitLoops) break;
}
if (exitLoops) break;
}
No there isn't (as far as i know). And why ? because if you need to exit several nested for loops all at once, then you have a code design problem, not a syntax problem. all the answers given above, except of #PinkTurtle , uses some sort of goto statement , which is not recommended .
In JavaScript you can do this
Copy paste the following the Chrome Dev Console,
free:
for(var i=0; i<10; i++) {
for(var j=0; j<10; j++) {
for(var k=0;k<10;k++){
console.log('I am at i='+i+' , j='+j+ ' , k='+k);
if(k==3) {
console.log('I will now break FREE...');
break free;
}
}
}
}
console.log('... And Now I am Here...')
Output
I am at i=0 , j=0 , k=0
I am at i=0 , j=0 , k=1
I am at i=0 , j=0 , k=2
I am at i=0 , j=0 , k=3
I will now break FREE...
... And Now I am Here...

Efficient Command Line Parsing

I have programmed a small Java application for fun, and it all works well. My problem is that when I was working on my method to parse the command-line parameters, I just felt that there should be a much more efficient way of doing it. My program accepts:
-l I (I is an integer for a new lower bound)
-u I (I is an integer for a new upper bound)
-? (Outputs available command-line options)
-v (Activates Verbose output for the main class)
I implemented my parseArgs method in the following way:
private static void parseArgs(String[] arguments) {
String t = "";
for (int c = 0; c < arguments.length; c++) t += arguments[c];
if (t.contains("-")) {
String[] params = t.split("-");
for (int c = 0; c < params.length; c++) params[c] = params[c].trim();
for (int c = 0; c < params.length; c++) {
if (params[c].startsWith("?") && !docOnly) {
docOnly = true;
printHelp();
}
if (params[c].startsWith("l") && startPoint == 1) {
try {
startPoint = Integer.parseInt(params[c].substring(1));
if (startPoint < 0) {
startPoint = 0;
}
} catch (NumberFormatException e) {
error = true;
System.out.println("\tParameter Error: " + params[c]);
}
}
if (params[c].startsWith("u") && endPoint == 1000) {
try {
endPoint = Integer.parseInt(params[c].substring(1));
if (endPoint < 0) {
endPoint = 1000;
}
} catch (NumberFormatException e) {
error = true;
System.out.println("\tParameter Error: " + params[c]);
}
}
if (params[c].startsWith("v") && !verbose) {
verbose = true;
}
}
} else {
error = true;
System.out.println("\tError in Parameters. Use -? for available options.");
}
}
As I said, my code all works fine and you can take a look at it if you'd like to verify that. I'm just curious how other programmers, professional or not, would tackle the situation of passing a variable number and order of parameters and having an efficient codepath that would parse them accurately. I know mine isn't the best, which is why I'm wondering. Any language will be okay for an answer, I'm just curious on procedure. I can adapt any language necessary to learn a bit more from it.
Thanks in advance.
~ David Collins
String t = "";
for (int c = 0; c < arguments.length; c++) t += arguments[c];
Use a StringBuilder instead. Or even easier, join() provided by any of a number of popular libraries.
if (t.contains("-")) {
String[] params = t.split("-");
Better:
String[] params = t.split("-");
if (params.length > 1) {
While that works for your particular case (arguments are non-negative integers), in general it will be problematic. You should look for - only at the beginning of parameters, so that someone can request a log file named my-log.txt.
startPoint = Integer.parseInt(params[c].substring(1));
if (startPoint < 0) {
startPoint = 0;
}
All - signs got eaten by split, so startPoint < 0 will never be true.
Why do you set an error flag for non-numeric data, silently ignore numbers out of range or repeated arguments?

How can I convert a JavaScript for-loop to CoffeeScript?

for (i = 0; i < 10; i++) {
doStuff();
}
That's the JavaScript code that I Want to convert to CoffeeScript.
doStuff() for i in [0 .. 9]
This is explained on the introduction page: http://coffeescript.org/#loops
Edit/Update by JP:
The exact translation is:
doStuff() for i in [0...10]
You need to be careful with the ".." vs "...", for example:
count = 0
doStuff() for i in [0..count] #still executes once!
So you think, no problem... I'll just loop until count-1!
count = 0
doStuff() for i in [0..count-1] #executes twice!! '0' and then '-1'
Literal translation of:
for (var i = 0; i < someCount; ++i)
doStuff()
is
for i in [0...someCount]
doStuff()
The marked answer is functionaly correct but the generated code doesn't match the original javascript.
The right way (read, the one closest to the following javascript)
for (i = 0; i < 10; i++) {
doStuff();
}
is doStuff() for i in [0..someCount] by 1
Note the by 1 on the for loop.
Now this code, still creates an extra _i variable. If you can't live with it, then use the following:
i=0
while i<=someCount
doStuff()
i++
Previous answers work. However, dropping the i generates it better for me:
for [0...10]
doStuff()
or
doStuff() for [0...10]
The other solutions add an extra iterator variable i for you to use inside of the loop, for example doStuff(i), but from http://coffeescript.org/v1/#loops:
If you don’t need the current iteration value you may omit it:
browser.closeCurrentTab() for [0...count]
In detail, the translation of for i in [0...10] is for (i = j = 0; j < 10; i = ++j), whereas the translation of for [0...10] is for (i = 0; i < 10; i++).
Note the discussion in other comments about 2-dots versus 3-dots ([0..9] vs. [0...10]).

Need ideas for an algorithm that generates an "echo text" from a given input

After having some fun in a chatbox on a certain website I had an interesting idea. What would be an algorithm that, given some input text, would generate an "echo" text from it. That is, it generates the echo that you would hear if you shouted the input text in a large empty cave. For example:
Input text: Hello!
Output text: Hello!
ello!
lo!
o!
The problem is I don't exactly know what I want myself. I have no idea on how to create such an algorithm or what would even be a criteria to determine if it's a good algorithm. But I suppose the general idea is clear, so I'd like to hear your thoughts.
You don't have to give a complete solution in your answers. Hints of the direction too look in, or just random thoughts about the problem are welcome too.
Bad but fun (imo) solution:
Run the input through a speech synthesizer to generate a waveform.
Run that waveform through an echo generator in a sound processing library.
Then run the resulting waveform through a speech recognition program.
You could create an array of characters, and then interate over the list of characters, using a different starting point for each iteration.
For example in C#
string Mystring = "Is There an Echo in Here?";
char[] charArray = Mystring.ToCharArray();
int k = 0;
string Echo = "";
for (int i = 0; i < (charArray.Length / 3) + 1; i++)
{
for (int j = k; i < charArray.Length; i++)
{
Echo += charArray[j];
}
Echo += Environment.NewLine;
k += 3;
}
Should produce an output something like this
Is there an Echo in Here?
there an Echo in here?
re an Echo in here?
an Echo in Here?
Echo in Here?
o in Here?
n Here?
ere?
?
Just one possible way of doing things, and you can play around with the values to change the echo effect.
Another solution would be to split the string by the words rather than characters
string Mystring = "Is There an Echo in Here?";
string[] Words = Mystring.Split(' ');
int k = 0;
string Echo = "";
for (int i = 0; i < Words.Length / 2; i++)
{
for (int j = k; i < Mystring.Length; i++)
{
Echo += Mystring[j];
}
Echo += Environment.NewLine;
k += 2;
}
Would produce the following
Is there an Echo in Here?
an Echo in Here?
in Here?

Resources