Variable declared and not used in a loop - go

Got confusion with a function
package main
import "fmt"
func dominantIndex(nums []int) int {
var max, max2 = -12423421, -12423421
var i, j = -1, -1
for k, num := range nums {
if num > max {
max, max2 = num, max
i, j = k, i
} else if num > max2 {
max2 = num
j = k
}
}
if max >= max2*2 {
return i
}
return -1
}
func main() {
var a = []int{3, 6, 100, 1, 0 }
fmt.Print(dominantIndex(a))
}
I have to insert a nonsense statement in the loop such as j = j. Otherwise, it raises ./hello.go:7:6: j declared and not used. Wonder if there is any fix.

You assign a value to j, but you don't use j. That is the problem. You could as well leave j out, without changing the functionality of the code.

Related

Sorting rows of a sparse CSC matrix Golang

I'm trying to analyze sparse matrices. Faced with the task of sorting rows in ascending order of the elements in them in the original matrix.
But I don't understand how to do this without damaging the empty elements.
I tried to bind the elements of the sum array to the rows and somehow move them. But some elements have been removed from the CSC structure.
It may be necessary to change the li/lj arrays themselves, but I don't have enough mathematical knowledge for this. More precisely, I don't understand how to track when elements should be rearranged unless additional elements (zeros) are explicitly specified in the structure.
package main
import (
"fmt"
)
type CSC struct {
a, lj, li []int
}
func getEl(i, j int, el *CSC) int {
for k := el.lj[j]; k < el.lj[j+1]; k++ {
if el.li[k] == i {
return el.a[k]
}
}
return 0
}
func maxSliceEl(lj []int) int {
max := 0
for _, v := range lj {
if v > max {
max = v
}
}
return max
}
func main() {
ma := CSC{
a: []int{8, 2, 5, 7, 1, 9, 2},
li: []int{0, 0, 1, 4, 4, 6, 4},
lj: []int{0, 1, 1, 4, 6, 7},
}
n := len(ma.lj) + 1
m := maxSliceEl(ma.li) - 1
fmt.Printf("Col: %v, Row: %v\n", n, m)
maxStr := []int{}
fmt.Println("Initial matrix:")
for i := 0; i < n; i++ {
sumStrEl := 0
for j := 0; j < m; j++ {
fmt.Print(getEl(i, j, &ma), " ")
sumStrEl += getEl(i, j, &ma)
}
maxStr = append(maxStr, sumStrEl)
fmt.Println("|sumStrEl: ", sumStrEl)
}
}
I found a solution to the problem by taking the structure as a solution: the sum of the elements + their index. The solution turned out to be simpler than expected, only the practice of solving sparse matrices was lacking. The position [i] of the sum must be passed to the getEl function as the first parameter.
package main
import (
"fmt"
"sort"
)
// Creating a CSC (CCS) matrix structure
type CSC struct {
// Array of values, column indexes, row indexing
a, lj, li []int
}
// Getting access to the element
func getEl(i, j int, el *CSC) int {
for k := el.lj[j]; k < el.lj[j+1]; k++ {
// If the element string is equal to the string of the searched element, then the element is found
if el.li[k] == i {
return el.a[k]
}
}
// Otherwise, we will return 0. It will be entered into the matrix
return 0
}
func maxSliceEl(lj []int) int {
max := 0
for _, v := range lj {
if v > max {
max = v
}
}
return max
}
type strInfo struct {
summa int
pos int
}
func main() {
// Set the CSC matrix
ma := CSC{
a: []int{8, 2, 5, 7, 1, 9, 2},
li: []int{0, 0, 1, 4, 4, 6, 4},
lj: []int{0, 1, 1, 4, 6, 7},
}
// Define the number of columns
n := len(ma.lj) + 1
// Define the number of rows
m := maxSliceEl(ma.li) - 1
fmt.Printf("Cols: %v, Rows: %v\n", m, n)
// Set a variable with a structure type for calculating
// the amount in a row and indexing each element in it
var stringsInfo []strInfo
fmt.Println("Initial matrix:")
for i := 0; i < n; i++ {
sumStrEl := 0
for j := 0; j < m; j++ {
sumStrEl += getEl(i, j, &ma)
fmt.Print(getEl(i, j, &ma), " ")
}
fmt.Println("|", sumStrEl)
// Adding a cell with the sum and index to the slice
var strI strInfo
strI.summa = sumStrEl
strI.pos = i
stringsInfo = append(stringsInfo, strI)
}
fmt.Println("stringsInfo: ", stringsInfo)
// Sorting the stringsInfo slice in ascending order of the sum elements
sort.Slice(stringsInfo, func(i, j int) (less bool) {
return stringsInfo[i].summa < stringsInfo[j].summa
})
fmt.Println("stringsInfo: ", stringsInfo)
fmt.Println("Sorted matrix:")
for i := range stringsInfo {
for j := 0; j < m; j++ {
// Output the matrix by idnex stringsInfo[i].pos
fmt.Print(getEl(stringsInfo[i].pos, j, &ma), " ")
}
fmt.Println("|", stringsInfo[i].summa)
}
}

Unexpected outcome of while loop?

I've just started learning Golang, so I set myself a challenge to order a slice of integers in highest to lowest and/or lowest to highest. I've got most of it right, but it seems to miss out the last item?
Expected: [5, 4, 1]
Got: [5, 4]
Now, this line is the issue,
for len(rebuiltNumbers) < len(numbers)
If I change it to this, it works fine:
for len(rebuiltNumbers) < len(numbers) + 2
but I don't understand why? Does while or for form of while work differently in go?
Here is the full code
package main
import "fmt"
func main() {
var numbers = []int { 1, 4, 5 }
fmt.Println(orderArrayOfNumbers(numbers, true))
}
func orderArrayOfNumbers(numbers []int, descending bool) []int {
var rebuiltNumbers []int
for len(rebuiltNumbers) < len(numbers) + 1 {
var next = 0
if descending {
next = getHighestItemInArray(numbers);
} else {
next = getLowestItemInArray(numbers);
}
rebuiltNumbers = append(rebuiltNumbers, next)
numbers = remove(numbers, next)
}
return rebuiltNumbers
}
func getHighestItemInArray(numbers []int) int {
var highest = 0
var hasSet = 0
for i := 0; i < len(numbers); i++ {
if numbers[i] > highest || hasSet == 0 {
highest = numbers[i]
hasSet = 1
}
}
return highest
}
func getLowestItemInArray(numbers []int) int {
var lowest = 0
var hasSet = 0
for i := 0; i < len(numbers); i++ {
if numbers[i] < lowest || hasSet == 0 {
lowest = numbers[i]
hasSet = 1
}
}
return lowest
}
func remove(slice []int, remove int) []int {
var rebuiltSlice = []int {}
for i := 0; i < len(slice); i++ {
if slice[i] != remove {
rebuiltSlice = append(rebuiltSlice, slice[i])
}
}
return rebuiltSlice
}
These two lines are important
rebuiltNumbers = append(rebuiltNumbers, next)
numbers = remove(numbers, next)
When you append to one array and remove from the other, the sizes will meet eventually in the middle. So you should rather save the size upfront, and then compare to that, e.g.
var nOrig = len(numbers)
for len(rebuiltNumbers) < nOrig {
// ...
}

Generate all the strings of length n drawn from 0 ... k-1

This problem is from the book Data Structure and Algorithms Made Easy by Narasimha Karumanchi chapter Recursion and Backtracking. The algorithm which is given in the book is as follows:
Let us assume we keep current k-ary string in an array A[0...n-1]. Call function k-string(n, k)
void k-string(int n, int k) {
// process all k-ary strings of length m
if(n < 1)
printf("%s", A); // Assume array A is a global variable
else {
for(int j=0; j<k; j++){
A[n-1] = j;
k-string(n-1, k);
}
}
}
I couldn't understand the algorithm. Like why did they assigned an integer j to a string element?
package main
import "fmt"
func printResult(A []int, n int) {
var i int
for ; i < n; i++ {
// Function to print the output
fmt.Print(A[i])
}
fmt.Printf("\n")
}
// Function to generate all k-ary strings
func generateK_aryStrings(n int, A []int, i int, k int) {
if i == n {
printResult(A, n)
return
}
for j := 0; j < k; j++ {
// assign j at ith position and try for all other permutations for remaining positions
A[i] = j
generateK_aryStrings(n, A, i+1, k)
}
}
func main() {
var n int = 4
A := make([]int, n)
// Print all binary strings
generateK_aryStrings(n, A, 0, 3)
return
}

Golang assignment

We want to calculate a sum of squares of some integers, excepting negatives
The first line of the input will be an integer N (1 <= N <= 100)
Each of the following N test cases consists of one line containing an integer X (0 < X <= 100), followed by X integers (Yn, -100 <= Yn <= 100) space-separated on the next line
For each test case, calculate the sum of squares of the integers excepting negatives, and print the calculated sum to the output. No blank line between test cases
(Take input from standard input, and output to standard output)
Do not use the for statement
Use only standard libraries
Write it in the Go programming language
Sample input
2
4
3 -1 1 14
5
9 6 -53 32 16
Sample Output
206
1397
So I am new to Golang , and I managed to solve this using for statements.
How can I abide by the given and not use for? using only standard libraries?
Any pointers would be greatly appreciated
package main
import "fmt"
func main() {
var N int
fmt.Scan(&N)
for a := 0; a < N; a++ {
var X int
var res int = 0
fmt.Scan(&X)
for b := 0; b < X; b++ {
var Y int
fmt.Scan(&Y)
if Y > 0 {
res = res + Y*Y
}
}
fmt.Println(res)
}
}
// I used fmt to read data from console. Sum of squares is found out only if the number is positive. Then computed sum is displayed to the screen
I got the same output expected, but not using the required method
This is how I did it in Java
import java.util.Scanner;
public class SumSquares {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m, num;
int i = 0;
while (i < n) {
int j = 0, sum = 0;
m = in.nextInt();
while (j < m) {
num = in.nextInt();
if (num > 0) {
sum += num*num;
}
j++;
}
System.out.println(sum);
i++;
}
}
}
Go does not have the while, until, or foreach loop constructs you may be familiar with from other languages. In Go, the for and range statements replace them all:
// Three expressions, i.e. the usual
for i := 0; i < n; i++ {
}
// Single expression; same as while(condition) in other languages
for condition {
}
// No expressions; endless loop, i.e. same as while(true) or for(;;)
for {
}
// for with range; foreach and similar in other languages. Works with slices, maps, and channels.
for i, x := range []T{} {
}
If you are not allowed to use Go's single loop construct, you are left with either recursion or the goto statement:
package main
import (
"fmt"
)
func main() {
var N int
fmt.Scan(&N)
fmt.Println(f(N, 0))
}
func f(n, sum int) int {
if n == 0 {
return sum
}
var Y int
fmt.Scan(&Y)
if Y > 0 {
sum += Y * Y
}
return f(n-1, sum)
}
With goto:
package main
import (
"fmt"
)
func main() {
var N, Y, sum int
fmt.Scan(&N)
again:
fmt.Scan(&Y)
if Y > 0 {
sum += Y * Y
}
N--
if N > 0 {
goto again
}
fmt.Println(sum)
}

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

Resources