世界上有哪些代码量很少,但很牛逼很经典的算法或项目案例?

1

AI核心代码,一亿估值。

package ai.core;
import java.util.Scanner;
/**
 * @description: AI核心代码
 */
public class AiMain {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str;
        while (true) {
            str = scanner.next();
            //输入为中文的字符格式
            str = str.replace("吗", "");
            str = str.replace("?", "!");
            System.out.println(str);
        }
    }
}

image.png

2

清除缓存

alert('缓存已清除');

改进版

<a href="javascript:  setTimeout(function() {  alert('清除成功')  },10000);">清除缓存</a>

将代码在原来的基础的上增加了10秒钟的延迟时间。也就是说当客户点击"清除缓存"链接后,需要等待10秒钟才会给予”“清除成功”的提示。

这样写的好处:

  • 更加真实,毕竟清除缓存也是需要时间的。

  • 如果客户对”清除缓存“的时间无法忍受,有可能会加钱优化!

3

算某个日期是星期几

public int DayOfTheWeek(int day, int month, int year)
{
    int m = month;
    int y = year;
    if (month <= 2)
    {
        m += 12;
        y -= 1;
    }
    int c = y / 100;
    y = y % 100;
    int w = (y + y / 4 + c / 4 - 2 * c + (26 * (m + 1) / 10) + day - 1) % 7;
    return (w + 7) % 7;
}

返回值从 0 ~ 6 分别代表 周日到 周六。代码很简短,但是看懂会很难吧?代码量少、易懂、便于维护,这类代码才是大部分程序认可的好代码。

4

99行代码的《冰雪奇缘》

来自姚班毕业生、MIT博士  @胡渊鸣  同学。

import taichi as ti
quality = 1 # Use a larger value for higher-res simulations
n_particles, n_grid = 9000 * quality ** 2, 128 * quality
dx, inv_dx = 1 / n_grid, float(n_grid)
dt = 1e-4 / quality
p_vol, p_rho = (dx * 0.5)**2, 1
p_mass = p_vol * p_rho
E, nu = 0.1e4, 0.2 # Young's modulus and Poisson's ratio
mu_0, lambda_0 = E / (2 * (1 + nu)), E * nu / ((1+nu) * (1 - 2 * nu)) # Lame parameters

x = ti.Vector(2, dt=ti.f32, shape=n_particles) # position
v = ti.Vector(2, dt=ti.f32, shape=n_particles) # velocity
C = ti.Matrix(2, 2, dt=ti.f32, shape=n_particles) # affine velocity field
F = ti.Matrix(2, 2, dt=ti.f32, shape=n_particles) # deformation gradient
material = ti.var(dt=ti.i32, shape=n_particles) # material id
Jp = ti.var(dt=ti.f32, shape=n_particles) # plastic deformation
grid_v = ti.Vector(2, dt=ti.f32, shape=(n_grid, n_grid)) # grid node momemtum/velocity
grid_m = ti.var(dt=ti.f32, shape=(n_grid, n_grid)) # grid node mass
ti.cfg.arch = ti.cuda # Try to run on GPU

@ti.kernel
def substep():
  for i, j in ti.ndrange(n_grid, n_grid):
    grid_v[i, j] = [0, 0]
    grid_m[i, j] = 0
  for p in range(n_particles): # Particle state update and scatter to grid (P2G)
    base = (x[p] * inv_dx - 0.5).cast(int)
    fx = x[p] * inv_dx - base.cast(float)
    # Quadratic kernels  [http://mpm.graphics   Eqn. 123, with x=fx, fx-1,fx-2]
    w = [0.5 * ti.sqr(1.5 - fx), 0.75 - ti.sqr(fx - 1), 0.5 * ti.sqr(fx - 0.5)]
    F[p] = (ti.Matrix.identity(ti.f32, 2) + dt * C[p]) @ F[p] # deformation gradient update
    h = ti.exp(10 * (1.0 - Jp[p])) # Hardening coefficient: snow gets harder when compressed
    if material[p] == 1: # jelly, make it softer
      h = 0.3
    mu, la = mu_0 * h, lambda_0 * h
    if material[p] == 0: # liquid
      mu = 0.0
    U, sig, V = ti.svd(F[p])
    J = 1.0
    for d in ti.static(range(2)):
      new_sig = sig[d, d]
      if material[p] == 2:  # Snow
        new_sig = min(max(sig[d, d], 1 - 2.5e-2), 1 + 4.5e-3)  # Plasticity
      Jp[p] *= sig[d, d] / new_sig
      sig[d, d] = new_sig
      J *= new_sig
    if material[p] == 0:  # Reset deformation gradient to avoid numerical instability
      F[p] = ti.Matrix.identity(ti.f32, 2) * ti.sqrt(J)
    elif material[p] == 2:
      F[p] = U @ sig @ V.T() # Reconstruct elastic deformation gradient after plasticity
    stress = 2 * mu * (F[p] - U @ V.T()) @ F[p].T() + ti.Matrix.identity(ti.f32, 2) * la * J * (J - 1)
    stress = (-dt * p_vol * 4 * inv_dx * inv_dx) * stress
    affine = stress + p_mass * C[p]
    for i, j in ti.static(ti.ndrange(3, 3)): # Loop over 3x3 grid node neighborhood
      offset = ti.Vector([i, j])
      dpos = (offset.cast(float) - fx) * dx
      weight = w[i][0] * w[j][1]
      grid_v[base + offset] += weight * (p_mass * v[p] + affine @ dpos)
      grid_m[base + offset] += weight * p_mass
  for i, j in ti.ndrange(n_grid, n_grid):
    if grid_m[i, j] > 0: # No need for epsilon here
      grid_v[i, j] = (1 / grid_m[i, j]) * grid_v[i, j] # Momentum to velocity
      grid_v[i, j][1] -= dt * 50 # gravity
      if i < 3 and grid_v[i, j][0] < 0:          grid_v[i, j][0] = 0 # Boundary conditions
      if i > n_grid - 3 and grid_v[i, j][0] > 0: grid_v[i, j][0] = 0
      if j < 3 and grid_v[i, j][1] < 0:          grid_v[i, j][1] = 0
      if j > n_grid - 3 and grid_v[i, j][1] > 0: grid_v[i, j][1] = 0
  for p in range(n_particles): # grid to particle (G2P)
    base = (x[p] * inv_dx - 0.5).cast(int)
    fx = x[p] * inv_dx - base.cast(float)
    w = [0.5 * ti.sqr(1.5 - fx), 0.75 - ti.sqr(fx - 1.0), 0.5 * ti.sqr(fx - 0.5)]
    new_v = ti.Vector.zero(ti.f32, 2)
    new_C = ti.Matrix.zero(ti.f32, 2, 2)
    for i, j in ti.static(ti.ndrange(3, 3)): # loop over 3x3 grid node neighborhood
      dpos = ti.Vector([i, j]).cast(float) - fx
      g_v = grid_v[base + ti.Vector([i, j])]
      weight = w[i][0] * w[j][1]
      new_v += weight * g_v
      new_C += 4 * inv_dx * weight * ti.outer_product(g_v, dpos)
    v[p], C[p] = new_v, new_C
    x[p] += dt * v[p] # advection

import random
group_size = n_particles // 3
for i in range(n_particles):
  x[i] = [random.random() * 0.2 + 0.3 + 0.10 * (i // group_size), random.random() * 0.2 + 0.05 + 0.32 * (i // group_size)]
  material[i] = i // group_size # 0: fluid 1: jelly 2: snow
  v[i] = [0, 0]
  F[i] = [[1, 0], [0, 1]]
  Jp[i] = 1

import numpy as np
gui = ti.GUI("Taichi MLS-MPM-99", res=512, background_color=0x112F41)
for frame in range(20000):
  for s in range(int(2e-3 // dt)):
    substep()
  colors = np.array([0x068587, 0xED553B, 0xEEEEF0], dtype=np.uint32)
  gui.circles(x.to_numpy(), radius=1.5, color=colors[material.to_numpy()])
  gui.show() # Change to gui.show(f'{frame:06d}.png') to write images to disk

原文地址:https://zhuanlan.zhihu.com/p/97700605 

一个简单的物理场景,普通PC仅需几分钟即可渲染完成,相比TensorFlow提速了188倍、比PyTorch快13.4倍,代码长度只有其他底层方法的十分之一。

甚至,Taichi的发明者胡渊鸣同学还为此编写了完整使用教程,网友们在围观之后也纷纷表示:渊鸣大神太强了。

5

经典:各种输出 Hello world牛逼:第一次输出 Hello world

///Lisp - 1958 年
(write-line "Hello, World!")

///BASIC - 1964 年
PRINT "Hello, World!"
END

///Pascal - 1970 年
begin
  writeln ('Hello, World!')
end.

///C - 1972 年
#include <stdio.h>
int main (void) {
  printf ("Hello, World!\n");
  return 0;
}

///SQL - 1978 年
CREATE TABLE message (text char(15));
INSERT INTO message (text) VALUES ('Hello, World!');
SELECT text FROM message;
DROP TABLE message;

///C++ - 1980 年
#include <iostream>
using namespace std;
int main () {
  cout << "Hello, World!" << endl;
  return 0;
}

///MATLAB - 1984 年
disp ('Hello, World!')

/// Objective-C - 1986 年
#import <Foundation/Foundation.h>
int main () {
    @autoreleasepool {
        NSLog (@"Hello, World!");
    }
}

///Python - 1991 年
print ("Hello, World!")

///Visual Basic - 1991 年
Public Sub Main ()
    Debug.Print "Hello, World!"
End Sub

///Ruby - 1995 年
puts 'Hello, World!'

///Java - 1995 年
class HelloWorld {
  public static void main (String[] args) {
    System.out.println ("Hello, World!");
  }
}

/// JavaScript - 1995 年
document.write ('Hello, World!');

/// PHP - 1995 年
<? echo "Hello, World!" ?>

///C# - 2000 年
using System;
internal static class HelloWorld {
  private static void Main () {
    Console.WriteLine ("Hello, World!");
  }
}

///F# - 2005
printfn "Hello, World!"

///Go - 2009 年
package main
import "fmt"
func main () {
  fmt.Println ("Hello, World!")
}

///Rust - 2010
fn main () {
    println ("Hello, World!");
}

///Kotlin - 2011 年
fun main (args: Array<String>) {
    println ("Hello, World!")
}

///TypeScript - 2012 年
console.log ("Hello, World!");

/// Swift - 2014 年
print ("Hello, World!")

6

获取第二天日期

public static Date getNextDay() throws InterruptedException {
        Thread.sleep(24 * 60 * 60 * 1000);
        return new Date();
    }

哼哼,到了下家公司我可学聪明了,坐等老板表扬

 public static Date getNextDay() throws InterruptedException {
        TimeUnit.DAYS.sleep(1);
        return new Date();
    }

7

懂得自然懂,比较经典

int get_root(int x) {
    return x == father[x] ? x : father[x] = get_root(father[x]);
}

8

估计找工作的,都会碰到面试官老是问道“递归算法”,感同身受,前段时间面试了三家,就有一家问道这个问题,算是非常典型的算法吧,和前面的回答比起来确实算不上牛逼。

public int Fibo(int n)
{
    double c = Math.Sqrt(5);
    return (int)((Math.Pow((1 + c) / 2, n) - Math.Pow((1 - c) / 2, n)) / c);
}

如果n再稍微大一点,所消耗的时间是成指数级增长的,比如n=64的时候,所消耗的时间可能是两三年!不信的话,你可以试试!

递归优化我们应该避免无数次重复的计算

为了避免无数次重复,可以从n=1开始往上计算,并把每一个计算出来的数据,用一个数组保存,需要最终值时直接从数组中取即可,算法如下:

public int fib(int n) {
    int[] fib = new int[n];
    fib[0] = 1;
    fib[1] = 1;
    for (int i = 2; i < n; i++) {
        fib[i] = fib[i - 2] + fib[i - 1];
    }
    return fib[n - 1];
}

至于递归优化,这里只是抛砖引玉,如果有兴趣的话,还有3种其他方法的优化。

推荐阅读

原创为什么说程序员做外包没前途?

上班最新全国各地复工、开学时间,人社局细解来了!

法律微信群转发“延期复工通知”,员工遭副总裁谩骂!处理结果来了

抗疫村干部们的智慧...

疫情疫情之下!国内互联网公司上班时间汇总!

转载百度之下,你绝对猜不到的国内第二大搜索引擎

定制武汉加油,中国加油

实践终于知道怎么做微信动态红包

微信后台回复“core”,获取全网最强.NET Core学习资料精选
回复“2019”,获取2019 .NET开发者峰会全部PPT
回复“pdf”,获取程序员必读电子书100+pdf

.NET Core已经崛起

长按关注,刷新认知

dotNet全栈开发

发布了131 篇原创文章 · 获赞 5083 · 访问量 177万+

猜你喜欢

转载自blog.csdn.net/kebi007/article/details/104177865
今日推荐