Why 10 == 10 || 10 != 10 && 10 < 10 is true - algorithm

Why do the following operators work like this?
10 == 10 || 10 != 10 && 10 < 10 -> true
but why? Isn't the priority as shown below and doesn't it start from the left side?
true && false ?
(10 == 10 || 10 != 10) && (10 < 10)
I expected it to be false but it was true!
*Update: This is the same for all languages

&& has higher precedence than ||, at least for c++. Note that not all languages have the same operator precedence rules.
So, your expression is evaluated as 10 == 10 || (10 != 10 && 10 < 10), which is true

Related

Count the number of zero digit in an integer number?

I wonder if there is a way to count the number of zero digit in an integer number by using only these operations: +, -, * and /
Others operations such as cast, div, mod, ... are not allowed.
Input: 16085021
Output: 2
It is a major restriction that numbers cannot be compared in a way to know that one is less than the other, and only equality checks can be done.
In my opinion that means there is nothing much else you can do than repeatedly add 1 to a variable until it hits a target (n) and derive from that what the least significant digit is of the original number n. This is of course terribly slow and not scalable, but it works in theory.
Here is a demo in Python using only ==, +, - and /:
n = 16085021
count = 0
while True:
# find out what least significant digit is
digit = 0
i = 0
while True:
if n == i:
break
digit = digit + 1
if digit == 10:
digit = 0
i = i + 1
# count any zero digit
if digit == 0:
count = count + 1
# shift that digit out of n
n = (n - digit) / 10
if n == 0:
break
print(count) # 2
Modulo can be implemented with subtractions: a % b = subtract b from a until you end up with something < b and that's the result. You say we can only use the == comparison operator, but we are only interested in modulo 10, so we can just check equality to 0, 1, ..., 9.
def modulo10WithSubtractions(a):
if a == 0 || a == 1 || ... || a == 9:
return a
while True:
a = a - b
if a == 0 || a == 1 || ... || a == 9:
return a
Integer division by 10 can be implemented in a similar fashion: a // 10 = add 10 to itself as many times as possible without exceeding a.
def div10WithAdditions(a):
if a == 0 || a == 1 || ... || a == 9:
return 0
k = 0
while True:
k += 1
if a - k*10 == 0 || a - k*10 == 1 || ... || a - k*10 == 9:
return k
Then we can basically do the classical algorithm:
count = 0
while True:
lastDigit = modulo10WithSubtractions(a)
if lastDigit == 0:
count += 1
a = div10WithAdditions(a)
if a == 0:
break
Asuuming / means integer division, then this snippet does the job.
int zeros = 0;
while(num > 0){
if(num / 10 == (num + 9) / 10){
zeros++;
}
num /= 10;
}

how can I write this code in a more compact way on cplex?

How can I write this code in a more compact way on CPLEX?
forall (j in J)
forall (i in I1)
{
if ( macc [i][j] == 1 || 2 || 4 || 5 || 7 || 11 || 12 || 13 || 14 || 15 || 16 || 17 || 18 || 19) {
y[i][j][m] == 1;
}
else {
if (macc [i][j] == 3) {
y[i][j][3] == 1 || y[i][j][4] == 1;
}
}
you can use "in" with data in an if condition:
{int} s={1,2,4,5,7,11,12,13,14,15,16,17,18,19};
int m=2;
dvar int x;
subject to
{
if (m in s) x==2;
}
works fine

Why is my GoLang algorithm going on an infinite loop?

I have been trying to solve the problem below in multiple ways (recursively, with the Go-version of do while loop, and with a for loop). But each one of them goes to an infinite loop. I tried using the same solution in JavaScript, and it works perfectly fine. Can someone please help me understand why the solution below is not working/going on an infinite loop?
// Write a function that takes in a number and returns the next number that is divisible by 7
package main
func solution9(num int) int {
var done bool = false
var result int = 0
for i := 1; done != true; i++ {
if (num + i % 7 == 0) {
result = num + i
done = true
}
}
return result
}
Your issue is operator precedence. The % operator has a higher precedence than the + operator, so if your num is, say, 10, your test is functionally:
10 + (0 % 7) == 0 => false (10)
10 + (1 % 7) == 0 => false (11)
10 + (2 % 7) == 0 => false (12)
etc.
Obviously, for any num > 0, you'll never satisfy the condition. Change your test to (num+i)%7 == 0 and you should find it works as expected.

Alphanumeric base conversion in Ruby

This is another Codewars Ruby problem that's got me stumped:
Description:
In this kata you have to implement a base converter, which converts between arbitrary bases / alphabets. Here are some pre-defined alphabets:
bin='01'
oct='01234567'
dec='0123456789'
hex='0123456789abcdef'
allow='abcdefghijklmnopqrstuvwxyz'
allup='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alpha='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
alphanum='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
The function convert() should take an input (string), the source alphabet (string) and the target alphabet (string). You can assume that the input value always consists of characters from the source alphabet. You don't need to validate it.
Examples:
convert("15", dec, bin) #should return "1111"
convert("15", dec, oct) #should return "17"
convert("1010", bin, dec) #should return "10"
convert("1010", bin, hex) #should return "a"
convert("0", dec, alpha) #should return "a"
convert("27", dec, allow) #should return "bb"
convert("hello", allow, hex) #should return "320048"
Additional Notes:
The maximum input value can always be encoded in a number without loss of precision in JavaScript. In Haskell, intermediate results will probably be to large for Int.
The function must work for any arbitrary alphabets, not only the pre-defined ones.
You don't have to consider negative numbers.
I've been playing with this for a couple of days and managed to get the numeric-base-conversion portion working. It's the alphabetical part of it that I can't figure out how to approach, and my brain is tired from trying. Here's my code:
def convert(input, source, target)
bases = {
:bin => '01',
:oct => '01234567',
:dec => '0123456789',
:hex => '0123456789abcdef',
:allow => 'abcdefghijklmnopqrstuvwxyz',
:allup => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
:alpha => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
:alphanum => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
}
base_from , base_to = 0
src_num_switch = 1 if source == bases[:bin] || [:oct] || [:dec] || [:hex]
tgt_num_switch = 1 if target == bases[:bin] || [:oct] || [:dec] || [:hex]
src_num_switch = 0 if source == bases[:allow] || [:allup] || [:alpha] || [:alphanum]
tgt_num_switch = 0 if target == bases[:allow] || [:allup] || [:alpha] || [:alphanum]
if source == bases[:bin] then base_from = 2
elsif source == bases[:oct] then base_from = 8
elsif source == bases[:dec] then base_from = 10
elsif source == bases[:hex] then base_from = 16
elsif source == bases[:allow] then base_from = 13
elsif source == bases[:allup] then base_from = 13
elsif source == bases[:alpha] then base_from = 13
elsif source == bases[:alphanum] then base_from = 13
else puts ":( no source match found :("
end
if target == bases[:bin] then puts base_to = 2
elsif target == bases[:oct] then base_to = 8
elsif target == bases[:dec] then base_to = 10
elsif target == bases[:hex] then base_to = 16
elsif target == bases[:allow] then base_to = 13
elsif target == bases[:allup] then base_to = 13
elsif target == bases[:alpha] then base_to = 13
elsif target == bases[:alphanum] then base_to = 13
else puts ":( no target match found :("
end
if base_from == base_to then
return input
elsif src_num_switch == 1 && tgt_num_switch == 1 then
return Integer(input, base_from).to_s(base_to)
elsif src_num_switch == 0 && tgt_num_switch == 0 then
return Integer(input, base_from).to_s(base_to)
# ### # :::::::::::::::::::::::::::::::::::::::::::::
else
puts "ouch, something broke"
end
end
I've got everything down to the "# ### #" portion working for me. Can anyone give me an idea of how to do the alpha-base portion? I've tried the following but had no luck:
if base_from == base_to then return input
elsif src_num_switch == 1 && tgt_num_switch == 1 then
return Integer(input, base_from).to_s(base_to)
elsif src_num_switch == 1 && tgt_num_switch == 0 then
if target == bases[:allup] then return bases[input.index].to_s.upcase
elsif target == bases[:allow] then return bases[input.index].to_s.downcase
end
end
elsif src_num_switch == 0 && tgt_num_switch == 1 then
return input.index.to_s(base_to)
elsif src_num_switch == 0 && tgt_num_switch == 0 then
return Integer(input, base_from).to_s(base_to)
else
puts "ouch, something broke"
end
This one too:
elsif src_num_switch == 1 && tgt_num_switch == 0 then # number-base to alphanumeric-base
if target == bases[:allup] then
return bases[input.index].to_s.upcase
elsif target == bases[:allow] then
return bases[input.index].to_s.downcase
end
elsif src_num_switch == 0 && tgt_num_switch == 1 then # alpha-base to number-base
return input.index.to_s(base_to)
There may be a very clever built-in Ruby solution, but I would guess based on the custom alphabets describing the number systems that there is not. So, I don't have a direct answer to how to complete your code, but I would suggest a slightly different strategy.
Converting from a decimal
Any number system can be converted from the decimal system like so:
vals_in_system = system.length
output_in_system = []
while (decimal_num != 0)
index_of_next_val = decimal_num % system.length
output_in_system.unshift(system[index_of_next_val])
decimal_num = decimal_num / vals_in_system # truncating is desired here
end
It's a bit tricky. This algorithm first tries to determine what value it has to put in the last position (which has the most granularity in whatever number system you're using). E.g. if you were to represent 12 in decimal (yes, it already is, but using this algorithm), a 2 has to go in the last position - no number you put in the tens place or higher will otherwise help you represent 12. If you were to represent 3 in binary, a 1 has to go in the last position of the binary - nothing you put in the next position will get you to a 3. Once it determines this, it can divide by the base, which will leave you with the number you would use to calculate the remaining positions. For example, if you were to represent 123 in decimal, dividing by 10 (the decimal base) and truncating would give you 12. 12 is the representation of the original number except for the final position (which was chopped off by dividing by the base). (I realize this isn't the clearest explanation so let me know if you have questions.) Some examples:
E.g. the decimal number 15 can be converted to binary:
15 % 2 = 1 # last position
15 / 2 = 7
7 % 2 = 1 # next to last position
7 / 2 = 3
3 % 2 = 1 # 3rd to last position
3 / 2 = 1
1 % 2 = 1 # 4th to last position
1 / 2 = 0 # stop
That's kinda boring, you just get 1111. Try something a little more interesting, like 10:
10 % 2 = 0 # last position
10 / 2 = 5
5 % 2 = 1 # next to last position
5 / 2 = 2
2 % 2 = 0 # 3rd to last position
2 / 2 = 1
1 % 2 = 1 # 4th to last position
1 / 2 = 0 # stop
And you get 1010, which is indeed 10 in binary. You can do this with any of those alphabets.
Converting to a decimal
Similarly, any number system can be converted to a decimal by doing the opposite:
vals_in_system = from.length
output_in_decimal = 0
val.each_char do |next_val|
output_in_decimal *= vals_in_system
output_in_decimal += from.index(next_val)
end
This is easier to understand than the "from decimal" algorithm. Consider if you were to apply this to the decimal number 123. This algorithm is essentially doing this equation
((1 * 10) + 2) * 10) + 3
or, much easier to read:
1 * (10 * 10) + 2 * (10) + 3
Just iteratively. It works for other number systems, by replacing the 10 with the base of the number system (i.e. the number of values the number system contains). The only other magic it does it converts a value in the number system into a decimal number using .index.
E.g. converting "bcdl" to decimal from their "allow" system. Using a 0-index, b = the 1st position, c = 2nd, d = 3rd, l = 11th
Start with 0
Multiply by the number system base, which is 26 (26 letters in the lowercase alphabet) = 0
Add the decimal value of b (1) => 1
1 * 26 = 26
Add decimal value of c (2) => 28
28 * 26 => 728
Add decimal value of d (3) => 731
731 * 26 => 19006
Add decimal value of l (11) => 19017 That's the decimal notation for "bcdl".
Putting it together
Once you have converters to and from decimal, you can write a pretty straightforward wrapper to handle every situation (I put DEC in a constant to make it visible in this method, it's the same as dec):
def convert(val, from, to)
case
when from == to then val
when from == DEC then convert_from_dec(val, to)
when to == DEC then convert_to_dec(val, from)
else
convert_from_dec(convert_to_dec(val, from), to)
end
end
After that, you mostly have to deal with edge cases.
As I said, not a direct answer to your question, but it seems like you'll have to use this general approach for the alpha number systems, at which point you may as well use it for everything :)
I honestly tried not to look at alexcavalli's solution, but in the end came to exact same algorithm with a different code. So for explanation why it works look at his much more explained answer. Here it's only code, written in a way if you save it under base_converter.rb name you can run it as:
$ ruby ../base_converer.rb 123 hex dec #=> 291
bases = {
bin: '01',
oct: '01234567',
dec: '0123456789',
hex: '0123456789abcdef',
allow: 'abcdefghijklmnopqrstuvwxyz',
allup: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
alpha: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
alphanum: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
}
def to_int(num, src)
src_map = src.split('').map.with_index.to_h
num.reverse.each_char.with_index.sum{ |c, i| src_map[c] * (src.size ** i) }
end
def from_int(num, dst)
res = []
while num > 0
res << dst[num % dst.size]
num /= dst.size
end
res.join.reverse
end
def convert(num, src, dst)
from_int(to_int(num, src), dst)
end
if ARGV.size > 2
puts convert(ARGV[0], bases[ARGV[1].to_sym], bases[ARGV[2].to_sym])
end

Using Boolean operators

This works fine
if ((a >= 40 && a <= 50) || (a >= 60 && a <= 80))
// do something
How do I do the reverse of it?
if ((a < 40 && a > 50) || (a < 60 && a > 80))
// do something
The code does not work as expected. I want something like if not (condition)
You might want to look at De Morgan's laws.
1. !((a >= 40 && a <= 50) || (a >= 60 && a <= 80))
2. (!(a >= 40 && a <= 50) && !(a >= 60 && a <= 80))
3. ((!(a >= 40) || !(a <= 50)) && (!(a >= 60) || !(a <= 80))
4. ((a < 40 || a > 50) && (a < 60 || a > 80))
or in other words: (a < 40 || (50 < a && a < 60) || 80 < a)
if ((a < 40 || a > 50) && (a < 60 || a > 80))
// do something
While I would recommend figuring out how to make it work properly (by rewriting it)
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
should work I believe.
You need a "OR"
if ((a < 40 || a > 50) && (a < 60 || a > 80))
Or, a NOT
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
You second example
if ((a < 40 && a > 50) || (a < 60 && a > 80))
doesn't make sense as a cannot be both less than 40 and greater than 50 (or less than 60 and greater than 80) at the same time.
Something like
if (!((a < 40 && a > 50) || (a < 60 && a > 80)))
or
if ((a < 40 || a > 50) && (a < 60 || a > 80))
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
Assuming that you want the equivalent of
if ( not ((a >= 40 && a <= 50) || (a >= 60 && a <= 80)) )
then, if you think about the original expression, it should be
if (a < 40 || (a > 50 && a < 60) || a > 80)
The first expression is allowing a to be a number from 40 to 50 or from 60 to 80. Negate that in English and you want a number less than 40 or between 50 and 60 or greater than 80.
De Morgan's Laws can get you an accurate answer, but I prefer code that you can read aloud and make sense of.

Resources