Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Execute GO Language Online

package main

import "fmt"

func main() {
   var a int = 20   /* actual variable declaration */
  fmt.Printf("Value of a variable: %d\n", a  )
  fmt.Printf("Value of a variable: %d\n", changeValue(a) )
   fmt.Printf("Value of a variable: %d\n", a  )
    fmt.Printf("Value of a variable: %d\n", changePtrValue(&a) )
   fmt.Printf("Value of a variable: %d\n", a  )
}

func changeValue(a int) int{
    a = a*a
    return a
}

func changePtrValue(a *int) int{
    *a = *a * *a
    fmt.Printf("Value of a variable: %d\n", *a  )
    return *a
}

ertert

package main

import "fmt"

func main() {
   fmt.Println("Hello, World!")
}

virus

package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Antivirus string
const(
        McAfee Antivirus = "McAfee"
        Norton  = "Norton"
        MSDefender  = "MSDefender"
        AVG  = "AVG"
        Avast  = "Avast"
        Eset  = "Eset"
)

//Virus represents simplified data of virus
type Virus struct {
	Uniqueness float64 // Uniqueness means number between 0 - 1, 0 - not unique, 1 - unique
}

//Subnet represents simplified data of each subnet
type Subnet struct {
	ID          int
	Antivirus   Antivirus
	Updated     float64 //Updated means number between 0 - 1, 0 - not updated, 1 - updated regularly
	ConnectedTo []int   //ConnectedTo is an array of connected subnets
	IsInfected  bool
}

//Entrydata represents topology of networks
var entryData = []Subnet{
	{
		ID:          0,
		Antivirus:   McAfee,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{1, 2},
	}, {
		ID:          1,
		Antivirus:   Norton,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{3, 4},
	}, {
		ID:          2,
		Antivirus:   MSDefender,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{5, 6},
	}, {
		ID:          3,
		Antivirus:   Eset,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          4,
		Antivirus:   AVG,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          5,
		Antivirus:   Avast,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          6,
		Antivirus:   McAfee,
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	},
}

func getChanceForUpdate(t Antivirus) bool {
    s := rand.NewSource(time.Now().UnixNano())
	chance := rand.New(s).Float64()
    switch(t){
        case McAfee:
        return chance <= 0.05 
        case Norton:
        return chance <= 0.2
        case MSDefender:
        return chance <= 0.6
        case AVG:
        return chance <= 0.5
        case Avast:
        return chance <= 0.55
        case Eset:
        return chance <= 0.60
    }
    return false
}

//getRandomNumber returns random float in range 0-1
func getRandomNumber() float64 {
	s := rand.NewSource(time.Now().UnixNano())
    newRand := rand.New(s)
	return newRand.Float64()
}

func getVirusUniqueness(index int) float64 {
	switch{
        case ((index >= 0) && (index <= 2)):
        return 1
        case ((index >= 3) && (index <= 5)):
        return 0.9
        case ((index >= 6) && (index <= 8)):
        return 0.7
        case ((index >= 9) && (index <= 10)):
        return 0.4
        case (index > 10):
        return 0.2
    }
    return 0
}

//getsInfected returns if node will be infected or not
func getsInfected(node *Subnet, virus *Virus) {
	nodeEndurance := node.Updated

	if !(node.Updated < 0.3) {
	  node.Updated += getRandomNumber() / 10
	}

	virusEndurance := virus.Uniqueness
	//if node endurance is lover than virus endurance, it means node is not protected enough and will be infected
	if nodeEndurance < virusEndurance {
		node.IsInfected = true
	}
}

func goThroughNet(index int, virus *Virus) {
    nextNodes := make([]int, 0)
    nextNodes = append(nextNodes, entryData[index].ConnectedTo...)
    j := 1
	for len(nextNodes) != 0 {
	    newNodes := make([]int, 0)
	    infectedNodes := make([]int, 0)
	    virus.Uniqueness = getVirusUniqueness(j)
	    for _, i := range nextNodes {
	        chanceToUpdate := getChanceForUpdate(entryData[i].Antivirus)
	        if chanceToUpdate {
	            entryData[i].Updated = 1
	        }
	        getsInfected(&entryData[i], virus)
	        if entryData[i].IsInfected {
	            infectedNodes = append(infectedNodes, i)
	            newNodes = append(newNodes, entryData[i].ConnectedTo...)
	        }
	    }
	    printInfectedNodes(j, infectedNodes)
	    nextNodes = newNodes
	    j++
	}
}
func printInfectedNodes(step int, ids []int){
    if len(ids) > 0 {
	        fmt.Print(step, ".krok - subnet ")
	        for _, i := range ids {
	            fmt.Print(i, ", ")
	        }
	        fmt.Print(" infikovan \n")
	    } else {
	        fmt.Println("V tomto kroku nebyl infikovan zadny subnet")
	    }
}
func main() {
	var virus = Virus{
		Uniqueness: getRandomNumber(),
	}
	goThroughNet(0, &virus)
}

virus

package main

import (
	"fmt"
	"math/rand"
	"time"
)

//Virus represents simplified data of virus
type Virus struct {
	Knowledge  float64 //Knowledge means number between 0 - 1, 0 - not known, 1 - very well known
	Uniqueness float64 // Uniqueness means number between 0 - 1, 0 - not unique, 1 - unique
}

//Subnet represents simplified data of each subnet
type Subnet struct {
	ID          int
	Antivirus   float64 //Antivirus means number between 0 - 1, 0 - not installed
	Updated     float64 //Updated means number between 0 - 1, 0 - not updated, 1 - updated regularly
	ConnectedTo []int   //ConnectedTo is an array of connected subnets
	IsInfected  bool
}

//Entrydata represents topology of networks
var entryData = []Subnet{
	{
		ID:          0,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{1, 2},
	}, {
		ID:          1,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{3, 4},
	}, {
		ID:          2,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{5, 6},
	}, {
		ID:          3,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          4,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          5,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	}, {
		ID:          6,
		Antivirus:   getRandomNumber(),
		Updated:     getRandomNumber(),
		ConnectedTo: []int{},
	},
}

var numberOfInfected = 0

//getRandomNumber returns random float in range 0-1
func getRandomNumber() float64 {
	s := rand.NewSource(time.Now().UnixNano())
  newRand := rand.New(s)
	return newRand.Float64()
}

//getsInfected returns if node will be infected or not
func getsInfected(node *Subnet, virus Virus) {
	nodeEndurance := node.Antivirus * node.Updated
	virusEndurance := (1 - virus.Knowledge) * virus.Uniqueness
	//if node endurance is lover than virus endurance, it means node is not protected enough and will be infected
	if nodeEndurance < virusEndurance {
		node.IsInfected = true
	}
}

func goThroughNet(index int, virus Virus) {
	node := &entryData[index]
	getsInfected(node, virus)
	if node.IsInfected {
		fmt.Println("Subnet ", node.ID, " gets infected.")
		numberOfInfected++

		for _, nextID := range node.ConnectedTo {
			goThroughNet(nextID, virus)
		}
	}
}
func main() {
	var virus = Virus{
		Knowledge:  0,
		Uniqueness: getRandomNumber(),
	}
	goThroughNet(0, virus)
	fmt.Println("Number of infected subnet: ", numberOfInfected)
}

Quiz-Musique

package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 100
 
   /* check the boolean condition */
   if( a == 10 ) {
      /* if condition is true then print the following */
      fmt.Printf("Value of a is 10\n" )
   } else if( a == 20 ) {
      /* if else if condition is true */
      fmt.Printf("Value of a is 20\n" )
   } else if( a == 30 ) {
      /* if else if condition is true  */
      fmt.Printf("Value of a is 30\n" )
   } else {
      /* if none of the conditions is true */
      fmt.Printf("None of the values is matching\n" )
   }
   fmt.Printf("Exact value of a is: %d\n", a )
}

goroutines-distribuida

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Response struct {
	Url string `json:"url"`
}

func Load(url string, c chan<- string) {

	// Load the URL
	resp, err := http.Get(url)

	// Check errors
	if err != nil {
		fmt.Println(fmt.Errorf("Error while getting data", err))
		return
	}

	// Connection will be closed when we exit the scope
	defer resp.Body.Close()

	// Parse JSON
	var d Response
	err = json.NewDecoder(resp.Body).Decode(&d)

	// Check errors
	if err != nil {
		fmt.Println(fmt.Errorf("Error while parsing JSON", err))
		return
	}

	// Extract response URL
	responseUrl := d.Url

	// Emit responseUrl
	c <- responseUrl
}

func main() {
	urls := []string{
		"https://httpbin.org/delay/6",
		"https://httpbin.org/delay/3",
		"https://httpbin.org/delay/1",
	}

	channel := make(chan string)

	for _, url := range urls {
	    fmt.Println(fmt.Sprintf("Launching %s", url))
		go Load(url, channel)
	}

	i := 0
	for resp := range channel {
		fmt.Println(resp)
		i++
		if i == 3 {
			break
		}
	}
}

Go String Length

package main

import "fmt"

func main() {
   var greeting =  "Hello world!"
   
   fmt.Printf("String Length is: ")
   fmt.Println(len(greeting))  
}

Go Returning Multiple Values

package main

import "fmt"

func swap(x, y string) (string, string) {
   return y, x
}
func main() {
   a, b := swap("Mahesh", "Kumar")
   fmt.Println(a, b)
}

Type Switch in Go

package main

import "fmt"

func main() {
   var x interface{}
     
   switch i := x.(type) {
      case nil:	  
         fmt.Printf("type of x :%T",i)                
      case int:	  
         fmt.Printf("x is int")                       
      case float64:
         fmt.Printf("x is float64")           
      case func(int) float64:
         fmt.Printf("x is func(int)")                      
      case bool, string:
         fmt.Printf("x is bool or string")       
      default:
         fmt.Printf("don't know the type")     
   }   
}

if else if else Statement

package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 100
 
   /* check the boolean condition */
   if( a == 10 ) {
      /* if condition is true then print the following */
      fmt.Printf("Value of a is 10\n" )
   } else if( a == 20 ) {
      /* if else if condition is true */
      fmt.Printf("Value of a is 20\n" )
   } else if( a == 30 ) {
      /* if else if condition is true  */
      fmt.Printf("Value of a is 30\n" )
   } else {
      /* if none of the conditions is true */
      fmt.Printf("None of the values is matching\n" )
   }
   fmt.Printf("Exact value of a is: %d\n", a )
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.