PESEL checksum validation(Javascript/HTML) - javascript

Im a student currently studying from home and im seriously stuck on a Checksum problem. The script is supposed to validate the PESEL(Polish equivilant of a social security number i think), Anyway the checksum works as follows for
PESEL: 70051012347
PESEL:7,0,0,5,1,0,1,2,3,4 (7)
(Multiply each Pesel number by its corresponding check number)
CHECK:1,3,7,9,1,3,7,9,1,3
(Sum Each number)
SUM: + 7,0,0,45,1,0,7,18,3,12 =93
MOD: 93 MOD 10 = 3
10 - 3 = 7(last digit of pesel)
Where the MOD 10 doesn't equal 0, the result of sum%10 is subtracted from 10 and then matched with the final digit in the original number, if they match its good, if not its bad. All i need to have is a good or bad result.
I'm pretty sure I have all of this fine in my code and there's a simple solution i just cant see it. Any help at all would be massively appreciated.
<html>
<head>
<meta charset="utf-8">
<title>Pesel Checker</title>
<script type="text/javascript">
function peselgood(y)
{
//sample PESEL's
//type 1
//70051012347
//02070803628
//07020803628
//type 2
//83102570819
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//hold original number
var a = parseInt(y);
//First 10 digits without check number and convert to array
y = y.substring(0,9);
y = parseInt(y);
var arr1 = new Array(10);
arr1 = y;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * arr1[i];
}
sum = sum%10;
if (sum !== 0)
{
sum = 10-sum;
if(sum != a[10])
{
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
function checkpesel()
{
num = document.getElementById("peselfield").value
if (peselgood(num))
{
document.getElementById("peselfield").style.background="#00ff00";
}
else
{
document.getElementById("peselfield").style.background="#ff6666";
}
}
</script>
</head>
<body>
<div>
Check Sum Template
<br/><br/>
<form name="form">
PESEL:
<input type="text" id="peselfield" value="70051012347" /> <button type="button" onclick="checkpesel()">Check</button>
<br/><br/>
</form>
</div>
<br/><br/>
</body>
</html>

You have made a couple of mistakes. If you step through your code using a JavaScript debugger, you will find out exactly what goes wrong. The most important fact is, that you don't have to convert a string to an array of integers. JavaScript automatically understands when to convert a character to an integer.
This is my solution:
function peselgood(y)
{
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * y[i];
}
sum = sum%10 == 0 ? 0 : 10-sum%10;
return sum == y[10];
}
else
{
return false;
}
}

function checksum(p) { let i, s = +p[ i = 10 ]; while( i-- ) s += "1379"[ i % 4 ] * p[i]; return ! ( s % 10 ); }
<input id="pesel" placeholder="PESEL" autofocus>
<input type="button" value="check" onclick="alert( checksum(pesel.value) ? 'Ok' : 'Bad' )">

Related

Calculate the sum of all even numbers between n and m [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I need to calculate numbers between n and m, but something goes wrong and I don't know what..
function even(){
var n = document.getElementById("n").value;
var m = document.getElementById("m").value;
var s = 0 ;
if(n<m){
i = n;
while(i<=n){
n*(n+2)/4;
i++;
alert(n.value)
}
}else if(n>m);{
i=m;
S=n*(n+2)/4;
i++
alert(m.value)
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
Unless you are specifically told to use a loop you should use the formula for sum of arithmetic progression.
function even() {
let n1 = Number(document.getElementById("n").value);
let n2 = Number(document.getElementById("m").value);
if (n1 > n2) [n1,n2] = [n2,n1];
n1 = 2*Math.ceil(n1/2);
n2 = 2*Math.floor(n2/2);
if (n1 > n2) return 0;
return (n1 + n2) * ((n2 - n1) / 2 + 1) / 2;
}
<input type="text" id="n" > <br><br>
<input type="text" id="m" > <br><br>
<button onclick="alert(even())">Click me !</button>
Even if you use a loop you should consider making number even first and then increment loop variable by 2 every time instead of checking parity on each iteration.
You were trying to calculate the sum, however, in your while loop, you were not adding it to the sum and trying to alert n.value or m.value which will be undefined here as there is no value property.
You can define a logic for the same (AP) rather than looping
function even(){
// convert the values to numbers otherwise it will be strings
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
if (n > m) [n, m] = [m, n]; // store smaller number in n
n = (n%2 === 0) ? n: n+1; // find the first even number
m = (m%2 === 0) ? m: m-1; // find the last even number
var s = 0; // initialize sum to 0
if(m >= n) {
var numbers = (m-n)/2 + 1; // number of even numbers in the range
/* Understanding the formula. It is a basic airthmetic series of n
* numbers, with first number being a, last number being l
* which is equal to (a + (n-1)d) where difference
* being d. The sum will be n/2(a+l) => n/2(a + a + (n-1)d)
* => n/2(2a + (n-1)d). With our d being 2, equation becomes
* n/2(2a +(n-1)2) => n(a + n -1). */
s = numbers*(n + numbers-1);
}
alert(s);
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
Or you can update your code to following
function even(){
// convert the values to numbers otherwise it will be strings
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0 ;
var i;
// Iterate over the numbers and check if it is divisible by 2 if yes then add it to the sum and finally alert the sum
if(n<m){
i = n;
while(i<=m){
if(i%2 === 0) s += i;
i++;
}
alert(s);
}else if(n>m) {
i=m;
while(i<=n){
if(i%2 === 0) s += i;
i++;
}
alert(s);
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
To perform calculations only for even numbers, you need to find the remainder of the division. The remainder of the division must be zero
let a = 2;
let b = 10;
for(let i = a; i <= b; i++){
if (i%2 === 0){
// do something here even numbers
}
}
Try this:
if (n < m) {
for (let i = n; i <= m; i++) {
if (i%2 === 0)
s += i;
}
} else {
for (let i = m; i <= n; i++) {
if (i%2 === 0)
s += i;
}
}
The line if (s%2 === 0) is key to this because it will only add the numbers in the range which have a 0 remainder when divided by 2 (are even).
I've also converted the while loops you had into for loops because they are cleaner and easier to read.
You could also attempt to use ternary operators to quickly set-up lower and upper variables if you want to eliminate the need for the outer if-else statements.
I have taken the numbers as 10 and 3 and I am not considering both the numbers in loop because you have asked for sum of even numbers between these two.I have taken sum as 0.I have found the highest and lowest number using Ternary operator.using for loop i have found the Even integers and added them.
var x=10;
var y=3;
var higher=x>y?x:y;
var lower=x>y?y:x;
var sum=0;
for(var i=lower+1;i<higher;i++){
if(i%2==0){
sum+=i;
}
}
console.log("sum is"+sum)

Printing the next 10 even and odd numbers ( java-script)

1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
i am newbie to programming and trying to learn java-script myself, the above is the question i am trying to solve. i am confused, i am not sure how to make the code to write the next 10 odd even number (i am referring to the first question).also the previous 5 (referring to second question).. below is my starting attempt. i am stuck
function isEven {
var value = prompt("");
if (value % 2 == 0) {
for (var i = 2; i <= ; i = i + 2;)
document.write(i + "<br>");
}
}
isEven();
Answer 1:
if(number>=0){
for(i=2;i<21;i+=2){
console.log(number+i);
}
}
Answer 2:
for(i=2;i<11;i+=2){
if((number-i)>=0){
console.log(number-i);
}
}
1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
function function1() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.write(value + "<br>");
}
}
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
function function2() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 5; i = i + 1){
value = value - 2;
document.write(value + "<br>");
}
}
Just to clarify. You want to print both the previous 5 numbers and next 10 numbers of same 'evenness' for any given number?
In which case, you should do just that... You dont need to care if the number is even or odd, because the next/previous is always 2 away. (What you do when you cross 0 is up to you)
for (var i = 1; i <= 5; i++)
document.write((INPUT - (i*2)) + "<br>");
for (var i = 1; i <= 10; i++)
document.write((INPUT + (i*2)) + "<br>");
refer this woking demo. hope this will help to you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
Enter a number : <input type="number" id="num">
<button id="butp" class="chk">print previous five numbers</button>
|| <button id="butn" class="chk">print next ten numbers</button>
<ul id="print">
</ul>
<script type="text/javascript">
$(".chk").click(function(){
var the_id = $(this).attr('id');
//alert(the_id);
var theVal = parseInt($("#num").val());
if (the_id =="butp") //this means user asking for previous
{
if (theVal==0 || theVal < 10)
{
alert("cannot continue the operation, please enter a valid nubmer to continue");
}
else
{
for (var i=1;i<6;i++)
{
newVal = theVal - (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
else // this means user asking for next
{
for (var i = 1;i<11;i++)
{
if (theVal==0)
{
alert("please enter a valid number to continue");
}
else
{
newVal = theVal + (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
});
$("#num").on('change keyup keydown', function(){
theVal = $(this).val();
if (theVal == "")
{
$("#print li").css({"display":"none"})
}
})
</script>
</body>
</html>
function evenOdd(value) {
if(value%2==0){
console.log(`it's and even number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}else{
console.log(`it's and odd number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}
}
evenOdd(13)

Sum all the digits of a number Javascript

I am newbie.
I want to make small app which will calculate the sum of all the digits of a number.
For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .
Please help me
Basically you have two methods to get the sum of all parts of an integer number.
With numerical operations
Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.
var value = 2568,
sum = 0;
while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}
console.log(sum);
Use string operations
Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.
var value = 2568,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
console.log(sum);
For returning the value, you need to addres the value property.
rezultat.value = sum;
// ^^^^^^
function sumDigits() {
var value = document.getElementById("thenumber").value,
sum = 0;
while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}
var rezultat = document.getElementById("result");
rezultat.value = sum;
}
<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>
How about this simple approach using modulo 9 arithmetic?
function sumDigits(n) {
return (n - 1) % 9 + 1;
}
With mathy formula:
function sumDigits(n) {
return (--n % 9) + 1;
}
Without mathy formula:
function sumDigits(n) {
if (typeof n !== 'string') {
n = n.toString();
}
if (n.length < 2) {
return parseInt(n);
}
​
return sumDigits(
n.split('')
.reduce((acc, num) => acc += parseInt(num), 0)
);
}
let's try recursivity
function sumDigits(n) {
if (n < 10) return n
return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
}
sumDigits(2) // 2
sumDigits(2568) // 3
The sum of digits can be calculated using that function (based on other answers):
function sumDigits(n) {
let sum = 0;
while (n) {
digit = n % 10;
sum += digit;
n = (n - digit) / 10;
}
return sum;
}
If you really need to sum the digits recursively there is recursive version of the function:
function sumDigitsRecursively(n) {
let sum = sumDigits(n);
if (sum < 10)
return sum;
else
return sumDigitsRecursively(sum);
}
The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.
Note that recursive solution by #FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.
You could do it this way.
function sums(input) {
let numArr = input.toString().split('');
let sum = numArr.reduce((a, b) => Number(a) + Number(b));
return sum < 10 ? sum : sums(sum);
}
Expanding upon #fethe 's answer, this sumOfDigit function is able to handle large number or BigInt
function sumOfDigits(n) {
return (Number.isSafeInteger(n)) ? (--n % 9) + 1 : Number((--n % 9n) + 1n);
}
console.log(sumOfDigits(101)); // 2
console.log(sumOfDigits(84932)); // 8
console.log(sumOfDigits(900000000000000000000000009n)); // 9
you can use this function and pass your number to it:
const solution = (n) => {
const arr = `${n}`
let sum = 0;
for (let index = 0; index < arr.length; index++) {
sum += parseInt(arr[index])
}
return sum;
}

Double Maths Random in Array with Javascript

I need your help because I'm totally lost with a javascript exercise (I learn alone).
I cut the exercice in steps
I generate an aleatory number between 3 and 20 (with Maths Random)
I generate an array of 100 cells: In each cells, there is one " _ "
If the number is 5: 5 " _ " is aleatory replaced by a " # " (second Maths Random)
I think my cut is good but I can't write it in code.
Before this exercise I've done exercises easier with maths random but now it's more diffult for me.
Some can help me to create the code?
Thank you very much
edit: I tried to do something but without maths random.
function hashtagLine(){
var number = prompt( "Saisissez un nombre entre 3 et 10" );
var line = "";
if (number >= 1 && number <= 10){
for ( var i = 1; i <= 100; i++ ) {
if ( i % number === 0 ) {
line += "#";
} else {
line += "_";
}
}
console.log( line );
} else {
alert( "vous avez entré un nombre qui ne correspond pas" );
}
}
hashtagLine();
Here is a simple implementation:
HTML
<table id="table"></table>
JS
var t = document.getElementById('table');
var rnd = Math.ceil(Math.random() * 17 + 3);
var string = '<tr>';
for (var i = 1; i <= 100; i++) {
if (i == rnd) {
string += '<td>#</td>';
} else {
string += '<td>_</td>';
}
// for new row...
if (i % 10 == 0) {
string += '</tr><tr>';
}
}
string += '</tr>';
t.innerHTML = string;
But if you're trying to learn the language, it's best to try yourself, not just have somebody hand you the answer.
It is still not clear to me what you are trying to achieve, but here is some code that may help you. If you come back with more information then I may be able to help you some more.
Math.random
// get reference to out output element
var pre = document.getElementById('out');
// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function hashtagLine() {
var min = 3,
max = 20,
cells = 100,
number = getRandomInt(min, max + 1),
line = [],
index;
// create the line array of length cells
for (index = 0; index < cells; index += 1) {
// unclear what you are trying to do here!
if (index % number === 0) {
line.push('#');
} else {
line.push('_');
}
}
// output the array as a line of text
pre.textContent += line.join('') + '\n';
}
// Add a click event listener to our generate button
document.getElementById('generate').addEventListener('click', hashtagLine, false);
<button id="generate">Generate</button>
<pre id="out"></pre>

javascript splitting a var that is numbers and letters

I'd prefer to not use regex, but if needed, so be it.
I have some code and I want to take a user's input and check to make sure that it is an isbn 10. In other words it must be a 10 digit number or a 9 digit number with an x at the end (the x represents the number 10). For my purposes, I'd like to turn the users input into an array of each digit. If there is an x I'd like to change that into a 10. I am having trouble doing this! I have seen other questions that are somewhat similar and they all use regex. Like I said, I'd prefer to not use regex, but if need be...
<h1>Problem #3:</h1>
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script src="js/jquery-2.0.3.min.js"></script>
<script>
$( document ).ready(function() {
alert("Welcome to ISBN Validator!");
//Add the event listener for the validate button here
//Look at toggling the CSS display property based on the result
$("#button").click(function(){
checker(document.form.isbn.value);
});
});
var checker = function(isbn){
isbn = isbn.toString().split('');
if (isbn[9] == 'x'|| isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else{
var sum = 0;
for (var x=10; x>0; x--){
sum += x*isbn[10-x];
}
alert("FINAL!!" + sum%11);
}
}
Input: 0375726721
Output: FINAL!!0
:Works
Input:067978330X
Expected Output: FINAL!!0
Actual Output: Invalid ISBN!0
:Does not work!
var isbn = '074759582x';
if (!/^\d{9}(\d|x)$/i.test(isbn)) // validation with regexp
alert('Invalid ISBN');
else {
var arr = isbn.split('');
arr[9] = arr[9].toLowerCase() == 'x' ? 10 : arr[9]; // replacement of x by 10
// below is your summation, just performed in another way.
var total = arr.map(function(el, index, arr) {
return (index + 1) * arr[10 - index - 1];
}).reduce(function(a, b) {return a + b;});
alert(total % 11);
}
Done
var isbn = '074759582x';
Split the string into characters using split. Apply map to grab the x and convert it to 10 if necessary. Then map each character to a number
array = isbn
.split('')
.map(function(char, i) {
return i === 9 && char.toLowerCase() === 'x' ? 10 : char;
})
.map(Number)
;
The ISBN is valid if it's of length 10, and there are no NaNs in it.
valid = array.length === 10 && !array.some(isNaN);
Checksum uses reduce, as in another answer:
sum = array.reduce(function(result, v, i) {
return result + (10-i) * v;
}, 0) % 11;
Problem #3:
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" onclick = "checker()" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script>
function checker () {
isbn = document.form.isbn.value;
isbn = isbn.toString().split('');
if (isbn[9] == 'x' || isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else {
var sum = 0;
for (var x = 10; x > 0; x--) {
sum += x * isbn[10 - x];
}
alert("FINAL!!" + sum % 11);
}
}
</script>

Categories