Resistance calculator: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: Added RPN version.)
No edit summary
Line 15: Line 15:


;Input
;Input
[https://photos.app.goo.gl/58heQVm8UJYf8Ra29 Parallel Resistor Calculator]
[https://photos.app.goo.gl/58heQVm8UJYf8Ra29 Resistance Calculator]


* Infix: ((((R8 + R10) * R9 + R7) * R6 + R5) * R4 + R3) * R2 + R1
* Infix: ((((10 + 2) * 6 + 8) * 6 + 4) * 8 + 4) * 8 + 6
* RPN: 10 2 + 6 * 8 + 6 * 4 + 8 * 4 + 8 * 6 +
* RPN: 10 2 + 6 * 8 + 6 * 4 + 8 * 4 + 8 * 6 +
* Voltage = 18.0 V
* Voltage = 18.0 V
Line 305: Line 305:
echo(" Ohm Volt Ampere Watt Network tree")
echo(" Ohm Volt Ampere Watt Network tree")
node.report()</lang>
node.report()</lang>

===Shunting Yard===
<lang python>import strutils, sequtils, sugar, strformat

proc shuntRPN(s:string): seq[string] =
let ops = "+*"
var input = s.replace("("," ( ")
input = input.replace(")"," ) ")
input = input.replace("+"," + ")
input = input.replace("*"," * ")
input = input.replace(" "," ")
var tokens = input.strip.split
tokens = tokens.filter x => x.strip != ""
var stack: seq[string]
var op: string
for token in tokens:
case token
of "(": stack.add token
of ")":
while stack.len > 0:
op = stack.pop()
if op == "(": break
result.add op
else:
if token in ops:
while stack.len > 0:
op = stack[^1]
if not (op in ops): break
if ops.find(token) >= ops.find(op): break
discard stack.pop()
result.add op
stack.add token
else: result.add token
while stack.len > 0: result.add stack.pop()

type
Node = ref object
kind : string # +=serial *=parallel r=resistor
resistance : float
voltage : float
a : Node
b : Node

proc res(node: Node) : float =
case node.kind:
of "+": node.a.res + node.b.res
of "*": 1/(1/node.a.res + 1/node.b.res)
else: node.resistance

proc current(node: Node) : float = return node.voltage / node.res
proc effect (node: Node) : float = return node.current * node.voltage

proc report(node: Node, level: string = "") =
echo fmt"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f} {level}{node.kind}"
if node.kind in "+*":
node.a.report level & "| "
node.b.report level & "| "

proc setVoltage(node: Node, voltage: float) =
node.voltage = voltage
if node.kind == "+":
let ra = node.a.res
let rb = node.b.res
node.a.setVoltage ra * voltage/(ra+rb)
node.b.setVoltage rb * voltage/(ra+rb)
if node.kind == "*":
node.a.setVoltage voltage
node.b.setVoltage voltage

proc build(tokens : seq[string]) : Node =
var stack: seq[Node]
for word in tokens:
case word:
of "+","*": stack.add Node(kind: word, a: stack.pop, b: stack.pop)
else: stack.add Node(kind: "r", resistance: parseFloat(word))
stack.pop

proc main =
let node = build shuntRPN "((((10+2)*6+8)*6+4)*8+4)*8+6"
node.setVoltage 18.0
echo " Ohm Volt Ampere Watt Network tree"
node.report

main()</lang>


=={{header|Perl 6}}==
=={{header|Perl 6}}==