Exemplo n.º 1
0
func readPlaces() ([]node, int) {
	f, err := os.Open("agraph")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	var numNodes int
	if _, err := fmt.Fscanln(f, &numNodes); err != nil {
		panic(err)
	}

	nodes := make([]node, numNodes)
	for i := range nodes {
		nodes[i].neighbours = make([]route, 0, numNodes/2)
	}

	for {
		var node int32
		var r route

		switch _, err := fmt.Fscanln(f, &node, &r.to, &r.cost); {
		case err == io.EOF:
			return nodes, numNodes
		case err != nil:
			panic(err)
		}
		nodes[node].neighbours = append(nodes[node].neighbours, r)
	}
}
Exemplo n.º 2
0
func main() {
	in := bufio.NewReader(os.Stdin)

	var n int
	fmt.Fscanln(in, &n)

	cnt := 0
	val := 0

	for i := 0; i < n; i++ {
		var k int
		fmt.Fscanln(in, &k)

		if cnt == 0 {
			cnt = 1
			val = k
		} else if val == k {
			cnt++
		} else {
			cnt--
		}
	}

	fmt.Println(val)
}
Exemplo n.º 3
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)

	var n, q int
	fmt.Fscanln(bi, &n)

	sums := make([]int, n+1)

	sum := 0
	for i := 1; i <= n; i++ {
		var a int
		fmt.Fscanln(bi, &a)
		sum += a
		sums[i] = sum
	}

	fmt.Fscanln(bi, &q)
	for i := 0; i < q; i++ {
		var s, e int
		fmt.Fscanln(bi, &s, &e)
		fmt.Fprintln(bo, sums[e]-sums[s-1])
	}
	bo.Flush()
}
Exemplo n.º 4
0
func setflag(c io.ReadWriteCloser) {
	defer c.Close()

	var flag_id string
	fmt.Fprintln(c, "room_id: ")
	_, err := fmt.Fscanln(c, &flag_id)
	if err != nil {
		return
	}
	var cookie string
	fmt.Fprintln(c, "auth_token: ")
	_, err = fmt.Fscanln(c, &cookie)
	if err != nil {
		return
	}
	var flag string
	fmt.Fprintln(c, "flag: ")
	_, err = fmt.Fscanln(c, &flag)
	if err != nil {
		return
	}

	if db.Set(flag_id, []string{cookie, flag}) {
		fmt.Fprintln(c, "set_flag flag_set")
		log.Println("setflag: flag set")
	} else if cookie == db.Get(flag_id)[0] {
		db.Update(flag_id, []string{cookie, flag})
		fmt.Fprintln(c, "setflag: flag_updated")
		log.Println("setflag: flag updated")
	} else {
		fmt.Fprintln(c, "setflag: flag_update_auth_fail")
		log.Println("setflag: auth fail")
	}
}
Exemplo n.º 5
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)

	var n int
	fmt.Fscanln(bi, &n)

	ls := make(Lectures, n)

	for i := 0; i < n; i++ {
		fmt.Fscanln(bi, &ls[i].S, &ls[i].E)
	}

	sort.Sort(ls)

	res := 0
	min_time := 0

	for _, l := range ls {
		if l.S > min_time {
			min_time = l.E
			res++
		}
	}

	fmt.Fprintln(bo, res)
	bo.Flush()
}
Exemplo n.º 6
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)
	defer bo.Flush()

	var n, prev int
	fmt.Fscanln(bi, &n)

	best_n := 1
	var best_d int64

	fmt.Fscanln(bi, &prev)
	for i := 1; i < n; i++ {
		var v int
		fmt.Fscanln(bi, &v)
		d := abs(int64(v) - int64(prev))

		if d >= best_d {
			best_n = i
			best_d = d
		}

		prev = v
	}

	fmt.Fprintln(bo, best_n, best_n+1)
}
Exemplo n.º 7
0
func getflag(c io.ReadWriteCloser) {
	defer c.Close()
	var flag_id string
	fmt.Fprintln(c, "flag_id: ")
	_, err := fmt.Fscanln(c, &flag_id)
	if err != nil {
		return
	}
	var cookie string
	fmt.Fprintln(c, "token_id: ")
	_, err = fmt.Fscanln(c, &cookie)
	if err != nil {
		return
	}
	entry := db.Get(flag_id)
	if entry == nil {
		fmt.Fprintln(c, "flagval: no_entry_exists")
		log.Println("getflag: request for non-existant entry")
	} else if cookie == entry[0] {
		fmt.Fprintln(c, "flagval:", entry[1])
		log.Println("getflag: got")
	} else {
		fmt.Fprintln(c, "flagval: getflag_auth_fail")
		log.Println("getflag: auth fail")
	}
	return
}
Exemplo n.º 8
0
func passDetails(
	binary_path string,
	begin_time time.Time,
	duration time.Duration,
	latitude_degrees,
	longitude_degrees,
	elevation_metres float64,
	tle string,
	resolution_seconds float64) ([]SatPoint, error) {

	begin_timestamp := 1e-9 * float64(begin_time.UnixNano())

	c := exec.Command("python", binary_path)
	in_pipe, err := c.StdinPipe()
	if err != nil {
		return nil, err
	}
	defer in_pipe.Close()
	out_pipe, err := c.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer out_pipe.Close()
	if err := c.Start(); err != nil {
		return nil, err
	}
	defer c.Wait()

	fmt.Fprintf(in_pipe, "%f\n%f\n%f\n%f\n%f\n%s\n%f\n",
		begin_timestamp,
		duration.Seconds(),
		latitude_degrees,
		longitude_degrees,
		elevation_metres,
		tle,
		resolution_seconds)
	in_pipe.Close()

	var n int
	_, err = fmt.Fscanln(out_pipe, &n)
	if err != nil {
		return nil, err
	}

	r := make([]SatPoint, n)
	for i := 0; i < n; i++ {
		p := &r[i]
		fmt.Fscanln(out_pipe,
			&p.Timestamp,
			&p.AzimuthDegrees,
			&p.AltitudeDegrees,
			&p.Range,
			&p.RangeVelocity,
			&p.LatitudeDegrees,
			&p.LongitudeDegrees,
			&p.Elevation,
			&p.IsEclipsed)
	}
	return r, nil
}
Exemplo n.º 9
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)
	defer bo.Flush()

	var n int
	fmt.Fscanln(bi, &n)

	a := make([]int, n)

	for i := range a {
		fmt.Fscanln(bi, &a[i])
	}

	sort.Ints(a)

	bi.ReadBytes('\n')

	var k int
	fmt.Fscanln(bi, &k)

	for i := 0; i < k; i++ {
		var v int
		fmt.Fscanln(bi, &v)
		fmt.Fprintln(bo, a[v-1])
	}
}
Exemplo n.º 10
0
func predict(
	predict_binary_path string,
	begin_time time.Time,
	duration time.Duration,
	latitude_degrees,
	longitude_degrees,
	elevation_metres,
	min_altitude_degrees,
	min_azimuth_degrees,
	max_azimuth_degrees float64,
	tle string) ([]Prediction, error) {

	begin_timestamp := 1e-9 * float64(begin_time.UnixNano())

	c := exec.Command("python", predict_binary_path)
	in_pipe, err := c.StdinPipe()
	if err != nil {
		return nil, err
	}
	defer in_pipe.Close()
	out_pipe, err := c.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer out_pipe.Close()
	if err := c.Start(); err != nil {
		return nil, err
	}
	defer c.Wait()

	fmt.Fprintf(in_pipe, "%f\n%f\n%f\n%f\n%f\n%f\n%f\n%f\n%s\n",
		begin_timestamp,
		duration.Seconds(),
		latitude_degrees,
		longitude_degrees,
		elevation_metres,
		min_altitude_degrees,
		min_azimuth_degrees,
		max_azimuth_degrees,
		tle)
	in_pipe.Close()

	var n int
	_, err = fmt.Fscanln(out_pipe, &n)
	if err != nil {
		return nil, err
	}

	r := make([]Prediction, n)
	for i := 0; i < n; i++ {
		p := &r[i]
		fmt.Fscanln(out_pipe,
			&p.StartTimestamp,
			&p.EndTimestamp,
			&p.StartAzimuthDegrees,
			&p.EndAzimuthDegrees,
			&p.MaxAltitudeDegrees)
	}
	return r, nil
}
Exemplo n.º 11
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)
	defer bo.Flush()

	const SIZE = 350000 // 15916 primes

	is_p := make([]bool, SIZE)
	for i := 0; i < SIZE; i++ {
		is_p[i] = true
	}
	is_p[0] = false
	is_p[1] = false

	ps := make([]int, 0)

	for i := 2; i <= SIZE/2; i++ {
		if is_p[i] {
			for v := i * 2; v < SIZE; v += i {
				is_p[v] = false
			}
			ps = append(ps, i)
		}
	}

	var n int
	fmt.Fscanln(bi, &n)

	for i := 0; i < n; i++ {
		var j int
		fmt.Fscanln(bi, &j)
		fmt.Fprintln(bo, ps[j-1])
	}
}
Exemplo n.º 12
0
Arquivo: config.go Projeto: lopaka/rsc
// CreateConfig creates a configuration file and saves it to the file at the given path.
func CreateConfig(path string) error {
	config, _ := LoadConfig(path)
	var emailDef, passwordDef, accountDef, hostDef string
	if config != nil {
		yn := PromptConfirmation("Found existing configuration file %v, overwrite? (y/N): ", path)
		if yn != "y" {
			PrintSuccess("Exiting")
			return nil
		}
		emailDef = fmt.Sprintf(" (%v)", config.Email)
		accountDef = fmt.Sprintf(" (%v)", config.Account)
		passwordDef = " (leave blank to leave unchanged)"
		if config.LoginHost == "" {
			config.LoginHost = "my.rightscale.com"
		}
		hostDef = fmt.Sprintf(" (%v)", config.LoginHost)
	} else {
		config = &ClientConfig{}
	}

	fmt.Fprintf(out, "Account id%v: ", accountDef)
	var newAccount string
	fmt.Fscanln(in, &newAccount)
	if newAccount != "" {
		a, err := strconv.Atoi(newAccount)
		if err != nil {
			return fmt.Errorf("Account ID must be an integer, got '%s'.", newAccount)
		}
		config.Account = a
	}

	fmt.Fprintf(out, "Login email%v: ", emailDef)
	var newEmail string
	fmt.Fscanln(in, &newEmail)
	if newEmail != "" {
		config.Email = newEmail
	}

	fmt.Fprintf(out, "Login password%v: ", passwordDef)
	var newPassword string
	fmt.Fscanln(in, &newPassword)
	if newPassword != "" {
		config.Password = newPassword
	}

	fmt.Fprintf(out, "API Login host%v: ", hostDef)
	var newLoginHost string
	fmt.Fscanln(in, &newLoginHost)
	if newLoginHost != "" {
		config.LoginHost = newLoginHost
	}

	err := config.Save(path)
	if err != nil {
		return fmt.Errorf("Failed to save config: %s", err)
	}

	return nil
}
Exemplo n.º 13
0
func load(stdin io.Reader) {
	var n int
	fmt.Fscanln(stdin, &n)
	var s string
	fmt.Fscanln(stdin, &s)
	s = s[0:n] // just in case string is overlong
	var k int
	fmt.Fscan(stdin, &k)
	fmt.Println(solve(s, k))
}
Exemplo n.º 14
0
func main() {
	if len(os.Args) < 2 {
		fmt.Println("Arquivo de entrada não encontrado")
		os.Exit(1)
	}

	file, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Println("Falha de leitura")
		os.Exit(1)
	}

	var input string
	_, err = fmt.Fscanln(file, &input)
	if err != nil {
		fmt.Println("Arquivo Vazio")
		fmt.Println(err.Error())
		os.Exit(1)
	}
	start := time.Now()
	for true {
		read, err := fmt.Fscanln(file, &input)
		values := strings.Split(input, ",")
		if read == 0 || err != nil {
			break
		}

		if len(values) != 4 {
			fmt.Println("Inputs errados")
			fmt.Println(values)
			os.Exit(1)
		}
		politica, ok := policies.Politicas[values[1]]
		seed, err := strconv.Atoi(values[3])
		if !ok {
			if values[1] == "reinforcement_learning" {
				rand.Seed(int64(seed))
				policies.TrainReinf()
				politica = policies.Politicas["reinforcement_learning"]
			} else {
				fmt.Println("Política Invalida")
				os.Exit(1)
			}

		}
		games, err := strconv.Atoi(values[0])
		pieces, err := strconv.Atoi(values[2])

		fmt.Println(tetris.Play_series(int64(seed), pieces, games, politica))
	}
	elapsed := time.Since(start)
	fmt.Println("Everything took", elapsed)
	os.Exit(0)
}
Exemplo n.º 15
0
func load(stdin io.Reader) {
	var n int
	fmt.Fscanln(stdin, &n)
	M := make([][]int, n)
	for y := 0; y < len(M); y++ {
		M[y] = make([]int, n)
		s := make([]byte, n)
		fmt.Fscanln(stdin, &s)
		for x := 0; x < len(M[y]); x++ {
			M[y][x] = int(s[x] - '0')
		}
	}
	solve(M)
}
Exemplo n.º 16
0
func getArgs(r io.Reader) []string {
	numArgs := 0
	_, err := fmt.Fscanln(r, &numArgs)

	timeArgs := []string{}
	for {
		timeArg := ""
		_, err = fmt.Fscanln(r, &timeArg)
		if err == io.EOF {
			break
		}
		timeArgs = append(timeArgs, timeArg)
	}
	return timeArgs
}
Exemplo n.º 17
0
func main() {
	in, _ := os.Open("10033.in")
	defer in.Close()
	out, _ := os.Create("10033.out")
	defer out.Close()

	var kase int
	var line string
	first := true
	fmt.Fscanf(in, "%d", &kase)
	for kase > 0 {
		if first {
			fmt.Fscanln(in)
			first = false
		} else {
			fmt.Fprintln(out)
		}
		var lines []string
		for {
			if _, err := fmt.Fscanf(in, "%s", &line); err != nil {
				break
			}
			lines = append(lines, line)
		}
		fmt.Fprintln(out, solve(lines))
		kase--
	}
}
Exemplo n.º 18
0
func main() {
	var num1 int
	var num2 float32
	var s string

	file1, _ := os.Open("hello1.txt")          // hello1.txt 파일 열기
	defer file1.Close()                        // main 함수가 끝나기 직전에 파일을 닫음
	n, _ := fmt.Fscan(file1, &num1, &num2, &s) // 파일을 읽은 뒤 공백, 개행 문자로
	// 구분된 문자열에서 입력을 받음
	fmt.Println("입력 개수:", n)   // 입력 개수: 3
	fmt.Println(num1, num2, s) // 1 1.1 Hello

	file2, _ := os.Open("hello2.txt")    // hello2.txt 파일 열기
	defer file2.Close()                  // main 함수가 끝나기 직전에 파일을 닫음
	fmt.Fscanln(file2, &num1, &num2, &s) // 파일을 읽은 뒤 공백으로
	// 구분된 문자열에서 입력을 받음
	fmt.Println("입력 개수:", n)   // 입력 개수: 3
	fmt.Println(num1, num2, s) // 1 1.1 Hello

	file3, _ := os.Open("hello3.txt")               // hello3.txt 파일 열기
	defer file3.Close()                             // main 함수가 끝나기 직전에 파일을 닫음
	fmt.Fscanf(file3, "%d,%f,%s", &num1, &num2, &s) // 파일을 읽은 뒤 문자열에서
	// 형식을 지정하여 입력을 받음
	fmt.Println("입력 개수:", n)   // 입력 개수: 3
	fmt.Println(num1, num2, s) // 1 1.1 Hello
}
Exemplo n.º 19
0
func main() {
	in, _ := os.Open("414.in")
	defer in.Close()
	out, _ := os.Create("414.out")
	defer out.Close()

	var n int
	var ch byte
	for {
		if fmt.Fscanf(in, "%d", &n); n == 0 {
			break
		}
		nums := make([]int, n)
		max := 0
		for n > 0 {
			num := 0
			for i := 1; i <= 25; i++ {
				if fmt.Fscanf(in, "%c", &ch); ch == 'X' {
					num++
				}
			}
			fmt.Fscanln(in)
			if num > max {
				max = num
			}
			nums[n-1] = num
			n--
		}
		total := 0
		for _, v := range nums {
			total += max - v
		}
		fmt.Fprintln(out, total)
	}
}
Exemplo n.º 20
0
func run(r io.Reader, w io.Writer) {
	var start, end int
	fmt.Fscanln(r, &start)
	fmt.Fscanln(r, &end)
	maxValue := 0
	for i := start; i < end; i++ {
		for j := i + 1; j <= end; j++ {
			v := i ^ j
			if maxValue < v {
				maxValue = v
			}
		}
	}

	fmt.Fprintln(w, maxValue)
}
Exemplo n.º 21
0
// There must be a better way if we call this a lot..
func meminfo() (total, free, buffers, cached ByteSize) {
	fd, err := os.Open("/proc/meminfo")
	defer fd.Close()
	if err != nil {
		panic(err)
	}

	mapping := map[string]*ByteSize{
		"MemTotal": &total,
		"MemFree":  &free,
		"Buffers":  &buffers,
		"Cached":   &cached,
	}

	var name, unit string
	var value int64

	for {
		n, err := fmt.Fscanln(fd, &name, &value, &unit)
		if err == io.EOF {
			break
		}
		if n < 2 {
			continue
		}
		what, present := mapping[name[:len(name)-1]]
		if present {
			*what = ByteSize(value) * kiB
		}
	}

	return
}
Exemplo n.º 22
0
func main() {
	in, _ := os.Open("455.in")
	defer in.Close()
	out, _ := os.Create("455.out")
	defer out.Close()

	var n int
	var line string
	first := true
	fmt.Fscanf(in, "%d", &n)
	for n > 0 {
		n--
		if first {
			first = false
		} else {
			fmt.Fprintln(out)
		}
		fmt.Fscanln(in)
		fmt.Fscanf(in, "%s", &line)
		ks := factors(len(line))
		for _, k := range ks {
			if periodic(line, k) {
				fmt.Fprintln(out, k)
				break
			}
		}
	}
}
Exemplo n.º 23
0
func ParseListCap(r io.Reader, urlStr string, capHint int) (p *PatchList, err error) {
	url, err := url.Parse(urlStr)
	if err != nil {
		return
	}
	p = &PatchList{URL: url, Entries: make([]PatchEntry, 0, capHint)}

	for err != io.EOF {
		var filename, hash string
		var filesize int64
		var n int
		n, err = fmt.Fscanln(r, &filename, &filesize, &hash)

		if err != nil || n != 3 {
			continue
		}

		var filehash []uint8
		n, err := fmt.Sscanf(hash, "%x", &filehash)
		if err != nil || n != 1 || len(filehash) != 0x10 {
			continue
		}

		e := PatchEntry{PatchList: p, Path: filename, Size: filesize}
		copy(e.MD5[:], filehash)

		p.Entries = append(p.Entries, e)
	}

	err = nil

	p.fillMap()

	return
}
Exemplo n.º 24
0
Arquivo: vm.go Projeto: JamesLinus/pl0
// Execute implements Instruction.
func (n *Read) Execute(m *VM) {
	fmt.Fprintf(m.Stdout, "?")
	var val int
	fmt.Fscanln(m.Stdin, &val)
	fp := m.fp(n.Frames)
	m.write(fp+n.Index, val)
}
Exemplo n.º 25
0
func (s *FMMSegment) InitDictionary(filename string) {
	s.dict = make(map[string]string)

	fmt.Printf("Load file: %s\n", filename)
	file, err := os.Open(filename)
	defer file.Close()
	if err != nil {
		fmt.Printf("Fail to load: \"%s\" \n", filename)
	}

	reader := bufio.NewReader(file)
	var text string
	var maxLen int
	for {
		size, _ := fmt.Fscanln(reader, &text)
		if size == 0 {
			break
		} else {
			if _, ok := s.dict[text]; !ok {
				s.dict[text] = text
				if maxLen < len(text) {
					maxLen = len(text)
				}
			}
		}

	}

	s.maxWordLen = maxLen
}
Exemplo n.º 26
0
// Load the model generated by the original word2vec.
func Load(filename string) (*Model, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	reader := bufio.NewReader(file)
	var vocabSize, layer1Size int
	fmt.Fscanln(reader, &vocabSize, &layer1Size)
	var word string
	model := &Model{
		Layer1Size: layer1Size,
		Vocab:      make(map[string]int),
		data:       make([]float32, layer1Size*vocabSize),
	}
	for i := 0; i < vocabSize; i++ {
		var vector = model.Vector(i)
		bytes, err := reader.ReadBytes(' ')
		if err != nil {
			return nil, err
		}
		word = string(bytes[:len(bytes)-1])
		err = binary.Read(reader, binary.LittleEndian, vector)
		if err != nil {
			return nil, err
		}
		vector.Normalize()
		reader.ReadByte()

		model.Vocab[word] = i
	}
	return model, nil
}
Exemplo n.º 27
0
func OpenHashTable(path string) (*HashTable, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}

	stat, err := os.Stat(path)
	if err != nil {
		return nil, err
	}

	var line string
	_, err = fmt.Fscanln(file, &line)
	if err != nil {
		return nil, err
	}

	_, err = file.Seek(0, 0)
	if err != nil {
		return nil, err
	}

	recordSize := len(line) + 1

	count := stat.Size() / int64(recordSize)

	table := &HashTable{
		Count:      count,
		RecordSize: recordSize,
		File:       file,
	}

	return table, nil
}
Exemplo n.º 28
0
func (cf *config) startAuthHelper(cmd string) error {
	c := exec.Command(cmd)
	in, err := c.StdinPipe()
	if err != nil {
		return err
	}
	out, err := c.StdoutPipe()
	if err != nil {
		return err
	}
	err = c.Start()
	if err != nil {
		return err
	}

	var m sync.Mutex
	cf.Authenticators = append(cf.Authenticators, func(user, password string) bool {
		m.Lock()
		defer m.Unlock()
		fmt.Fprintln(in, user, password)
		var response string
		fmt.Fscanln(out, &response)
		if response == "OK" {
			return true
		}
		return false
	})

	return nil
}
Exemplo n.º 29
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)

	var n int
	fmt.Fscanln(bi, &n)

	w := true

	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(bi, &a)
		if a/2%2 == 0 {
			w = !w
		}
	}

	if w {
		fmt.Fprintln(bo, "Daenerys")
	} else {
		fmt.Fprintln(bo, "Stannis")
	}

	bo.Flush()
}
Exemplo n.º 30
0
func (t *unixTransport) Auth() error {
	cred := syscall.UnixCredentials(&syscall.Ucred{
		Pid: int32(os.Getpid()),
		Uid: uint32(os.Getuid()),
		Gid: uint32(os.Getgid()),
	})
	_, _, err := t.WriteMsgUnix([]byte{0}, cred, nil)
	if err != nil {
		return err
	}

	if _, err := fmt.Fprintf(t, "AUTH EXTERNAL %x\r\n", fmt.Sprintf("%d", os.Getuid())); err != nil {
		return err
	}

	var code, cookie string
	if _, err := fmt.Fscanln(t, &code, &cookie); err != nil {
		return err
	}

	fmt.Println(code, cookie)

	if _, err := fmt.Fprintf(t, "BEGIN\r\n"); err != nil {
		return err
	}
	return nil
}