[go: up one dir, main page]

Przejdź do zawartości

Kody źródłowe/Implementacja NIP

Z Wikibooks, biblioteki wolnych podręczników.

Implementacje algorytmu obliczania cyfry kontrolnej w numerze NIP

Implementacja algorytmu w języku Ruby

class String
    def valid_nip?
        if length === 10 && match(/^\d+$/)
            weights = [6, 5, 7, 2, 3, 4, 5, 6, 7]
            nip = (split //).collect &:to_i
            checksum = weights.inject(0) { |sum, weight| sum + weight * nip.shift }
            return checksum % 11 === nip.shift
        else
            return false
        end
    end
end

Implementacja algorytmu w języku Python

from operator import mul

def validate_nip(nip_str):
  nip_str = nip_str.replace('-', '')
  if len(nip_str) != 10 or not nip_str.isdigit(): 
    return False
  digits = map(int, nip_str)
  weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
  check_sum = sum(map(mul, digits[0:9], weights)) % 11
  return check_sum == digits[9]

Implementacja algorytmu w języku Common Lisp

(defun valid-nip? (nip)
  (when (= (length nip) 10)
    (let ((checksum (loop for w in '(6 5 7 2 3 4 5 6 7)
		 for i across nip
		 sum (* w (digit-char-p i)))))
	 (= (digit-char-p (elt nip 9)) (rem checksum 11)))))

Sprawdzenie:

(valid-nip? "7680002466")
T

Implementacja algorytmu w języku PHP

    function NIPIsValid($pNip) {
	if(!empty($pNip)) {
            $weights = array(6, 5, 7, 2, 3, 4, 5, 6, 7);
            $nip = preg_replace('/[\s-]/', '', $pNip);
            if (strlen($nip) == 10 && is_numeric($nip)) {	 
                $sum = 0;
                for($i = 0; $i < 9; $i++)
                    $sum += $nip[$i] * $weights[$i];
                return ($sum % 11) == $nip[9];
            }
	}
        return false;
    }

Implementacja algorytmu w języku Visual Basic

Function check_nip(ByVal str As String) As Boolean

Dim wagi() As String
Dim NIP As String
Dim sum As Integer
Dim i As Integer

check_nip = False

sum = 0

wagi = Split("6, 5, 7, 2, 3, 4, 5, 6, 7", ",")

NIP = Replace(str, "-", "")

If Len(NIP) = 10 And IsNumeric(NIP) Then 
    i = 0    
    For i = 0 To 8 Step 1    
        sum = sum + (Mid(NIP, i + 1, 1) * CInt(wagi(i)))    
    Next i    
    If sum Mod 11 = Mid(NIP, 10, 1) Then check_nip = True
End If

End Function

Implementacja algorytmu w języku Java

boolean isNIPValid(String nip) {
	if (nip.length() == 13) {
		nip = nip.replaceAll("-", "");
	}
	if (nip.length() != 10) return false;
	int[] weights = {6, 5, 7, 2, 3, 4, 5, 6, 7};
	try {
		int sum = 0;
		for (int i = 0; i < weights.length; i++) {
			sum += Integer.parseInt(nip.substring(i, i + 1)) * weights[i];
		}
		return (sum % 11) == Integer.parseInt(nip.substring(9, 10));
	} catch (NumberFormatException e) {
		return false;
	}		
}

Implementacja algorytmu w języku Scala

def isValidNip(number: String): Boolean = {
	val nip = number.replaceAll("\\D*","")
	if (nip.length() != 10) return false
        val weights: List[Int] = List(6,5,7,2,3,4,5,6,7,0)
	val sum: Int = nip.zipWithIndex.foldLeft(0) { case (partSum, (c, i)) =>
            partSum + c.toString.toInt * weights(i)
        }
        (sum % 11 == nip.substring(9,10).toInt)
}

Implementacja algorytmu w języku JavaScript

function NIPIsValid(nip) {
        var weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
        nip = nip.replace(/[\s-]/g, '');
                   
        if (nip.length == 10 && parseInt(nip, 10) > 0) {
                var sum = 0;
                for(var i = 0; i < 9; i++){
                        sum += nip[i] * weights[i];
                }                     
                return (sum % 11) == nip[9];
        }
        return false;		
}

Implementacja algorytmu w języku C#

    public bool ValidateNip(string nip)
    {
        if (nip.Length != 10)
            return false;
        if (!nip.All(cyfra => cyfra >= '0' && cyfra <= '9'))
            return false;

        int[] wagi = new int[] { 6, 5, 7, 2, 3, 4, 5, 6, 7, 0 };
        int suma = nip.Zip(wagi, (cyfra, waga) => (cyfra - '0') * waga)
                      .Sum();

        return (suma % 11) == (nip[9] - '0');
    }

Implementacja algorytmu w języku Perl

sub nip_check {
        my @weights=qw/6 5 7 2 3 4 5 6 7/;
        my $my_sum;
        my $nip=shift;
        #remove hypens
        $nip=~s/-//g;
        unless($nip=~m/^\d{10}$/){
                print  "NIP must be ten digits length string with/without hypens\n";
                return 0;
        }
        ($nip,my $their_sum)=$nip=~m/(\d{1,9})/g;
        my @nip=split(//,$nip);
        $_*=shift(@weights) for(@nip);
        $my_sum+=$_ for(@nip);
        $my_sum%=11;
        return 1 if($my_sum==$their_sum);
}

Implementacja algorytmu w języku Bash

function check_nip {
        weights="657234567"
        nip=$1
        #remove hypens
        nip=${nip//-/}
        if [[! $nip =~ ^[0-9]{10,10}$]] ; then
                echo "NIP must be ten digits lenght string with/without hypens"
                return 1
        fi
        their_sum=${nip:$((-1))}
        nip=${nip:0:9}
        while ([ ! -z  $nip ]) ; do
                my_sum=$((my_sum + ${nip:0:1} * ${weights:0:1} ))
                nip=${nip#?}
                weights=${weights#?}
        done
        my_sum=$((my_sum % 11))
        if [ $my_sum -eq $their_sum ] ; then
                return 0
        else
                return 1
        fi
}

Implementacja algorytmu w języku PL/SQL

  function getNIP return varchar2 is
    a number := 0;
    b number := 0;
    TYPE array_t IS TABLE OF number;
    c array_t;
    e array_t;
    d varchar2(100);
  
    function getDigit return number is
    begin
      return substr(dbms_random.value(1, 10), 0, 1);
    end;
    
    function getDigitNZ return number is
      a number := 0;
    begin
      WHILE (a = 0) LOOP
        a := getDigit();
      END LOOP;
    
      return a;
    End;
  
  begin
    c := array_t(6, 5, 7, 2, 3, 4, 5, 6, 7);
    LOOP
      a := 0;
      e := array_t(getDigitNZ(),
                   getDigitNZ(),
                   getDigitNZ(),
                   getDigit(),
                   getDigit(),
                   getDigit(),
                   getDigit(),
                   getDigit(),
                   getDigit());
      FOR b IN 1 .. e.last() LOOP
        a := (c(b) * e(b)) + a;
      END LOOP;
      a := MOD(a, 11);
      EXIT WHEN a <> 10;
    END LOOP;
  
    d := '';
    FOR b IN 1 .. e.last() LOOP
      d := d || to_char(e(b));
    END LOOP;
    d := d || to_char(a);
  
    return d;
  end;