How can I delete elements from a Perl array? - arrays

I have a pretty big array and I want to delete the 2nd, 8th, 14th etc. element from an array. My array currently is like this:
Element1 x A B C
Element 2 y A B C
Element 3 z A B C
Broadly, I want to delete the x, y and z (just as an example, my array is slighly more complex). And pull up the rest. As in, I don't want to have a blank space in their positions. I want to get:
Element 1 A B C
Element 2 A B C
Element 3 A B C
I tried to give this a try with my array "todelete":
print "#Before Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];
for ($count=2; $count<#todelete;
$count=$count+6) { delete
$todelete[$count]; }
print "#After Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];$todelete[3];
But, currently, I think it just unitializes my value, because when I print the result, it tells me:
Use of uninitialized value in print
Suggestions?

The function you want is splice.

delete $array[$index] is the same as calling $array[$index] = undef; it leaves a blank space in your array. For your specific problem, how about something like
#array = #array[ grep { $_ % 6 != 2 } 0 .. $#array ];

You can also use grep as a filter:
my $cnt = 0;
#todelete = grep { ++$cnt % 6 != 2 } #todelete;

Related

Ruby arrays and how to print them

There was a one-liner in Ruby I saw on this site and lost track of:
if I need to print the results of some action with integers:
print {|e| e = e * e}
but how do I let Ruby know e is, say, 1 to 10?
use parenthesis around your range
(1..10).map {|ele| ele + 3} // 1 to 10 including the last number
(1...10).map {|ele| ele + 3 } // 1 to 9 excluding the last number
It's not really clear what you want to do, but here's an input
(1..10).to_a
This gives you an array of numbers from 1 to 10.

Print array elements in reverse order

The first line contains an integer N, (the size of our array).
The second line contains N space-separated integers describing array's(A's) elements.
I have tried the following, however I looked at the solution page. However I do not understand how this code works. Can someone please explain it to me. I am pretty new in this coding world.
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
input 1234
output 4 3 2 1
In Python3:
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print(" ".join(str(x) for x in arr[::-1]))
Input:
1 4 3 2
Output:
2 3 4 1
You are creating a list of integer values, by removing spaces and splitting the values at ' '. After obtaining the list of integers, you are iterating over the list and converting the ith element from the back (a negative value of index denotes element with ith index from right and it is 1 based) of arr back to string and printing the number.
Example:
arr = [1,2,3,4]
print(arr[1]) #prints 2 on the console, i.e 2nd element from the left.
print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.
Let's take this code snippet
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
The method input() will take the user input from key board. int(input()) will convert the input into int, if the input is in string format. like "4" instead of 4. The input value stored into variable n.
The Array input will be like this "1 2 3 4". So, we need to separate the string with space delimiter.
The strip() method returns a copy of the string with both leading and trailing characters removed.
The split() method returns a list of strings after breaking the given string by the specified separator.Here the separator is space. So, split(' ')
input().strip().split(' ') will take "1 2 3 4" as input and the output is "1" "2" "3" "4".
Now we need to take each element after separated. And then covert into int and store into array.
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
arr_one is a variable, this variable stores each element after split. For each element, we converted it into int and then storing into a array arr.
In python, array index start from 0. If we want to access from last index in the array, the index will start from -1, -2, -3, and so on.
for i in range(len(arr)): The for loop will iterate from index 0 to length of the array. in this example, size is 4.
printing array elements from index -1. and the end argument is used to end the print statement with given character, here the end character is " ". So the output will be 4 3 2 1.
The above code can be rewritten as below with more readability.
if __name__ == '__main__':
n = int(input())
inp = input("Enter the numbers seperated by spaces:::")
inp = inp.strip() # To remove the leading and trailing spaces
array = []
for item in inp.split(' '): # Splitting the input with space and iterating over each element
array.append(int(item)) # converting the element into integer and appending it to the list
print(array[::-1]) # here -1 says to display the items in the reverse order. Look into list comprehension for more details
For more details on list slicing, look in the python documentation.
Try this!
if __name__ == '__main__':
n = int(input()) # input as int from stream
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
"""
1. asking for input from user
2. strip() function removes leading and trailing characters.
3. split(' ') function split your input on space into list of characters
4. arr_one variable contains yours splited character and your iterating over it using for loop
5. int(arr_one) converts it into integer and [] is nothing just storing everything into another list.
6. In last you are assigning new list to arr variable
"""
for i in reversed(arr): # loop over list in reverse order with built in fucntion
print(i, end = " ") # printing whatever comes in i
It should work like this:
3 # your n
1 2 3 # your input
3 2 1 # output

Python: Comparing values in one array and replacing that value in another array at the same index from the first array

I’m trying to take user input and compare that input to the values in array B. Should the user input match one of those values in array B, I capture the index it is at and replace array A with the user input at the same index it found it in array B.
In the code example if I enter 11 it finds 11 in array B and inserts it into the same index point in array A. But if I choose 22, 33, or 44 it does not replace anything.
What do you see wrong with the code below? Why does it recognize number 11 in array B and replaces it with 1 in array A, but not the others?
a = [1,2,3,4]
b = [11,22,33,44]
c = input("Enter a Number: ")
for i in b:
if c == i:
x = b.index(i)
a.pop(x)
a.insert(x,c)
break
else:
print "Not in list b"
break
print a
Try this:
a = [1,2,3,4]
b = [11,22,33,44]
c = input("Enter a Number: ")
for i in b:
if c == i:
x = b.index(i)
print x
a.pop(x)
a.insert(x,c)
break
else:
print "Not in list b"
print a
Putting the else statement outside of the for loop should make it work as expected. As it was, the loop would, 100% of the time, break after 1 iteration.

Perl: array splitting and complex merging

I have the following string A B C D E F G H I J. I want to make an array out of it, so I use this
my #string = split/(\W)/, $text;
It works ok, and I get an array of 20 lines looking like this:
A
B
C
D
...
Now, I want to split this array in a given number of pieces (let's say 4 in this case), thus resulting I imagine in 4 smaller arrays of 5 lines each, looking like this #1 = A, ,B, ,C , #2 = ,D, ,E,, #3 = F, ,G, ,H and #4 = ,I, ,J,.
Finally, I want to interleave these 4 arrays in order to get an output array in which I first have the first line of each array, the the second line of each array, and so on... the final thing looking like this :
A
F
D
I
B
G
E
J
C
H
How to achieve this?
To make a slice of an array in Perl:
my #oldArray = (a, ,b, ,c, ,d, ,e, ,f, ,g, h, ,i, ,j, );
my #newArray1 = #oldArray[elemIndex1,elemIndex2,elemIndexN];
OR
my #newArray1 = #oldArray[firstElemIndex..lastElemIndex]
Where elemIndex is the index of the element you want in the newArray array.
firstElemIndex..lastElemIndex is used when you want consecutive indexes to be in the sliced array.
To add elements at the end of an array:
push(#interleavedArray,$newArray1[elemIndex]);
Where $newArray1[elemIndex] is the element from #newArray1 you want to add to #interleavedArray
To add elements in order:
Just do a for loop:
for my $index (0..3){
push(#interleavedArray,$newArray1[$index]);
push(#interleavedArray,$newArray2[$index]);
push(#interleavedArray,$newArray3[$index]);
push(#interleavedArray,$newArray4[$index]);
}

Dual array correspondance

I just found myself in a position where I have two arrays in Tcl.
I'm given $W_Array and $P_Array.
I need to traverse through one array not knowing what the size of each one is before hand, and execute a command only when there is a value for both arrays. Yes the array lengths could be different.
What is the best way of doing this?
The other answers jumped to using lists, I presume you mean Tcl's array, which are also called hash maps or associative arrays.
I think you're asking for something like:
array set a1 {a 1 b 2 c 3 d 4 e 5}
array set a2 {z 0 x 1 b 2 e 99}
foreach n [array names a1] {
if {[info exists a2($n)]} {
puts "Do something with $a1($n) and $a2($n)"
}
}
# FOREACH LOOP RESULTS IN THESE TWO PRINTOUTS
Do something with 5 and 99
Do something with 2 and 2
Not sure exactly what you mean by "a value for both arrays", but tcl's foreach supports iteration over multiple arrays at once... so you can say e.g.
foreach w $W_Array p $P_Array {
if {$w == $val && $p == $val} {
...
}
}
When the arrays are not of the same length, foreach will return all values from the longest array and the empty value {} for the missing elements in any shorter arrays.
Use llength command to find out if the arrays contain a value.
if {[llength $W_Array] > 0 && [llength $P_Array] > 0} {
# Do something
}

Resources