www.91084.com

GVKun编程网logo

计算字符串出现在数组中并与另一个数组比较的次数(计算字符串数组的长度)

7

最近很多小伙伴都在问计算字符串出现在数组中并与另一个数组比较的次数和计算字符串数组的长度这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展2023-02-20:小A认为如果在数组中有

最近很多小伙伴都在问计算字符串出现在数组中并与另一个数组比较的次数计算字符串数组的长度这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展2023-02-20:小A认为如果在数组中有一个数出现了至少k次, 且这个数是该数组的众数,即出现次数最多的数之一, 那么这个数组被该数所支配, 显然当k比较大的时候,有些数组不被任何数所支配。 现在、c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数、C语言计算字符串数组中每个字符串出现的个数、C语言:对传入sp的字符进行统计,三组两个相连字母“ea”"ou""iu"出现的次数,并将统计结果存入ct所指的数组中。-在数组中找出最小值,并与第一个元...等相关知识,下面开始了哦!

本文目录一览:

计算字符串出现在数组中并与另一个数组比较的次数(计算字符串数组的长度)

计算字符串出现在数组中并与另一个数组比较的次数(计算字符串数组的长度)

您可以使用Array.prototype.reduce()来获取数组,然后使用Array.prototype.sort()来获取具有最高置换率的数组。

let arr = ["5281-A","5280-A","5280-B","5281-B"];
let arr2 = ["5281-A","5281-B"];

// get the count of repititions
const getCountArray = (arr) => 
 Object.entries(
  arr.map((id) => id.split("-")[1]) // map the elements as "A" or "B"
   .reduce((a,c) => ((a[c] = (a[c] || 0) + 1),a),{})
 );

// return what is missing from two arrays
const whatIsMissing = (baseArray,secondArray) => {
  const [a,b] = [baseArray,secondArray].map(([[,a],[,b]]) => [a,b])
   .reduce(([a,b],[c,d]) => [a - c,b - d])
  
  return `A requires ${a} more,and B requires ${b} more`;
}

console.log(whatIsMissing(getCountArray(arr),getCountArray(arr2)))

,

您可以拆分然后计数。我选择在名为countBySuffix的函数中返回一个普通对象(如您提到的那样)。

然后我添加了另一个函数diff,该函数将比较两个这样的对象(由countBySuffix返回),并且仅返回差异。不同之处在于包含三个元素的数组:

[suffix,count 1,count 2]

例如,示例中的后缀为“ A”,则计数为该后缀在第一个输入和第二个输入中出现的次数。

摘要:

function countBySuffix(arr) {
  arr = arr.map(s => s.split("-").pop());
  let map = Object.fromEntries(arr.map(s => [s,0]));
  for (let s of arr) map[s]++;
  return map;
}

function diff(a,b) {
  let res = [];
  for (let prop in a) {
    if (b[prop] != a[prop]) res.push([prop,a[prop],b[prop]]);
  }
  for (let prop in b) {
    if (!a[prop]) res.push([prop,undefined,b[prop]]);
  }
  return res;
}

// demo
let arr1 = [ "5281-A","5281-B" ];
let arr2 = [ "5284-A","5283-B","5282-A"];

let count1 = countBySuffix(arr1);
let count2 = countBySuffix(arr2);

console.log(diff(count1,count2));

,

您可以使用map

let arr = ["5281-A","5281-B"]
let map = new Map();
arr.forEach((item) => {
  const txt = item.charAt(item.length - 1);
  if (!map.has(txt)) {
    map.set(txt,1)
  } else {
    const val = map.get(txt);
    map.set(txt,val + 1)
  }
})
let newArr = [];
for (let [key,value] of map.entries()) {
  newArr.push([key,value])
};
console.log(newArr)

,

这应该创建一个对象:

let obj = {};
arr.forEach(item => {
 let letter = item.split("-")[1];
 obj[letter] = obj[letter] ? obj[letter] + 1 : 1;
})

output: {"A": 2,"B": 2}

如果需要以[“ A”,2]格式使用:

let outputArray = Object.entries(obj);
,

以下代码将实现您的目标。

let arr = [ "5281-A","5281-B" ]

let newObj = arr.reduce((a,b) => {
    const str = b.split('-')[1]
    a[str] = a[str] ? a[str] += 1 : 1
    return a
},{})

此答案比使用for循环更好,因为它可以更轻松地传递给新对象。

2023-02-20:小A认为如果在数组中有一个数出现了至少k次, 且这个数是该数组的众数,即出现次数最多的数之一, 那么这个数组被该数所支配, 显然当k比较大的时候,有些数组不被任何数所支配。 现在

2023-02-20:小A认为如果在数组中有一个数出现了至少k次, 且这个数是该数组的众数,即出现次数最多的数之一, 那么这个数组被该数所支配, 显然当k比较大的时候,有些数组不被任何数所支配。 现在

2023-02-20:小A认为如果在数组中有一个数出现了至少k次, 且这个数是该数组的众数,即出现次数最多的数之一, 那么这个数组被该数所支配, 显然当k比较大的时候,有些数组不被任何数所支配。 现在小A拥有一个长度为n的数组,她想知道内部有多少个区间是被某个数支配的。 2 <= k <= n <= 100000, 1 <= 数组的值 <= n。 来自小红书。

答案2023-02-20:

窗口问题。 求总数,求不被支配的数量。 时间复杂度:O(N)。 空间复杂度:O(N)。

代码用rust编写。代码如下:

use rand::Rng;
use std::collections::HashMap;
use std::iter::repeat;
fn main() {
    let nn = 100;
    let test_times = 5000;
    println!("测试开始");
    for i in 0..test_times {
        let n = rand::thread_rng().gen_range(0, nn) + 1;
        let mut arr = random_array(n);
        let k = rand::thread_rng().gen_range(0, n) + 1;
        let ans1 = dominates1(&mut arr, k);
        let ans2 = dominates2(&mut arr, k);
        if ans1 != ans2 {
            println!("出错了!");
            return;
        }
    }
    println!("测试结束");
}

// 暴力方法
// 为了验证
// 时间复杂度O(N^3)
fn dominates1(arr: &mut Vec<i32>, k: i32) -> i32 {
    let n = arr.len() as i32;
    let mut ans = 0;
    for l in 0..n {
        for r in l..n {
            if ok(arr, l, r, k) {
                ans += 1;
            }
        }
    }
    return ans;
}

fn ok(arr: &mut Vec<i32>, l: i32, r: i32, k: i32) -> bool {
    let mut map: HashMap<i32, i32> = HashMap::new();
    for i in l..=r {
        if map.contains_key(&arr[i as usize]) {
            map.insert(arr[i as usize], map.get(&arr[i as usize]).unwrap() + 1);
        } else {
            map.insert(arr[i as usize], 1);
        }
    }
    for (_, times) in map.iter() {
        if *times >= k {
            return true;
        }
    }
    return false;
}

// 正式方法
// 时间复杂度O(N)
fn dominates2(arr: &mut Vec<i32>, k: i32) -> i32 {
    let n = arr.len() as i32;
    // 总数量
    let all = n * (n + 1) / 2;
    // 不被支配的区间数量
    let mut except = 0;
    // 次数表
    // 0 : 0
    // 1 : 0
    // 2 : 0
    let mut cnt: Vec<i32> = repeat(0).take((n + 1) as usize).collect();
    // l ... r
    // 窗口用这个形式[l,r)
    // l...r-1 r(x)
    // l == 0 r == 0 [l,r) 一个数也没有
    // l == 0 r == 1 [0..0]
    let mut l = 0;
    let mut r = 0;
    while l < n {
        // [r] 即将要进来的
        // cnt[arr[r]] + 1 < k
        while r < n && cnt[arr[r as usize] as usize] + 1 < k {
            // cnt[arr[r]]++;
            // r++
            cnt[arr[r as usize] as usize] += 1;
            r += 1;
        }
        // l..l
        // l..l+1
        // l..l+2
        // l..r-1
        except += r - l;
        cnt[arr[l as usize] as usize] -= 1;
        l += 1;
    }
    return all - except;
}

// 为了测试
fn random_array(n: i32) -> Vec<i32> {
    let mut ans: Vec<i32> = repeat(0).take(n as usize).collect();
    for i in 0..n {
        ans[i as usize] = rand::thread_rng().gen_range(0, n) + 1;
    }
    return ans;
}

在这里插入图片描述

c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数

c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数

我试图计算在另一个字节序列中字节序列发生的所有时间.但是,如果已经计算了它们,则无法重复使用字节.例如给定字符串
k.k.k.k.k.k.假设字节序列是k.k,那么它只会发现3次而不是5次,因为它们会像以下那样被分解:[k.k].[k.k].[k.k].并不喜欢[k.[k].[k].[k].[k] .k]他们在一圈并且基本上只是向右移动2.

理想情况下,我们的想法是了解压缩字典或运行时编码的外观.所以目标就是获得

k.k.k.k.k.k.只有2个部分,因为(k.k.k.)是你可以拥有的最大和最好的符号.

到目前为止这是源:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;


    static class Compression 
    {
        static int Main(string[] args)
        {

            List<byte> bytes = File.ReadAllBytes("ok.txt").ToList();
            List<List<int>> list = new List<List<int>>();

            // Starting Numbers of bytes - This can be changed manually.
            int StartingNumBytes = bytes.Count;
            for (int i = StartingNumBytes; i > 0; i--)
            {
                Console.WriteLine("i: " + i);

                for (int ii = 0; ii < bytes.Count - i; ii++)
                {
                    Console.WriteLine("ii: " + i);
                    // New pattern comes with refresh data.
                    List<byte> pattern = new List<byte>();

                    for (int iii = 0; iii < i; iii++)
                    {
                        pattern.Add(bytes[ii + iii]);
                    }



                    displayBinary(bytes,"red");
                    displayBinary(pattern,"green");

                    int matches = 0;
                   // foreach (var position in bytes.ToArray().Locate(pattern.ToArray()))
                    for (int position = 0; position < bytes.Count; position++) {
                        if (pattern.Count > (bytes.Count - position))
                        {
                            continue;
                        }


                        for (int iiii = 0; iiii < pattern.Count; iiii++)
                        {
                            if (bytes[position + iiii] != pattern[iiii])
                            {
                                //Have to use goto because C# doesn't support continue <level>
                                goto outer;
                            }

                        }

                        // If it made it this far,it has found a match.
                        matches++;
                        Console.WriteLine("Matches: " + matches + " Orig Count: " + bytes.Count + " POS: " + position);
                        if (matches > 1)
                        {
                            int numBytesToRemove = pattern.Count;
                            for (int ra = 0; ra < numBytesToRemove; ra++)
                            {
                                // Remove it at the position it was found at,once it
                                // deletes the first one,the list will shift left and you'll need to be here again.
                                bytes.RemoveAt(position);
                            }
                            displayBinary(bytes,"red");
                            Console.WriteLine(pattern.Count + " Bytes removed.");

                            // Since you deleted some bytes,set the position less because you will need to redo the pos.
                            position = position - 1;
                        }


                        outer:
                            continue;
                    }

                    List<int> sublist = new List<int>();
                    sublist.Add(matches);
                    sublist.Add(pattern.Count);
                    // Some sort of calculation to determine how good the symbol was
                    sublist.Add(bytes.Count-((matches * pattern.Count)-matches));
                    list.Add(sublist);

                }

            }



            display(list);
            Console.Read();
            return 0;
        }


        static void displayBinary(List<byte> bytes,string color="white")
        {
            switch(color){
                case "green":
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                case "red":
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                default:
                    break;
            }


            for (int i=0; i<bytes.Count; i++)
            {
                if (i % 8 ==0)
                    Console.WriteLine();
                Console.Write(GetIntBinaryString(bytes[i]) + " ");
            }
            Console.WriteLine();
            Console.ResetColor();
        }
        static string GetIntBinaryString(int n)
        {
            char[] b = new char[8];
            int pos = 7;
            int i = 0;

            while (i < 8)
            {
                if ((n & (1 << i)) != 0)
                {
                    b[pos] = '1';
                }
                else
                {
                    b[pos] = '0';
                }
                pos--;
                i++;
            }
            //return new string(b).Trimstart('0');
            return new string(b);
        }

        static void display(List<List<int>> list)
        {
            //
            // display everything in the List.
            //
            Console.WriteLine("Elements:");
            foreach (var sublist in list)
            {
                foreach (var value in sublist)
                {
                    Console.Write("{0,4}",value);

                }
                Console.WriteLine();
            }

            //
            // display total count.
            //
            int count = 0;
            foreach (var sublist in list)
            {
                count += sublist.Count;
            }
            Console.WriteLine("Count:");
            Console.WriteLine(count);
        }

        static public int SearchBytePattern(byte[] pattern,byte[] bytes)
        {
            int matches = 0;
            // precomputing this shaves some seconds from the loop execution
            int maxloop = bytes.Length - pattern.Length;
            for (int i = 0; i < maxloop; i++)
            {
                if (pattern[0] == bytes[i])
                {
                    bool ismatch = true;
                    for (int j = 1; j < pattern.Length; j++)
                    {
                        if (bytes[i + j] != pattern[j])
                        {
                            ismatch = false;
                            break;
                        }
                    }
                    if (ismatch)
                    {
                        matches++;
                        i += pattern.Length - 1;
                    }
                }
            }
            return matches;
        }
    }

请参考帖子获取文件的非二进制文件,这里是二进制数据:
011010110010111001101011001011100110101100101110011010110010111001101011001011100110101100101110我希望它比它的起点小.

解决方法

private static int CountOccurences(byte[] target,byte[] pattern)
{
    var targetString = BitConverter.ToString(target);
    var patternString = BitConverter.ToString(pattern);
    return new Regex(patternString).Matches(targetString).Count;
}

C语言计算字符串数组中每个字符串出现的个数

C语言计算字符串数组中每个字符串出现的个数

unsigned int str_num(char *str[], int num[], int len)
{
    int i, j;
    int count;
    int flag[len];
    for (i = 0; i < len; i++)
    {
        num[i] = 0;
        flag[i] = 0;
    }
    
    for (i = 0; i < len; i ++)
    {
        for (j = 0; j <=  len; j ++)
        {
            if((0 == flag[i])&&  (0 == strncmp(str[j], str[i], 
            strlen(str[j]) > strlen(str[i]) ? strlen(str[j]) : strlen(str[i]))))
            {
                num[i] ++;
                flag[i] = 1;
            }
        }
    }
}

利用一个数组,记录每个字符串的个数,另一个flag数组标记已经计数过的字符串

C语言:对传入sp的字符进行统计,三组两个相连字母“ea”

C语言:对传入sp的字符进行统计,三组两个相连字母“ea”"ou""iu"出现的次数,并将统计结果存入ct所指的数组中。-在数组中找出最小值,并与第一个元...

//对传入sp的字符进行统计,三组两个相连字母“ea”"ou""iu"出现的次数,并将统计结果存入ct所指的数组中。

 1 #include <stdio.h> 
 2 #include <string.h>
 3 #pragma warning (disable:4996)
 4 void fun(char*sp ,int *ct)
 5 {
 6     int a=0, b=0, c=0;
 7     while (*sp != ''\0'')
 8     {
 9         if (*sp == ''e'')//利用if多重并列判断。
10         {
11             sp++;
12             if (*sp == ''a'')
13             {
14                 a++;
15                 //sp--;
16             }
17         }
18         else if (*sp == ''o'')
19         {
20             sp++;
21             if (*sp == ''u'')
22             {
23                 b++;
24                 //sp--;
25             }
26         }
27         else if (*sp == ''i'')
28         {
29             sp++;
30             if (*sp == ''u'')
31             {
32                 c++;
33                 //sp--;
34             }
35         }
36         else//这一步很关键,切记。
37         {
38             sp++;
39         }
40     }
41     ct[0] = a;
42     ct[1] = b;
43     ct[2] = c;
44 }
45 main()
46 {    void NONO();
47     char txt[200]="abeaeafeeaoukgdoouuoiouifwieeotiu";
48     int c[3];
49     fun(txt,c);
50     printf("%d,%d,%d\n",c[0],c[1],c[2]); 
51     NONO();
52 }
53 void NONO ()
54 {/* 请在此函数内打开文件,输入测试数据,调用 fun 函数,输出数据,关闭文件。 */
55   FILE *rf, *wf ;
56   int i, c[3] ;
57   char txt[200], *p ;
58 
59   rf = fopen("in.dat","r") ;
60   wf = fopen("out.dat","w") ;
61   for(i = 0 ; i < 10 ; i++) {
62     fgets(txt, 200, rf) ;
63     p = strchr(txt, ''\n'') ;
64     if(p != NULL) *p = 0 ;
65     fun(txt,c);
66     fprintf(wf, "%d,%d,%d\n",c[0],c[1],c[2]); 
67   }
68   fclose(rf) ; fclose(wf) ;
69 }

//在数组中找出最小值,并与第一个元素交换位置。

 1 #include<stdio.h>
 2 #pragma warning (disable:4996)
 3 void fun(int *dt,int n)
 4 {
 5     int i,m,t;
 6 /**********************found***********************/
 7     m = 0;//注意下标与数组两种方式的转换。
 8     for(i=1;i<n;i++)
 9 /**********************found***********************/
10         if(dt[i]<dt[m])
11             m=i;
12     t=dt[0];
13 /**********************found***********************/
14     dt[0] = dt[m];
15     dt[m]=t;
16 }
17 main()
18 {
19     int a[10]={ 30,20,15,64,85,28 }; 
20     int i,n=6;
21     for(i=0;i<n;i++)
22         printf("%4d",a[i]);
23     printf("\n");
24     fun(a,n);
25     for(i=0;i<n;i++)
26         printf("%4d",a[i]);
27     printf("\n");
28 }

 

今天的关于计算字符串出现在数组中并与另一个数组比较的次数计算字符串数组的长度的分享已经结束,谢谢您的关注,如果想了解更多关于2023-02-20:小A认为如果在数组中有一个数出现了至少k次, 且这个数是该数组的众数,即出现次数最多的数之一, 那么这个数组被该数所支配, 显然当k比较大的时候,有些数组不被任何数所支配。 现在、c# – 使用另一个字节列表/数组计算字节列表/数组中的出现次数、C语言计算字符串数组中每个字符串出现的个数、C语言:对传入sp的字符进行统计,三组两个相连字母“ea”"ou""iu"出现的次数,并将统计结果存入ct所指的数组中。-在数组中找出最小值,并与第一个元...的相关知识,请在本站进行查询。

本文标签: