Count the number of elements of array that contain a digit - arrays
i am new to Ruby and stuck on this exercice. I have this array including string value and i am looking for the number of value including a figure ?
array = ["#jcunniet","#PaulLampon","#Aziliz31","#ssoumier","#marionsouzeau","#gaellombart","#bendarag","#AurelieLebelle","#julienduffe","#thomaspoupeau","#LilyRossignol","#ClairGuedon","#stephanieauguy","#claw_prolongeau","#_JulieMenard","#LColcomb","#Zlauwereys","#MeLonguet","#DorotheeLN","#NolwennCosson","#ADaboval","#Remibaldy","#bderveaux","#amandechap","#ELODIESOULIE","#nbongarcon","#HeloAb","#Panamorama","#gregplou","#BenoitBerthe","#LauraBruneau89","#Anthony_Lieures","#Sharonwaj","#mcsonkin","#pverduzier","#emiliel3","#Julien_MARION","#SophiFay","#bdelombre","#annalecerf","#AdriaBudry","#DejNikolic","#iJaffre","#CyrusleVirus","#GPardigon","#e_vallerey","#IsabelleSouquet","#AudeDavidRossi","#Yoann_Pa","#CeliaPenavaire","#perraultvincent","#cboulate","#JustineWeyl","#Paulinejacot","#juliechab","#aslechevallier","#phnou","#Seb_Pommier","#Alex_Bensaid","#GuillaumeGaven","#annelaurechouin","#Oliviader","#guerricp","#JMMarchaut","#cyceron","#gregory_raymond","#vhunsinger","#l_peillon","#fannyguinochet","#EAssayag","#KibweAdom","#YvonHerry","#JohanGarciajg","#saidlabidi","#lauranneprov","#LeaDavy","#francois_remy","#CGuicheteau","#FloMaillet","#m_perroud","#oBrunet_TSMF","#MoonVdc","#jc2taille","#NellyMoussu","#VirginK","#b_misa","#FabriceCouste","#barbara_prose","#lelia2m","#brunoaskenazi","#laurenechamp","#ysisbox","#juliengagliardi","#PierreLel","#kdeniau","#_TerraInc","#DominicArpin","#antoinfonteneau","#nanotousch","#jb_roch","#YaniKhezzar","#Anne_Bechet","#NCapart","#SamyBenNaceur","#Joumany","#Julietteraynal","#TGiraudet","#SaraTanit","#HappeFrederic","#antoinellorca","#michelpicot","#Sev_Ryne","#bobdobolino","#murdever","#YGrandmontagne","#Mnyo","#EdKOSCIANSKI","#tnoisette","#jankari","#delbello_rom","#rflechaux","#NadiaSorelli","#IT_Digital","#abarbaux","#PhilippeLeroy","#schaptal","#marionspee","#lisavignoli","#ChloeAeberhardt","#MartineJacot","#JuliaPascualita","#curieusedetout","#sgraveleau","#bif_o","#ElisaPineau","#zinebdryef","#apiquard","#pierrehaski","#StephanieDelmas","#Blandine_Garot","#vergara_i","#evan_lebastard","#SophieVclt","#OlivierLevrault","#alicedorgeval","#LouiseMalnoy","#alix_fx","#pierre_baudis","#LucMagoutier","#AgatheMuller","#SGianninelli","#PaulineBoyer33","#NaomiHalll","#romaindlx","#marionbr","#Burtschy","#JacobEtienne","#as_lizzani","#marie_simon","#LaureDaussy","#FabriceAmedeo","#LoubnaChlaikhy","#PlummerWilliam","#OlivierMarin1","#alaurefremont","#mwesfreid","#ChBaDe","#pmathon","#theobaldmarie","#Lnpagesy","#marclandre","#paoliniesther","#Feertchak","#JBLitzler","#GuillaumeErrard","#quentinperinel","#TristanQM","#mlbo","#constancejamet","#LoraTerrazas","#emiliegeffray","#Mathilde_Sd","#CaroPiquet","#DCanivez","#TIM_7375","#blandinelc","#ivanrioufol","#arthurberdah","#SarahLecoeuvre","#guillaume_gui","#DamienMercereau","#W_Chloe","#Assma_MD","#EugenieBastie","#HiTech_lexpress","#bcondominas","#Laurie_Z_","#jeanfrancgerard","#MathieuPagura","#BGUYF","#AlainPiffaretti","#AudreyKucinskas","#julienhory","#Pierrefalga","#TiphThuillier","#cdaniez","#LigerBaptiste","#D_Peras","#julie_dlb","#Fatiha_Temmouri","#julian2lamancha","#GaetaneDeljurie","#JulianMattei","#M_Vicuna","#DeBruynOlivier","#Nehed_Jendoubi","#antoine_grenapi","#ColonnaGen","#VictoriaGairin","#Clement_Lacombe","#TVigoureux","#MargauxObriot","#solinedelos","#RocheSabine","#dangerkens","#EdouardDutour","#MDondeyne","#DupuisNathalie1","#bouscarel","#Mathieu2jean","#Sophie_T_J","#laurentcalixte","#patrockwilliams","#PascaleKremer","#AlexJaquin","#LauraIsaaz","#cath_robin","#Del_Gautherin","#Isaduriez","#lucietuile","#AugeyBastien","#mcastagnet","#AminaKalache","#mvaudano","#CParrot","#ombelinetips","#_JoinLion","#BarbolosiRose","#ToiBruno1","#FloraClodic","#xjbdx","#AlexiaEy","#Emjy_STARK","#elcoco01","#rabilebon","#pflovens_","#FabriceFrossard","#MorganeSERRES","#MarjolaineKoch","#edgarsnow","#SRNLF","#CChassigneux","#KerinecMoran","#NassiraELM","#NewsRicard","#Sandreene","#Emilezrt","#Pierre_Do","#Micode","#CColumelli","#DavidAbiker","#ClementBergantz","#benjaminrabier","#celinekallmann","#edwyplenel","#C_Barbier","#JJBourdin_RMC","#LaurenceFerrari","#aslapix","#IsaMillet","#MaximeSwitek","#tomjoubert","#jszanchi","#roqueeva","#XavierBiseul","#florencesantrot","#AntoineCrochet","#freeman59","#MaudeML","#philippe_gulpi","#mathieum76","#kiouari","#imanemoustakir","#BenedicteMallet","#Emilie_Brouze","#antoinebarret","#_nicolasbocquet","#remibuhagiar","#CourretB","#AymericRobert","#miraelmartins","#pmaniere","#jesuisraphk","#David_Ingram","#pcelerier","#technomedia","#Geraldinedauver","#ThierryLabro","#Newsdusud","#nrauline","#gbregeras","#SCouasnonBFM","#actualites_nrv","#dimitrimoulins","#oli_aura","#FabieChiche","#Vincent_Raimblt","#ChristophGreuet","#PAlbuchay","#MarrauddesGrot","#vtalmon","#cedric","#olivierfrigara","#Julien_Jay","#LydiaBerroyer","#Shuua","#datisdaz","#Steuph","#ameliecharnay","#Bruno_LesNums","#LelloucheNico","#CciliaDiQuinzio","#Elodie_C","#SylvRolland","#Kocobe","#FL_Debes","#jdupontcalbo","#GarciaVictor_","#NicoRichaud","#RHoueix","#simottel","#DamienLicata","#annabelle_L","#Lea_Lejeune","#axel_deb","#marin_eben","#ptiberry","#MatthieuDelach","#sandrinecassini","#benjaminferran","#ppgarcia75","#NotPatrick","#ivalerio","#FabienneSchmitt","#alexgoude","#JeromeColombain","#manhack","#Capucine_Cousin","#Fsorel","#oliviertesquet","#marjoriepaillon","#ginades","#PierreTran","#DelphineCuny","#reesmarc","#lauratenoudji","#ldupin","#carolinedescham","#Lucile_Quillet","#cgabizon","#Allocab","#epenser","#JAGventeprivee","#frwrds","#Laure__Bourdon","#Xavier75","#maximeverner","#s_jourdain","#LoriHelloc"]
i = 0
array.each do |n|
if n.include?("1,2,3,4,5,6,7,8,9,10")
then i += 1
end
puts i
end
Do you mean something like this?
array.grep(/[1-9]/).count
Edit: Changed regEx from /[1-10]/ to /[1-9]/
Often code that is the direct translation of the question is best: “Count the number of elements of array that contain a digit”.
array.count { |s| s.match? /\d/ }
See Array#count and String#match?.
Related
looping through nested arrays and accessing elements RUBY
I want to iterate through a nested array and operate on each element, so square each number in this case. I know how to do it for a normal array but for some reason i am getting undefined map method when include deeper iteration to access the inner arrays. Am a newbie too so if you could explain how it works that would help my learning. Thanks def SquareArrayElements(n) n.each do |number| number.map do |num| squared_nums = num * num end end squared_nums end SquareArrayElements([10,[[10],10],[10]])
Since you've said in the comments that: i want to square the 10s and return them to one array =>[100,100,100,100]. I assume that you don't need to preserve the original arrays and just want one array with the squared results. If that's the case you can #flatten the array and then square the numbers: def square_array(arr) arr.flatten.map { |e| e ** 2 } end square_array([10,[[10],10],[10]]) #=> [100, 100, 100, 100]
You only need to call map on the arrays, not on the integers. That's why you're getting an undefined map method, integers don't support that method. Try def square_array(element) if element.responds_to?(:map) element.map{|m| square_array(m)} else element * element end end
How to find all the ranges in an array of numbers
I have an array of numbers that sorted. I need a method that return ranges of numbers in this array. input: [1,2,3,7,9,10,11,13] output: [(1..3),(7..7),(9..11),(13..13)]
You didn't write any code, so I won't either. The documentation of Enumerable#chunk_while has an example which is very similar to yours.
This is a way of doing that without constructing an array of arrays and then converting the inner arrays to ranges. arr = [1,2,3,7,9,10,11,13] arr.each_with_object([]) do |n,a| if a.any? and a.last.last == n-1 a[-1] = (a.last.first..n) else a << (n..n) end end #=> [1..3, 7..7, 9..11, 13..13] Note that parentheses are required around the ranges, lest, for example, a << n..n be parsed as (a << n)..n, resulting in ArgumentError (bad value for range).
How can I find if the index number for a specific item in an array also exists as an integer in the same array?
I'm trying to find the index value of the word "odd", then return true if that index value also exists an integer within the same array. E.g. array = ["even",9,"even",88,"even",777,"even",10,"odd",8,"even"] The index of "odd" here is [8]. When I store the index value as a variable named odd, then use .include? to see if it is in the array above, my function returns false. Since the number 8 exists in array and the value of odd is also 8, why does my function return false? def does_the_index_of_odd_exist(x) odd = x.each_index.select { |i| x[i] == "odd" } x.include?(odd) end Any help explaining this is greatly appreciated. I've just started learning!
If I understand the point, you should be able to use just: array.include? array.index "odd"
x.each_index.select { |i| x[i] == "odd" } => [8] #array but not "odd" so use find instead of select, it returns string element in array
How can I remove a numerical extension from an array of filenames?
I want to remove the last 11 characters of strings inside of an array. The array is: ["cool.mp3?3829483927", "wow.mp3?3872947629", "woa.mp3?8392748308"] I want to convert the strings to this: ["cool.mp3", "wow.mp3", "woa.mp3"] Is there a method specifically for this in Ruby? I know of chop and chomp, but nothing that can access each string in an array.
TL;DR There are lots of ways to transform your string, including #slice, #split, #sub, and #partition to name a few. What you're really missing is the Array#map method, which applies a method or block to each element of an array. Partition Your Filenames One way to modify your array elements is to map the Enumerable#partition method onto each element, which splits your filenames into an array of components. Ordinarily, this would return an array of arrays where each partitioned string is a sub-array, but you can have the #map block return just the components you want. In this case, what you want is the first element of each partitioned array. This may sound complicated, but it's actually very simple. For example: files = ['cool.mp3?3829483927', 'wow.mp3?3872947629', 'woa.mp3?8392748308'] files.map { |filename| filename.partition('?').first } #=> ["cool.mp3", "wow.mp3", "woa.mp3"] A Minified Version If you value compactness over readability, you can get the same result as the solution above with: files = %w(cool.mp3?3829483927 wow.mp3?3872947629 woa.mp3?8392748308) files.map { |f| f.partition(??)[0] } #=> ["cool.mp3", "wow.mp3", "woa.mp3"]
If you want what is before the first '?', do this : arr.map{|thing| thing.split('?')[0]}
If it's always 11 chars you can do: arr=["cool.mp3?3829483927","wow.mp3?3872947629", "woa.mp3?8392748308"] new=arr.map{|thing| thing[0...-11]}
String::slice can take a regex as an argument, so you could extract the names that you want (rather than dropping the last 11 characters): arr = ["cool.mp3?3829483927","wow.mp3?3872947629", "woa.mp3?8392748308"] arr.map! {|x| x.slice(/\w+\.mp3/) } #=> ["cool.mp3", "wow.mp3", "woa.mp3"]
If arr is your array of strings: arr.map { |s| s[/[^?]+/] } # => ["cool.mp3", "wow.mp3", "woa.mp3"] The regular expression /[^?]+/ matches one or more characters that are not (^ at the beginning of the character class) question marks. This uses the methods Array#map and String#[].
Find a Duplicate in an array Ruby
I am trying to find the duplicate values in an array of strings between 1 to 1000000. However, with the code I have, I get the output as all the entries that are doubled. So for instance, if I have [1,2,3,4,3,4], it gives me the output of 3 4 3 4 instead of 3 4. Here is my code: array = [gets] if array.uniq.length == array.length puts "array does not contain duplicates" else puts "array does contain duplicates" print array.select{ |x| array.count(x) > 1} end Also, every time I test my code, I have to define the array as array = [1,2,3,4,5,3,5]. The puts works but it does not print when I use array [gets]. Can someone help me how to fix these two problems?
How I wish we had a built-in method Array#difference: class Array def difference(other) h = other.tally reject { |e| h[e] > 0 && h[e] -= 1 } end end though #user123's answer is more straightforward. (Array#difference is probably the more efficient of the two, as it avoids the repeated invocations of count.) See my answer here for a description of the method and links to its use. In a nutshell, it differs from Array#- as illustrated in the following example: a = [1,2,3,4,3,2,4,2] b = [2,3,4,4,4] a - b #=> [1] a.difference b #=> [1, 3, 2, 2] For the present problem, if: arr = [1,2,3,4,3,4] the duplicate elements are given by: arr.difference(arr.uniq).uniq #=> [3, 4]
For your first problem, you need to uniq function like array.select{ |x| array.count(x) > 1}.uniq For your second problem, when you receive a value using array = [gets] it would receive your entire sequence of array numbers as a single string, so everything would be stored in a[0] like ["1, 2 3 4\n"].
puts "Enter array" array = gets.chomp.split(",").map(&:to_i) if array.uniq.length == array.length puts "array does not contain duplicates" else puts "array does contain duplicates" print array.select{ |x| array.count(x) > 1}.uniq end copy this code in ruby file and try to run using ruby file_name.rb
Coming to your 'gets' problem, When you are doing a gets, your are basically getting a string as an input but not an array. 2.2.0 :001 > array = [gets] 1,2,1,4,1,2,3 => ["1,2,1,4,1,2,3\n"] See the above example, how the ruby interpreter took all your elements as a single string and put it in an array as a single array element. So you need to explicitly convert the input to an array with comma as a delimiter. The below will address both your questions. array = gets.chomp array = array.split(',').map(&:to_i) if array.uniq.length == array.length puts "array does not contain duplicates" else puts "array does contain duplicates" print array.select{ |x| array.count(x) > 1}.uniq! end