Why is my GoLang algorithm going on an infinite loop? - algorithm

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.

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 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.

How to take this conditional statement and rewrite it without if-then statements

In a project that I have for class the correct code for a specific method is:
if ((volume % 10) % 6 == 0)
return 0;
else if ((volume % 10) % 6 <= 4)
return 1;
else
return 2;
However the teacher recently added a new condition stating that you are not allowed to use if statements.
What I have so far is :
return ((volume % 10) % 6)/4 + ((volume % 10) % 6 % 4`);
however it doesnt work while ((volume % 10) % 6 % 4) is equal to 2.(it needs to be equal to 1)
I treid fixing it by dividing that by 2 but then when ((volume % 10) % 6 % 4) is equal to one it rounds down to 0
any ideas??
How about:
return ((k%10)%6 + 3)/4;
Heres how i would do it
theres a repeating pattern when you run your code from 0...n
the pattern is: 0,1,1,1,1,2,0,1,1,1
//initialize an array with the pattern. This is for javascript.
var a=[0,1,1,1,1,2,0,1,1,1];
return a[(volume%10)];
You can rewrite it using ternary operator. condition ? true expression :false expression. https://msdn.microsoft.com/en-us/library/ty67wk28.aspx
In below code false will be a new ternary operation.
return (volume % 10) % 6 == 0 ? 0 : ((volume % 10) % 6
<= 4 ? 1 : 2 );
Hate to use a loophole, but will
return ((volume % 10 ) % 6 == 0 :0 ? <the sub expressions>)
work?

Check if a number from 1 to N has a number 3 in it

How do I check how many numbers from 1 to N (N < 100) have number 3 in it without converting it to a string to check it?
You can use th % mod operator to take the digits of the number one by one, and check them with 3.
Like,
int x;
while(num != 0) // num here goes from 1 to 100
{
x = num % 10;
if(x == 3)
{
//eureka
}
num /= 10;
}
EDIT
Lets check the algorithm for 35.
First iteration
//num = 35
x = num % 10; // x = 5 (35 % 10)
if(x == 3) // is x equal to 3 (NO)
{
//eureka
}
num /= 10; // num = 3 (35 / 10)
While loop check
num != 0 // num = 5
Second Iteration
//num = 35
x = num % 10; // x = 3 (5 % 10)
if(x == 3) // is x equal to 3 (YES)
{
//eureka
}
num /= 10; // num = 0 (5 / 10)
While loop check
num != 0 // num = 0
// While loop exits
I think the simplest way is by remainder and checking if number is between 30 and 39
if((x%10)==3||(x<40&&x>=30))
{
//Thats it
}
You can make use of the modulas operator % such that if(n % 3 == 1){success operation}

Count number of 1 digits in 11 to the power of N

I came across an interesting problem:
How would you count the number of 1 digits in the representation of 11 to the power of N, 0<N<=1000.
Let d be the number of 1 digits
N=2 11^2 = 121 d=2
N=3 11^3 = 1331 d=2
Worst time complexity expected O(N^2)
The simple approach where you compute the number and count the number of 1 digits my getting the last digit and dividing by 10, does not work very well. 11^1000 is not even representable in any standard data type.
Powers of eleven can be stored as a string and calculated quite quickly that way, without a generalised arbitrary precision math package. All you need is multiply by ten and add.
For example, 111 is 11. To get the next power of 11 (112), you multiply by (10 + 1), which is effectively the number with a zero tacked the end, added to the number: 110 + 11 = 121.
Similarly, 113 can then be calculated as: 1210 + 121 = 1331.
And so on:
11^2 11^3 11^4 11^5 11^6
110 1210 13310 146410 1610510
+11 +121 +1331 +14641 +161051
--- ---- ----- ------ -------
121 1331 14641 161051 1771561
So that's how I'd approach, at least initially.
By way of example, here's a Python function to raise 11 to the n'th power, using the method described (I am aware that Python has support for arbitrary precision, keep in mind I'm just using it as a demonstration on how to do this an an algorithm, which is how the question was tagged):
def elevenToPowerOf(n):
# Anything to the zero is 1.
if n == 0: return "1"
# Otherwise, n <- n * 10 + n, once for each level of power.
num = "11"
while n > 1:
n = n - 1
# Make multiply by eleven easy.
ten = num + "0"
num = "0" + num
# Standard primary school algorithm for adding.
newnum = ""
carry = 0
for dgt in range(len(ten)-1,-1,-1):
res = int(ten[dgt]) + int(num[dgt]) + carry
carry = res // 10
res = res % 10
newnum = str(res) + newnum
if carry == 1:
newnum = "1" + newnum
# Prepare for next multiplication.
num = newnum
# There you go, 11^n as a string.
return num
And, for testing, a little program which works out those values for each power that you provide on the command line:
import sys
for idx in range(1,len(sys.argv)):
try:
power = int(sys.argv[idx])
except (e):
print("Invalid number [%s]" % (sys.argv[idx]))
sys.exit(1)
if power < 0:
print("Negative powers not allowed [%d]" % (power))
sys.exit(1)
number = elevenToPowerOf(power)
count = 0
for ch in number:
if ch == '1':
count += 1
print("11^%d is %s, has %d ones" % (power,number,count))
When you run that with:
time python3 prog.py 0 1 2 3 4 5 6 7 8 9 10 11 12 1000
you can see that it's both accurate (checked with bc) and fast (finished in about half a second):
11^0 is 1, has 1 ones
11^1 is 11, has 2 ones
11^2 is 121, has 2 ones
11^3 is 1331, has 2 ones
11^4 is 14641, has 2 ones
11^5 is 161051, has 3 ones
11^6 is 1771561, has 3 ones
11^7 is 19487171, has 3 ones
11^8 is 214358881, has 2 ones
11^9 is 2357947691, has 1 ones
11^10 is 25937424601, has 1 ones
11^11 is 285311670611, has 4 ones
11^12 is 3138428376721, has 2 ones
11^1000 is 2469932918005826334124088385085221477709733385238396234869182951830739390375433175367866116456946191973803561189036523363533798726571008961243792655536655282201820357872673322901148243453211756020067624545609411212063417307681204817377763465511222635167942816318177424600927358163388910854695041070577642045540560963004207926938348086979035423732739933235077042750354729095729602516751896320598857608367865475244863114521391548985943858154775884418927768284663678512441565517194156946312753546771163991252528017732162399536497445066348868438762510366191040118080751580689254476068034620047646422315123643119627205531371694188794408120267120500325775293645416335230014278578281272863450085145349124727476223298887655183167465713337723258182649072572861625150703747030550736347589416285606367521524529665763903537989935510874657420361426804068643262800901916285076966174176854351055183740078763891951775452021781225066361670593917001215032839838911476044840388663443684517735022039957481918726697789827894303408292584258328090724141496484460001, has 105 ones
real 0m0.609s
user 0m0.592s
sys 0m0.012s
That may not necessarily be O(n2) but it should be fast enough for your domain constraints.
Of course, given those constraints, you can make it O(1) by using a method I call pre-generation. Simply write a program to generate an array you can plug into your program which contains a suitable function. The following Python program does exactly that, for the powers of eleven from 1 to 100 inclusive:
def mulBy11(num):
# Same length to ease addition.
ten = num + '0'
num = '0' + num
# Standard primary school algorithm for adding.
result = ''
carry = 0
for idx in range(len(ten)-1, -1, -1):
digit = int(ten[idx]) + int(num[idx]) + carry
carry = digit // 10
digit = digit % 10
result = str(digit) + result
if carry == 1:
result = '1' + result
return result
num = '1'
print('int oneCountInPowerOf11(int n) {')
print(' static int numOnes[] = {-1', end='')
for power in range(1,101):
num = mulBy11(num)
count = sum(1 for ch in num if ch == '1')
print(',%d' % count, end='')
print('};')
print(' if ((n < 0) || (n > sizeof(numOnes) / sizeof(*numOnes)))')
print(' return -1;')
print(' return numOnes[n];')
print('}')
The code output by this script is:
int oneCountInPowerOf11(int n) {
static int numOnes[] = {-1,2,2,2,2,3,3,3,2,1,1,4,2,3,1,4,2,1,4,4,1,5,5,1,5,3,6,6,3,6,3,7,5,7,4,4,2,3,4,4,3,8,4,8,5,5,7,7,7,6,6,9,9,7,12,10,8,6,11,7,6,5,5,7,10,2,8,4,6,8,5,9,13,14,8,10,8,7,11,10,9,8,7,13,8,9,6,8,5,8,7,15,12,9,10,10,12,13,7,11,12};
if ((n < 0) || (n > sizeof(numOnes) / sizeof(*numOnes)))
return -1;
return numOnes[n];
}
which should be blindingly fast when plugged into a C program. On my system, the Python code itself (when you up the range to 1..1000) runs in about 0.6 seconds and the C code, when compiled, finds the number of ones in 111000 in 0.07 seconds.
Here's my concise solution.
def count1s(N):
# When 11^(N-1) = result, 11^(N) = (10+1) * result = 10*result + result
result = 1
for i in range(N):
result += 10*result
# Now count 1's
count = 0
for ch in str(result):
if ch == '1':
count += 1
return count
En c#:
private static void Main(string[] args)
{
var res = Elevento(1000);
var countOf1 = res.Select(x => int.Parse(x.ToString())).Count(s => s == 1);
Console.WriteLine(countOf1);
}
private static string Elevento(int n)
{
if (n == 0) return "1";
//Otherwise, n <- n * 10 + n, once for each level of power.
var num = "11";
while (n > 1)
{
n--;
// Make multiply by eleven easy.
var ten = num + "0";
num = "0" + num;
//Standard primary school algorithm for adding.
var newnum = "";
var carry = 0;
foreach (var dgt in Enumerable.Range(0, ten.Length).Reverse())
{
var res = int.Parse(ten[dgt].ToString()) + int.Parse(num[dgt].ToString()) + carry;
carry = res/10;
res = res%10;
newnum = res + newnum;
}
if (carry == 1)
newnum = "1" + newnum;
// Prepare for next multiplication.
num = newnum;
}
//There you go, 11^n as a string.
return num;
}

Resources