On what line number is the fundamental operation? - pseudocode

def linear_search(values, key):
for i := 1 to n:
if values[i] == key:
return true
return false

Related

What would be the time complexity of Search Range problem solution DnC

I would appreciate some help in figuring out the time complexity of the solution for Search Range problem from leetcode which involves recursion and DnC algorithm.
I am not sure whether it is O(N) or O(NlogN) and why?
func searchRange(nums []int, target int) []int {
if (len(nums) == 0) {
return []int{-1, -1}
}
return helper(nums, target, 0, len(nums) - 1)
}
func helper(nums []int, target, start, end int) []int {
res := []int {-1, -1}
if (nums[start] > target || nums[end] < target || start > end || (start == end && nums[start] != target)) {
return res
}
if (start == end) {
res[0] = start
res[1] = end
return res
}
mid := (start + end) / 2
res1 := helper(nums, target, start, mid)
res2 := helper(nums, target, mid + 1, end)
if (res1[0] == -1) {
return res2
}
if (res2[0] == -1) {
return res1
}
res[0] = res1[0]
res[1] = res2[1]
return res
}

Why is is leetcode saying my atoi answer is incorrect? Is it acutally incorrect? Or is there a bug in leetcode

I am doing the atoi problem in leetcode and I submitted my code below which isn't too important. I am wondering if it is a valid failure leetcode gave me. It seems like my code is doing the right thing.
Here is the problem description:
Here is the code:
const (
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
)
func myAtoi(str string) int {
if len(str) < 1 {
return 0
}
// count to keep track of the number of digits
count := 0
// container for digits
values := make([]rune, 0)
// constant we are going to need
minus := "-"
plus := "+"
lastWasPrefix := false
// is the number negative or lead with dash
negative := false
clean := strings.TrimSpace(str)
for _, char := range clean {
isNumber := unicode.IsNumber(char)
isMinus := string(char) == minus
isPlus := string(char) == plus
isPrefix := isMinus || isPlus
// checking for two prefixes following eachother
if isPrefix && lastWasPrefix {
return 0
}
if isPrefix {
lastWasPrefix = true
}
curLen := len(values)
if !isNumber && !isPrefix && curLen == 0 {
return 0
}
if !isNumber && !isPrefix && curLen != 0 {
break
}
if isMinus {
negative = true
continue
}
if isNumber {
// add value in order and inc. count
values = append(values, char)
count++
}
}
postLen := len(values)
if postLen == 0 {
return 0
}
multiplier := int32(1)
ten := int32(10)
total := int32(0)
for i := postLen - 1; i >= 0; i-- {
diff := MaxInt32 - total
added := CharToNum(values[i]) * multiplier
// added will be zero if we overflow the int
if added > diff || added < 0 {
return MinInt32
}
total += added
multiplier *= ten
}
if negative {
return int(total * int32(-1))
} else {
return int(total)
}
}
/**
a rune is a uni code char so we need to conver from unicode int to digit
*/
func CharToNum(r rune) (int32) {
for i := 48; i <= 57; i++ {
if int(r) == i {
return int32(r) - 48
}
}
return -1
}
Any help understanding this error would be much appreciated. I don't want any help with the algorithm. Is this a valid error or not?
Without checking your algorithm I can see the following in the error message:
The maximum 32bit int value is 2,147,483,647 which is expected to be returned when you get a string representing a larger value than that (e.g. your input was "2147483648" which is larger by one). Your program apparently returns -2147483648.
The specification is ambiguous "if the numerical value is out of the range of representable values INT_MAX or INT_MIN is retuned". The authors had in mind to return the value matching in sign but this is not clearly stated.
So I would say when you return INT_MIN for a number that is larger than INT_MAX this could be considered correct (although it is somewhat illogical).

generate combinations/permutation of specific length

The project is more complex but the blocking issue is: How to generate a sequence of words of specific length from a list?
I've found how to generate all the possible combinations(see below) but the issue is that I need only the combinations of specific length.
Wolfram working example (it uses permutations though, I need only combinations(order doesn't matter)) :
Permutations[{a, b, c, d}, {3}]
Example(pseudo go):
list := []string{"alice", "moon", "walks", "mars", "sings", "guitar", "bravo"}
var premutationOf3
premutationOf3 = premuate(list, 3)
// this should return a list of all premutations such
// [][]string{[]string{"alice", "walks", "moon"}, []string{"alice", "signs", "guitar"} ....}
Current code to premutate all the possible sequences (no length limit)
for _, perm := range permutations(list) {
fmt.Printf("%q\n", perm)
}
func permutations(arr []string) [][]string {
var helper func([]string, int)
res := [][]string{}
helper = func(arr []string, n int) {
if n == 1 {
tmp := make([]string, len(arr))
copy(tmp, arr)
res = append(res, tmp)
} else {
for i := 0; i < n; i++ {
helper(arr, n-1)
if n%2 == 1 {
tmp := arr[i]
arr[i] = arr[n-1]
arr[n-1] = tmp
} else {
tmp := arr[0]
arr[0] = arr[n-1]
arr[n-1] = tmp
}
}
}
}
helper(arr, len(arr))
return res
}
I implement twiddle algorithm for generating combination in Go. Here is my implementation:
package twiddle
// Twiddle type contains all information twiddle algorithm
// need between each iteration.
type Twiddle struct {
p []int
b []bool
end bool
}
// New creates new twiddle algorithm instance
func New(m int, n int) *Twiddle {
p := make([]int, n+2)
b := make([]bool, n)
// initiate p
p[0] = n + 1
var i int
for i = 1; i != n-m+1; i++ {
p[i] = 0
}
for i != n+1 {
p[i] = i + m - n
i++
}
p[n+1] = -2
if m == 0 {
p[1] = 1
}
// initiate b
for i = 0; i != n-m; i++ {
b[i] = false
}
for i != n {
b[i] = true
i++
}
return &Twiddle{
p: p,
b: b,
}
}
// Next creates next combination and return it.
// it returns nil on end of combinations
func (t *Twiddle) Next() []bool {
if t.end {
return nil
}
r := make([]bool, len(t.b))
for i := 0; i < len(t.b); i++ {
r[i] = t.b[i]
}
x, y, end := t.twiddle()
t.b[x] = true
t.b[y] = false
t.end = end
return r
}
func (t *Twiddle) twiddle() (int, int, bool) {
var i, j, k int
var x, y int
j = 1
for t.p[j] <= 0 {
j++
}
if t.p[j-1] == 0 {
for i = j - 1; i != 1; i-- {
t.p[i] = -1
}
t.p[j] = 0
x = 0
t.p[1] = 1
y = j - 1
} else {
if j > 1 {
t.p[j-1] = 0
}
j++
for t.p[j] > 0 {
j++
}
k = j - 1
i = j
for t.p[i] == 0 {
t.p[i] = -1
i++
}
if t.p[i] == -1 {
t.p[i] = t.p[k]
x = i - 1
y = k - 1
t.p[k] = -1
} else {
if i == t.p[0] {
return x, y, true
}
t.p[j] = t.p[i]
t.p[i] = 0
x = j - 1
y = i - 1
}
}
return x, y, false
}
you can use my tweedle package as follow:
tw := tweedle.New(1, 2)
for b := tw.Next(); b != nil; b = tw.Next() {
fmt.Println(b)
}

Too many results in a loop for Project Euler #145

I am trying to create a solution for Project Euler #145. I am writing in Go. When I run my program I get a result of 125. The expected result is 120. I have 2 different ways I have tried to write the code but both come up with the same answer. Any help pointing out my error would be appreciated.
Code option #1 using strings:
package main
import (
"fmt"
"strconv"
)
//checks to see if all the digits in the number are odd
func is_Odd(sum int) bool {
intString := strconv.Itoa(sum)
for x := len(intString); x > 0; x-- {
newString := intString[x-1]
if newString%2 == 0 {
return false
}
}
return true
}
//reverse the number passed
func reverse_int(value int) int {
intString := strconv.Itoa(value)
newString := ""
for x := len(intString); x > 0; x-- {
newString += string(intString[x-1])
}
newInt, err := strconv.Atoi(newString)
if err != nil {
fmt.Println("Error converting string to int")
}
return newInt
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter := 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
fmt.Println(counter, ":", i, "+", flipped, "=", sum)
counter++
}
}
counter--
fmt.Println("total = ", counter)
}
Code option #2 using only ints:
package main
import (
"fmt"
)
var counter int
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func is_Odd(n int) bool {
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse_int(n int) int {
var new_int int
for n > 0 {
remainder := n % 10
new_int *= 10
new_int += remainder
n /= 10
}
return new_int
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter = 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
//fmt.Println(counter,":",i,"+",flipped,"=",sum)
counter++
}
}
counter--
fmt.Println(counter)
}
Leading zeroes are not allowed in either n or reverse(n) so in reverse(n int) int remove Leading zeroes like so:
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
try this:
package main
import (
"fmt"
)
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func isOdd(n int) bool {
if n <= 0 {
return false
}
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse(n int) int {
first := true
t := 0
for n > 0 {
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
t *= 10
t += remainder
n /= 10
}
return t
}
func main() {
counter := 0
for i := 0; i < 1000; i++ {
flipped := reverse(i)
if flipped == 0 {
continue
}
sum := add(flipped, i)
if isOdd(sum) {
counter++
//fmt.Println(counter, ":", i, "+", flipped, "=", sum)
}
}
fmt.Println(counter)
}
output:
120
You're ignoring this part of the criteria:
Leading zeroes are not allowed in either n or reverse(n).
Five of the numbers you count as reversible end in 0. (That means their reverse has a leading zero.) Stop counting those as reversible and you're done.
Some positive integers n have the property that the sum [ n +
reverse(n) ] consists entirely of odd (decimal) digits. For instance,
36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers
reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are
not allowed in either n or reverse(n).
All digits of the sum must all be odd.
Try this one: https://play.golang.org/p/aUlvKrb9SB

prime numbers program gives wrong answer

I recently created a program which will tell you if a number is prime or not. It gets all answers right but the prime number of 9.
package main
import "fmt"
func isPrime(num int) bool {
for x := 2; x > 1; x++ {
if num%2 == 0 {
return false
} else {
return true
}
}
return true
}
func main() {
fmt.Printf("is it a prime number: %v \n", isPrime(9))
}
What is the problem?
Thanks in advance!
1- Here is the working version of your code: try it on The Go Playground.
package main
import "fmt"
func isPrime(num int) bool {
if num < 2 {
return false
}
for x := 2; x < num; x++ {
if num%x == 0 {
return false
}
}
return true
}
func main() {
fmt.Printf("is it a prime number: %v \n", isPrime(9))
}
2- The only even prime is 2, so it is better to check it first:
if n == 2 {
return true
}
Then there is no other even prime number: remove them all, and there is no prime number less than 2:
if n < 2 || n&1 == 0 {
return false
}
and you don't need to check more than square root of n:
sqrt := int(math.Sqrt(float64(n)))
And now you may start from 3, with just odd numbers (i += 2):
for i := 3; i <= sqrt; i += 2 {
if n%i == 0 {
return false
}
}
Try it on The Go Playground:
package main
import (
"fmt"
"math"
)
func isPrime(n int) bool {
if n == 2 {
return true
}
if n < 2 || n&1 == 0 {
return false
}
sqrt := int(math.Sqrt(float64(n)))
for i := 3; i <= sqrt; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
func main() {
fmt.Printf("is it a prime number: %v \n", isPrime(9))
for i := 0; i < 120; i++ {
if isPrime(i) {
fmt.Print(i, " ")
}
}
fmt.Println()
}
output:
is it a prime number: false
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
See:
Prime number
Generating primes
As it is, your code is only checking if a number's parity and returning false if it is even. I don't actually know Go, but I did manage to work out this problem for you using the following code:
func isPrime(num int) bool {
for x := 2; x < num; x++{
if num%x == 0 && num!=2{
return false
}
}return true;
}
According to prime number definition A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself, in your code you're only checking if it's odd or not.
I left you a fast solution in Go https://play.golang.org/p/2XXTUFbjhy It does only go until the square root of the number.
func isPrime(n int) bool {
if n <= 1 {
return false
}
for ix, sqn := 2, int(math.Sqrt(float64(n))); ix <= sqn; ix++ {
if n%ix == 0 {
return false
}
}
return true
}
Also if you're interested in a faster way to know if a number is primer or not I recommend you read about the Sieve of Eratosthenes

Resources