vb.net - Visual Basic - Counting the occurrence of numbers from a random array -
i need use arrays , strings. program should search 1 number user enter (0-9). here code below. uses array random number, , it's testing occurrences each number. it's not working, don't need test every number anyway.
the program must test 1 number user requests. if random number that's generated say.. '7417', , user user has chosen '7', program report there have been 2 sevens. i'm going use textbox 'txtenter' users number search for. can me? thanks!
private sub button1_click(byval sender system.object, byval e system.eventargs) handles button1.click randomize() dim arraynum(1) integer arraynum(0) = int(rnd() * 100000) lbldisplaynumber.text = arraynum(0) dim num integer txtenter.text = num dim counts = c in num.tostring() group c group select digitgroup = new {.count = group.count(), .digit = c, .group = group} order digitgroup.count descending select string.format("there {0} number {1}'s found.", digitgroup.count, digitgroup.digit) dim message = string.join(environment.newline, counts) end sub
if want use linq, it's short , readable:
dim counts = c in num.tostring() group c group select digitgroup = new {.count = group.count(), .digit = c, .group = group } order digitgroup.count descending select string.format("there {0} number {1}'s found.", digitgroup.count, digitgroup.digit) dim message = string.join(environment.newline, counts)
update: here complete sample shows result of entered number , summary:
dim rnd new random() dim randomint = rnd.next(0, 100000) lbldisplaynumber.text = randomint.tostring() dim num integer if int32.tryparse(txtenter.text, num) andalso num >= 0 andalso num < 10 dim counts = c in randomint.tostring() group c group select digitgroup = new {.count = group.count(), .digit = c, .group = group} order digitgroup.count descending, digitgroup.digit dim numcount = counts.firstordefault(function(grp) grp.digit.tostring() = num.tostring()) if numcount isnot nothing dim nummessage = string.format("there {0} number {1}'s found.", numcount.count, num) messagebox.show(nummessage) else messagebox.show("number not contain " & num) end if dim summarycount = grp in counts select string.format("there {0} number {1}'s found.", grp.count, grp.digit) dim summarymessage = string.join(environment.newline, summarycount) messagebox.show("summary:" & environment.newline & summarymessage) else messagebox.show("please enter number between 0 , 9.") end if
Comments
Post a Comment