Turn this if-then logic into a boolean expression? - algorithm

I'm having a bit of a brain fart on making this code more concise(preferably a single boolean expression)
This is my code:
if (d.Unemployed)
{
if (type.Unemployed)
{
tmp.Unemployed = true;
}
else
{
tmp.Unemployed = false;
}
}
else
{
if (type.Unemployed)
{
tmp.Unemployed = false;
}
else
{
tmp.Unemployed = true;
}
}
Basically the point is that if either type or d is not unemployed, then tmp should be set to not unemployed.

How about:
tmp.Unemployed = type.Unemployed == d.Unemployed;

If we construct a truth table by following the code, we get
d | type | tmp
---+------+----
1 | 1 | 1
---+------+----
1 | 0 | 0
----+-----+----
0 | 1 | 0
----+-----+----
0 | 0 | 1
The above is equivalent with the negation of the xor operation.
tmp = not (d xor type)
If the language doesn't have the xor operator we can use the != on boolean values.
tmp = ! (d != type);
// or
tmp = d == type;

Thinking about how much "brain fart" this caused you I would consider using a well named variable to avoid having to go through this mental process again in future. Something like this:
isTmpUnemployed = (type.Unemployed == d.Unemployed);
tmp.Unemployed = isTmpUnemployed;

The above code means "both unemployed or both not unemployed". Thus, not (A xor B):
tmp.Unemployed = ! ( D.Unemployed ^ type.Unemployed)

tmp.Unemployed = d.Unemployed || type.Unemployed ? !tmp.Unemployed : null;

Related

How not get out of bound in Kotlin?

I got the code that compare current element with the next element in array. But it crashes with out of bound because I guess when its on the last element there is no next element to compare with so it crashes.How to handle this to avoid crash and stop comparing on the last element? Here is my code
fun myFunction(arr: Array<Int>): Int{
if (arr.isEmpty()) return 0
var result = 0
for (item in arr.indices) {
if (arr[item] > 0 && arr[item + 1] < 0){
result ++
}
if (arr[item] < 0 && arr[item + 1] > 0){
result ++
}
}
return result
}
The direct answer to your question:
Instead of
for (item in arr.indices)
you should write
for (item in 0..(arr.lastIndex - 1))
Explanation: arr.indices returns the range 0..arr.lastIndex but in the loop you are checking the element after the current index; therefore you should only go up to arr.lastIndex - 1.
Some further advice:
IntArray is more efficient than Array<Int>
You can combine the two if statements into one using the || (or) operator.
If you are counting the number of sign changes, you need to consider how to interpret 0. In your code, an input of [1,-1] would give a result of 1 sign change, but [1,0,-1] would give 0, which seems wrong. To fix that, treat 0 as positive:
if ((arr[item] >= 0 && arr[item + 1] < 0) || arr[item] < 0 && arr[item + 1] >= 0) {
result++
}
You don't need to check if the array is empty; just remove that line. The loop won't be entered if the array is empty or if it has only 1 element.
Finally, you can use some cool features of the standard libray (look them up in the documentation to learn them) which can make your function succinct:
fun myFunction(arr: IntArray): Int {
var result = 0
arr.asList().zipWithNext().forEach { (a, b) ->
if ((a >= 0 && b < 0) || (a < 0 && b >= 0))
result++
}
return result
}
and even more succinct still:
fun myFunction(arr: IntArray) =
arr.asList().zipWithNext().count { (a, b) -> (a >= 0) != (b >= 0) }
References: single-expression functions, zipWithNext, count, destructuring.

Algorithm to check matching parenthesis

This relates to the Coursera Scala course so I want to directly ask you NOT to give me the answer to the problem, but rather to help me debug why something is happening, as a direct answer would violate the Coursera honor code.
I have the following code:
def balance(chars: List[Char]): Boolean = {
val x = 0
def loop(list: List[Char]): Boolean = {
println(list)
if (list.isEmpty) if(x == 0) true
else if (list.head == '(') pushToStack(list.tail)
else if (list.head == ')') if(x <= 0) false else decreaseStack(list.tail)
else loop(list.tail)
true
}
def pushToStack(myList: List[Char]) { x + 1; loop(myList)}
def decreaseStack(myList: List[Char]) { x - 1; loop(myList)}
loop(chars)
}
A simple explanation:
If the code sees a "(" then it adds 1 to a variable. If it sees a ")" then it first checks whether the variable is equal to or smaller than 0. If this is the case, it returns false. If the value is bigger than 0 then it simply decreases one from the variable.
I have tried running the following:
if(balance("This is surely bad :-( ) (".toList)) println("balanced") else println("not balanced");
Clearly this is not balanced, but my code is returning balanced.
Again: I am not asking for help in writing this program, but rather help in explained why the code is returning "balanced" when clearly the string is not balanced
--EDIT--
def balance(chars: List[Char]): Boolean = {
val temp = 0;
def loop(list: List[Char], number: Int): Boolean = {
println(list)
if (list.isEmpty) if(number == 0) true
else if (list.head == '(') loop(list.tail, number + 1)
else if (list.head == ')') if(number <= 0) false else loop(list.tail, number - 1)
else loop(list.tail,number)
true
}
loop(chars,0)
}
^^ Still prints out balanced
You are using an immutable x when you really want a mutable x.
Here, let me rewrite it for you in a tail recursive style to show you what you're actually doing:
#tailrec def loop(myList: List[Char], cur: Int = 0): Boolean = myList match{
case "(" :: xs =>
val tempINeverUse = cur+1
loop(xs, cur) //I passed in 0 without ever changing "cur"!
case ")" :: xs if cur < 0 => false //This is a bug, regardless if you fix the rest of it
case ")" :: xs =>
val tempINeverUse = cur-1
loop(xs, cur) //Passed in 0 again!
case x :: xs => loop(xs, cur)
case Nil => cur == 0 //Since I've never changed it, it will be 0.
}
You need to keep a context of parenthesis in comments or in quotes as well. You can use a counter to achieve that. If the counter is set for a comment or a double quote then ignore any parenthesis that comes your way. Reset the counter whenever you find a finishing comment or double quote

syntactic predicates - Upgrading from Antlr 3 to Antlr 4

I have syntactic predicated that I have to convert into the Antlr 4. The grammar is not written my me so I have no idea how to convert them in a meaningful way. These are the main variations of the grammar that I have to convert.
1.
simpleSelector
: elementName
((esPred)=>elementSubsequent)*
| ((esPred)=>elementSubsequent)+
;
esPred
: HASH | DOT | LBRACKET | COLON
;
elementSubsequent
: HASH
| cssClass
| attrib
| pseudo
;
2.
fragment EMS :; // 'em'
fragment EXS :; // 'ex'
fragment LENGTH :; // 'px'. 'cm', 'mm', 'in'. 'pt', 'pc'
fragment ANGLE :; // 'deg', 'rad', 'grad'
fragment TIME :; // 'ms', 's'
fragment FREQ :; // 'khz', 'hz'
fragment DIMENSION :; // nnn'Somethingnotyetinvented'
fragment PERCENTAGE :; // '%'
NUMBER
:(
'0'..'9' ('.' '0'..'9'+)?
| '.' '0'..'9'+
)
(
(E (M|X))=>
E
(
M { $type = EMS; } //action in lexer rule 'NUMBER' must be last element of single outermost alt
| X { $type = EXS; }
)
| (P(X|T|C))=>
P
(
X
| T
| C
)
{ $type = LENGTH; }
| (C M)=>
C M { $type = LENGTH; }
| (M (M|S))=>
M
(
M { $type = LENGTH; }
| S { $type = TIME; }
)
| (I N)=>
I N { $type = LENGTH; }
| (D E G)=>
D E G { $type = ANGLE; }
| (R A D)=>
R A D { $type = ANGLE; }
| (S)=>S { $type = TIME; }
| (K? H Z)=>
K? H Z { $type = FREQ; }
| IDENT { $type = DIMENSION; }
| '%' { $type = PERCENTAGE; }
| // Just a number
)
;
3.
URI : U R L
'('
((WS)=>WS)? (URL|STRING) WS?
')'
;
some guidance is greatly appreciated.
Edit:
Is it as below.
simpleSelector
: elementName
(elementSubsequent)*
| (elementSubsequent)+
;
Syntactic predicates were only used to work around a prediction weakness in ANTLR 3 that is not present in ANTLR 4. You can simply remove them during your transition to ANTLR 4.
Edit:
A syntactic predicate in ANTLR 3 had the following form:
(stuff) =>
Wherever you see that form in your grammar, just remove it. Here's what your second example looks like with the predicates removed.
NUMBER
:(
'0'..'9' ('.' '0'..'9'+)?
| '.' '0'..'9'+
)
(
E
(
M { $type = EMS; }
| X { $type = EXS; }
)
| P
(
X
| T
| C
)
{ $type = LENGTH; }
| C M { $type = LENGTH; }
| M
(
M { $type = LENGTH; }
| S { $type = TIME; }
)
| I N { $type = LENGTH; }
| D E G { $type = ANGLE; }
| R A D { $type = ANGLE; }
| S { $type = TIME; }
| K? H Z { $type = FREQ; }
| IDENT { $type = DIMENSION; }
| '%' { $type = PERCENTAGE; }
| // Just a number
)
;

bash bcmath functions

I have two functions for GNU bc in a Bash script.
BC_CEIL="define ceil(x) { if (x>0) { if (x%1>0) return x+(1-(x%1)) else return x } else return -1*floor(-1*x) }\n"
BC_FLOOR="define floor(x) { if (x>0) return x-(x%1) else return -1*ceil(-1*x) }\n"
echo -e "scale=2"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc
Both functions work fine in interactive bc. bc does not seem to allow multiple functions on one line separated by ; though, so I have to echo -n | bc with newlines at the end of each function. The above output is 2.5, not the expected 3.0 that I get if I type it into bc -i myself. It seems that bash calls bc for each line of echo output, rather than echo'ing it all to a single instance. Is there any workaround for this?
The scale needs to be zero for x%1 to work. You should normally only have one return from a function.
define ceil(x) { auto savescale; savescale = scale; scale = 0; if (x>0) { if (x%1>0) result = x+(1-(x%1)) else result = x } else result = -1*floor(-1*x); scale = savescale; return result }
define floor(x) { auto savescale; savescale = scale; scale = 0; if (x>0) result = x-(x%1) else result = -1*ceil(-1*x); scale = savescale; return result }
This needs a newline after the scale statement:
echo -e "scale=2\n"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc
I believe 1. is incorrect.
The if() comparison needs to be X >= 0 .
I find this works
define ceil(x) {
if (x >= 0) { if (x%1>0) return x+(1-(x%1)) else return x }
else return -1*floor(-1*x)
}
define floor(x) {
if (x >= 0) return x-(x%1)
else return -1*ceil(-1*x)
}

How can I generate this pattern of numbers?

Given inputs 1-32 how can I generate the below output?
in. out
1
1
1
1
2
2
2
2
1
1
1
1
2
2
2
2
...
Edit Not Homework.. just lack of sleep.
I am working in C#, but I was looking for a language agnostic algorithm.
Edit 2 To provide a bit more background... I have an array of 32 items that represents a two dimensional checkerboard. I needed the last part of this algorithm to convert between the vector and the graph, where the index aligns on the black squares on the checkerboard.
Final Code:
--Index;
int row = Index >> 2;
int col = 2 * Index - (((Index & 0x04) >> 2 == 1) ? 2 : 1);
Assuming that you can use bitwise operators you can check what the numbers with same output have in common, in this case I preferred using input 0-31 because it's simpler (you can just subtract 1 to actual values)
What you have?
0x0000 -> 1
0x0001 -> 1
0x0010 -> 1
0x0011 -> 1
0x0100 -> 2
0x0101 -> 2
0x0110 -> 2
0x0111 -> 2
0x1000 -> 1
0x1001 -> 1
0x1010 -> 1
0x1011 -> 1
0x1100 -> 2
...
It's quite easy if you notice that third bit is always 0 when output should be 1 and viceversa it's always 1 when output should be 2
so:
char codify(char input)
{
return ((((input-1)&0x04)>>2 == 1)?(2):(1));
}
EDIT
As suggested by comment it should work also with
char codify(char input)
{
return ((input-1 & 0x04)?(2):(1));
}
because in some languages (like C) 0 will evaluate to false and any other value to true. I'm not sure if it works in C# too because I've never programmed in that language. Of course this is not a language-agnostic answer but it's more C-elegant!
in C:
char output = "11112222"[input-1 & 7];
or
char output = (input-1 >> 2 & 1) + '1';
or after an idea of FogleBird:
char output = input - 1 & 4 ? '2' : '1';
or after an idea of Steve Jessop:
char output = '2' - (0x1e1e1e1e >> input & 1);
or
char output = "12"[input-1>>2&1];
C operator precedence is evil. Do use my code as bad examples :-)
You could use a combination of integer division and modulo 2 (even-odd): There are blocks of four, and the 1st, 3rd, 5th block and so on should result in 1, the 2nd, 4th, 6th and so on in 2.
s := ((n-1) div 4) mod 2;
return s + 1;
div is supposed to be integer division.
EDIT: Turned first mod into a div, of course
Just for laughs, here's a technique that maps inputs 1..32 to two possible outputs, in any arbitrary way known at compile time:
// binary 1111 0000 1111 0000 1111 0000 1111 0000
const uint32_t lu_table = 0xF0F0F0F0;
// select 1 bit out of the table
if (((1 << (input-1)) & lu_table) == 0) {
return 1;
} else {
return 2;
}
By changing the constant, you can handle whatever pattern of outputs you want. Obviously in your case there's a pattern which means it can probably be done faster (since no shift is needed), but everyone else already did that. Also, it's more common for a lookup table to be an array, but that's not necessary here.
The accepted answer return ((((input-1)&0x04)>>2 == 1)?(2):(1)); uses a branch while I would have just written:
return 1 + ((input-1) & 0x04 ) >> 2;
Python
def f(x):
return int((x - 1) % 8 > 3) + 1
Or:
def f(x):
return 2 if (x - 1) & 4 else 1
Or:
def f(x):
return (((x - 1) & 4) >> 2) + 1
In Perl:
#!/usr/bin/perl
use strict; use warnings;
sub it {
return sub {
my ($n) = #_;
return 1 if 4 > ($n - 1) % 8;
return 2;
}
}
my $it = it();
for my $x (1 .. 32) {
printf "%2d:%d\n", $x, $it->($x);
}
Or:
sub it {
return sub {
my ($n) = #_;
use integer;
return 1 + ( (($n - 1) / 4) % 2 );
}
}
In Haskell:
vec2graph :: Int -> Char
vec2graph n = (cycle "11112222") !! (n-1)
Thats pretty straightforward:
if (input == "1") {Console.WriteLine(1)};
if (input == "2") {Console.WriteLine(1)};
if (input == "3") {Console.WriteLine(1)};
if (input == "4") {Console.WriteLine(1)};
if (input == "5") {Console.WriteLine(2)};
if (input == "6") {Console.WriteLine(2)};
if (input == "7") {Console.WriteLine(2)};
if (input == "8") {Console.WriteLine(2)};
etc...
HTH
It depends of the language you are using.
In VB.NET, you could do something like this :
for i as integer = 1 to 32
dim intAnswer as integer = 1 + (Math.Floor((i-1) / 4) mod 2)
' Do whatever you need to do with it
next
It might sound complicated, but it's only because I put it into a sigle line.
In Groovy:
def codify = { i ->
return (((((i-1)/4).intValue()) %2 ) + 1)
}
Then:
def list = 1..16
list.each {
println "${it}: ${codify(it)}"
}
char codify(char input)
{
return (((input-1) & 0x04)>>2) + 1;
}
Using Python:
output = 1
for i in range(1, 32+1):
print "%d. %d" % (i, output)
if i % 4 == 0:
output = output == 1 and 2 or 1
JavaScript
My first thought was
output = ((input - 1 & 4) >> 2) + 1;
but drhirsch's code works fine in JavaScript:
output = input - 1 & 4 ? 2 : 1;
and the ridiculous (related to FogleBird's answer):
output = -~((input - 1) % 8 > 3);
Java, using modulo operation ('%') to give the cyclic behaviour (0,1,2...7) and then a ternary if to 'round' to 1(?) or 2(:) depending on returned value.
...
public static void main(String[] args) {
for (int i=1;i<=32;i++) {
System.out.println(i+"="+ (i%8<4?1:2) );
}
Produces:
1=1 2=1 3=1 4=2 5=2 6=2 7=2 8=1 9=1
10=1 11=1 12=2 13=2 14=2 15=2 16=1
17=1 18=1 19=1 20=2 21=2 22=2 23=2
24=1 25=1 26=1 27=1 28=2 29=2 30=2
31=2 32=1

Resources