Only take first value from loop GOLANG - go

Does anyone know why it took first value when I call variable inside the loop ? I want to make palindrome but the code just like this, can someone explain me. I'm new in GO
package main
import "fmt"
func main() {
var kata, kosong, kebalikan, katanya string
fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata) - 1
for i := panjang; i >= 0; i-- {
kebalikan = kosong + fmt.Sprint(string(kata[i]))
fmt.Print(kebalikan)
}
fmt.Print("\n")
for i := 0; i <= panjang; i++ {
katanya = kosong + fmt.Sprint(string(kata[i]))
fmt.Print(katanya)
}
fmt.Println(katanya)
fmt.Println(kebalikan)
if fmt.Sprint(katanya) == fmt.Sprint(kebalikan) {
fmt.Println(true)
} else {
fmt.Println(false)
}
}

You have your greater than and less than symbols the wrong way around. i >= 0 checks for when I is greater than or equal to 0, which it will be from the start because you're setting i to the length of that string.

i have my answer from my own question, here i mean
var kata, kebalikan string
fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata) - 1
for i := panjang; i >= 0; i-- {
kebalikan = kebalikan + fmt.Sprint(string(kata[i]))
}
if fmt.Sprint(kata) == fmt.Sprint(kebalikan) {
fmt.Println(true)
} else {
fmt.Println(false)
}

Related

What is the correct terminating condition for swapping in bubble sort?

I am learning golang, and I am trying to work through writing bubblesort and working with pointers.
package main
import (
"fmt"
"math/rand"
)
func main() {
testTwo := make([]int, 10)
for i := 0; i <= len(testTwo)-1; i++ {
fmt.Print("\n")
testTwo[i] = rand.Intn(10)
}
for i := 0; i <= len(testTwo)-1; i++ {
for j := i + 1; j <= len(testTwo)-1; j++ {
testTwo[i], testTwo[i+1] = swap(testTwo[i], testTwo[i+1])
}
}
}
/*
Swaps the pointers of two adjacent elements in an array
*/
func swap(valOne, valTwo int) (int, int) {
valAddress := &valOne
valAddressTwo := &valTwo
if valOne <= valTwo {
temp_address := *valAddressTwo
*valAddressTwo = valOne
*valAddress = temp_address
} else {
temp_address := *valAddress
*valAddress = valTwo
*valAddressTwo = temp_address
}
return valOne, valTwo
}
This is an example of what is being done so far. The input slice might be
[4 1 2 9 8 4 1 5 7 6]. But it stops short of sorting everything.[1 4 9 2 4 8 5 1 6 7]. Is there another condition I should add or is there something wrong with how I am using the pointers in the swap function?
package main
import (
"fmt"
"math/rand"
)
func main() {
testTwo := make([]int, 10)
for i := 0; i <= len(testTwo)-1; i++ {
fmt.Print("\n")
testTwo[i] = rand.Intn(10)
}
for i := 0; i <= len(testTwo)-1; i++ {
for j := i + 1; j <= len(testTwo)-1; j++ {
if testTwo[i] > testTwo[j] {
// here we swap pointers
testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])
}
}
}
fmt.Print(testTwo)
}
/*
GO always sends arguments by value. Pointers cannot be swapped here, unless we use *int
*/
func swap(valOne, valTwo int) (int, int) {
if valOne <= valTwo {
return valOne, valTwo
} else {
return valTwo, valOne
}
}
You forgot to compare 2 variables and you have mistaken using i+1 instead of j.
for i := 0; i <= len(testTwo)-1; i++ {
for j := i + 1; j <= len(testTwo)-1; j++ {
if testTwo[i] < testTwo[j] {
testTwo[i], testTwo[j] = swap(testTwo[i], testTwo[j])
}
}
}

how to simplimize my go script because always get time out in hackerrank

I have a test interview as a Go Developer and have to do some of the tasks on hackerrank.
I've done the task, but when I submit my script it always "times out".. maybe because there are a lot of loops that I use to do this function, and the task is :
So, my solution are :
Loop from a to b with a increment.
Define the digit sum with modulus by 10, sum the result with the leftover.
Define the square sum with converting int(a) to string then use for-range to sum the values.
checking if digit sum and square sum is a prime number, if so then count++
My script is :
func main() {
fmt.Printf("Jadi ada %d bilangan prima \n", luckyNumbers(1, 20))
}
func luckyNumbers(a int64, b int64) int64 {
count := 0
for min, max := a, b; min <= max; min++ {
squareSum := digitSquare(min)
digitSum := digitSum(min)
if isPrime(digitSum) && isPrime(squareSum) {
count++
}
}
return int64(count)
}
func digitSquare(number int64) int64 {
numStr := strconv.Itoa(int(number))
var firstDigit, secondDigit int
for _, digit := range numStr {
numInt, _ := strconv.Atoi(string(digit))
pow := int(math.Pow(float64(numInt), 2))
if firstDigit == 0 {
firstDigit += pow
} else {
secondDigit += pow
}
}
squareSum := int64(firstDigit + secondDigit)
return squareSum
}
func digitSum(number int64) int64 {
var remainder, sumResult int64 = 0, 0
for number != 0 {
remainder = number % 10
sumResult += remainder
number /= 10
}
return sumResult
}
func isPrime(num int64) bool {
if num < 2 {
return false
}
for i := int64(2); i <= int64(math.Sqrt(float64(num))); i++ {
if num%i == 0 {
return false
}
}
return true
}
The script above is the best script that I can make right now, I understand that I do a lot of iterations, so when I try to submit it will always show "time out". So I want to learn from you and want to see if there is a simpler script so that it can be submitted.
Thank you,
Regards

Palindrome - Is it possible to make my code faster

I have an ASCII-only string which is either already a palindrome, or else can be made a palindrome by removing one character. I need to determine whether it's already a palindrome, and if not, I need to find the index of the character that would need to be removed. For example, if the string is 'aaba', then it can be made into the palindrome 'aba' by removing the first character, so I need to return 0.
I have working code, but I am wondering if it is possible to make it faster, because I need to work with many long strings.
Here is my code:
package main
import (
"fmt"
)
func Palindrome(s string) bool {
var l int = len(s)
for i := 0; i < l / 2; i++ {
if s[i] != s[l - 1 - i] {
return false;
}
}
return true
}
func RemoveChar(s string, idx int) string {
return s[0:idx-1] + s[idx:len(s)]
}
func findIdx(s string) int {
if Palindrome(s) {
return -1
}
for i := 0; i < len(s); i++ {
if Palindrome(RemoveChar(s, i + 1)) {
return i
}
}
return -2
}
func main() {
var s string = "aabaab"
fmt.Println(findIdx(s))
}
This should be very slightly more efficient than ruakh's solution. You shouldn't have to use isPalindrome() to check that s[i + 1:len(s) - i] is a palindrome because it's quicker to check that s[i:len(s) - i - 1] is not a palindrome. In the solution below, in most cases j won't get very far at all before the function returns.
func findIdx(s string) int {
var n int = len(s)
for i := 0; i < n / 2; i++ {
if s[i] != s[n - i - 1] {
for j := 0; ;j++ {
if s[i + j] != s[n - 2 - i - j] {
return i;
}
if s[i + j + 1] != s[n - 1 - i - j] {
return n - 1 - i;
}
}
}
}
return -1
}
Here is a much more efficient approach:
func findIdx(s string) int {
for i := 0; i < len(s) / 2; i++ {
if s[i] != s[len(s) - i - 1] {
if isPalindrome(s[i+1:len(s)-i]) {
return i
} else {
return len(s) - i - 1
}
}
}
return -1
}
It just proceeds from the ends of the string until it finds a pair of bytes that should match, if the string were a palindrome, but that do not. It then knows that it will return the index of one of these two bytes, so it only needs to perform one "is this a palindrome?" check; and it doesn't need to use the RemoveChar function, since the "is this a palindrome?" check only needs to consider the middle portion of the string (that hasn't already been examined).

Generating prime numbers in Go

EDIT: The question essentially asks to generate prime numbers up to a certain limit. The original question follows.
I want my if statement to become true if only these two conditions are met:
for i := 2; i <= 10; i++ {
if i%i == 0 && i%1 == 0 {
} else {
}
}
In this case every possible number gets past these conditions, however I want only the numbers 2, 3, 5, 7, 11... basically numbers that are divisible only with themselves and by 1 to get past, with the exception being the very first '2'. How can I do this?
Thanks
It seems you are looking for prime numbers. However the conditions you described are not sufficient. In fact you have to use an algorithm to generate them (up to a certain limit most probably).
This is an implementation of the Sieve of Atkin which is an optimized variation of the ancient Sieve of Eratosthenes.
Demo: http://play.golang.org/p/XXiTIpRBAu
For the sake of completeness:
package main
import (
"fmt"
"math"
)
// Only primes less than or equal to N will be generated
const N = 100
func main() {
var x, y, n int
nsqrt := math.Sqrt(N)
is_prime := [N]bool{}
for x = 1; float64(x) <= nsqrt; x++ {
for y = 1; float64(y) <= nsqrt; y++ {
n = 4*(x*x) + y*y
if n <= N && (n%12 == 1 || n%12 == 5) {
is_prime[n] = !is_prime[n]
}
n = 3*(x*x) + y*y
if n <= N && n%12 == 7 {
is_prime[n] = !is_prime[n]
}
n = 3*(x*x) - y*y
if x > y && n <= N && n%12 == 11 {
is_prime[n] = !is_prime[n]
}
}
}
for n = 5; float64(n) <= nsqrt; n++ {
if is_prime[n] {
for y = n * n; y < N; y += n * n {
is_prime[y] = false
}
}
}
is_prime[2] = true
is_prime[3] = true
primes := make([]int, 0, 1270606)
for x = 0; x < len(is_prime)-1; x++ {
if is_prime[x] {
primes = append(primes, x)
}
}
// primes is now a slice that contains all primes numbers up to N
// so let's print them
for _, x := range primes {
fmt.Println(x)
}
}
Here's a golang sieve of Eratosthenes
package main
import "fmt"
// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
b := make([]bool, N)
for i := 2; i < N; i++ {
if b[i] == true { continue }
primes = append(primes, i)
for k := i * i; k < N; k += i {
b[k] = true
}
}
return
}
func main() {
primes := sieveOfEratosthenes(100)
for _, p := range primes {
fmt.Println(p)
}
}
The simplest method to get "numbers that are divisible only with themselves and by 1", which are also known as prime numbers is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
It's not a "simple if statement".
If you don't mind a very small chance (9.1e-13 in this case) of them not being primes you can use ProbablyPrime from math/big like this (play)
import (
"fmt"
"math/big"
)
func main() {
for i := 2; i < 1000; i++ {
if big.NewInt(int64(i)).ProbablyPrime(20) {
fmt.Printf("%d is probably prime\n", i)
} else {
fmt.Printf("%d is definitely not prime\n", i)
}
}
}
Just change the constant 20 to be as sure as you like that they are primes.
Simple way(fixed):
package main
import "math"
const n = 100
func main() {
print(1, " ", 2)
L: for i := 3; i <= n; i += 2 {
m := int(math.Floor(math.Sqrt(float64(i))))
for j := 2; j <= m; j++ {
if i%j == 0 {
continue L
}
}
print(" ", i)
}
}
just change the 100 in the outer for loop to the limit of the prime number you want to find. cheers!!
for i:=2; i<=100; i++{
isPrime:=true
for j:=2; j<i; j++{
if i % j == 0 {
isPrime = false
}
}
if isPrime == true {
fmt.Println(i)
}
}
}
Here try this by checking all corner cases and optimised way to find you numbers and run the logic when the function returns true.
package main
import (
"math"
"time"
"fmt"
)
func prime(n int) bool {
if n < 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 && n > 2 {
return false
}
var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))
//d := 3
for d:=3 ;d <= 1 + maxDivisor; d += 2 {
if n%d == 0 {
return false
}
}
return true
}
//======Test Function=====
func main() {
// var t0 = time.Time{}
var t0= time.Second
for i := 1; i <= 1000; i++ {
fmt.Println(prime(i))
}
var t1= time.Second
println(t1 - t0)
}
package main
import (
"fmt"
)
func main() {
//runtime.GOMAXPROCS(4)
ch := make(chan int)
go generate(ch)
for {
prime := <-ch
fmt.Println(prime)
ch1 := make(chan int)
go filter(ch, ch1, prime)
ch = ch1
}
}
func generate(ch chan int) {
for i := 2; ; i++ {
ch <- i
}
}
func filter(in, out chan int, prime int) {
for {
i := <-in
if i%prime != 0 {
out <- i
}
}
}
A C like logic (old school),
package main
import "fmt"
func main() {
var num = 1000
for j := 2; j < num ; j++ {
var flag = 0
for i := 2; i <= j/2 ; i++ {
if j % i == 0 {
flag = 1
break
}
}
if flag == 0 {
fmt.Println(j)
}
}
}
Simple solution for generating prime numbers up to a certain limit:
func findNthPrime(number int) int {
if number < 1{
fmt.Println("Please provide positive number")
return number
}
var primeCounter, nthPrimeNumber int
for i:=2; primeCounter < number; i++{
isPrime := true
for j:=2; j <= int(math.Sqrt(float64(i))) && i != 2 ; j++{
if i % j == 0{
isPrime = false
}
}
if isPrime{
primeCounter++
nthPrimeNumber = i
fmt.Println(primeCounter, "th prime number is ", nthPrimeNumber)
}
}
fmt.Println("Nth prime number is ", nthPrimeNumber)
return nthPrimeNumber
}
A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17.
What is Prime Number?
A Prime Number is a whole number that cannot be made by multiplying other whole numbers
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number.
Go Language Program to Check Whether a Number is Prime or Not
https://www.golanguagehub.com/2021/01/primenumber.html

Go : longest common subsequence to print result array

I have implemented Longest Common Subsequence algorithm and getting the right answer for longest but cannot figure out the way to print out what makes up the longest common subsequence.
That is, I succeeded to get the length of longest commond subsequence array but I want to print out the longest subsequence.
The Playground for this code is here
http://play.golang.org/p/0sKb_OARnf
/*
X = BDCABA
Y = ABCBDAB => Longest Comman Subsequence is B C B
Dynamic Programming method : O ( n )
*/
package main
import "fmt"
func Max(more ...int) int {
max_num := more[0]
for _, elem := range more {
if max_num < elem {
max_num = elem
}
}
return max_num
}
func Longest(str1, str2 string) int {
len1 := len(str1)
len2 := len(str2)
//in C++,
//int tab[m + 1][n + 1];
//tab := make([][100]int, len1+1)
tab := make([][]int, len1+1)
for i := range tab {
tab[i] = make([]int, len2+1)
}
i, j := 0, 0
for i = 0; i <= len1; i++ {
for j = 0; j <= len2; j++ {
if i == 0 || j == 0 {
tab[i][j] = 0
} else if str1[i-1] == str2[j-1] {
tab[i][j] = tab[i-1][j-1] + 1
if i < len1 {
fmt.Printf("%c", str1[i])
}
} else {
tab[i][j] = Max(tab[i-1][j], tab[i][j-1])
}
}
}
fmt.Println()
return tab[len1][len2]
}
func main() {
str1 := "AGGTABTABTABTAB"
str2 := "GXTXAYBTABTABTAB"
fmt.Println(Longest(str1, str2))
//Actual Longest Common Subsequence: GTABTABTABTAB
//GGGGGTAAAABBBBTTTTAAAABBBBTTTTAAAABBBBTTTTAAAABBBB
//13
str3 := "AGGTABGHSRCBYJSVDWFVDVSBCBVDWFDWVV"
str4 := "GXTXAYBRGDVCBDVCCXVXCWQRVCBDJXCVQSQQ"
fmt.Println(Longest(str3, str4))
//Actual Longest Common Subsequence: ?
//GGGTTABGGGHHRCCBBBBBBYYYJSVDDDDDWWWFDDDDDVVVSSSSSBCCCBBBBBBVVVDDDDDWWWFWWWVVVVVV
//14
}
When I try to print out the subsequence when the tab gets updates, the outcome is duplicate.
I want to print out something like "GTABTABTABTAB" for the str1 and str2
Thanks in advance.
EDIT: It seems that I jumped the gun on answering this. On the Wikipedia page for Longest Common Subsequnce they give the pseudocode for printing out the LCS once it has been calculated. I'll put an implementation in go up here as soon as I have time for it.
Old invalid answer
You are forgetting to move along from a character once you have registered it as part of the subsequence.
The code below should work. Look at the two lines right after the fmt.Printf("%c", srt1[i]) line.
playground link
/*
X = BDCABA
Y = ABCBDAB => Longest Comman Subsequence is B C B
Dynamic Programming method : O ( n )
*/
package main
import "fmt"
func Max(more ...int) int {
max_num := more[0]
for _, elem := range more {
if max_num < elem {
max_num = elem
}
}
return max_num
}
func Longest(str1, str2 string) int {
len1 := len(str1)
len2 := len(str2)
//in C++,
//int tab[m + 1][n + 1];
//tab := make([][100]int, len1+1)
tab := make([][]int, len1+1)
for i := range tab {
tab[i] = make([]int, len2+1)
}
i, j := 0, 0
for i = 0; i <= len1; i++ {
for j = 0; j <= len2; j++ {
if i == 0 || j == 0 {
tab[i][j] = 0
} else if str1[i-1] == str2[j-1] {
tab[i][j] = tab[i-1][j-1] + 1
if i < len1 {
fmt.Printf("%c", str1[i])
//Move on the the next character in both sequences
i++
j++
}
} else {
tab[i][j] = Max(tab[i-1][j], tab[i][j-1])
}
}
}
fmt.Println()
return tab[len1][len2]
}
func main() {
str1 := "AGGTABTABTABTAB"
str2 := "GXTXAYBTABTABTAB"
fmt.Println(Longest(str1, str2))
//Actual Longest Common Subsequence: GTABTABTABTAB
//GGGGGTAAAABBBBTTTTAAAABBBBTTTTAAAABBBBTTTTAAAABBBB
//13
str3 := "AGGTABGHSRCBYJSVDWFVDVSBCBVDWFDWVV"
str4 := "GXTXAYBRGDVCBDVCCXVXCWQRVCBDJXCVQSQQ"
fmt.Println(Longest(str3, str4))
//Actual Longest Common Subsequence: ?
//GGGTTABGGGHHRCCBBBBBBYYYJSVDDDDDWWWFDDDDDVVVSSSSSBCCCBBBBBBVVVDDDDDWWWFWWWVVVVVV
//14
}

Resources