I need to convert amount in words. For example, the amount I will get it from service is 9876, I need to display in a table "Nine Thousand Eight Hundred and Seventy Six" in a table.
I need to do this using angularjs. Please help me how can I do this.
JSFIDDLE
function convertNumberToWords(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
}
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=convertNumberToWords(this.value)" />
<div id="word"></div>
I refered this javascript fiddle. But I want to it in a angularjs.
I used this for Angular 8.
Input : 123456789.09 Output : twelve crore thirty four lakh fifty six thousand seven eighty nine point zero nine
n: string;
a = ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
ngOnInit(): void {
console.log(this.inWords(123456789.09));
}
inWords (num): string {
num = Math.floor(num * 100);
if ((num = num.toString()).length > 11) { return 'overflow'; }
let n;
n = ('00000000' + num).substr(-11).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})(\d{1})(\d{1})$/);
if (!n) { return; } let str = '';
// tslint:disable-next-line:triple-equals
str += (n[1] != 0) ? (this.a[Number(n[1])] || this.b[n[1][0]] + ' ' + this.a[n[1][1]]) + 'crore ' : '';
// tslint:disable-next-line:triple-equals
str += (n[2] != 0) ? (this.a[Number(n[2])] || this.b[n[2][0]] + ' ' + this.a[n[2][1]]) + 'lakh ' : '';
// tslint:disable-next-line:triple-equals
str += (n[3] != 0) ? (this.a[Number(n[3])] || this.b[n[3][0]] + ' ' + this.a[n[3][1]]) + 'thousand ' : '';
// tslint:disable-next-line:triple-equals
str += (n[4] != 0) ? (this.a[Number(n[4])] || this.b[n[4][0]] + ' ' + this.a[n[4][1]]) : 'hundred';
// tslint:disable-next-line:triple-equals
str += (n[5]) ? (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' + this.a[n[5][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[6]) ? ((str != '') ? 'point ' : '') + (this.a[Number(n[6])] || this.b[n[6][0]] + ' ' + this.a[n[6][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[7] != 0) ? (this.a[Number(n[7])] || this.b[n[7][0]] + ' ' + this.a[n[7][1]]) : '';
return str;
}
Define a filter to convert number to word such as following code:
angular.module('myModuleName')
.filter('convertToWord', function() {
return function(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
};
});
Then in your templates (views) use this filter as follow:
{{amount | converToWord}}
For example to show inserted value in an input field:
<input type="text" name="number" placeholder="Number OR Amount" ng-model="myValue" />
<div id="word">{{myValue | convertToWord}}</div>
Related
I really love this pen https://codepen.io/himalayasingh/pen/QZKqOX and have been having lots of fun tinkering around with this audio player, but I can't for the life of me seem to get it to loop through the playlist properly. after every track the audio stops, I've been able to get the selected track to loop but not loop through the entire playlist. any insight?
$(function()
{
var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, albumName = $('#album-name'), trackName = $('#track-name'), albumArt = $('#album-art'), sArea = $('#s-area'), seekBar = $('#seek-bar'), trackTime = $('#track-time'), insTime = $('#ins-time'), sHover = $('#s-hover'), playPauseButton = $("#play-pause-button"), i = playPauseButton.find('i'), tProgress = $('#current-time'), tTime = $('#track-length'), seekT, seekLoc, seekBarPos, cM, ctMinutes, ctSeconds, curMinutes, curSeconds, durMinutes, durSeconds, playProgress, bTime, nTime = 0, buffInterval = null, tFlag = false, albums = ['Dawn','Me & You','Electro Boy','Home','Proxy (Original Mix)'], trackNames = ['Skylike - Dawn','Alex Skrindo - Me & You','Kaaze - Electro Boy','Jordan Schor - Home','Martin Garrix - Proxy'], albumArtworks = ['_1','_2','_3','_4','_5'], trackUrl = ['https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/2.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/1.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/3.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/4.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/5.mp3'], playPreviousTrackButton = $('#play-previous'), playNextTrackButton = $('#play-next'), currIndex = -1;
function playPause()
{
setTimeout(function()
{
if(audio.paused)
{
playerTrack.addClass('active');
albumArt.addClass('active');
checkBuffering();
i.attr('class','fas fa-pause');
audio.play();
}
else
{
playerTrack.removeClass('active');
albumArt.removeClass('active');
clearInterval(buffInterval);
albumArt.removeClass('buffering');
i.attr('class','fas fa-play');
audio.pause();
}
},300);
}
function showHover(event)
{
seekBarPos = sArea.offset();
seekT = event.clientX - seekBarPos.left;
seekLoc = audio.duration * (seekT / sArea.outerWidth());
sHover.width(seekT);
cM = seekLoc / 60;
ctMinutes = Math.floor(cM);
ctSeconds = Math.floor(seekLoc - ctMinutes * 60);
if( (ctMinutes < 0) || (ctSeconds < 0) )
return;
if( (ctMinutes < 0) || (ctSeconds < 0) )
return;
if(ctMinutes < 10)
ctMinutes = '0'+ctMinutes;
if(ctSeconds < 10)
ctSeconds = '0'+ctSeconds;
if( isNaN(ctMinutes) || isNaN(ctSeconds) )
insTime.text('--:--');
else
insTime.text(ctMinutes+':'+ctSeconds);
insTime.css({'left':seekT,'margin-left':'-21px'}).fadeIn(0);
}
function hideHover()
{
sHover.width(0);
insTime.text('00:00').css({'left':'0px','margin-left':'0px'}).fadeOut(0);
}
function playFromClickedPos()
{
audio.currentTime = seekLoc;
seekBar.width(seekT);
hideHover();
}
function updateCurrTime()
{
nTime = new Date();
nTime = nTime.getTime();
if( !tFlag )
{
tFlag = true;
trackTime.addClass('active');
}
curMinutes = Math.floor(audio.currentTime / 60);
curSeconds = Math.floor(audio.currentTime - curMinutes * 60);
durMinutes = Math.floor(audio.duration / 60);
durSeconds = Math.floor(audio.duration - durMinutes * 60);
playProgress = (audio.currentTime / audio.duration) * 100;
if(curMinutes < 10)
curMinutes = '0'+curMinutes;
if(curSeconds < 10)
curSeconds = '0'+curSeconds;
if(durMinutes < 10)
durMinutes = '0'+durMinutes;
if(durSeconds < 10)
durSeconds = '0'+durSeconds;
if( isNaN(curMinutes) || isNaN(curSeconds) )
tProgress.text('00:00');
else
tProgress.text(curMinutes+':'+curSeconds);
if( isNaN(durMinutes) || isNaN(durSeconds) )
tTime.text('00:00');
else
tTime.text(durMinutes+':'+durSeconds);
if( isNaN(curMinutes) || isNaN(curSeconds) || isNaN(durMinutes) || isNaN(durSeconds) )
trackTime.removeClass('active');
else
trackTime.addClass('active');
seekBar.width(playProgress+'%');
if( playProgress == 100 )
{
i.attr('class','fa fa-play');
seekBar.width(0);
tProgress.text('00:00');
albumArt.removeClass('buffering').removeClass('active');
clearInterval(buffInterval);
}
}
function checkBuffering()
{
clearInterval(buffInterval);
buffInterval = setInterval(function()
{
if( (nTime == 0) || (bTime - nTime) > 1000 )
albumArt.addClass('buffering');
else
albumArt.removeClass('buffering');
bTime = new Date();
bTime = bTime.getTime();
},100);
}
function selectTrack(flag)
{
if( flag == 0 || flag == 1 )
++currIndex;
else
--currIndex;
if( (currIndex > -1) && (currIndex < albumArtworks.length) )
{
if( flag == 0 )
i.attr('class','fa fa-play');
else
{
albumArt.removeClass('buffering');
i.attr('class','fa fa-pause');
}
seekBar.width(0);
trackTime.removeClass('active');
tProgress.text('00:00');
tTime.text('00:00');
currAlbum = albums[currIndex];
currTrackName = trackNames[currIndex];
currArtwork = albumArtworks[currIndex];
audio.src = trackUrl[currIndex];
nTime = 0;
bTime = new Date();
bTime = bTime.getTime();
if(flag != 0)
{
audio.play();
playerTrack.addClass('active');
albumArt.addClass('active');
clearInterval(buffInterval);
checkBuffering();
}
albumName.text(currAlbum);
trackName.text(currTrackName);
albumArt.find('img.active').removeClass('active');
$('#'+currArtwork).addClass('active');
bgArtworkUrl = $('#'+currArtwork).attr('src');
bgArtwork.css({'background-image':'url('+bgArtworkUrl+')'});
}
else
{
if( flag == 0 || flag == 1 )
--currIndex;
else
++currIndex;
}
}
function initPlayer()
{
audio = new Audio();
selectTrack(0);
audio.loop = false;
playPauseButton.on('click',playPause);
sArea.mousemove(function(event){ showHover(event); });
sArea.mouseout(hideHover);
sArea.on('click',playFromClickedPos);
$(audio).on('timeupdate',updateCurrTime);
playPreviousTrackButton.on('click',function(){ selectTrack(-1);} );
playNextTrackButton.on('click',function(){ selectTrack(1);});
}
initPlayer();
});
I want to convert number into words. Like 234 in word would be 2 hundred thirty-four. Similarly 1000 will be one thousand. Similarly 100 means one hundred.
Is there any library for this in angularjs. If then how we will write in angularjs directive/service so that we can use it again..
Create a words filter.
I got the "toWords" algorithm from this blog post: http://ravindersinghdang.blogspot.com/2013/04/convert-numbers-into-words-using.html
var app = angular.module('app',[]);
app.filter('words', function() {
function isInteger(x) {
return x % 1 === 0;
}
return function(value) {
if (value && isInteger(value))
return toWords(value);
return value;
};
});
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s)
{
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++)
{
if ((x-i)%3==2)
{
if (n[i] == '1')
{
str += tn[Number(n[i+1])] + ' ';
i++;
sk=1;
}
else if (n[i]!=0)
{
str += tw[n[i]-2] + ' ';
sk=1;
}
}
else if (n[i]!=0)
{
str += dg[n[i]] +' ';
if ((x-i)%3==0) str += 'hundred ';
sk=1;
}
if ((x-i)%3==1)
{
if (sk) str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
if (x != s.length)
{
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
window.toWords = toWords;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="app">
<input type="text" ng-model="name" /> {{name | words}}
</div>
I have done this for Angular 8.
It also works for float/double numbers.
I am making a maze using Depth-First search algorithm as a school project. The maze is working pretty much as I want but I have a little problem. I have to use # as a wall and . as a path when printing the maze but I used 0 as a wall and 1 as a path at first thinking that it is gonna be easy to change it later but I was wrong. How can I change 0 and 1 into # and .?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void nahodne_suradnice(int *r, int *s, int n)
{
srand(time(NULL));
*r = ((rand() % n) - 1) + 2;
if (*r == 1 || *r == n)
{
*s = (rand() % n) + 2;
}
else
{
if (rand() % 2 == 1)
*s = 1;
else
*s = n;
}
}
int main()
{
int i, j, n, r, s,smer,posledny_smer[1500];
int maze[500][500];
scanf_s("%d", &n);
if (n < 10 || n > 100)
{
return 0;
}
//vynulovanie pola/bludiska
for (i = 1; i < n + 1; i++)
{
for (j = 1; j < n + 1; j++)
{
maze[i][j] = 0;
}
}
//nahodny vyber zaciatku bludiska
nahodne_suradnice(&r, &s, n);
//generovanie bludiska
j = 0;
maze[r][s] = 2;
for (i = 0 ;; i++)
{
//backtracking
if ((maze[r - 1][s] == 1 || maze[r - 2][s] == 1 || r - 2 <=1 || s==n || s==1) && (maze[r][s + 1] == 1 || maze[r][s + 2] == 1 || s + 2 >= n || r == n || r==1) && (maze[r + 1][s] == 1 || maze[r + 2][s] == 1 || r + 2 >= n || s == n || s==1) && (maze[r][s - 1] == 1 || maze[r][s - 2] == 1 || s - 2 <=1 || r == n || r==1))
{
if (posledny_smer[j-1] == 1)
if (maze[r + 1][s] == 1 && maze[r + 2][s] == 1)
{
r += 2;
j--;
continue;
}
else
{
j--;
continue;
}
if (posledny_smer[j-1] == 2)
if (maze[r][s - 1] == 1 && maze[r][s - 2] == 1)
{
s -= 2;
j--;
continue;
}
else
{
j--;
continue;
}
if (posledny_smer[j-1] == 3)
if (maze[r - 1][s] == 1 && maze[r - 2][s] == 1)
{
r -= 2;
j--;
continue;
}
else
{
j--;
continue;
}
if (posledny_smer[j-1] == 4)
if (maze[r][s + 1] == 1 && maze[r][s + 2] == 1)
{
s += 2;
j--;
continue;
}
else
{
j--;
continue;
}
if (j == 0)
{
if (r == n)
{
nahodne_suradnice(&r, &s,n);
maze[1][s] = 3;
maze[2][s] = 3;
}
if (r == 1)
{
nahodne_suradnice(&r, &s, n);
maze[n][s] = 3;
maze[n - 1][s] = 3;
}
if (s == n-2)
{
nahodne_suradnice(&r, &s, n);
maze[r][1] = 3;
maze[r][2] = 3;
}
if (s == 3)
{
nahodne_suradnice(&r, &s, n);
maze[r][n] = 3;
maze[r][n-1] = 3;
}
break;
}
}
//buranie stien
smer = (rand() % 4) + 1;
if (smer == 1)
{
if (r - 2 >1 && s<n && s>1)
{
if (maze[r - 1][s] == 1 || maze[r - 2][s] == 1)
continue;
maze[r - 1][s] = 1;
maze[r - 2][s] = 1;
r -= 2;
posledny_smer[j] = smer;
j++;
continue;
}
}
if (smer == 2)
{
if (s + 2 < n && r < n && r>1)
{
if (maze[r][s+1] == 1 || maze[r][s+2] == 1)
continue;
maze[r][s + 1] = 1;
maze[r][s + 2] = 1;
s += 2;
posledny_smer[j] = smer;
j++;
continue;
}
}
if (smer == 3)
{
if (r + 2 < n && s < n && s>1)
{
if (maze[r + 1][s] == 1 || maze[r + 2][s] == 1)
continue;
maze[r + 1][s] = 1;
maze[r + 2][s] = 1;
r += 2;
posledny_smer[j] = smer;
j++;
continue;
}
}
if (smer == 4)
{
if (s - 2 >1 && r < n && r>1)
{
if (maze[r][s-1] == 1 || maze[r][s-2] == 1)
continue;
maze[r][s - 1] = 1;
maze[r][s - 2] = 1;
s -= 2;
posledny_smer[j] = smer;
j++;
continue;
}
}
}
//vypis bludiska
for (i = 1; i < n + 1; i++)
{
for (j = 1; j < n + 1; j++)
{
printf("%d", maze[i][j]);
}
printf("\n");
}
system("PAUSE");
return 0;
}
`
Thanks.
Change the definition of maze to:
char maze[500][500]
and change all references to use char instead of int. Then return '#' and '.' instead of 0 and 1.
You can change from 0 and 1 to # and . (or any other representation) when printing. For instance you can change:
printf("%d", maze[i][j]);
to
switch(maze[i][j]) {
case 0:
printf("#");
break;
case 1:
printf(".");
break;
default:
printf("X"); /* in case you have some value other than 0 or 1 in the maze */
}
If you do it like this, you can change which letters you want to display the maze as without changing other parts of your code.
So I'm I've been working with C for the very first time, and I think I'm having trouble using recursion. For instance, to return a value for a recursive call in C#, I might use return methodRecursiveCall(parameter). In C, I have this statement, which is a part of a roman numeral converter:
int convert(char *s)
{
int val = 0;
int index = 0;
int length = strlen(s);
while (length >1)
{
if (s[index] == 'I')
{
if(s[index + 1] == 'V' || s[index + 1] == 'X' || s[index + 1] == 'C' || s[index + 1] == 'D' || s[index + 1] == 'M')
{
val--;
index++;
length--;
convert(&(s[index]));
}
else
{
val++;
index++;
length--;
convert(&(s[index]));
}
}
if (s[index] == 'V')
{
if(s[index + 1] == 'X' || s[index + 1] == 'C' || s[index + 1] == 'D' || s[index + 1] == 'M')
{
val = val - 5;
index++;
length--;
convert(&(s[index]));
}
else
{
val = val + 5;
index++;
length--;
convert(&(s[index]));
}
}
if (s[index] == 'X')
{
if(s[index + 1] == 'C' || s[index + 1] == 'D' || s[index + 1] == 'M')
{
val = val - 10;
index++;
length--;
convert(&(s[index]));
}
else
{
val = val + 10;
index++;
length--;
convert(&(s[index]));
}
}
if (s[index] == 'C')
{
if((s[index + 1]) == 'D' || (s[index + 1]) == 'M')
{
val = val - 100;
index++;
length--;
convert(&(s[index]));
}
else
{
val = val + 100;
index++;
length--;
convert(&(s[index]));
}
}
if (s[index] == 'D')
{
if(s[index + 1] == 'M')
{
val = val - 500;
index++;
length--;
convert(&(s[index]));
}
else
{
val = val + 500;
index++;
length--;
convert(&(s[index]));
}
}
if (s[index] == 'M')
{
val = val + 500;
index++;
length--;
convert(&(s[index]));
}
}
return val;
}
My question specifically is about the convert(&(s[index]));, which is meant to be a recursive call. It is meant to convert an entire Roman numeral to decimal, however it only converts the first character. That is normally where I would put a 'return'. I'm not sure how to pull this off in C, however.
For this fragment from near the end:
if (s[index] == 'M')
{
val = val + 500;
index++;
length--;
convert(&(s[index]));
}
You probably want something like:
if (s[index] == 'M')
val = 1000 + convert(&s[index+1]);
You know that the M maps to 1,000; the total value will be 1000 + the value of what follows the M, which is what the expression states. Note that the parentheses around s[index+1] are not necessary.
You'll need to make similar changes throughout the code. You also need to review why you have iteration mixed in with recursion; you should use one or the other.
Note that your code doesn't seem to cover L aka 50.
Personally, I think this is not the best way to do the conversion. All else apart, it will be hard to spot that MXMC is invalid. My code uses an array of structures containing a string and the corresponding value (M and 1000; CM and 900) etc, and once one of the values has been used up (CM can only be used once; M can be used multiple times; CD can be used once; C can be used multiple times — that's coded too), then it can't appear again later. And it uses iteration rather than recursion.
Here's a moderately simple adaptation and fix to your code. It works OK for converting 'known to be valid' Roman numbers; it doesn't work well for validating them.
#include <stdio.h>
int convert(const char *s);
int convert(const char *s)
{
int val = 0;
int i = 0;
if (s[i] == '\0')
return 0;
if (s[i] == 'I')
{
if (s[i + 1] != 'I' && s[i + 1] != '\0')
val = convert(&s[i + 1]) - 1;
else
val = 1 + convert(&s[i + 1]);
}
if (s[i] == 'V')
val = 5 + convert(&s[i + 1]);
if (s[i] == 'X')
{
if (s[i + 1] == 'L' || s[i + 1] == 'C' || s[i + 1] == 'D' || s[i + 1] == 'M')
val = convert(&s[i + 1]) - 10;
else
val = 10 + convert(&s[i + 1]);
}
if (s[i] == 'L')
val = 50 + convert(&s[i + 1]);
if (s[i] == 'C')
{
if ((s[i + 1]) == 'D' || (s[i + 1]) == 'M')
val = convert(&s[i + 1]) - 100;
else
val = 100 + convert(&s[i + 1]);
}
if (s[i] == 'D')
val = 500 + convert(&s[i + 1]);
if (s[i] == 'M')
val = 1000 + convert(&s[i + 1]);
return val;
}
int main(void)
{
const struct roman
{
const char *str;
int num;
} test[] =
{
{ "I", 1 },
{ "II", 2 },
{ "III", 3 },
{ "IV", 4 },
{ "V", 5 },
{ "VI", 6 },
{ "VII", 7 },
{ "VIII", 8 },
{ "VIIII", 9 },
{ "IX", 9 },
{ "X", 10 },
{ "XI", 11 },
{ "XII", 12 },
{ "XIII", 13 },
{ "XIV", 14 },
{ "XV", 15 },
{ "XVI", 16 },
{ "XVII", 17 },
{ "XVIII", 18 },
{ "XIX", 19 },
{ "XVIIII", 19 },
{ "XX", 20 },
{ "XXI", 21 },
{ "XXX", 30 },
{ "XL", 40 },
{ "L", 50 },
{ "LXXVIII", 78 },
{ "XCVIII", 98 },
{ "IC", 99 },
{ "XCIX", 99 },
{ "C", 100 },
{ "D", 500 },
{ "M", 1000 },
{ "MMMDCCCLXXXVIII", 3888 },
{ "MDCMMCCLXIIIIII", 3666 }, // Not good for validating!
};
enum { NUM_TEST = sizeof(test) / sizeof(test[0]) };
for (int i = 0; i < NUM_TEST; i++)
{
int value = convert(test[i].str);
printf("%s %15s = %4d vs %4d\n", (value == test[i].num) ? "== PASS ==" : "!! FAIL !!",
test[i].str, value, test[i].num);
}
return 0;
}
Sample output:
== PASS == I = 1 vs 1
== PASS == II = 2 vs 2
== PASS == III = 3 vs 3
== PASS == IV = 4 vs 4
== PASS == V = 5 vs 5
== PASS == VI = 6 vs 6
== PASS == VII = 7 vs 7
== PASS == VIII = 8 vs 8
== PASS == VIIII = 9 vs 9
== PASS == IX = 9 vs 9
== PASS == X = 10 vs 10
== PASS == XI = 11 vs 11
== PASS == XII = 12 vs 12
== PASS == XIII = 13 vs 13
== PASS == XIV = 14 vs 14
== PASS == XV = 15 vs 15
== PASS == XVI = 16 vs 16
== PASS == XVII = 17 vs 17
== PASS == XVIII = 18 vs 18
== PASS == XIX = 19 vs 19
== PASS == XVIIII = 19 vs 19
== PASS == XX = 20 vs 20
== PASS == XXI = 21 vs 21
== PASS == XXX = 30 vs 30
== PASS == XL = 40 vs 40
== PASS == L = 50 vs 50
== PASS == LXXVIII = 78 vs 78
== PASS == XCVIII = 98 vs 98
== PASS == IC = 99 vs 99
== PASS == XCIX = 99 vs 99
== PASS == C = 100 vs 100
== PASS == D = 500 vs 500
== PASS == M = 1000 vs 1000
== PASS == MMMDCCCLXXXVIII = 3888 vs 3888
== PASS == MDCMMCCLXIIIIII = 3666 vs 3666
Note that the last 'number' is horribly bogus (1000 + 500 + 900 + 1000 + 100 + 100 + 50 + 10 + 1 + 1 + 1 + 1 + 1 + 1).
First time poster, long time reader.
I've been having a problem with figuring this out. I've been stuck in my game for 4 hours now, googling and trying to figure out how to do it.
I have a game where i add some cartoonish ants, that when they are clicked, they need to be removed from stage. There are 4 differend kinds of ants, so im doing a Math.random for picking which one to add. (ant 1+2+3 have 50% chance to spawn and 4th 50%)
rnd_nbr = (Math.random() * 5)+1;
I have a timer doing 10 tick, and i reset the timer to make neverending.
Then i have a math random and if sentences adding mc' to the stage with movement from Tweener, and event listeners for clicks.
But i cant figure out how to remove them when clicked.
I have done alot of failed tries right inside the click_candy_anty function.
I've left them commented out.
I apologize for abit messy coding, but it will be cleaned up when(hopefully) it gets working.
Help is highly appreciated.
import caurina.transitions.Tweener;
var ant_index:Array = new Array(10); //index for ants
var ant_number:int;
var ant_temp:int;
var rnd_nbr:int; //var for rnd number
var score:int = 0;
var score_update:String;
var reset_timer:Boolean = false;
var antTimer:Timer = new Timer(800,10); //timer
antTimer.addEventListener(TimerEvent.TIMER, create_ant);
var anty0_:anty_0; //creating ant vars for all 5 kind
var anty1_:anty_1;
var anty2_:anty_2;
var anty3_:anty_3;
var anty4_:anty_4;
var screen_number:int = 0;
var antyArray:Array = new Array(10);
var main:main_mc = new main_mc;
main.x = 0; //0,0
main.y = 0;
addChild(main);
var score_format:TextFormat = new TextFormat();
score_format.size = 25;
score_format.align = TextFormatAlign.CENTER;
var score_txt:TextField = new TextField();
score_txt.defaultTextFormat = score_format;
score_txt.text = "" + score;
score_txt.x = 600;
score_txt.y = 20;
score_txt.border = true;
score_txt.autoSize = TextFieldAutoSize.LEFT ;
score_txt.height = 40;
addChild(score_txt);
var score_txt_update:TextField = new TextField();
score_txt_update.defaultTextFormat = score_format;
score_txt_update.text = "0";
score_txt_update.x = 550;
score_txt_update.y = 20;
score_txt_update.border = true;
score_txt_update.autoSize = TextFieldAutoSize.LEFT ;
score_txt_update.height = 40;
score_txt_update.alpha = 0;
addChild(score_txt_update);
function click_candy_anty(event:MouseEvent):void{
if (score < 20){
//trace("evt: " + evt);
//this.removeChild();
//this.removeChild(this);
//removeChild(evt.currentTarget);
//removeChild(evt.target.name.substr(7));
//removeChild(this);
//removeChild(evt.currentTarget.name);
// trace("The " + evt.target.label + " button was clicked");
// trace(evt.type)
score++;
score_txt.text = "" + score;
//score_update = "+1";
score_txt_update.text = "+1";
//ori position x:570 y:20
score_txt_update.y = -30;
Tweener.addTween(score_txt_update, {y: 20, alpha: 1, time: 0.8, transition:"linear", onComplete:score_txt_update_fade});
}
else {
stop_game();
trace("48");
}
}
function score_txt_update_fade(Event = null){
Tweener.addTween(score_txt_update, {y: 50, alpha: 0, time: 0.4, transition:"linear"});
}
function click_leaf_anty(Event = null):void{
if (score > 0 && score < 20){
score--;
score_txt.text = "" + score;
score_txt_update.text = "-1";
score_txt_update.y = 50;
Tweener.addTween(score_txt_update, {y: 20, alpha: 1, time: 0.4, transition:"linear", onComplete:score_txt_update_fade_neg});
trace("12 wrong");
}
/* else {
stop_game();
trace("12");
trace("score: " + score + ", ");
}*/
}
function score_txt_update_fade_neg(Event = null){
Tweener.addTween(score_txt_update, {y: -30, alpha: -1, time: 0.8, transition:"linear"});
}
//screen1();
start_timer();
function screen1(Event = null):void {
screen_number = 2;//slet når event listener til scr1 kommer
if (screen_number == 2){
}
else {
screen_number = 2;
}
}
function screen2(Event = null):void {
if (screen_number == 3){
}
else {
screen_number = 3;
}
start_timer();
}
function start_timer(Event = null):void {
if (score < 20) {
if (reset_timer == false){
antTimer.start();
//trace("antTimer initialized");
}
if (reset_timer == true){
antTimer.reset();
antTimer.start();
//trace("antTimer RESETTED & initialized");
}
}
else {
stop_game();
trace("57");
}
}
function stop_game(Event = null):void {
if (screen_number != 2){
screen_number = 2;
trace("Game completed - launching end screen");
// move to next screen
for (var i:Number=0; i<=9;i++){
ant_temp = ant_number;
if (ant_temp < 9) {
//trace("ant_temp er lavere end 9::: " + ant_temp );
ant_temp++;
}
else if (ant_temp == 9) {
//trace("ant_temp lig med 9::: " + ant_temp );
ant_temp = 0;
}
if (ant_index[ant_temp] == 1){
//removeChild(anty1_);
if ("anty1_" + ant_temp != null){
removeChild(getChildByName("anty1_" + (ant_temp)));
}
}
if (ant_index[ant_temp] == 2){
//removeChild(anty2_);
if ("anty2_" + ant_temp != null){
removeChild(getChildByName("anty2_" + (ant_temp)));
}
}
if (ant_index[ant_temp] == 3){
//removeChild(anty3_);
if ("anty3_" + ant_temp != null){
removeChild(getChildByName("anty3_" + (ant_temp)));
}
}
else if (ant_index[ant_temp] == 4){
//removeChild(anty4_);
if ("anty4_" + ant_temp != null){
removeChild(getChildByName("anty4_" + (ant_temp)));
}
}
}//for loop end
screen3();
}
}
function screen3 (Event = null):void{
var end:end_mc = new end_mc;
end.x = 0; //0,0
end.y = 0; //
addChild(end);
}
function create_ant(Event = null):void {
//trace("antTimer triggered");
if (score < 20) {
rnd_nbr = (Math.random() * 5)+1;
ant_index[ant_number] = rnd_nbr;
trace("ant_number" + ant_number);
//trace("ant_index[" + ant_number + "]: " + ant_index[ant_number]);
if (ant_index[ant_number] == 1){
anty1_ = new anty_1();
anty1_.name = "anty1_" + (ant_number);
anty1_.height = 118;
anty1_.width = 102;
anty1_.x = 100;
anty1_.y = 300;
addChild(anty1_);
Tweener.addTween(anty1_, {x: 541, time: 3, transition:"linear"});
anty1_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty1_" + ant_number);
//trace("" + anty_1[ant_number].name);
}
if (ant_index[ant_number] == 2){
anty2_ = new anty_2();
anty2_.name = "anty2_" + (ant_number);
anty2_.height = 118;
anty2_.width = 102;
anty2_.x = 100;
anty2_.y = 300;
addChild(anty2_);
Tweener.addTween(anty2_, {x: 541, time: 3, transition:"linear"});
anty2_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty2_" + ant_number);
}
if (ant_index[ant_number] == 3){
anty3_ = new anty_3();
anty3_.name = "anty3_" + (ant_number);
anty3_.height = 118;
anty3_.width = 102;
anty3_.x = 100;
anty3_.y = 300;
addChild(anty3_);
Tweener.addTween(anty3_, {x: 541, time: 3, transition:"linear"});
anty3_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty3_" + ant_number);
}
else if (ant_index[ant_number] > 3 && ant_index[ant_number] < 7){
anty4_ = new anty_4();
anty4_.name = "anty4_" + (ant_number);
anty4_.height = 118;
anty4_.width = 102;
anty4_.x = 100;
anty4_.y = 300;
addChild(anty4_);
Tweener.addTween(anty4_, {x: 541, time: 3, transition:"linear"});
anty4_.addEventListener(MouseEvent.MOUSE_DOWN, click_leaf_anty);
//trace("anty4_" + ant_number);
}
ant_temp = ant_number;
if (ant_temp < 9) {
//trace("ant_temp er lavere end 9::: " + ant_temp );
ant_temp++;
}
else if (ant_temp == 9) {
//trace("ant_temp lig med 9::: " + ant_temp );
ant_temp = 0;
}
if (ant_index[ant_temp] == 1){
//removeChild(anty1_);
removeChild(getChildByName("anty1_" + (ant_temp)));
}
if (ant_index[ant_temp] == 2){
//removeChild(anty2_);
removeChild(getChildByName("anty2_" + (ant_temp)));
}
if (ant_index[ant_temp] == 3){
//removeChild(anty3_);
removeChild(getChildByName("anty3_" + (ant_temp)));
}
else if (ant_index[ant_temp] == 4){
//removeChild(anty4_);
removeChild(getChildByName("anty4_" + (ant_temp)));
}
/* if (ant_number == 9) { //resets the ant_number - being the end of the 10th ant
ant_number = 0;
start_timer(); // launches the timer again
trace("Timer resetted");
for (var i:Number=0; i<=9;i++){
if (ant_index[i] == 1){
//removeChild(anty1_);
removeChild(getChildByName("anty1_" + (i)));
}
if (ant_index[i] == 2){
//removeChild(anty2_);
removeChild(getChildByName("anty2_" + (i)));
}
if (ant_index[i] == 3){
//removeChild(anty3_);
removeChild(getChildByName("anty3_" + (i)));
}
else if (ant_index[i] == 4){
//removeChild(anty4_);
removeChild(getChildByName("anty4_" + (i)));
}
}//for loop end
}//ends if=9 reset*/
if (ant_number == 9) { //resets the ant_number at 10th ant, and restarts the timer
ant_number = 0;
reset_timer = true;
start_timer();
}
else {
ant_number++;
}
/*else {
ant_number++;
}*/
}
else if (score >= 20 && screen_number != 2){
stop_game();
trace("14");
}
} //create_ant func end
You can also use:
removeChild( evt.currentTarget as DisplayObject );
Or
var clicked_ant:DisplayObject = evt.currentTarget as DisplayObject;
removeChild( clicked_ant );
Let's say that you've created a Ant class, you could have something like this
private function init():void
{
this.addEventListener( MouseEvent.CLICK , clickHandler );
}
private function clickHandler( event:MouseEvent ):void
{
this.removeEventListener( MouseEvent.CLICK , clickHandler );
if( this.parent != null )
this.parent.removeChild( this );
}