カテゴリー
Scala

小学生向け、簡単計算問題

import scala.util.control.Breaks

object Main {
  def main(args: Array[String]): Unit = {
    val b1 = new Breaks

    val msg: java.util.Hashtable[String, String] = new java.util.Hashtable[String, String]
    msg.put("monument", "2つの数字は")
    msg.put("answer", "答えは? ")
    msg.put("good", " 正解!\n\n")
    msg.put("no", " 残念!\n\n")
    msg.put("cond", "%d と %d の、")

    val jk: Array[Jyouken] = new Array[Jyouken](4)
    jk(0) = new Jyouken("+", 1, 1)
    jk(1) = new Jyouken("-", 1, 1)
    jk(2) = new Jyouken("*", 1, 1)
    jk(3) = new Jyouken("/", 1, 1)
    val kekka = Array(0,0)

    b1.breakable {
      while (true) {
        for (i <- 1 to 8) {
          val env: Env = new Env(msg, jk((i - 1) / 2), kekka)
          env.read.eval.print
          if (kekka(1) >= 3) b1.break()
        }
        printf("レベルアップします!\n\n")
        jk.foreach(x => x.levelup)
      }
    }
    printf("正解数 %5d, 誤回答 %5d", kekka(0), kekka(1))
  }
}
import java.util
import java.util.{Random, Scanner}

class Env(var msg:util.Hashtable[String, String],val jk:Jyouken, var kekka:Array[Int]){
  private val scanner = new Scanner(System.in)
  private var x :Int = 0
  private var y :Int = 0
  private var z :Int = 0
  private var rVal: Boolean = false

  def read: Env = {
    val w1 = jk.getitibanme * 10
    val w2 = jk.getnibanme * 10
    val keisan =
      jk.en match {
        case "+" => "足し算 "
        case "-" => "引き算 "
        case "*" => "掛け算 "
        case "/" => "割り算 "
      }
    printf("%s", keisan)
    printf(this.msg.get("monument"))
    val rnd2: Random = new Random()
    y = rnd2.nextInt(w2)
    val rnd: Random = new Random
    x = rnd.nextInt(w1)
    if (jk.en == "/"){
      if (x == 0 || y == 0) {
        x += 1; y += 1
      }
    }

    if (jk.en == "-" || jk.en == "/"){
      if (y > x){
        val work = x; x = y; y = work
      }
    }
    printf("%3d, %3d の", x, y)
    this
  }

  def eval: Env = {
    printf(this.msg.get("answer"))
    z = scanner.nextInt()
    rVal =
      jk.en match {
        case "+" => if (z == x + y) true else false
        case "-" => if (z == x - y) true else false
        case "*" => if (z == x * y) true else false
        case "/" => if (z == x / y) true else false
      }
    this
  }

  def print:Env = {
    printf(this.msg.get("cond"), x, y)
    val siki =
      jk.en match {
        case "+" => "和は"
        case "-" => "差は"
        case "*" => "積は"
        case "/" => "商は"
      }
    printf("%s %3d", siki, z)

    if (rVal) {
      printf(this.msg.get("good"))
      kekka(0) += 1
    } else {
      printf(this.msg.get("no"))
      kekka(1) += 1
    }
    this
  }
}
class Jyouken(val en:String, val iti: Int, val ni: Int){
  private val enzan: String = en
  private var itibanme: Int = iti
  private var nibanme: Int = ni

  def levelup: Jyouken = {
    if (enzan == "+" || enzan == "-" || enzan == "/") {
      itibanme += 1; nibanme += 1
    } else {
      itibanme += 1; nibanme = 1
    }
    this
  }
  def getitibanme: Int = itibanme
  def getnibanme: Int = nibanme
}
カテゴリー
Visual Basic

「三山崩しゲーム」VB版

Module Program
    Sub Main(args As String())
        Dim a(4), i, j, k, imax, nn As Integer
        Dim my_flag As Boolean
        Dim dmyss As String

        For i = 1 To 3
            Console.Write(i & "番目の石の数? ")
            dmyss = Console.ReadLine()
            a(i) = Int(dmyss)
            If a(i) <= 0 Then End
        Next

        my_flag = True
        While True
            Console.WriteLine()
            Console.WriteLine(String.Format("現在の石 {0}, {1}, {2}", a(1), a(2), a(3)))

            imax = 1
            For i = 2 To 3
                If a(imax) < a(i) Then
                    imax = i
                End If
            Next
            If a(imax) = 0 Then Exit While

            If my_flag = True Then
                For i = 1 To 3
                    j = i + 1
                    If j > 3 Then j -= 3
                    k = i + 2
                    If k > 3 Then k -= 3
                    If a(i) > (a(j) Xor a(k)) Then
                        nn = a(j) Xor a(k)
                        Exit For
                    End If
                Next
                If i = 4 Then
                    i = imax
                    nn = a(imax) - 1
                End If
                Console.WriteLine("コンピュータ: {0}の山から{1}個取りました。", i, a(i) - nn)
                a(i) = nn

            Else
                Do
                    Console.Write("何番目の山から取りますか(1-3)? ")
                    dmyss = Console.ReadLine()
                    i = Int(dmyss)
                Loop While (i < 1 Or 3 < i Or a(i) = 0)
                Do
                    Console.Write("何個取りますか? ")
                    dmyss = Console.ReadLine()
                    nn = Int(dmyss)
                Loop While (nn <= 0 Or a(i) < nn)
                a(i) -= nn
            End If

            my_flag = Not my_flag

        End While

        If my_flag = True Then
            Console.WriteLine("--- あなたの勝ち ---")
        Else
            Console.WriteLine("--- コンピュータの勝ち ---")
        End If
        'Console.WriteLine("Hello World!")
    End Sub
End Module
カテゴリー
Scala

「三山崩しゲーム」

下はMain.scalaです。ハイライターがScala無かったので、JavaScriptになってます。

import java.util.Random

object Main {
  def main(args: Array[String]): Unit = {
    val msg: java.util.Hashtable[String, String] = new java.util.Hashtable[String, String]
    //val msg = collection.mutable.HashMap.empty[String, String]
    //msg.put("yama","山は")
    msg.put("you", "あなた")
    msg.put("comp", "コンピュータ")
    msg.put("took", "%sが,山 %d から%d個取った\n")
    msg.put("take", "石を取って!(1〜%d) > ")
    msg.put("cond", "現在の石の数: %d, %d, %d\n\n")
    msg.put("win", "%sの勝ち\n")
    val rnd: Random = new Random
    val bVal: Boolean = rnd.nextBoolean
    val env: Env = new Env(Array[Int](2, 4, 5), bVal, msg)
    env.print
    System.out.printf("%sが先攻\n", if (bVal) {
      msg.get("you")
    }
    else {
      msg.get("comp")
    })
    while (env.num(0) > 0 || env.num(1) > 0 || env.num(2) > 0) {
      env.read
      env.eval
      env.print
    }
    System.out.printf(msg.get("win"), if (env.turn) {
      msg.get("you")
    }
    else {
      msg.get("comp")
    })
  }
}

下はEnv.scalaですが、やはりJavaScriptになってます。

import java.util
import java.util.{Random, Scanner}
import scala.util.control.Breaks

class Env(var num: Array[Int], var turn: Boolean, var msg:util.Hashtable[String, String]) {
  this.msg = msg
  private val scanner = new Scanner(System.in)
  private var x: Int = -1
  private var y: Int = -1

  def read: Env = {
    val b1 = new Breaks
    if (!this.turn) {
      this
    } else {
      b1.breakable {
        while (true) {
          System.out.printf("山は?(1~3) > ")
          this.y = scanner.nextInt() - 1
          System.out.printf(this.msg.get("take"), if (this.num(this.y) > 3) 3
          else this.num(this.y))
          this.x = scanner.nextInt
          if (this.x > 0 && this.x <= this.num(this.y))
             b1.break()
        }
      }
      this
    }
  }

  def eval: Env = {
    val b1 = new Breaks
    if (!this.turn) {
      b1.breakable {
        while (true) {
          val rnd2: Random =new Random()
          this.y = rnd2.nextInt(3)
          val rnd: Random = new Random
          this.x = rnd.nextInt(3) + 1
          if (this.x <= this.num(this.y))
            b1.break()
        }
      }
    }
    this.num(this.y) -= this.x
    this.turn = !this.turn
    this
  }

  def print: Env = {
    if (this.turn && !(this.y == -1)) System.out.printf(this.msg.get("took"), this.msg.get("comp"), this.y + 1, this.x)
    System.out.printf(this.msg.get("cond"), this.num(0),this.num(1), this.num(2))
    this
  }
}
カテゴリー
F#

F#Pipelines

module Tour10_BPipelines
/// Square the odd values of the input and add one, using F# pipe operators.
let squareAndAddOdd values =
    values
    |> List.filter (fun x -> x % 2 <> 0)
    |> List.map (fun x -> x * x + 1)

let numbers = [ 1; 2; 3; 4; 5 ]

let result = squareAndAddOdd numbers
printfn $"{result}"

let function1 x = x + 1
let ans = function1 100
let res = 100 |> function1 |> function1
printfn $"{res}"
カテゴリー
Visual Basic

BinaryTreeを基本からやってみる。VBで。

Public Class Node

    Public Property LeftNode As Node = Nothing
    Dim a As Node = _LeftNode

    Public Property RightNode As Node = Nothing
    Dim b As Node = _RightNode

    Public Property Value As Int32 = 0
    Dim c As Int32 = _Value

    Public Sub New(ByVal value As Int32)
        '-- new nodes don't have children yet, just a value
        _LeftNode = Nothing
        _RightNode = Nothing
        _Value = value

    End Sub
    Public Sub insert(data As Node)
        If data.Value <> 0 Then
            If data.Value < _Value Then
                If _LeftNode Is Nothing Then
                    _LeftNode = data
                Else
                    _LeftNode.insert(data)

                End If
            ElseIf data.Value > _Value Then
                If _RightNode Is Nothing Then
                    _RightNode = data
                Else
                    _RightNode.insert(data)
                End If
            End If
        Else
            _Value = data.Value
        End If

    End Sub
    Public Sub PrintTree()
        If Not (_LeftNode Is Nothing) Then
            _LeftNode.PrintTree()
        End If

        Console.WriteLine(_Value)

        If Not (_RightNode Is Nothing) Then
            _RightNode.PrintTree()
        End If
    End Sub

Imports System
Module Program
    Public Function Change2Node(ByVal v) As Node
        Dim w As Node = New Node(v)
        Return w
    End Function

    Sub Main(args As String())
        Dim root As Node = New Node(10)

        root.insert(Change2Node(6))
        root.insert(Change2Node(14))
        root.insert(Change2Node(3))
        root.PrintTree()
        Console.ReadLine()
    End Sub
End Module
カテゴリー
Visual Basic

VBによるBinaryTree、ネットから拾いました。

Public Class Node

 

    Private _leftNode As Node = Nothing

    Private _rightNode As Node = Nothing

 

    Private _lValue As Int32 = 0

 

    Public Property LeftNode As Node

        Get

            Return _leftNode

        End Get

        Set(value As Node)

            _leftNode = value

        End Set

    End Property

 

    Public Property RightNode As Node

        Get

            Return _rightNode

        End Get

        Set(value As Node)

            _rightNode = value

        End Set

    End Property

 

    Public Property Value As Int32

        Get

            Return _lValue

        End Get

        Set(value As Int32)

            _lValue = value

        End Set

    End Property

 

    Public Sub New(ByVal value As Int32)

'-- new nodes don't have children yet, just a value

        _leftNode = Nothing

        _rightNode = Nothing

        _lValue = value

    End Sub

 

End Class


Public Class BinTree

    Private _root As Node = Nothing '-- tree has to have a root.ツリーにはルートが必要です



    Public Sub New(ByVal value As Int32)

        _root = New Node(value)  '-- create our nodeノードを作成します

        Console.WriteLine(String.Format("Root Inserting: {0}", value)) '-- output what we have done.行ったことを出力します

    End Sub



    '-- Inserting takes two nodes.  The current node we want to do the insert on, and a next node for the loop.
    '--挿入には2つのノードが必要です。挿入を実行する現在のノードと、ループの次のノード

    Public Sub InsertNode(ByVal input As Int32)

            Dim currentNode As Node = _root

            Dim nextNode As Node = _root



        '-- loop through all the nodes left to right based on our rule of greater than/less than.
        '--より大きい/より小さいというルールに基づいて、すべてのノードを左から右にループします

        '--  When we find a node who doesn't have any more children we know we have found spot to insert! 
        '--子がもうないノードを見つけると、挿入する場所が見つかりました。

        '-- (because we have been filtered down here by our rules to this point)
        '--(これまでのルールによってここでフィルタリングされているため)

        '-- Side note - this could probably be done recursively but doing EVERYTHING recursively might be boring.
        '--補足-これはおそらく再帰的に実行できますが、すべてを再帰的に実行するのは退屈かもしれません。

        While currentNode.Value <> input AndAlso nextNode IsNot Nothing

                currentNode = nextNode

                If nextNode.Value < input Then

                    nextNode = nextNode.RightNode

                Else

                    nextNode = nextNode.LeftNode

                End If

            End While



        '-- Once we find our node with no children that follow our rules check our rules one last time to figure out
        '--ルールに従っている子がないノードを見つけたら、最後にもう一度ルールをチェックして把握します

        '-- which side to tack on our node. 
        '--どちら側をノードにタックするか。

        '-- Oh, and no duplicates!  They screw up the order of things!
        '--ああ、重複はありません!彼らは物事の順序を台無しにします!

        If currentNode.Value = input Then

                Console.WriteLine("Can't insert duplicates!")

            ElseIf currentNode.Value < input Then

                currentNode.RightNode = New Node(input)

                Console.WriteLine(String.Format("Inserting: {0}", input))

            Else

                currentNode.LeftNode = New Node(input)

                Console.WriteLine(String.Format("Inserting: {0}", input))

            End If

        End Sub



    '-- Printing is loads of recursive fun.  I have two basic types here: Inorder and PreOrder.
    '--印刷は再帰的な楽しみの山です。ここには、InorderとPreOrderの2つの基本的なタイプがあります。

    Public Sub Print(ByVal doInOrder As Boolean)

            If doInOrder Then

                InOrder(_root)

            Else

                PreOrder(_root, 0, "")

            End If

        End Sub



    '-- InOrder follows a depth first run.  check left, print, check right.
    '--InOrderは、深さ優先実行に従います。左をチェックし、印刷し、右をチェックします。

    '-- It attempts to find a right node.  If found it goes to the right node and then searches all the left nodes, prints, and goes to the right node.
    '--適切なノードを見つけようとします。見つかった場合は、右側のノードに移動し、次に左側のすべてのノードを検索して印刷し、右側のノードに移動します。

    '-- The joys of recursion are over floweth here.
    '--再帰の喜びはここに溢れています

    Private Sub InOrder(ByVal myNode As Node)

            If myNode.LeftNode IsNot Nothing Then InOrder(myNode.LeftNode)

            Console.WriteLine(myNode.Value)

            If myNode.RightNode IsNot Nothing Then InOrder(myNode.RightNode)

        End Sub





    '-- PreOrder I decided to take some liberties and make it pretty.  I added a hyphen to signify the level, and
    '--事前注文私はいくつかの自由を取り、それをきれいにすることにしました。レベルを示すためにハイフンを追加し、

    '-- also visual indicators on which node (left or right) the value is from. 
    '--また、値がどのノード(左または右)からのものであるかを視覚的に示します。

    '-- The idea here is we print which node we are on, check left, check right.
    '--ここでの考え方は、現在のノードを印刷し、左をチェックし、右をチェックすることです。

    '--

    '-- The level As Int32 is only needed for printing the hyphen.. you can remove it and it still works (sans printing hyphens).
    '--レベルAsInt32は、ハイフンを印刷するためにのみ必要です。それを削除しても、引き続き機能します(ハイフンの印刷はありません)。

    Private Sub PreOrder(ByVal myNode As Node, ByVal level As Int32, ByVal side As String)

            Dim sVal As String = String.Empty



            For i As Int32 = 0 To level - 1

                sVal += "-"

            Next

        '-- Actual meat of the method.  '--メソッドの実際の肉。

        Console.WriteLine(String.Format("{0}{1} {2}", sVal, side, myNode.Value))

            If myNode.LeftNode IsNot Nothing Then PreOrder(myNode.LeftNode, level + 1, "L")

            If myNode.RightNode IsNot Nothing Then PreOrder(myNode.RightNode, level + 1, "R")

        End Sub



    '-- Here we will take in a value and attempt to find the path to that value. 
    '--ここでは、値を取り込んで、その値へのパスを見つけようとします。

    Public Sub FindPathToNode(ByVal input As Int32)

            Console.WriteLine(String.Format("Finding value: {0}", input))

        Dim path As New List(Of Int32) '-- instead of printing the path we will have it saved to a list. '--パスを印刷する代わりに、リストに保存します。

        Dim bFound As Boolean = False '-- helps us determine if was found or not. '--見つかったかどうかを判断するのに役立ちます。

        Dim sPath As String = String.Empty



        '-- basic check to make sure the root wasn't it!
        '--ルートがそれではなかったことを確認するための基本的なチェック!
        If _root.Value = input Then

                Console.WriteLine("root is input!")

            Else

            '-- Dive into the recursion.    '--再帰に飛び込みます。

            bFound = PostOrder(_root, input, path)



                If bFound Then

                '-- print our the path - from the root to the searched node
                '--ルートから検索されたノードまでのパスを出力します'-
                '-- (the path is in the order of found node then it exits each itteration to the root)
                '--(パスは見つかったノードの順序であり、ルートへの各イテレーションを終了します)
                For i As Int32 = path.Count - 1 To 0 Step -1

                        sPath += path(i).ToString + " "

                    Next

                    Console.WriteLine("Path: " + sPath)

                Else

                    Console.WriteLine("No found!")

                End If

            End If

        End Sub



    '-- A modification of the post order.  We take in a node, the value we are looking for, and the path from the node back up to the root.
    '--ポストオーダーの変更。ノード、探している値、およびノー??ドからルートに戻るパスを取り込みます。
    '-- The trick with this one is we evaluate the nodes first then interact with our current node.  In this case we look left, we look right, and then
    '--これの秘訣は、最初にノードを評価してから、現在のノードと対話することです。この場合、左を見て、右を見て、次に
    '-- evaluate if we are the node in question.  If we are record our value on the list and exit with a 'return true'.  The calling iteration then receives this "true"
    '--問題のノードであるかどうかを評価します。リストに値を記録し、「returntrue」で終了する場合。次に、呼び出し元の反復はこの「真」を受け取ります
    '--  and record's its value, and return true.  This trickles up to the root and out we go.
    '--して、その値を記録し、trueを返します。これは根元まで滴り落ち、私たちは出て行きます。
    '-- If the value isn't found returning false let's everyone know this.
    '--値がfalseを返すことが見つからない場合は、誰もがこれを知ってみましょう。
    Private Function PostOrder(ByVal myNode As Node, ByVal input As Int32, ByVal thePath As List(Of Int32)) As Boolean

        '-- check the l

        If myNode.LeftNode IsNot Nothing Then

            If PostOrder(myNode.LeftNode, input, thePath) Then

                thePath.Add(myNode.Value)

                Return True

            End If

        End If



        If myNode.RightNode IsNot Nothing Then

            If PostOrder(myNode.RightNode, input, thePath) Then

                thePath.Add(myNode.Value)

                Return True

            End If

        End If





        If myNode.Value = input Then

            thePath.Add(myNode.Value)

            Return True

        End If



        Return False

    End Function

End Class
Imports System
Module Program
    Sub Main(args As String())
        Dim bar As New BinTree(5)

        bar.InsertNode(2)

        bar.InsertNode(1)

        bar.InsertNode(8)

        bar.InsertNode(3)

        bar.InsertNode(10)

        bar.InsertNode(7)

        bar.InsertNode(12)

        Console.WriteLine("------------------")

        bar.Print(False)

        Console.WriteLine("------------------")

        bar.Print(True)

        Console.WriteLine("------------------")

        bar.FindPathToNode(12)

        Console.WriteLine("------------------")

        bar.FindPathToNode(13)



        Console.ReadLine()
    End Sub
End Module

上がメインです。

カテゴリー
Visual Basic

普通の書式をRPNに変換する。()、累乗半分対応?

Imports System

Module Program
    Class elem
        Public ope As String
        Public lev As Integer
    End Class
    Sub Main(args As String())
        'Dim inpstr As String = "6.1 + 5.2 * 4.3 - 3.4 / 2.5 * 1.6  "   '答え 6.1 5.2 4.3 * + 3.4 2.5 / 1.6 * -
        'Dim inpstr As String = "( a + b ) * c "                        '答え a b + c *
        'Dim inpstr As String = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 "        '答え 3 4 2 * 1 5 - 2 3 ^ ^ / +              =>X
        'Dim inpstr As String = "3 + 4 * 2 / ( 1 - 5 ) ^ ( 2 ^ 3 ) "     '答え 3 4 2 * 1 5 - 2 3 ^ ^ / +
        'Dim inpstr As String = "3 + 4 * 2 / ( 4 - 2 ) "                '答え 3 4 2 * 4 2 - / +
        'Dim inpstr As String = "( a + b ) ^ 2 "                        '答え a b + 2 ^
        'Dim inpstr As String = "a + b ^ 2 "                            '答え a b 2 ^ +
        'Dim inpstr As String = "a ^ b ^ c "                            '答え a b c ^ ^                               => X
        'Dim inpstr As String = "a ^ ( b ^ c ) "                        '答え a b c ^ ^
        Dim inpstr As String = "a / b / c "                              '答え a b / c / 
        Dim rpnstr As String = ""
        Dim opeStack As New Stack
        Dim aelem As New elem

        While True
            If inpstr.Length = 0 Then
                GoTo owari
            End If

            Dim fSpacePosition As Integer = inpstr.IndexOf(" ")
            Dim fstr As String = inpstr.Substring(0, fSpacePosition)
            Dim nstr As String = Strings.Right(inpstr, inpstr.Length - fSpacePosition - 1)

            If Not (fstr = "+" Or fstr = "-" Or fstr = "*" Or fstr = "/" Or
                    fstr = "^" Or fstr = "(" Or fstr = ")" Or fstr = "^") Then
                '演算子以外の数値は出力する
                rpnstr += fstr + " "

            Else
                If opeStack.Count >= 1 Then
                    Dim wope As elem = opeStack.Peek
                    Dim currentlev As Integer

                    Select Case fstr
                        Case "^" : currentlev = 3
                        Case "*" : currentlev = 2
                        Case "/" : currentlev = 2
                        Case "+" : currentlev = 1
                        Case "-" : currentlev = 1
                        Case ")" : DoPopUntilLeftPara(rpnstr, opeStack)
                            GoTo nextread
                        Case "(" : currentlev = 4
                        Case Else : currentlev = 0
                    End Select

                    Do While wope.lev >= currentlev And opeStack.Count >= 1
                        If wope.ope = "(" Then GoTo pass
                        rpnstr += wope.ope + " "
                        opeStack.Pop()
                        If opeStack.Count > 0 Then
                            wope = opeStack.Peek
                        End If
                    Loop
pass:

                    Dim belem As New elem
                    belem.ope = fstr
                    belem.lev = currentlev
                    opeStack.Push(belem)

                Else
                    '最初のスタックへの積上げ
                    Select Case fstr
                        Case "^" : aelem.lev = 3
                        Case "*" : aelem.lev = 2
                        Case "/" : aelem.lev = 2
                        Case "+" : aelem.lev = 1
                        Case "-" : aelem.lev = 1
                        Case Else : aelem.lev = 0
                    End Select
                    aelem.ope = fstr
                    opeStack.Push(aelem)
                End If

            End If
nextread:
            inpstr = nstr
        End While
owari:
        Dim welem As elem
        Do While opeStack.Count > 0
            welem = opeStack.Pop
            rpnstr += welem.ope + " "
        Loop
        Console.WriteLine(rpnstr)
        Console.WriteLine("Hello World!")
    End Sub
    Public Function DoPopUntilLeftPara(ByRef rpnstr As String, ByRef opeStack As Stack) As String
        Dim w As elem
        While True
            w = opeStack.Pop
            If w.ope = "(" Then
                Return rpnstr
            Else
                rpnstr += w.ope + " "
            End If
        End While
        Return rpnstr
    End Function
End Module
カテゴリー
Visual Basic

Visual Basic 自動実装Property

Imports System

Module Program
    Class elem
        Public Property Ope As String
        Dim a As String = _Ope

        Public Property Lve As Integer
        Dim b As Integer = _Lve

    End Class
    Sub Main(args As String())

        Dim a As New elem
        a.Ope = "100"
        a.Lve = 0

        Dim b As New elem With {.Ope = "+", .Lve = 1}

        Dim c As New elem With {.Ope = "*", .Lve = 2}

        Dim elemstack As New Stack

        Dim w As elem
        elemstack.Push(a)
        elemstack.Push(b)
        elemstack.Push(c)
        Do While elemstack.Count > 0
            w = elemstack.Pop
            Console.Write(w.Ope + ", ")
            Console.WriteLine(w.Lve)
        Loop

        Console.WriteLine("Hello World!")
    End Sub
End Module
カテゴリー
Visual Basic

クラスにPropertyを設定してみる

Imports System

Module Program
    Class elem
        Private _ope As String
        Private _lve As Integer

        Public Property Ope() As String
            Get
                Return _ope
            End Get
            Set(value As String)
                _ope = value
            End Set
        End Property

        Public Property Lve() As Integer
            Get
                Return _lve
            End Get
            Set(value As Integer)
                _lve = value
            End Set
        End Property

    End Class
    Sub Main(args As String())

        Dim a As New elem
        a.Ope = "100"
        a.Lve = 0

        Dim b As New elem With {.Ope = "+", .Lve = 1}

        Dim c As New elem With {.Ope = "*", .Lve = 2}

        Dim elemstack As New Stack

        Dim w As elem
        elemstack.Push(a)
        elemstack.Push(b)
        elemstack.Push(c)
        Do While elemstack.Count > 0
            w = elemstack.Pop
            Console.Write(w.Ope + ", ")
            Console.WriteLine(w.Lve)
        Loop

        Console.WriteLine("Hello World!")
    End Sub
End Module
カテゴリー
Visual Basic

Visual Basicで逆ポーランド記法の式を作る。()無し

Imports System

Module Program
    Class elem
        Public ope As String
        Public lev As Integer
    End Class
    Sub Main(args As String())
        Dim inpstr As String = "6.1 + 5.2 * 4.3 - 3.4 / 2.5 * 1.6 "
        Dim rpnstr As String = ""
        Dim opeStack As New Stack
        Dim aelem As New elem

        While True
            If inpstr.Length = 0 Then
                GoTo owari
            End If

            Dim fSpacePosition As Integer = inpstr.IndexOf(" ")
            Dim fstr As String = inpstr.Substring(0, fSpacePosition)
            Dim nstr As String = Strings.Right(inpstr, inpstr.Length - fSpacePosition - 1)

            If Not (fstr = "+" Or fstr = "-" Or fstr = "*" Or fstr = "/") Then
                '演算子以外の数値は出力する
                rpnstr += fstr + " "

            Else
                If opeStack.Count >= 1 Then
                    Dim wope As elem = opeStack.Peek
                    Dim currentlev As Integer

                    Select Case fstr
                        Case "*" : currentlev = 2
                        Case "/" : currentlev = 2
                        Case "+" : currentlev = 1
                        Case "-" : currentlev = 1
                        Case Else : currentlev = 0
                    End Select

                    Do While wope.lev >= currentlev And opeStack.Count >= 1
                        rpnstr += wope.ope + " "
                        opeStack.Pop()
                        If opeStack.Count > 0 Then
                            wope = opeStack.Peek
                        End If
                    Loop

                    Dim belem As New elem
                    belem.ope = fstr
                    belem.lev = currentlev
                    opeStack.Push(belem)

                Else
                    '最初のスタックへの積上げ
                    If fstr = "+" Or fstr = "-" Then
                        aelem.lev = 1
                    Else
                        aelem.lev = 2
                    End If
                    aelem.ope = fstr
                    opeStack.Push(aelem)
                End If

            End If
            inpstr = nstr
        End While
owari:
        Dim welem As elem
        Do While opeStack.Count > 0
            welem = opeStack.Pop
            rpnstr += welem.ope + " "
        Loop
        Console.WriteLine(rpnstr)
        Console.WriteLine("Hello World!")
    End Sub
End Module
inserted by FC2 system