伪代码

Pseudocode[1] is an informal high-level description of the operating principle of a computer program or other algorithm.

It uses the structural conventions of a normal programming language, but is intended for human reading rather than machine reading. Pseudocode typically omits details that are essential for machine understanding of the algorithm, such as variable declarations, system-specific code and some subroutines. The programming language is augmented with natural language description details, where convenient, or with compact mathematical notation. The purpose of using pseudocode is that it is easier for people to understand than conventional programming language code, and that it is an efficient and environment-independent description of the key principles of an algorithm. It is commonly used in textbooks and scientific publications that are documenting various algorithms, and also in planning of computer program development, for sketching out the structure of the program before the actual coding takes place.

No standard for pseudocode syntax exists, as a program in pseudocode is not an executable program. Pseudocode resembles, but should not be confused with, skeleton programs which can be compiled without errors. Flowchartsdrakon-charts and Unified Modeling Language (UML) charts can be thought of as a graphical alternative to pseudocode, but are more spacious on paper. Languages such as HAGGIS bridge the gap between pseudocode and code written on programming languages. Its main use is to introduce students to high level languages through use of this hybrid language.

-------------

Application[edit]

Textbooks and scientific publications related to computer science and numerical computation often use pseudocode in description of algorithms, so that all programmers can understand them, even if they do not all know the same programming languages. In textbooks, there is usually an accompanying introduction explaining the particular conventions in use. The level of detail of the pseudo-code may in some cases approach that of formalized general-purpose languages.

programmer who needs to implement a specific algorithm, especially an unfamiliar one, will often start with a pseudocode description, and then "translate" that description into the target programming language and modify it to interact correctly with the rest of the program. Programmers may also start a project by sketching out the code in pseudocode on paper before writing it in its actual language, as a top-down structuring approach, with a process of steps to be followed as a refinement.

Syntax[edit]

As the name suggests, pseudocode generally does not actually obey the syntax rules of any particular language; there is no systematic standard form, although any particular writer will generally borrow style and syntax; for example, control structures from some conventional programming language. Popular syntax sources include FortranPascalBASICCC++JavaLisp, and ALGOL. Variable declarations are typically omitted. Function calls and blocks of code, such as code contained within a loop, are often replaced by a one-line natural language sentence.

Depending on the writer, pseudocode may therefore vary widely in style, from a near-exact imitation of a real programming language at one extreme, to a description approaching formatted prose at the other.

This is an example of pseudocode (for the mathematical game fizz buzz):

Fortran style pseudo code

program fizzbuzz
  Do i = 1 to 100 
    set print_number to true
    If i is divisible by 3
      print "Fizz"
      set print_number to false
    If i is divisible by 5
      print "Buzz" 
      set print_number to false
    If print_number, print i
    print a newline
  end do

Pascal style pseudo code

procedure fizzbuzz
  For i := 1 to 100 do
    set print_number to true;
    If i is divisible by 3 then
      print "Fizz";
      set print_number to false;
    If i is divisible by 5 then
      print "Buzz";
      set print_number to false;
    If print_number, print i;
    print a newline;
  end

C style pseudo code:

void function fizzbuzz {
  for (i = 1; i <= 100; i++) {
    set print_number to true;
    If i is divisible by 3 {
      print "Fizz";
      set print_number to false; }
    If i is divisible by 5 {
      print "Buzz";
      set print_number to false; }
    If print_number, print i;
    print a newline;
  }
}

Structured Basic style pseudo code

Sub fizzbuzz()
  For i = 1 to 100
    print_number = True
    If i is divisible by 3 Then
      Print "Fizz"
      print_number = False
    End If
    If i is divisible by 5 Then
      Print "Buzz"
      print_number = False
    End If
    If print_number = True Then print i
    Print a newline
  Next i
End Sub

See also: Category:Articles with example pseudocode.

Mathematical style pseudocode[edit]

In numerical computation, pseudocode often consists of mathematical notation, typically from set and matrix theory, mixed with the control structures of a conventional programming language, and perhaps also natural language descriptions. This is a compact and often informal notation that can be understood by a wide range of mathematically trained people, and is frequently used as a way to describe mathematical algorithms. For example, the sum operator (capital-sigma notation) or the product operator (capital-pi notation) may represent a for-loop and a selection structure in one expression:

Return {\displaystyle \sum _{k\in S}x_{k}}

Normally non-ASCII typesetting is used for the mathematical equations, for example by means of markup languages, such as TeX or MathML, or proprietary formula editors.

Mathematical style pseudocode is sometimes referred to as pidgin code, for example pidgin ALGOL (the origin of the concept), pidgin Fortranpidgin BASICpidgin Pascalpidgin C, and pidgin Lisp.

Common mathematical symbols[edit]

Type of operationSymbolExample
Assignment← or :=c ← 2πrc := 2πr
Comparison=, ≠, <, >, ≤, ≥ 
Arithmetic+, −, ×, /, mod 
Floor/ceiling⌊, ⌋, ⌈, ⌉a ← ⌊b⌋ + ⌈c
Logicalandor 
Sums, products∑ ∏h ← ∑aA 1/a

Example[edit]

Here follows a longer example of mathematical-style pseudo-code, for the Ford–Fulkerson algorithm:

algorithm ford-fulkerson is
    input: Graph G with flow capacity c, 
           source node s, 
           sink node t
    output: Flow f such that f is maximal from s to t

    (Note that f(u,v) is the flow from node u to node v, and c(u,v) is the flow capacity from node u to node v)

    for each edge (u, v) in GE do
        f(u, v) ← 0
        f(v, u) ← 0

    while there exists a path p from s to t in the residual network Gf do
        let cf be the flow capacity of the residual network Gf
        cf(p) ← min{cf(u, v) | (u, v) in p}
        for each edge (u, v) in p do
            f(u, v) ←  f(u, v) + cf(p)
            f(v, u) ← −f(u, v)

    return f

Machine compilation of pseudocode style languages[edit]

Natural language grammar in programming languages[edit]

Various attempts to bring elements of natural language grammar into computer programming have produced programming languages such as HyperTalkLingoAppleScriptSQLInform and to some extent Python. In these languages, parentheses and other special characters are replaced by prepositions, resulting in quite talkative code. These languages are typically dynamically typed, meaning that variable declarations and other boilerplate code can be omitted. Such languages may make it easier for a person without knowledge about the language to understand the code and perhaps also to learn the language. However, the similarity to natural language is usually more cosmetic than genuine. The syntax rules may be just as strict and formal as in conventional programming, and do not necessarily make development of the programs easier.

Mathematical programming languages[edit]

An alternative to using mathematical pseudocode (involving set theory notation or matrix operations) for documentation of algorithms is to use a formal mathematical programming language that is a mix of non-ASCII mathematical notation and program control structures. Then the code can be parsed and interpreted by a machine.

Several formal specification languages include set theory notation using special characters. Examples are:

Some array programming languages include vectorized expressions and matrix operations as non-ASCII formulas, mixed with conventional control structures. Examples are:

See also[edit]

References[edit]

  1. Jump up^ BJ Furman (29 December 2010). "Notes on Algorithms, Pseudocode, and Flowcharts"engr.sjsu.edu.
  • Justin Zobel (2013). "Algorithms" in Writing for Computer Science (second edition). Springer. ISBN 1-85233-802-4.

External links[edit]

Look up pseudocode in Wiktionary, the free dictionary.

Categories

--------------------

伪代码的写法

伪代码(Pseudocode)是一种算法描述语言。使用伪代码的目的是为了使被描述的算法可以容易地以任何一种编程语言(Pascal,C,Java,etc)实现。因此,伪代码必须结构清晰、代码简单、可读性好,并且类似自然语言。 介于自然语言与编程语言之间。

  它以编程语言的书写形式指明算法的职能。相比于程序语言(例如Java, C++,C, Dephi 等等)它更类似自然语言。它是半角式化、不标准的语言。我们可以将整个算法运行过程的结构用接近自然语言的形式(这里,你可以使用任何一种你熟悉的文字,中文,英文 等等,关键是你把你程序的意思表达出来)描述出来. 使用伪代码, 可以帮助我们更好的表述算法, 不用拘泥于具体的实现.

  人们在用不同的编程语言实现同一个算法时意识到,他们的实现(注意:这里是实现,不是功能)很不同。尤其是对于那些熟练于不同编程语言的程序员要理解一个(用其他编程语言编写的程序的)功能时可能很难,因为程序语言的形式限制了程序员对程序关键部分的理解。这样伪代码就应运而生了。

  当考虑算法功能(而不是其语言实现)时,伪代码常常得到应用。计算机科学在教学中通常使用虚拟码,以使得所有的程序员都能理解。

  综上,简单的说,让人便于理解的代码。不依赖于语言的,用来表示程序执行过程,而不一定能编译运行的代码。在数据结构讲算法的时候用的很多。 

语法规则

  例如,类Pascal语言的伪代码的语法规则是: 在伪代码中,每一条指令占一行(else if,例外)。指令后不跟任何符号(Pascal和C中语句要以分号结尾)。书写上的“缩进”表示程序中的分支程序结构。这种缩进风格也适用于if-then-else语句。用缩进取代传统Pascal中的begin和end语句来表示程序的块结构可以大大提高代码的清晰性;同一模块的语句有相同的缩进量,次一级模块的语句相对与其父级模块的语句缩进。

    算法的伪代码语言在某些方面可能显得不太正规,但是给我们描述算法提供了很多方便,并且可以使我们忽略算法实现中很多麻烦的细节。通常每个算法开始时都要描述它的输入和输出,而且算法中的每一行都给编上号码,在解释算法的过程中会经常使用算法步骤中的行号来指代算法的步骤。算法的伪代码描述形式上并不是非常严格,其主要特性和通常的规定如下:
        1) 算法中出现的数组、变量可以是以下类型:整数、实数、字符、位串或指针。通常这些类型可以从算法的上下文来看是清楚的,并不需要额外加以说明。
        2) 在算法中的某些指令或子任务可以用文字来叙述,例如,"设x是A中的最大项",这里A是一个数组;或者"将x插入L中",这里L是一个链表。这样做的目的是为了避免因那些与主要问题无关的细节使算法本身杂乱无章。
        3) 算术表达式可以使用通常的算术运算符(+,-,*,/,以及表示幂的^)。逻辑表达式可以使用关系运算符=,≠,<,>,≤和≥,以及逻辑运算符与(and),或(or),非(not)。
        4) 赋值语句是如下形式的语句:a<-b 。
这里a是变量、数组项,b是算术表达式、逻辑表达式或指针表达式。语句的含义是将b的值赋给a。
        5) 若a和b都是变量、数组项,那么记号a<->b 表示a和b的内容进行交换。
        6) goto语句具有形式
                                        goto label(goto标号)
它将导致转向具有指定标号的语句。
        7) 条件语句有以下两种形式:
                                            if c then s或者 
                                               if c then s
                                                  else s′
这里c是逻辑表达式,s和s′是单一的语句或者是被括在do和end之间的语句串。对于上述两种形式,假若c为真,则s被执行一次。假若c为假,则在第一种形式中,if语句的执行就完成了,而在第二种形式中,执行s′。在所有的情况下,控制就进行到了下一个语句,除非在s或s′中的goto语句使控制转向到其它地方。
         8) 有两种循环指令:while和for。
         while语句的形式是
                                              while c do  
                                                    s
                                                  end
这里c是逻辑表达式,而s是由一个或更多个语句组成的语句串。当c为真时,执行s。在每一次执行s之前,c都被检查一下;假若c为假,控制就进行到紧跟在while语句后面的语句。注意,当控制第一次达到while语句时,假若c为假,则s一次也不执行。 
       for语句的形式是
                                      for var init to limit by incr do
                                                        s
                                                      end
这里var是变量,init、limit和incr都是算术表达式,而s是由一个或多个语句组成的语句串。初始时,var被赋予init的值。假若incr≥0,则只要var≤limit,就执行s并且将incr加到var上。(假若incr<0,则只要var≥limit,就执行s并且将incr加到var上)。incr的符号不能由s来该改变。
      9) exit语句可以在通常的结束条件满足之前,被用来结束while循环或者for循环的执行。exit导致转向到紧接在包含exit的(最内层)while或者for循环后面的一个语句。
     10) return用来指出一个算法执行的终点;如果算法在最后一条指令之后结束,它通常是被省略的;它被用得最多的场合是检测到不合需要的条件时。return的后面可以紧接被括在引号的信息。
      11) 算法中的注释被括在/* */之中。诸如read和output之类的各种输入或者输出也在需要时被用到。
     

伪代码实例

  伪代码只是像流程图一样用在程序设计的初期,帮助写出程序流程。简单的程序一般都不用写流程、写思路,但是复杂的代码,最好还是把流程写下来,总体上去考虑整个功能如何实现。写完以后不仅可以用来作为以后测试,维护的基础,还可用来与他人交流。但是,如果把全部的东西写下来必定可能会让费很多时间,那么这个时候可以采用伪代码方式。比如:

  IF 九点以前 THEN

     do 私人事务;

  ELSE 9点到18点 THEN

  工作;

  ELSE

  下班;

  END IF

  这样不但可以达到文档的效果,同时可以节约时间. 更重要的是,使结构比较清晰,表达方式更加直观.

  下面介绍一种类Pascal语言的伪代码的语法规则。

  在伪代码中,每一条指令占一行(else if 例外,),指令后不跟任何符号(Pascal和C中语句要以分号结尾);

  书写上的“缩进”表示程序中的分支程序结构。这种缩进风格也适用于if-then-else语句。用缩进取代传统Pascal中的begin和end语句来表示程序的块结构可以大大提高代码的清晰性;同一模块的语句有相同的缩进量,次一级模块的语句相对与其父级模块的语句缩进; 

  在伪代码中,通常用连续的数字或字母来标示同一即模块中的连续语句,有时也可省略标号。

  符号△后的内容表示注释;

  在伪代码中,变量名和保留字不区分大小写,这一点和Pascal相同,与C或C++不同;

  在伪代码中,变量不需声明,但变量局部于特定过程,不能不加显示的说明就使用全局变量;

  赋值语句用符号←表示,x←exp表示将exp的值赋给x,其中x是一个变量,exp是一个与x同类型的变量或表达式(该表达式的结果与x同类型);多重赋值i←j←e是将表达式e的值赋给变量i和j,这种表示与j←e和i←e等价。

  例如:

  x←y

  x←20*(y+1)

  x←y←30

  以上语句用C分别表示为:

  x = y;

  x = 20*(y+1);

  x = y = 30;

  选择语句用if-then-else来表示,并且这种if-then-else可以嵌套,与Pascal中的if-then-else没有什么区别。

  例如:

  if (Condition1)

  then [ Block 1 ]

  else if (Condition2)

  then [ Block 2 ]

  else [ Block 3 ]

  循环语句有三种:while循环、repeat-until循环和for循环,其语法均与Pascal类似,只是用缩进代替begin - end;

  例如:

  1. x ← 0

  2. y ← 0

  3. z ← 0

  4. while x < N

  1. do x ← x + 1

  2. y ← x + y

  3. for t ← 0 to 10

  1. do z ← ( z + x * y ) / 100

  2. repeat

  1. y ← y + 1

  2. z ← z - y

  3. until z < 0

  4. z ← x * y

  5. y ← y / 2

   上述语句用C或C++来描述是:

  x = y = z = 0;

  while( z < N )

  {

  x ++;

  y += x;

  for( t = 0; t < 10; t++ )

  {

  z = ( z + x * y ) / 100;

  do {

  y ++;

  z -= y;

  } while( z >= 0 );

     }

  z = x * y;

  }

  y /= 2;

  数组元素的存取有数组名后跟“[下标]”表示。例如A[j]指示数组A的第j个元素。符号“ …”用来指示数组中值的范围。

  例如:

  A[1…j]表示含元素A[1], A[2], … , A[j]的子数组;

  复合数据用对象(Object)来表示,对象由属性(attribute)和域(field)构成。域的存取是由域名后接由方括号括住的对象名表示。

  例如:

  数组可被看作是一个对象,其属性有length,表示其中元素的个数,则length[A]就表示数组A中的元素的个数。在表示数组元素和对象属性时都要用方括号,一般来说从上下文可以看出其含义。

  用于表示一个数组或对象的变量被看作是指向表示数组或对象的数据的一个指针。对于某个对象x的所有域f,赋值y←x就使f[y]=f[x],更进一步,若有f[x]←3,则不仅有f[x]=3,同时有f[y]=3,换言之,在赋值y←x后,x和y指向同一个对象。

  有时,一个指针不指向任何对象,这时我们赋给他nil。

  函数和过程语法与Pascal类似。

  函数值利用 “return (函数返回值)” 语句来返回,调用方法与Pascal类似;过程用 “call 过程名”语句来调用;

  例如:

  1. x ← t + 10

  2. y ← sin(x)

  3. call CalValue(x,y)

  参数用按值传递方式传给一个过程:被调用过程接受参数的一份副本,若他对某个参数赋值,则这种变化对发出调用的过程是不可见的。当传递一个对象时,只是拷贝指向该对象的指针,而不拷贝其各个域。  

----

伪代码是用介于自然语言和计算机语言之间的文字和符号来描述算法。它采用某一程序设计语言的基本语法,如操作指令可以结合自然语言来设计,而且它不用符号,书写方便,没有固定的语法和格式,具有很大的随意性,便于向程序过渡。下面的例子用伪代码描述算法。

【例3.10】用伪代码描述两个正整数a和b最大公约数的算法。

01   开始
02   c=a%b;
03   循环直到c=0
04     a=b;
05     b=c;
06     c=a%b;
07   输出b;
08   结束

说明:虽然伪代码不是一种实际的编程语言,但是在表达能力上类似于编程语言,同时避免了描述技术细节带来的麻烦,所以伪代码更适合描述算法,故被称为“算法语言”或“第一语言”。

【例3.11】用伪代码描述n!。

01   开始
02   如果n=0,输出s=1;
03   如果n>0,
04   s=1,i=1;
05   循环直到i>n
06   s=s*i;
07   i=i+1;
08   输出s;
09   结束

--------

30down votefavorite

11

I have been looking for an algorithm to perform a transitive reduction on a graph, but without success. There's nothing in my algorithms bible (Introduction To Algorithms by Cormen et al) and whilst I've seen plenty of transitive closure pseudocode, I haven't been able to track down anything for a reduction. The closest I've got is that there is one in "Algorithmische Graphentheorie" by Volker Turau (ISBN:978-3-486-59057-9), but unfortunately I don't have access to this book! Wikipedia is unhelpful and Google is yet to turn up anything. :^(

Does anyone know of an algorithm for performing a transitive reduction?

algorithm graph pseudocode

shareedit

asked Nov 6 '09 at 22:33

i alarmed alien

5,79721633

 

add a comment

 

7 Answers

activeoldestvotes

 

up vote12down vote

See Harry Hsu. "An algorithm for finding a minimal equivalent graph of a digraph.", Journal of the ACM, 22(1):11-16, January 1975. The simple cubic algorithm below (using an N x N path matrix) suffices for DAGs, but Hsu generalizes it to cyclic graphs.

// reflexive reduction
for (int i = 0; i < N; ++i)
  m[i][i] = false;

// transitive reduction
for (int j = 0; j < N; ++j)
  for (int i = 0; i < N; ++i)
    if (m[i][j])
      for (int k = 0; k < N; ++k)
        if (m[j][k])
          m[i][k] = false;

shareedit

edited Nov 24 '14 at 21:41

answered Jul 15 '11 at 2:47

Alan Donovan

24434

 
   

(for DAGs) In other words: look at each edge (i,j), remove it if there is a reason for not being in the transitive reduction. The edges not removed must be inside the transitive reduction. – galath Sep 10 '11 at 20:26

3 

According to the reference you cite, you should be starting from the path matrix, not the adjacency matrix – Michael Clerx May 3 '13 at 11:09

3 

This does not work for all cases. In a graph with edges (A,B), (B,C), (C,D) and (A,D) the last edge (A,D) should be deleted. It is not, because there is no combination of two edges (m[i][j] and m[j][k]) that leads from A to D. – Renze de Waal Jul 30 '13 at 9:28

1 

@MichaelClerx quite right, I meant path matrix. Thanks for pointing out the error. If you have an adjacency matrix, apply Warshal's algorithm first to transitively close it. – Alan Donovan Nov 24 '14 at 21:42

add a comment

 

 

up vote8down vote

The basic gist of the transitive reduction algorithm I used is


foreach x in graph.vertices
   foreach y in graph.vertices
      foreach z in graph.vertices
         delete edge xz if edges xy and yz exist

The transitive closure algorithm I used in the same script is very similar but the last line is


         add edge xz if edges xy and yz OR edge xz exist

shareedit

answered Mar 3 '10 at 14:49

i alarmed alien

5,79721633

 
   

You need to add if (x,z) != (x,y) && (x,z) != (y,z) before delete edge... to avoid incorrect deletions in the event of cycles. Other than that, and although it'd be better to have a faster linear-time algorithm, I like this answer: nice and simple. – Joey Adams Jun 6 '10 at 8:20

1 

Also, if the graph has cycles, this algorithm won't always produce the minimal transitive reduction. For instance, try it on [0,1,2,3,4,5] where A points to B for all A and B (even when they're the same). It should produce something like 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 0, but running this algorithm (with my tweak) brings in 5 -> 2 and 5 -> 4 in addition to 0 -> ... -> 5 -> 0. Running it without my tweak produces no edges at all. – Joey Adams Jun 7 '10 at 5:30

   

I should have stated that my code included checks for the identical edges you mentioned, and also that I'm working solely with DAGs, so the cycles aren't an issue. – i alarmed alien Jun 10 '10 at 18:04

   

Are you sure of your algorithm for the transitive closure? For that task I would use Floyd-Warshall's algorithm, which is foreach y in graph.vertices: foreach x in graph.vertices: foreach z in graph.vertices: add edge xz if edges xy and yz exist OR edge xz exist. Note the different order in x and y. I thought the order mattered. It doesn't? – galath Sep 10 '11 at 20:16 

5 

As noted by cmn, thi algorithm does clear edges that connect nodes that are also connected through a path that has more than two edges. Example: A -> B -> C -> D; A -> C; A-> D. The algorithm would clear A -> C, but not A -> D. – Penz Jun 28 '12 at 1:53 

show 1 more comment

 

up vote3down vote

The algorithm of "girlwithglasses" forgets that a redundant edge could span a chain of three edges. To correct, compute Q = R x R+ where R+ is the transitive closure and then delete all edges from R that show up in Q. See also the Wikipedia article.

shareedit

answered Dec 8 '10 at 19:42

cmh

311

 
1 

Can you suggest some pseudocode for doing this? The transitive reduction algorithm posted below would run on the transitive closure graph, so for an edge x-y which could also be reached by x-A-B-y, you would also have x-A-y and x-B-y. – i alarmed alien May 10 '11 at 18:07 

   

What is Q supposed to represent? What do you do with it? – Brian Gordon Jul 1 '13 at 19:55

add a comment

 

up vote3down vote

Based on the reference provided by Alan Donovan, which says you should use the path matrix (which has a 1 if there is a path from node i to node j) instead of the adjacency matrix (which has a 1 only if there is an edge from node i to node j).

Some sample python code follows below to show the differences between the solutions

def prima(m, title=None):
    """ Prints a matrix to the terminal """
    if title:
        print title
    for row in m:
        print ', '.join([str(x) for x in row])
    print ''

def path(m):
    """ Returns a path matrix """
    p = [list(row) for row in m]
    n = len(p)
    for i in xrange(0, n):
        for j in xrange(0, n):
            if i == j:
                continue
            if p[j][i]:
                for k in xrange(0, n):
                    if p[j][k] == 0:
                        p[j][k] = p[i][k]
    return p

def hsu(m):
    """ Transforms a given directed acyclic graph into its minimal equivalent """
    n = len(m)
    for j in xrange(n):
        for i in xrange(n):
            if m[i][j]:
                for k in xrange(n):
                    if m[j][k]:
                        m[i][k] = 0

m = [   [0, 1, 1, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 1, 1],
        [0, 0, 0, 0, 1],
        [0, 1, 0, 0, 0]]

prima(m, 'Original matrix')
hsu(m)
prima(m, 'After Hsu')

p = path(m)
prima(p, 'Path matrix')
hsu(p)
prima(p, 'After Hsu')

Output:

Adjacency matrix
0, 1, 1, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 1, 1
0, 0, 0, 0, 1
0, 1, 0, 0, 0

After Hsu
0, 1, 1, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 1, 0
0, 0, 0, 0, 1
0, 1, 0, 0, 0

Path matrix
0, 1, 1, 1, 1
0, 0, 0, 0, 0
0, 1, 0, 1, 1
0, 1, 0, 0, 1
0, 1, 0, 0, 0

After Hsu
0, 0, 1, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 1, 0
0, 0, 0, 0, 1
0, 1, 0, 0, 0

shareedit

answered May 3 '13 at 11:16

Michael Clerx

1,68021738

 
   

I'm puzzled because it seems that, if you removed the edges in the right order, you could get right back to the original (redundant) adjacency matrix by applying the algorithm to the path matrix. So basically you've gotten nowhere. See this example: i.imgur.com/fbt6oK1.png Say you start with just the black edges, and of course you want to eliminate the dotted black/green edge. So you add the red edges to get the path matrix. Then you remove the red edges because they can both be removed by the algorithm. And now you're stuck. – Brian Gordon Jul 1 '13 at 18:41 

   

Using m = [[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]] as input works fine :) – Michael Clerx Jul 1 '13 at 20:55

   

I think that It can work as long as you're not unlucky about which edges are removed first. – Brian Gordon Jul 2 '13 at 15:54

   

Try it, the order makes no difference. – Michael Clerx Jul 2 '13 at 17:19

   

OK, sorry, you're right, I can't find any case where the dotted black/green edge is removed before the two red eges. When I get home tonight I'll try to figure out why this happens. – Brian Gordon Jul 2 '13 at 20:14 

add a comment

 

up vote2down vote

The Wikipedia article on transitive reduction points to an implementation within GraphViz (which is open source). Not exactly pseudocode, but maybe someplace to start?

LEDA includes a transitive reduction algorithm. I don't have a copy of the LEDA book anymore, and this function might have been added after the book was published. But if it's in there, then there will be a good description of the algorithm.

Google points to an algorithm that somebody suggested for inclusion in Boost. I didn't try to read it, so maybe not correct?

Also, this might be worth a look.

shareedit

answered Nov 7 '09 at 15:42

Eric

7,888104789

 
   

Thanks (belatedly!) for your response. In the end, I emailed the author of an algorithms book and asked him to verify whether some pseudocode I'd written was correct, which he kindly did. – i alarmed alien Mar 3 '10 at 14:42 

1 

The tred source code is barely readable thanks to the absence of any comment in the code. – Bram Schoenmakers Mar 16 '12 at 12:02

add a comment

 

up vote1down vote

Depth-first algorithm in pseudo-python:

for vertex0 in vertices:
    done = set()
    for child in vertex0.children:
        df(edges, vertex0, child, done)

df = function(edges, vertex0, child0, done)
    if child0 in done:
        return
    for child in child0.children:
        edge.discard((vertex0, child))
        df(edges, vertex0, child, done)
    done.add(child0)

The algorithm is sub-optimal, but deals with the multi-edge-span problem of the previous solutions. The results are very similar to what tred from graphviz produces.

It is one way to describe an algorithm. Other answers have addressed what this can look like. In short, it is written typically (and usually for good reason) in a machine independent way based on a model of computation (usually not drilled down that far in, as you can use different models to analyze the same algorithm). This is because when we research and study algorithms they typically are not tied to one implementation. Normally researchers and those interested try to describe algorithms in a mathematical way to avoid the pitfalls of implementation details and more so to focus on the algorithm itself and things such as its time complexity. Algorithms are mathematical, hence, they can be described formally without needing to implement them. That’s why somebody like me can design an algorithm and never actually implement it on a computer. We learnt years ago that Maths is an extremely powerful way to capture computation.

One of the answers claims it is “informal” (see Ricky Putra's answer to What is pseudocode? ), I disagree with this sentiment. If somebody properly described their algorithm with pseudocode, it is formal because it follows the definition of what an algorithm is. Most common definitions of algorithms will say an algorithm is an unambiguous step-by-step procedure that takes in input from an input instance and produces output (if the output is always the solution, then we say the algorithm is correct; with many deviations from this). If one writes decent pseudocode, that captures the above definition, it’s formal. I guess they may be meaning “formal” in maybe a different sense? Like that we don’t write out the most elementary operations possible? I mean, some believe mathematical proofs are not formal enough unless we break it down into the very bedrock mathematical logic, maybe they mean it in that sense? I’m not sure. But it is extremely common for theoreticians to describe the algorithms they figure out in pseudocode or in English, and I wouldn’t try to say that their work is informal, because it is not in the literature.

577 Views · 1 Upvote

Upvote1Downvote

Share

 

RecommendedAll

Lorry Pan

 

Promoted by General Assembly

Learn data science - part-time course at General Assembly.

Learn to build robust predictive models, test their validity, and communicate results. Apply now!

Apply now at generalassemb.ly/data

 

 

Valentine Chriz

Valentine Chriz, works at Philadelphia, PA

Answered Feb 24

main-qimg-60c92015861e0bf722fa2a9e5af00975.webp

Pseudo-code is a kind of structured English for describing algorithms in an easily readable and modular form. It allows the designer to focus the logic of the algorithm without being distracted by details of language syntax in which the code is going to be written. The pseudo-code needs to be complete. It describes the entire logic of the algorithm so that implementation becomes a routine mechanical task of translating line by line into the source code of the target language. Thus, it must include flow of control.

This helps in describing how the system will solve the given problem. Pseudo code does not refer to precise form of expression. It refers to the simple use of standard English. Pseudo code must use a restricted subset of English in such a way that it resembles a good high level programming language.

Web Designing Services in Lancaster

296 Views

UpvoteDownvote

Share

 

RecommendedAll

Lorry Pan

 

 

Alex Jarvis

Alex Jarvis, Computer Engineer

Answered Dec 9, 2015

Pseudo code is a way of writing an algorithm down in an abstract form which cannot be programmed directly. Basically pseudo code syntax is best ran on a human(as in manually running the code by hand with paper) and actual code is meant for a computer. 

It is useful for planning out algorithms. For example, if I wanted a bit shift and add algorithm it would look like this in assembly for my own designed 8 bit CPU. It looks messy and is really hard to understand what is being done to each register. 

main-qimg-0249e87fd650255a01c78a994b2852c6.webp


This code is a bit complicated, and is not really pseudo code.  I'll provide a great example from Wikipedia.

This is the pseudo code for Bresenhams line drawing algorithm. You will notice how much simpler it is than my assembly multiplication algorithm.
 

main-qimg-ba42eeb95c35bb0503bfa2621d4030cc.webp


This is the algorithm used to draw a straight line between any 2 points on a screen. 

I hope this helped somewhat!

1.1k Views · 2 Upvotes

Upvote2Downvote

Share

 

Páll Haraldsson

Páll Haraldsson

There is a language that is almost identical to (this) pseudocode, called Julia (and fast as C)....

Promoted by Coding Dojo

Learn to program in LA. Become a developer in 14 weeks.

No experience required. Part time courses and scholarships available. Average starting salary is $76k.

Learn more at codingdojo.com/los-angeles

 

 

Kauan Raphael Mayworm Klein

Kauan Raphael Mayworm Klein, self taught developer since 8 years old, started with C# and never looked back

Answered Jun 19

It’s any formal way to describe an algorithm or a section of one. A pseudocode generally has its grammar, and syntax like any computer programming language, but the former is less strict. Even when not following any strict pseudocode language, programmers from different backgrounds can understand one another when writing loose pseudocode, for example, imagine this is a pseudocode to drive a vacuum cleaning robot (as you can see, a lot of stuff is left out of pseudocode, because it is used to convey a certain message, in this robot’s case, the message is: When it gets started, it vacuum cleans the spot where it is; then, it marks that spot as clean, uses its sensors to find a next spot around it that is not marked clean and isn’t an obstacle; if it can’t find any, it waits for some time (sleeps); If it can, it moves to the location it found, and goes back to the line labelled as `loop`.

 
  1. routine OnStart begin
  2.  
  3. loop:
  4. callroutine vacuum_ground( )
  5. callroutine set_position_as_clean( )
  6. var direction = callroutine find_next_position( )
  7. if not direction then
  8. begin
  9. callroutine sleep( )
  10. end
  11. else
  12. begin
  13. callroutine move_to_next_position( )
  14. goto loop
  15. end
  16. endif
  17. end

At first glance, we don’t know what any of the routines actually do. We trust that they do what we expect. One different developer could be charged to write each of the other routines then (`vaccum_ground`, `set_position_as_clean`, etc), each one of them knowing which role each of their routine play in the robot’s behaviour.

In short, pseudocode helps in a lot of ways, and it’s used to plan ahead and to exchange information between different developers. Writing precise and accurate pseudocode (which, by extension, could be considered diagrams in a specific extendable language created just for that, called UML) is an extremely valuable ability to a project manager or architect.

142 Views

UpvoteDownvote

Share

 

RecommendedAll

Lorry Pan

 

 

Robert Sampson

Robert Sampson, Academic trainer

Answered Dec 15, 2015

Pseudocode is a detailed yet readable description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language. Pseudocode is sometimes used as a detailed step in the process of developing a program. It allows designers or lead programmers to express the design in great detail and provides programmers a detailed template for the next step of writing code in a specific programming language. Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. It is simply one step - an important one - in producing the final code. The benefit of pseudocode is that it enables the programmer to concentrate on the algorithms without worrying about all the syntactic details of a particular programming language

148 Views

UpvoteDownvote

Share

 

RecommendedAll

Lorry Pan

 

 

Ajay Sharma Dharmani

Ajay Sharma Dharmani, works at SportsQwizz

Answered May 18

Pseudo code means False code .

It is not exact code for solving the problem but it would give us an idea that how the problem is going to be solved.

 

转载于:https://my.oschina.net/u/3127489/blog/1555300

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值